cmdbsource.class.inc.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. $oKPI = new ExecutionKPI();
  230. $result = mysqli_query(self::$m_resDBLink, $sSQLQuery);
  231. if (!$result)
  232. {
  233. throw new MySQLException('Failed to issue SQL query', array('query' => $sSQLQuery));
  234. }
  235. $oKPI->ComputeStats('Query exec (mySQL)', $sSQLQuery);
  236. return $result;
  237. }
  238. public static function GetNextInsertId($sTable)
  239. {
  240. $sSQL = "SHOW TABLE STATUS LIKE '$sTable'";
  241. $result = self::Query($sSQL);
  242. $aRow = mysqli_fetch_assoc($result);
  243. $iNextInsertId = $aRow['Auto_increment'];
  244. return $iNextInsertId;
  245. }
  246. public static function GetInsertId()
  247. {
  248. $iRes = mysqli_insert_id(self::$m_resDBLink);
  249. if (is_null($iRes))
  250. {
  251. return 0;
  252. }
  253. return $iRes;
  254. }
  255. public static function InsertInto($sSQLQuery)
  256. {
  257. if (self::Query($sSQLQuery))
  258. {
  259. return self::GetInsertId();
  260. }
  261. return false;
  262. }
  263. public static function DeleteFrom($sSQLQuery)
  264. {
  265. self::Query($sSQLQuery);
  266. }
  267. public static function QueryToScalar($sSql)
  268. {
  269. $oKPI = new ExecutionKPI();
  270. $result = mysqli_query(self::$m_resDBLink, $sSql);
  271. $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
  272. if (!$result)
  273. {
  274. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  275. }
  276. if ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  277. {
  278. $res = $aRow[0];
  279. }
  280. else
  281. {
  282. mysqli_free_result($result);
  283. throw new MySQLException('Found no result for query', array('query' => $sSql));
  284. }
  285. mysqli_free_result($result);
  286. return $res;
  287. }
  288. public static function QueryToArray($sSql)
  289. {
  290. $aData = array();
  291. $oKPI = new ExecutionKPI();
  292. $result = mysqli_query(self::$m_resDBLink, $sSql);
  293. $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
  294. if (!$result)
  295. {
  296. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  297. }
  298. while ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  299. {
  300. $aData[] = $aRow;
  301. }
  302. mysqli_free_result($result);
  303. return $aData;
  304. }
  305. public static function QueryToCol($sSql, $col)
  306. {
  307. $aColumn = array();
  308. $aData = self::QueryToArray($sSql);
  309. foreach($aData as $aRow)
  310. {
  311. @$aColumn[] = $aRow[$col];
  312. }
  313. return $aColumn;
  314. }
  315. public static function ExplainQuery($sSql)
  316. {
  317. $aData = array();
  318. $result = mysqli_query(self::$m_resDBLink, "EXPLAIN $sSql");
  319. if (!$result)
  320. {
  321. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  322. }
  323. $aNames = self::GetColumns($result);
  324. $aData[] = $aNames;
  325. while ($aRow = mysqli_fetch_array($result, MYSQLI_ASSOC))
  326. {
  327. $aData[] = $aRow;
  328. }
  329. mysqli_free_result($result);
  330. return $aData;
  331. }
  332. public static function TestQuery($sSql)
  333. {
  334. $result = mysqli_query(self::$m_resDBLink, "EXPLAIN $sSql");
  335. if (!$result)
  336. {
  337. return self::GetError();
  338. }
  339. mysqli_free_result($result);
  340. return '';
  341. }
  342. public static function NbRows($result)
  343. {
  344. return mysqli_num_rows($result);
  345. }
  346. public static function AffectedRows()
  347. {
  348. return mysqli_affected_rows(self::$m_resDBLink);
  349. }
  350. public static function FetchArray($result)
  351. {
  352. return mysqli_fetch_array($result, MYSQLI_ASSOC);
  353. }
  354. public static function GetColumns($result)
  355. {
  356. $aNames = array();
  357. for ($i = 0; $i < (($___mysqli_tmp = mysqli_num_fields($result)) ? $___mysqli_tmp : 0) ; $i++)
  358. {
  359. $meta = mysqli_fetch_field_direct($result, $i);
  360. if (!$meta)
  361. {
  362. throw new MySQLException('mysql_fetch_field: No information available', array('query'=>$sSql, 'i'=>$i));
  363. }
  364. else
  365. {
  366. $aNames[] = $meta->name;
  367. }
  368. }
  369. return $aNames;
  370. }
  371. public static function Seek($result, $iRow)
  372. {
  373. return mysqli_data_seek($result, $iRow);
  374. }
  375. public static function FreeResult($result)
  376. {
  377. return ((mysqli_free_result($result) || (is_object($result) && (get_class($result) == "mysqli_result"))) ? true : false);
  378. }
  379. public static function IsTable($sTable)
  380. {
  381. $aTableInfo = self::GetTableInfo($sTable);
  382. return (!empty($aTableInfo));
  383. }
  384. public static function IsKey($sTable, $iKey)
  385. {
  386. $aTableInfo = self::GetTableInfo($sTable);
  387. if (empty($aTableInfo)) return false;
  388. if (!array_key_exists($iKey, $aTableInfo["Fields"])) return false;
  389. $aFieldData = $aTableInfo["Fields"][$iKey];
  390. if (!array_key_exists("Key", $aFieldData)) return false;
  391. return ($aFieldData["Key"] == "PRI");
  392. }
  393. public static function IsAutoIncrement($sTable, $sField)
  394. {
  395. $aTableInfo = self::GetTableInfo($sTable);
  396. if (empty($aTableInfo)) return false;
  397. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  398. $aFieldData = $aTableInfo["Fields"][$sField];
  399. if (!array_key_exists("Extra", $aFieldData)) return false;
  400. //MyHelpers::debug_breakpoint($aFieldData);
  401. return (strstr($aFieldData["Extra"], "auto_increment"));
  402. }
  403. public static function IsField($sTable, $sField)
  404. {
  405. $aTableInfo = self::GetTableInfo($sTable);
  406. if (empty($aTableInfo)) return false;
  407. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  408. return true;
  409. }
  410. public static function IsNullAllowed($sTable, $sField)
  411. {
  412. $aTableInfo = self::GetTableInfo($sTable);
  413. if (empty($aTableInfo)) return false;
  414. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  415. $aFieldData = $aTableInfo["Fields"][$sField];
  416. return (strtolower($aFieldData["Null"]) == "yes");
  417. }
  418. public static function GetFieldType($sTable, $sField)
  419. {
  420. $aTableInfo = self::GetTableInfo($sTable);
  421. if (empty($aTableInfo)) return false;
  422. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  423. $aFieldData = $aTableInfo["Fields"][$sField];
  424. return ($aFieldData["Type"]);
  425. }
  426. public static function HasIndex($sTable, $sIndexId, $aFields = null)
  427. {
  428. $aTableInfo = self::GetTableInfo($sTable);
  429. if (empty($aTableInfo)) return false;
  430. if (!array_key_exists($sIndexId, $aTableInfo['Indexes'])) return false;
  431. if ($aFields == null)
  432. {
  433. // Just searching for the name
  434. return true;
  435. }
  436. // Compare the columns
  437. $sSearchedIndex = implode(',', $aFields);
  438. $sExistingIndex = implode(',', $aTableInfo['Indexes'][$sIndexId]);
  439. return ($sSearchedIndex == $sExistingIndex);
  440. }
  441. // Returns an array of (fieldname => array of field info)
  442. public static function GetTableFieldsList($sTable)
  443. {
  444. assert(!empty($sTable));
  445. $aTableInfo = self::GetTableInfo($sTable);
  446. if (empty($aTableInfo)) return array(); // #@# or an error ?
  447. return array_keys($aTableInfo["Fields"]);
  448. }
  449. // Cache the information about existing tables, and their fields
  450. private static $m_aTablesInfo = array();
  451. private static function _TablesInfoCacheReset()
  452. {
  453. self::$m_aTablesInfo = array();
  454. }
  455. private static function _TableInfoCacheInit($sTableName)
  456. {
  457. if (isset(self::$m_aTablesInfo[strtolower($sTableName)])
  458. && (self::$m_aTablesInfo[strtolower($sTableName)] != null)) return;
  459. try
  460. {
  461. // Check if the table exists
  462. $aFields = self::QueryToArray("SHOW COLUMNS FROM `$sTableName`");
  463. // Note: without backticks, you get an error with some table names (e.g. "group")
  464. foreach ($aFields as $aFieldData)
  465. {
  466. $sFieldName = $aFieldData["Field"];
  467. self::$m_aTablesInfo[strtolower($sTableName)]["Fields"][$sFieldName] =
  468. array
  469. (
  470. "Name"=>$aFieldData["Field"],
  471. "Type"=>$aFieldData["Type"],
  472. "Null"=>$aFieldData["Null"],
  473. "Key"=>$aFieldData["Key"],
  474. "Default"=>$aFieldData["Default"],
  475. "Extra"=>$aFieldData["Extra"]
  476. );
  477. }
  478. }
  479. catch(MySQLException $e)
  480. {
  481. // Table does not exist
  482. self::$m_aTablesInfo[strtolower($sTableName)] = null;
  483. }
  484. if (!is_null(self::$m_aTablesInfo[strtolower($sTableName)]))
  485. {
  486. $aIndexes = self::QueryToArray("SHOW INDEXES FROM `$sTableName`");
  487. $aMyIndexes = array();
  488. foreach ($aIndexes as $aIndexColumn)
  489. {
  490. $aMyIndexes[$aIndexColumn['Key_name']][$aIndexColumn['Seq_in_index']-1] = $aIndexColumn['Column_name'];
  491. }
  492. self::$m_aTablesInfo[strtolower($sTableName)]["Indexes"] = $aMyIndexes;
  493. }
  494. }
  495. //public static function EnumTables()
  496. //{
  497. // self::_TablesInfoCacheInit();
  498. // return array_keys(self::$m_aTablesInfo);
  499. //}
  500. public static function GetTableInfo($sTable)
  501. {
  502. self::_TableInfoCacheInit($sTable);
  503. // perform a case insensitive match because on Windows the table names become lowercase :-(
  504. //foreach(self::$m_aTablesInfo as $sTableName => $aInfo)
  505. //{
  506. // if (strtolower($sTableName) == strtolower($sTable))
  507. // {
  508. // return $aInfo;
  509. // }
  510. //}
  511. return self::$m_aTablesInfo[strtolower($sTable)];
  512. //return null;
  513. }
  514. public static function DumpTable($sTable)
  515. {
  516. $sSql = "SELECT * FROM `$sTable`";
  517. $result = mysqli_query(self::$m_resDBLink, $sSql);
  518. if (!$result)
  519. {
  520. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  521. }
  522. $aRows = array();
  523. while ($aRow = mysqli_fetch_array($result, MYSQLI_ASSOC))
  524. {
  525. $aRows[] = $aRow;
  526. }
  527. mysqli_free_result($result);
  528. return $aRows;
  529. }
  530. /**
  531. * Returns the value of the specified server variable
  532. * @param string $sVarName Name of the server variable
  533. * @return mixed Current value of the variable
  534. */
  535. public static function GetServerVariable($sVarName)
  536. {
  537. $result = '';
  538. $sSql = "SELECT @@$sVarName as theVar";
  539. $aRows = self::QueryToArray($sSql);
  540. if (count($aRows) > 0)
  541. {
  542. $result = $aRows[0]['theVar'];
  543. }
  544. return $result;
  545. }
  546. /**
  547. * Returns the privileges of the current user
  548. * @return string privileges in a raw format
  549. */
  550. public static function GetRawPrivileges()
  551. {
  552. try
  553. {
  554. $result = self::Query('SHOW GRANTS'); // [ FOR CURRENT_USER()]
  555. }
  556. catch(MySQLException $e)
  557. {
  558. return "Current user not allowed to see his own privileges (could not access to the database 'mysql' - $iCode)";
  559. }
  560. $aRes = array();
  561. while ($aRow = mysqli_fetch_array($result, MYSQLI_NUM))
  562. {
  563. // so far, only one column...
  564. $aRes[] = implode('/', $aRow);
  565. }
  566. mysqli_free_result($result);
  567. // so far, only one line...
  568. return implode(', ', $aRes);
  569. }
  570. /**
  571. * Determine the slave status of the server
  572. * @return bool true if the server is slave
  573. */
  574. public static function IsSlaveServer()
  575. {
  576. try
  577. {
  578. $result = self::Query('SHOW SLAVE STATUS');
  579. }
  580. catch(MySQLException $e)
  581. {
  582. throw new CoreException("Current user not allowed to check the status", array('mysql_error' => $e->getMessage()));
  583. }
  584. if (mysqli_num_rows($result) == 0)
  585. {
  586. return false;
  587. }
  588. // Returns one single row anytime
  589. $aRow = mysqli_fetch_array($result, MYSQLI_ASSOC);
  590. mysqli_free_result($result);
  591. if (!isset($aRow['Slave_IO_Running']))
  592. {
  593. return false;
  594. }
  595. if (!isset($aRow['Slave_SQL_Running']))
  596. {
  597. return false;
  598. }
  599. // If at least one slave thread is running, then we consider that the slave is enabled
  600. if ($aRow['Slave_IO_Running'] == 'Yes')
  601. {
  602. return true;
  603. }
  604. if ($aRow['Slave_SQL_Running'] == 'Yes')
  605. {
  606. return true;
  607. }
  608. return false;
  609. }
  610. }
  611. ?>