cmdbsource.class.inc.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * DB Server abstraction
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('MyHelpers.class.inc.php');
  25. require_once(APPROOT.'core/kpi.class.inc.php');
  26. class MySQLException extends CoreException
  27. {
  28. public function __construct($sIssue, $aContext)
  29. {
  30. $aContext['mysql_error'] = CMDBSource::GetError();
  31. $aContext['mysql_errno'] = CMDBSource::GetErrNo();;
  32. parent::__construct($sIssue, $aContext);
  33. }
  34. }
  35. /**
  36. * CMDBSource
  37. * database access wrapper
  38. *
  39. * @package iTopORM
  40. */
  41. class CMDBSource
  42. {
  43. protected static $m_sDBHost;
  44. protected static $m_sDBUser;
  45. protected static $m_sDBPwd;
  46. protected static $m_sDBName;
  47. protected static $m_resDBLink;
  48. public static function Init($sServer, $sUser, $sPwd, $sSource = '')
  49. {
  50. self::$m_sDBHost = $sServer;
  51. self::$m_sDBUser = $sUser;
  52. self::$m_sDBPwd = $sPwd;
  53. self::$m_sDBName = $sSource;
  54. $aConnectInfo = explode(':', self::$m_sDBHost);
  55. if (count($aConnectInfo) > 1)
  56. {
  57. // Override the default port
  58. $sServer = $aConnectInfo[0];
  59. $iPort = $aConnectInfo[1];
  60. self::$m_resDBLink = @mysqli_connect($sServer, self::$m_sDBUser, self::$m_sDBPwd, '', $iPort);
  61. }
  62. else
  63. {
  64. self::$m_resDBLink = @mysqli_connect(self::$m_sDBHost, self::$m_sDBUser, self::$m_sDBPwd);
  65. }
  66. if (!self::$m_resDBLink)
  67. {
  68. throw new MySQLException('Could not connect to the DB server', array('host'=>self::$m_sDBHost, 'user'=>self::$m_sDBUser));
  69. }
  70. if (!empty($sSource))
  71. {
  72. if (!((bool)mysqli_query(self::$m_resDBLink, "USE `$sSource`")))
  73. {
  74. throw new MySQLException('Could not select DB', array('host'=>self::$m_sDBHost, 'user'=>self::$m_sDBUser, 'db_name'=>self::$m_sDBName));
  75. }
  76. }
  77. }
  78. public static function SetCharacterSet($sCharset = 'utf8', $sCollation = 'utf8_general_ci')
  79. {
  80. if (strlen($sCharset) > 0)
  81. {
  82. if (strlen($sCollation) > 0)
  83. {
  84. self::Query("SET NAMES '$sCharset' COLLATE '$sCollation'");
  85. }
  86. else
  87. {
  88. self::Query("SET NAMES '$sCharset'");
  89. }
  90. }
  91. }
  92. public static function SetTimezone($sTimezone = null)
  93. {
  94. // Note: requires the installation of MySQL special tables,
  95. // otherwise, only 'SYSTEM' or "+10:00' may be specified which is NOT sufficient because of day light saving times
  96. if (!is_null($sTimezone))
  97. {
  98. $sQuotedTimezone = self::Quote($sTimezone);
  99. self::Query("SET time_zone = $sQuotedTimezone");
  100. }
  101. }
  102. public static function ListDB()
  103. {
  104. $aDBs = self::QueryToCol('SHOW DATABASES', 'Database');
  105. // Show Database does return the DB names in lower case
  106. return $aDBs;
  107. }
  108. public static function IsDB($sSource)
  109. {
  110. try
  111. {
  112. $aDBs = self::ListDB();
  113. foreach($aDBs as $sDBName)
  114. {
  115. // perform a case insensitive test because on Windows the table names become lowercase :-(
  116. if (strtolower($sDBName) == strtolower($sSource)) return true;
  117. }
  118. return false;
  119. }
  120. catch(Exception $e)
  121. {
  122. // In case we don't have rights to enumerate the databases
  123. // Let's try to connect directly
  124. return @((bool)mysqli_query(self::$m_resDBLink, "USE `$sSource`"));
  125. }
  126. }
  127. public static function GetDBVersion()
  128. {
  129. $aVersions = self::QueryToCol('SELECT Version() as version', 'version');
  130. return $aVersions[0];
  131. }
  132. public static function SelectDB($sSource)
  133. {
  134. if (!((bool)mysqli_query(self::$m_resDBLink, "USE `$sSource`")))
  135. {
  136. throw new MySQLException('Could not select DB', array('db_name'=>$sSource));
  137. }
  138. self::$m_sDBName = $sSource;
  139. }
  140. public static function CreateDB($sSource)
  141. {
  142. self::Query("CREATE DATABASE `$sSource` CHARACTER SET utf8 COLLATE utf8_unicode_ci");
  143. self::SelectDB($sSource);
  144. }
  145. public static function DropDB($sDBToDrop = '')
  146. {
  147. if (empty($sDBToDrop))
  148. {
  149. $sDBToDrop = self::$m_sDBName;
  150. }
  151. self::Query("DROP DATABASE `$sDBToDrop`");
  152. if ($sDBToDrop == self::$m_sDBName)
  153. {
  154. self::$m_sDBName = '';
  155. }
  156. }
  157. public static function CreateTable($sQuery)
  158. {
  159. $res = self::Query($sQuery);
  160. self::_TablesInfoCacheReset(); // reset the table info cache!
  161. return $res;
  162. }
  163. public static function DropTable($sTable)
  164. {
  165. $res = self::Query("DROP TABLE `$sTable`");
  166. self::_TablesInfoCacheReset(true); // reset the table info cache!
  167. return $res;
  168. }
  169. public static function GetErrNo()
  170. {
  171. if (self::$m_resDBLink)
  172. {
  173. return mysqli_errno(self::$m_resDBLink);
  174. }
  175. else
  176. {
  177. return mysqli_connect_errno();
  178. }
  179. }
  180. public static function GetError()
  181. {
  182. if (self::$m_resDBLink)
  183. {
  184. return mysqli_error(self::$m_resDBLink);
  185. }
  186. else
  187. {
  188. return mysqli_connect_error();
  189. }
  190. }
  191. public static function DBHost() {return self::$m_sDBHost;}
  192. public static function DBUser() {return self::$m_sDBUser;}
  193. public static function DBPwd() {return self::$m_sDBPwd;}
  194. public static function DBName() {return self::$m_sDBName;}
  195. public static function Quote($value, $bAlways = false, $cQuoteStyle = "'")
  196. {
  197. // Quote variable and protect against SQL injection attacks
  198. // Code found in the PHP documentation: quote_smart($value)
  199. // bAlways should be set to true when the purpose is to create a IN clause,
  200. // otherwise and if there is a mix of strings and numbers, the clause
  201. // would always be false
  202. if (is_null($value))
  203. {
  204. return 'NULL';
  205. }
  206. if (is_array($value))
  207. {
  208. $aRes = array();
  209. foreach ($value as $key => $itemvalue)
  210. {
  211. $aRes[$key] = self::Quote($itemvalue, $bAlways, $cQuoteStyle);
  212. }
  213. return $aRes;
  214. }
  215. // Stripslashes
  216. if (get_magic_quotes_gpc())
  217. {
  218. $value = stripslashes($value);
  219. }
  220. // Quote if not a number or a numeric string
  221. if ($bAlways || is_string($value))
  222. {
  223. $value = $cQuoteStyle . mysqli_real_escape_string(self::$m_resDBLink, $value) . $cQuoteStyle;
  224. }
  225. return $value;
  226. }
  227. public static function Query($sSQLQuery)
  228. {
  229. // Add info into the query as a comment, for easier error tracking
  230. // disabled until we need it really!
  231. //
  232. //$aTraceInf['file'] = __FILE__;
  233. // $sSQLQuery .= MyHelpers::MakeSQLComment($aTraceInf);
  234. $oKPI = new ExecutionKPI();
  235. $result = mysqli_query(self::$m_resDBLink, $sSQLQuery);
  236. if (!$result)
  237. {
  238. throw new MySQLException('Failed to issue SQL query', array('query' => $sSQLQuery));
  239. }
  240. $oKPI->ComputeStats('Query exec (mySQL)', $sSQLQuery);
  241. return $result;
  242. }
  243. public static function GetNextInsertId($sTable)
  244. {
  245. $sSQL = "SHOW TABLE STATUS LIKE '$sTable'";
  246. $result = self::Query($sSQL);
  247. $aRow = mysqli_fetch_assoc($result);
  248. $iNextInsertId = $aRow['Auto_increment'];
  249. return $iNextInsertId;
  250. }
  251. public static function GetInsertId()
  252. {
  253. $iRes = mysqli_insert_id(self::$m_resDBLink);
  254. if (is_null($iRes))
  255. {
  256. return 0;
  257. }
  258. return $iRes;
  259. }
  260. public static function InsertInto($sSQLQuery)
  261. {
  262. if (self::Query($sSQLQuery))
  263. {
  264. return self::GetInsertId();
  265. }
  266. return false;
  267. }
  268. public static function DeleteFrom($sSQLQuery)
  269. {
  270. self::Query($sSQLQuery);
  271. }
  272. public static function QueryToScalar($sSql)
  273. {
  274. $result = mysqli_query(self::$m_resDBLink, $sSql);
  275. if (!$result)
  276. {
  277. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  278. }
  279. if ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  280. {
  281. $res = $aRow[0];
  282. }
  283. else
  284. {
  285. mysqli_free_result($result);
  286. throw new MySQLException('Found no result for query', array('query' => $sSql));
  287. }
  288. mysqli_free_result($result);
  289. return $res;
  290. }
  291. public static function QueryToArray($sSql)
  292. {
  293. $aData = array();
  294. $result = mysqli_query(self::$m_resDBLink, $sSql);
  295. if (!$result)
  296. {
  297. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  298. }
  299. while ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  300. {
  301. $aData[] = $aRow;
  302. }
  303. mysqli_free_result($result);
  304. return $aData;
  305. }
  306. public static function QueryToCol($sSql, $col)
  307. {
  308. $aColumn = array();
  309. $aData = self::QueryToArray($sSql);
  310. foreach($aData as $aRow)
  311. {
  312. @$aColumn[] = $aRow[$col];
  313. }
  314. return $aColumn;
  315. }
  316. public static function ExplainQuery($sSql)
  317. {
  318. $aData = array();
  319. $result = mysqli_query(self::$m_resDBLink, "EXPLAIN $sSql");
  320. if (!$result)
  321. {
  322. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  323. }
  324. $aNames = self::GetColumns($result);
  325. $aData[] = $aNames;
  326. while ($aRow = mysqli_fetch_array($result, MYSQLI_ASSOC))
  327. {
  328. $aData[] = $aRow;
  329. }
  330. mysqli_free_result($result);
  331. return $aData;
  332. }
  333. public static function TestQuery($sSql)
  334. {
  335. $result = mysqli_query(self::$m_resDBLink, "EXPLAIN $sSql");
  336. if (!$result)
  337. {
  338. return self::GetError();
  339. }
  340. mysqli_free_result($result);
  341. return '';
  342. }
  343. public static function NbRows($result)
  344. {
  345. return mysqli_num_rows($result);
  346. }
  347. public static function AffectedRows()
  348. {
  349. return mysqli_affected_rows(self::$m_resDBLink);
  350. }
  351. public static function FetchArray($result)
  352. {
  353. return mysqli_fetch_array($result, MYSQLI_ASSOC);
  354. }
  355. public static function GetColumns($result)
  356. {
  357. $aNames = array();
  358. for ($i = 0; $i < (($___mysqli_tmp = mysqli_num_fields($result)) ? $___mysqli_tmp : 0) ; $i++)
  359. {
  360. $meta = mysqli_fetch_field_direct($result, $i);
  361. if (!$meta)
  362. {
  363. throw new MySQLException('mysql_fetch_field: No information available', array('query'=>$sSql, 'i'=>$i));
  364. }
  365. else
  366. {
  367. $aNames[] = $meta->name;
  368. }
  369. }
  370. return $aNames;
  371. }
  372. public static function Seek($result, $iRow)
  373. {
  374. return mysqli_data_seek($result, $iRow);
  375. }
  376. public static function FreeResult($result)
  377. {
  378. return ((mysqli_free_result($result) || (is_object($result) && (get_class($result) == "mysqli_result"))) ? true : false);
  379. }
  380. public static function IsTable($sTable)
  381. {
  382. $aTableInfo = self::GetTableInfo($sTable);
  383. return (!empty($aTableInfo));
  384. }
  385. public static function IsKey($sTable, $iKey)
  386. {
  387. $aTableInfo = self::GetTableInfo($sTable);
  388. if (empty($aTableInfo)) return false;
  389. if (!array_key_exists($iKey, $aTableInfo["Fields"])) return false;
  390. $aFieldData = $aTableInfo["Fields"][$iKey];
  391. if (!array_key_exists("Key", $aFieldData)) return false;
  392. return ($aFieldData["Key"] == "PRI");
  393. }
  394. public static function IsAutoIncrement($sTable, $sField)
  395. {
  396. $aTableInfo = self::GetTableInfo($sTable);
  397. if (empty($aTableInfo)) return false;
  398. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  399. $aFieldData = $aTableInfo["Fields"][$sField];
  400. if (!array_key_exists("Extra", $aFieldData)) return false;
  401. //MyHelpers::debug_breakpoint($aFieldData);
  402. return (strstr($aFieldData["Extra"], "auto_increment"));
  403. }
  404. public static function IsField($sTable, $sField)
  405. {
  406. $aTableInfo = self::GetTableInfo($sTable);
  407. if (empty($aTableInfo)) return false;
  408. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  409. return true;
  410. }
  411. public static function IsNullAllowed($sTable, $sField)
  412. {
  413. $aTableInfo = self::GetTableInfo($sTable);
  414. if (empty($aTableInfo)) return false;
  415. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  416. $aFieldData = $aTableInfo["Fields"][$sField];
  417. return (strtolower($aFieldData["Null"]) == "yes");
  418. }
  419. public static function GetFieldType($sTable, $sField)
  420. {
  421. $aTableInfo = self::GetTableInfo($sTable);
  422. if (empty($aTableInfo)) return false;
  423. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  424. $aFieldData = $aTableInfo["Fields"][$sField];
  425. return ($aFieldData["Type"]);
  426. }
  427. public static function HasIndex($sTable, $sIndexId, $aFields = null)
  428. {
  429. $aTableInfo = self::GetTableInfo($sTable);
  430. if (empty($aTableInfo)) return false;
  431. if (!array_key_exists($sIndexId, $aTableInfo['Indexes'])) return false;
  432. if ($aFields == null)
  433. {
  434. // Just searching for the name
  435. return true;
  436. }
  437. // Compare the columns
  438. $sSearchedIndex = implode(',', $aFields);
  439. $sExistingIndex = implode(',', $aTableInfo['Indexes'][$sIndexId]);
  440. return ($sSearchedIndex == $sExistingIndex);
  441. }
  442. // Returns an array of (fieldname => array of field info)
  443. public static function GetTableFieldsList($sTable)
  444. {
  445. assert(!empty($sTable));
  446. $aTableInfo = self::GetTableInfo($sTable);
  447. if (empty($aTableInfo)) return array(); // #@# or an error ?
  448. return array_keys($aTableInfo["Fields"]);
  449. }
  450. // Cache the information about existing tables, and their fields
  451. private static $m_aTablesInfo = array();
  452. private static function _TablesInfoCacheReset()
  453. {
  454. self::$m_aTablesInfo = array();
  455. }
  456. private static function _TableInfoCacheInit($sTableName)
  457. {
  458. if (isset(self::$m_aTablesInfo[strtolower($sTableName)])
  459. && (self::$m_aTablesInfo[strtolower($sTableName)] != null)) return;
  460. try
  461. {
  462. // Check if the table exists
  463. $aFields = self::QueryToArray("SHOW COLUMNS FROM `$sTableName`");
  464. // Note: without backticks, you get an error with some table names (e.g. "group")
  465. foreach ($aFields as $aFieldData)
  466. {
  467. $sFieldName = $aFieldData["Field"];
  468. self::$m_aTablesInfo[strtolower($sTableName)]["Fields"][$sFieldName] =
  469. array
  470. (
  471. "Name"=>$aFieldData["Field"],
  472. "Type"=>$aFieldData["Type"],
  473. "Null"=>$aFieldData["Null"],
  474. "Key"=>$aFieldData["Key"],
  475. "Default"=>$aFieldData["Default"],
  476. "Extra"=>$aFieldData["Extra"]
  477. );
  478. }
  479. }
  480. catch(MySQLException $e)
  481. {
  482. // Table does not exist
  483. self::$m_aTablesInfo[strtolower($sTableName)] = null;
  484. }
  485. if (!is_null(self::$m_aTablesInfo[strtolower($sTableName)]))
  486. {
  487. $aIndexes = self::QueryToArray("SHOW INDEXES FROM `$sTableName`");
  488. $aMyIndexes = array();
  489. foreach ($aIndexes as $aIndexColumn)
  490. {
  491. $aMyIndexes[$aIndexColumn['Key_name']][$aIndexColumn['Seq_in_index']-1] = $aIndexColumn['Column_name'];
  492. }
  493. self::$m_aTablesInfo[strtolower($sTableName)]["Indexes"] = $aMyIndexes;
  494. }
  495. }
  496. //public static function EnumTables()
  497. //{
  498. // self::_TablesInfoCacheInit();
  499. // return array_keys(self::$m_aTablesInfo);
  500. //}
  501. public static function GetTableInfo($sTable)
  502. {
  503. self::_TableInfoCacheInit($sTable);
  504. // perform a case insensitive match because on Windows the table names become lowercase :-(
  505. //foreach(self::$m_aTablesInfo as $sTableName => $aInfo)
  506. //{
  507. // if (strtolower($sTableName) == strtolower($sTable))
  508. // {
  509. // return $aInfo;
  510. // }
  511. //}
  512. return self::$m_aTablesInfo[strtolower($sTable)];
  513. //return null;
  514. }
  515. public static function DumpTable($sTable)
  516. {
  517. $sSql = "SELECT * FROM `$sTable`";
  518. $result = mysqli_query(self::$m_resDBLink, $sSql);
  519. if (!$result)
  520. {
  521. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  522. }
  523. $aRows = array();
  524. while ($aRow = mysqli_fetch_array($result, MYSQLI_ASSOC))
  525. {
  526. $aRows[] = $aRow;
  527. }
  528. mysqli_free_result($result);
  529. return $aRows;
  530. }
  531. /**
  532. * Returns the value of the specified server variable
  533. * @param string $sVarName Name of the server variable
  534. * @return mixed Current value of the variable
  535. */
  536. public static function GetServerVariable($sVarName)
  537. {
  538. $result = '';
  539. $sSql = "SELECT @@$sVarName as theVar";
  540. $aRows = self::QueryToArray($sSql);
  541. if (count($aRows) > 0)
  542. {
  543. $result = $aRows[0]['theVar'];
  544. }
  545. return $result;
  546. }
  547. /**
  548. * Returns the privileges of the current user
  549. * @return string privileges in a raw format
  550. */
  551. public static function GetRawPrivileges()
  552. {
  553. try
  554. {
  555. $result = self::Query('SHOW GRANTS'); // [ FOR CURRENT_USER()]
  556. }
  557. catch(MySQLException $e)
  558. {
  559. return "Current user not allowed to see his own privileges (could not access to the database 'mysql' - $iCode)";
  560. }
  561. $aRes = array();
  562. while ($aRow = mysqli_fetch_array($result, MYSQLI_NUM))
  563. {
  564. // so far, only one column...
  565. $aRes[] = implode('/', $aRow);
  566. }
  567. mysqli_free_result($result);
  568. // so far, only one line...
  569. return implode(', ', $aRes);
  570. }
  571. /**
  572. * Determine the slave status of the server
  573. * @return bool true if the server is slave
  574. */
  575. public static function IsSlaveServer()
  576. {
  577. try
  578. {
  579. $result = self::Query('SHOW SLAVE STATUS');
  580. }
  581. catch(MySQLException $e)
  582. {
  583. throw new CoreException("Current user not allowed to check the status", array('mysql_error' => $e->getMessage()));
  584. }
  585. if (mysqli_num_rows($result) == 0)
  586. {
  587. return false;
  588. }
  589. // Returns one single row anytime
  590. $aRow = mysqli_fetch_array($result, MYSQLI_ASSOC);
  591. mysqli_free_result($result);
  592. if (!isset($aRow['Slave_IO_Running']))
  593. {
  594. return false;
  595. }
  596. if (!isset($aRow['Slave_SQL_Running']))
  597. {
  598. return false;
  599. }
  600. // If at least one slave thread is running, then we consider that the slave is enabled
  601. if ($aRow['Slave_IO_Running'] == 'Yes')
  602. {
  603. return true;
  604. }
  605. if ($aRow['Slave_SQL_Running'] == 'Yes')
  606. {
  607. return true;
  608. }
  609. return false;
  610. }
  611. }
  612. ?>