cmdbsource.class.inc.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * DB Server abstraction
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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. return mysqli_errno(self::$m_resDBLink);
  160. }
  161. public static function GetError()
  162. {
  163. return mysqli_error(self::$m_resDBLink);
  164. }
  165. public static function DBHost() {return self::$m_sDBHost;}
  166. public static function DBUser() {return self::$m_sDBUser;}
  167. public static function DBPwd() {return self::$m_sDBPwd;}
  168. public static function DBName() {return self::$m_sDBName;}
  169. public static function Quote($value, $bAlways = false, $cQuoteStyle = "'")
  170. {
  171. // Quote variable and protect against SQL injection attacks
  172. // Code found in the PHP documentation: quote_smart($value)
  173. // bAlways should be set to true when the purpose is to create a IN clause,
  174. // otherwise and if there is a mix of strings and numbers, the clause
  175. // would always be false
  176. if (is_null($value))
  177. {
  178. return 'NULL';
  179. }
  180. if (is_array($value))
  181. {
  182. $aRes = array();
  183. foreach ($value as $key => $itemvalue)
  184. {
  185. $aRes[$key] = self::Quote($itemvalue, $bAlways, $cQuoteStyle);
  186. }
  187. return $aRes;
  188. }
  189. // Stripslashes
  190. if (get_magic_quotes_gpc())
  191. {
  192. $value = stripslashes($value);
  193. }
  194. // Quote if not a number or a numeric string
  195. if ($bAlways || is_string($value))
  196. {
  197. $value = $cQuoteStyle . mysqli_real_escape_string(self::$m_resDBLink, $value) . $cQuoteStyle;
  198. }
  199. return $value;
  200. }
  201. public static function Query($sSQLQuery)
  202. {
  203. // Add info into the query as a comment, for easier error tracking
  204. // disabled until we need it really!
  205. //
  206. //$aTraceInf['file'] = __FILE__;
  207. // $sSQLQuery .= MyHelpers::MakeSQLComment($aTraceInf);
  208. $oKPI = new ExecutionKPI();
  209. $result = mysqli_query(self::$m_resDBLink, $sSQLQuery);
  210. if (!$result)
  211. {
  212. throw new MySQLException('Failed to issue SQL query', array('query' => $sSQLQuery));
  213. }
  214. $oKPI->ComputeStats('Query exec (mySQL)', $sSQLQuery);
  215. return $result;
  216. }
  217. public static function GetNextInsertId($sTable)
  218. {
  219. $sSQL = "SHOW TABLE STATUS LIKE '$sTable'";
  220. $result = self::Query($sSQL);
  221. $aRow = mysqli_fetch_assoc($result);
  222. $iNextInsertId = $aRow['Auto_increment'];
  223. return $iNextInsertId;
  224. }
  225. public static function GetInsertId()
  226. {
  227. $iRes = mysqli_insert_id(self::$m_resDBLink);
  228. if (is_null($iRes))
  229. {
  230. return 0;
  231. }
  232. return $iRes;
  233. }
  234. public static function InsertInto($sSQLQuery)
  235. {
  236. if (self::Query($sSQLQuery))
  237. {
  238. return self::GetInsertId();
  239. }
  240. return false;
  241. }
  242. public static function DeleteFrom($sSQLQuery)
  243. {
  244. self::Query($sSQLQuery);
  245. }
  246. public static function QueryToScalar($sSql)
  247. {
  248. $result = mysqli_query(self::$m_resDBLink, $sSql);
  249. if (!$result)
  250. {
  251. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  252. }
  253. if ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  254. {
  255. $res = $aRow[0];
  256. }
  257. else
  258. {
  259. mysqli_free_result($result);
  260. throw new MySQLException('Found no result for query', array('query' => $sSql));
  261. }
  262. mysqli_free_result($result);
  263. return $res;
  264. }
  265. public static function QueryToArray($sSql)
  266. {
  267. $aData = array();
  268. $result = mysqli_query(self::$m_resDBLink, $sSql);
  269. if (!$result)
  270. {
  271. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  272. }
  273. while ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  274. {
  275. $aData[] = $aRow;
  276. }
  277. mysqli_free_result($result);
  278. return $aData;
  279. }
  280. public static function QueryToCol($sSql, $col)
  281. {
  282. $aColumn = array();
  283. $aData = self::QueryToArray($sSql);
  284. foreach($aData as $aRow)
  285. {
  286. @$aColumn[] = $aRow[$col];
  287. }
  288. return $aColumn;
  289. }
  290. public static function ExplainQuery($sSql)
  291. {
  292. $aData = array();
  293. $result = mysqli_query(self::$m_resDBLink, "EXPLAIN $sSql");
  294. if (!$result)
  295. {
  296. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  297. }
  298. $aNames = self::GetColumns($result);
  299. $aData[] = $aNames;
  300. while ($aRow = mysqli_fetch_array($result, MYSQLI_ASSOC))
  301. {
  302. $aData[] = $aRow;
  303. }
  304. mysqli_free_result($result);
  305. return $aData;
  306. }
  307. public static function TestQuery($sSql)
  308. {
  309. $result = mysqli_query(self::$m_resDBLink, "EXPLAIN $sSql");
  310. if (!$result)
  311. {
  312. return self::GetError();
  313. }
  314. mysqli_free_result($result);
  315. return '';
  316. }
  317. public static function NbRows($result)
  318. {
  319. return mysqli_num_rows($result);
  320. }
  321. public static function FetchArray($result)
  322. {
  323. return mysqli_fetch_array($result, MYSQLI_ASSOC);
  324. }
  325. public static function GetColumns($result)
  326. {
  327. $aNames = array();
  328. for ($i = 0; $i < (($___mysqli_tmp = mysqli_num_fields($result)) ? $___mysqli_tmp : 0) ; $i++)
  329. {
  330. $meta = mysqli_fetch_field_direct($result, $i);
  331. if (!$meta)
  332. {
  333. throw new MySQLException('mysql_fetch_field: No information available', array('query'=>$sSql, 'i'=>$i));
  334. }
  335. else
  336. {
  337. $aNames[] = $meta->name;
  338. }
  339. }
  340. return $aNames;
  341. }
  342. public static function Seek($result, $iRow)
  343. {
  344. return mysqli_data_seek($result, $iRow);
  345. }
  346. public static function FreeResult($result)
  347. {
  348. return ((mysqli_free_result($result) || (is_object($result) && (get_class($result) == "mysqli_result"))) ? true : false);
  349. }
  350. public static function IsTable($sTable)
  351. {
  352. $aTableInfo = self::GetTableInfo($sTable);
  353. return (!empty($aTableInfo));
  354. }
  355. public static function IsKey($sTable, $iKey)
  356. {
  357. $aTableInfo = self::GetTableInfo($sTable);
  358. if (empty($aTableInfo)) return false;
  359. if (!array_key_exists($iKey, $aTableInfo["Fields"])) return false;
  360. $aFieldData = $aTableInfo["Fields"][$iKey];
  361. if (!array_key_exists("Key", $aFieldData)) return false;
  362. return ($aFieldData["Key"] == "PRI");
  363. }
  364. public static function IsAutoIncrement($sTable, $sField)
  365. {
  366. $aTableInfo = self::GetTableInfo($sTable);
  367. if (empty($aTableInfo)) return false;
  368. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  369. $aFieldData = $aTableInfo["Fields"][$sField];
  370. if (!array_key_exists("Extra", $aFieldData)) return false;
  371. //MyHelpers::debug_breakpoint($aFieldData);
  372. return (strstr($aFieldData["Extra"], "auto_increment"));
  373. }
  374. public static function IsField($sTable, $sField)
  375. {
  376. $aTableInfo = self::GetTableInfo($sTable);
  377. if (empty($aTableInfo)) return false;
  378. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  379. return true;
  380. }
  381. public static function IsNullAllowed($sTable, $sField)
  382. {
  383. $aTableInfo = self::GetTableInfo($sTable);
  384. if (empty($aTableInfo)) return false;
  385. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  386. $aFieldData = $aTableInfo["Fields"][$sField];
  387. return (strtolower($aFieldData["Null"]) == "yes");
  388. }
  389. public static function GetFieldType($sTable, $sField)
  390. {
  391. $aTableInfo = self::GetTableInfo($sTable);
  392. if (empty($aTableInfo)) return false;
  393. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  394. $aFieldData = $aTableInfo["Fields"][$sField];
  395. return ($aFieldData["Type"]);
  396. }
  397. public static function HasIndex($sTable, $sField)
  398. {
  399. $aTableInfo = self::GetTableInfo($sTable);
  400. if (empty($aTableInfo)) return false;
  401. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  402. $aFieldData = $aTableInfo["Fields"][$sField];
  403. // $aFieldData could be 'PRI' for the primary key, or 'MUL', or ?
  404. return (strlen($aFieldData["Key"]) > 0);
  405. }
  406. // Returns an array of (fieldname => array of field info)
  407. public static function GetTableFieldsList($sTable)
  408. {
  409. assert(!empty($sTable));
  410. $aTableInfo = self::GetTableInfo($sTable);
  411. if (empty($aTableInfo)) return array(); // #@# or an error ?
  412. return array_keys($aTableInfo["Fields"]);
  413. }
  414. // Cache the information about existing tables, and their fields
  415. private static $m_aTablesInfo = array();
  416. private static function _TablesInfoCacheReset()
  417. {
  418. self::$m_aTablesInfo = array();
  419. }
  420. private static function _TableInfoCacheInit($sTableName)
  421. {
  422. if (isset(self::$m_aTablesInfo[strtolower($sTableName)])
  423. && (self::$m_aTablesInfo[strtolower($sTableName)] != null)) return;
  424. try
  425. {
  426. // Check if the table exists
  427. $aFields = self::QueryToArray("SHOW COLUMNS FROM `$sTableName`");
  428. // Note: without backticks, you get an error with some table names (e.g. "group")
  429. foreach ($aFields as $aFieldData)
  430. {
  431. $sFieldName = $aFieldData["Field"];
  432. self::$m_aTablesInfo[strtolower($sTableName)]["Fields"][$sFieldName] =
  433. array
  434. (
  435. "Name"=>$aFieldData["Field"],
  436. "Type"=>$aFieldData["Type"],
  437. "Null"=>$aFieldData["Null"],
  438. "Key"=>$aFieldData["Key"],
  439. "Default"=>$aFieldData["Default"],
  440. "Extra"=>$aFieldData["Extra"]
  441. );
  442. }
  443. }
  444. catch(MySQLException $e)
  445. {
  446. // Table does not exist
  447. self::$m_aTablesInfo[strtolower($sTableName)] = null;
  448. }
  449. }
  450. //public static function EnumTables()
  451. //{
  452. // self::_TablesInfoCacheInit();
  453. // return array_keys(self::$m_aTablesInfo);
  454. //}
  455. public static function GetTableInfo($sTable)
  456. {
  457. self::_TableInfoCacheInit($sTable);
  458. // perform a case insensitive match because on Windows the table names become lowercase :-(
  459. //foreach(self::$m_aTablesInfo as $sTableName => $aInfo)
  460. //{
  461. // if (strtolower($sTableName) == strtolower($sTable))
  462. // {
  463. // return $aInfo;
  464. // }
  465. //}
  466. return self::$m_aTablesInfo[strtolower($sTable)];
  467. //return null;
  468. }
  469. public static function DumpTable($sTable)
  470. {
  471. $sSql = "SELECT * FROM `$sTable`";
  472. $result = mysqli_query(self::$m_resDBLink, $sSql);
  473. if (!$result)
  474. {
  475. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  476. }
  477. $aRows = array();
  478. while ($aRow = mysqli_fetch_array($result, MYSQLI_ASSOC))
  479. {
  480. $aRows[] = $aRow;
  481. }
  482. mysqli_free_result($result);
  483. return $aRows;
  484. }
  485. /**
  486. * Returns the value of the specified server variable
  487. * @param string $sVarName Name of the server variable
  488. * @return mixed Current value of the variable
  489. */
  490. public static function GetServerVariable($sVarName)
  491. {
  492. $result = '';
  493. $sSql = "SELECT @@$sVarName as theVar";
  494. $aRows = self::QueryToArray($sSql);
  495. if (count($aRows) > 0)
  496. {
  497. $result = $aRows[0]['theVar'];
  498. }
  499. return $result;
  500. }
  501. /**
  502. * Returns the privileges of the current user
  503. * @return string privileges in a raw format
  504. */
  505. public static function GetRawPrivileges()
  506. {
  507. try
  508. {
  509. $result = self::Query('SHOW GRANTS'); // [ FOR CURRENT_USER()]
  510. }
  511. catch(MySQLException $e)
  512. {
  513. return "Current user not allowed to see his own privileges (could not access to the database 'mysql' - $iCode)";
  514. }
  515. $aRes = array();
  516. while ($aRow = mysqli_fetch_array($result, MYSQLI_NUM))
  517. {
  518. // so far, only one column...
  519. $aRes[] = implode('/', $aRow);
  520. }
  521. mysqli_free_result($result);
  522. // so far, only one line...
  523. return implode(', ', $aRes);
  524. }
  525. /**
  526. * Determine the slave status of the server
  527. * @return bool true if the server is slave
  528. */
  529. public static function IsSlaveServer()
  530. {
  531. try
  532. {
  533. $result = self::Query('SHOW SLAVE STATUS');
  534. }
  535. catch(MySQLException $e)
  536. {
  537. throw new CoreException("Current user not allowed to check the status", array('mysql_error' => $e->getMessage()));
  538. }
  539. if (mysqli_num_rows($result) == 0)
  540. {
  541. return false;
  542. }
  543. // Returns one single row anytime
  544. $aRow = mysqli_fetch_array($result, MYSQLI_ASSOC);
  545. mysqli_free_result($result);
  546. if (!isset($aRow['Slave_IO_Running']))
  547. {
  548. return false;
  549. }
  550. if (!isset($aRow['Slave_SQL_Running']))
  551. {
  552. return false;
  553. }
  554. // If at least one slave thread is running, then we consider that the slave is enabled
  555. if ($aRow['Slave_IO_Running'] == 'Yes')
  556. {
  557. return true;
  558. }
  559. if ($aRow['Slave_SQL_Running'] == 'Yes')
  560. {
  561. return true;
  562. }
  563. return false;
  564. }
  565. }
  566. ?>