cmdbsource.class.inc.php 16 KB

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