cmdbsource.class.inc.php 17 KB

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