cmdbsource.class.inc.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. <?php
  2. // Copyright (C) 2010-2015 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-2015 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, $oException = null)
  29. {
  30. if ($oException != null)
  31. {
  32. $aContext['mysql_errno'] = $oException->getCode();
  33. $this->code = $oException->getCode();
  34. $aContext['mysql_error'] = $oException->getMessage();
  35. }
  36. else
  37. {
  38. $aContext['mysql_errno'] = CMDBSource::GetErrNo();
  39. $this->code = CMDBSource::GetErrNo();
  40. $aContext['mysql_error'] = CMDBSource::GetError();
  41. }
  42. parent::__construct($sIssue, $aContext);
  43. }
  44. }
  45. /**
  46. * CMDBSource
  47. * database access wrapper
  48. *
  49. * @package iTopORM
  50. */
  51. class CMDBSource
  52. {
  53. protected static $m_sDBHost;
  54. protected static $m_sDBUser;
  55. protected static $m_sDBPwd;
  56. protected static $m_sDBName;
  57. protected static $m_oMysqli;
  58. public static function Init($sServer, $sUser, $sPwd, $sSource = '')
  59. {
  60. self::$m_sDBHost = $sServer;
  61. self::$m_sDBUser = $sUser;
  62. self::$m_sDBPwd = $sPwd;
  63. self::$m_sDBName = $sSource;
  64. self::$m_oMysqli = null;
  65. mysqli_report(MYSQLI_REPORT_STRICT); // *some* errors (like connection errors) will throw mysqli_sql_exception instead
  66. // of generating warnings printed to the output but some other errors will still
  67. // cause the query() method to return false !!!
  68. try
  69. {
  70. $aConnectInfo = explode(':', self::$m_sDBHost);
  71. if (count($aConnectInfo) > 1)
  72. {
  73. // Override the default port
  74. $sServer = $aConnectInfo[0];
  75. $iPort = (int)$aConnectInfo[1];
  76. self::$m_oMysqli = new mysqli($sServer, self::$m_sDBUser, self::$m_sDBPwd, '', $iPort);
  77. }
  78. else
  79. {
  80. self::$m_oMysqli = new mysqli(self::$m_sDBHost, self::$m_sDBUser, self::$m_sDBPwd);
  81. }
  82. }
  83. catch(mysqli_sql_exception $e)
  84. {
  85. throw new MySQLException('Could not connect to the DB server', array('host'=>self::$m_sDBHost, 'user'=>self::$m_sDBUser), $e);
  86. }
  87. if (!empty($sSource))
  88. {
  89. try
  90. {
  91. mysqli_report(MYSQLI_REPORT_STRICT); // Errors, in the next query, will throw mysqli_sql_exception
  92. self::$m_oMysqli->query("USE `$sSource`");
  93. }
  94. catch(mysqli_sql_exception $e)
  95. {
  96. throw new MySQLException('Could not select DB', array('host'=>self::$m_sDBHost, 'user'=>self::$m_sDBUser, 'db_name'=>self::$m_sDBName), $e);
  97. }
  98. }
  99. }
  100. public static function SetCharacterSet($sCharset = 'utf8', $sCollation = 'utf8_general_ci')
  101. {
  102. if (strlen($sCharset) > 0)
  103. {
  104. if (strlen($sCollation) > 0)
  105. {
  106. self::Query("SET NAMES '$sCharset' COLLATE '$sCollation'");
  107. }
  108. else
  109. {
  110. self::Query("SET NAMES '$sCharset'");
  111. }
  112. }
  113. }
  114. public static function SetTimezone($sTimezone = null)
  115. {
  116. // Note: requires the installation of MySQL special tables,
  117. // otherwise, only 'SYSTEM' or "+10:00' may be specified which is NOT sufficient because of day light saving times
  118. if (!is_null($sTimezone))
  119. {
  120. $sQuotedTimezone = self::Quote($sTimezone);
  121. self::Query("SET time_zone = $sQuotedTimezone");
  122. }
  123. }
  124. public static function ListDB()
  125. {
  126. $aDBs = self::QueryToCol('SHOW DATABASES', 'Database');
  127. // Show Database does return the DB names in lower case
  128. return $aDBs;
  129. }
  130. public static function IsDB($sSource)
  131. {
  132. try
  133. {
  134. $aDBs = self::ListDB();
  135. foreach($aDBs as $sDBName)
  136. {
  137. // perform a case insensitive test because on Windows the table names become lowercase :-(
  138. if (strtolower($sDBName) == strtolower($sSource)) return true;
  139. }
  140. return false;
  141. }
  142. catch(Exception $e)
  143. {
  144. // In case we don't have rights to enumerate the databases
  145. // Let's try to connect directly
  146. return @((bool)self::$m_oMysqli->query("USE `$sSource`"));
  147. }
  148. }
  149. public static function GetDBVersion()
  150. {
  151. $aVersions = self::QueryToCol('SELECT Version() as version', 'version');
  152. return $aVersions[0];
  153. }
  154. public static function SelectDB($sSource)
  155. {
  156. if (!((bool)self::$m_oMysqli->query("USE `$sSource`")))
  157. {
  158. throw new MySQLException('Could not select DB', array('db_name'=>$sSource));
  159. }
  160. self::$m_sDBName = $sSource;
  161. }
  162. public static function CreateDB($sSource)
  163. {
  164. self::Query("CREATE DATABASE `$sSource` CHARACTER SET utf8 COLLATE utf8_unicode_ci");
  165. self::SelectDB($sSource);
  166. }
  167. public static function DropDB($sDBToDrop = '')
  168. {
  169. if (empty($sDBToDrop))
  170. {
  171. $sDBToDrop = self::$m_sDBName;
  172. }
  173. self::Query("DROP DATABASE `$sDBToDrop`");
  174. if ($sDBToDrop == self::$m_sDBName)
  175. {
  176. self::$m_sDBName = '';
  177. }
  178. }
  179. public static function CreateTable($sQuery)
  180. {
  181. $res = self::Query($sQuery);
  182. self::_TablesInfoCacheReset(); // reset the table info cache!
  183. return $res;
  184. }
  185. public static function DropTable($sTable)
  186. {
  187. $res = self::Query("DROP TABLE `$sTable`");
  188. self::_TablesInfoCacheReset(true); // reset the table info cache!
  189. return $res;
  190. }
  191. public static function GetErrNo()
  192. {
  193. if (self::$m_oMysqli->errno != 0)
  194. {
  195. return self::$m_oMysqli->errno;
  196. }
  197. else
  198. {
  199. return self::$m_oMysqli->connect_errno;
  200. }
  201. }
  202. public static function GetError()
  203. {
  204. if (self::$m_oMysqli->error != '')
  205. {
  206. return self::$m_oMysqli->error;
  207. }
  208. else
  209. {
  210. return self::$m_oMysqli->connect_error;
  211. }
  212. }
  213. public static function DBHost() {return self::$m_sDBHost;}
  214. public static function DBUser() {return self::$m_sDBUser;}
  215. public static function DBPwd() {return self::$m_sDBPwd;}
  216. public static function DBName() {return self::$m_sDBName;}
  217. public static function Quote($value, $bAlways = false, $cQuoteStyle = "'")
  218. {
  219. // Quote variable and protect against SQL injection attacks
  220. // Code found in the PHP documentation: quote_smart($value)
  221. // bAlways should be set to true when the purpose is to create a IN clause,
  222. // otherwise and if there is a mix of strings and numbers, the clause
  223. // would always be false
  224. if (is_null($value))
  225. {
  226. return 'NULL';
  227. }
  228. if (is_array($value))
  229. {
  230. $aRes = array();
  231. foreach ($value as $key => $itemvalue)
  232. {
  233. $aRes[$key] = self::Quote($itemvalue, $bAlways, $cQuoteStyle);
  234. }
  235. return $aRes;
  236. }
  237. // Stripslashes
  238. if (get_magic_quotes_gpc())
  239. {
  240. $value = stripslashes($value);
  241. }
  242. // Quote if not a number or a numeric string
  243. if ($bAlways || is_string($value))
  244. {
  245. $value = $cQuoteStyle . self::$m_oMysqli->real_escape_string($value) . $cQuoteStyle;
  246. }
  247. return $value;
  248. }
  249. public static function Query($sSQLQuery)
  250. {
  251. $oKPI = new ExecutionKPI();
  252. try
  253. {
  254. $oResult = self::$m_oMysqli->query($sSQLQuery);
  255. }
  256. catch(mysqli_sql_exception $e)
  257. {
  258. throw new MySQLException('Failed to issue SQL query', array('query' => $sSQLQuery, $e));
  259. }
  260. $oKPI->ComputeStats('Query exec (mySQL)', $sSQLQuery);
  261. if ($oResult === false)
  262. {
  263. throw new MySQLException('Failed to issue SQL query', array('query' => $sSQLQuery));
  264. }
  265. return $oResult;
  266. }
  267. public static function GetNextInsertId($sTable)
  268. {
  269. $sSQL = "SHOW TABLE STATUS LIKE '$sTable'";
  270. $oResult = self::Query($sSQL);
  271. $aRow = $oResult->fetch_assoc();
  272. $iNextInsertId = $aRow['Auto_increment'];
  273. return $iNextInsertId;
  274. }
  275. public static function GetInsertId()
  276. {
  277. $iRes = self::$m_oMysqli->insert_id;
  278. if (is_null($iRes))
  279. {
  280. return 0;
  281. }
  282. return $iRes;
  283. }
  284. public static function InsertInto($sSQLQuery)
  285. {
  286. if (self::Query($sSQLQuery))
  287. {
  288. return self::GetInsertId();
  289. }
  290. return false;
  291. }
  292. public static function DeleteFrom($sSQLQuery)
  293. {
  294. self::Query($sSQLQuery);
  295. }
  296. public static function QueryToScalar($sSql)
  297. {
  298. $oKPI = new ExecutionKPI();
  299. try
  300. {
  301. $oResult = self::$m_oMysqli->query($sSql);
  302. }
  303. catch(mysqli_sql_exception $e)
  304. {
  305. $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
  306. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
  307. }
  308. $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
  309. if ($oResult === false)
  310. {
  311. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  312. }
  313. if ($aRow = $oResult->fetch_array(MYSQLI_BOTH))
  314. {
  315. $res = $aRow[0];
  316. }
  317. else
  318. {
  319. $oResult->free();
  320. throw new MySQLException('Found no result for query', array('query' => $sSql));
  321. }
  322. $oResult->free();
  323. return $res;
  324. }
  325. public static function QueryToArray($sSql)
  326. {
  327. $aData = array();
  328. $oKPI = new ExecutionKPI();
  329. try
  330. {
  331. $oResult = self::$m_oMysqli->query($sSql);
  332. }
  333. catch(mysqli_sql_exception $e)
  334. {
  335. $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
  336. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
  337. }
  338. $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
  339. if ($oResult === false)
  340. {
  341. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  342. }
  343. while ($aRow = $oResult->fetch_array(MYSQLI_BOTH))
  344. {
  345. $aData[] = $aRow;
  346. }
  347. $oResult->free();
  348. return $aData;
  349. }
  350. public static function QueryToCol($sSql, $col)
  351. {
  352. $aColumn = array();
  353. $aData = self::QueryToArray($sSql);
  354. foreach($aData as $aRow)
  355. {
  356. @$aColumn[] = $aRow[$col];
  357. }
  358. return $aColumn;
  359. }
  360. public static function ExplainQuery($sSql)
  361. {
  362. $aData = array();
  363. try
  364. {
  365. $oResult = self::$m_oMysqli->query($sSql);
  366. }
  367. catch(mysqli_sql_exception $e)
  368. {
  369. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
  370. }
  371. if ($oResult === false)
  372. {
  373. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  374. }
  375. $aNames = self::GetColumns($oResult);
  376. $aData[] = $aNames;
  377. while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC))
  378. {
  379. $aData[] = $aRow;
  380. }
  381. $oResult->free();
  382. return $aData;
  383. }
  384. public static function TestQuery($sSql)
  385. {
  386. try
  387. {
  388. $oResult = self::$m_oMysqli->query($sSql);
  389. }
  390. catch(mysqli_sql_exception $e)
  391. {
  392. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
  393. }
  394. if ($oResult === false)
  395. {
  396. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  397. }
  398. if (is_object($oResult))
  399. {
  400. $oResult->free();
  401. }
  402. return '';
  403. }
  404. public static function NbRows($oResult)
  405. {
  406. return $oResult->num_rows;
  407. }
  408. public static function AffectedRows()
  409. {
  410. return self::$m_oMysqli->affected_rows;
  411. }
  412. public static function FetchArray($oResult)
  413. {
  414. return $oResult->fetch_array(MYSQLI_ASSOC);
  415. }
  416. public static function GetColumns($oResult)
  417. {
  418. $aNames = array();
  419. for ($i = 0; $i < (($___mysqli_tmp = $oResult->field_count) ? $___mysqli_tmp : 0) ; $i++)
  420. {
  421. $meta = $oResult->fetch_field_direct($i);
  422. if (!$meta)
  423. {
  424. throw new MySQLException('mysql_fetch_field: No information available', array('query'=>$sSql, 'i'=>$i));
  425. }
  426. else
  427. {
  428. $aNames[] = $meta->name;
  429. }
  430. }
  431. return $aNames;
  432. }
  433. public static function Seek($oResult, $iRow)
  434. {
  435. return $oResult->data_seek($iRow);
  436. }
  437. public static function FreeResult($oResult)
  438. {
  439. $oResult->free(); /* returns void */
  440. return true;
  441. }
  442. public static function IsTable($sTable)
  443. {
  444. $aTableInfo = self::GetTableInfo($sTable);
  445. return (!empty($aTableInfo));
  446. }
  447. public static function IsKey($sTable, $iKey)
  448. {
  449. $aTableInfo = self::GetTableInfo($sTable);
  450. if (empty($aTableInfo)) return false;
  451. if (!array_key_exists($iKey, $aTableInfo["Fields"])) return false;
  452. $aFieldData = $aTableInfo["Fields"][$iKey];
  453. if (!array_key_exists("Key", $aFieldData)) return false;
  454. return ($aFieldData["Key"] == "PRI");
  455. }
  456. public static function IsAutoIncrement($sTable, $sField)
  457. {
  458. $aTableInfo = self::GetTableInfo($sTable);
  459. if (empty($aTableInfo)) return false;
  460. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  461. $aFieldData = $aTableInfo["Fields"][$sField];
  462. if (!array_key_exists("Extra", $aFieldData)) return false;
  463. //MyHelpers::debug_breakpoint($aFieldData);
  464. return (strstr($aFieldData["Extra"], "auto_increment"));
  465. }
  466. public static function IsField($sTable, $sField)
  467. {
  468. $aTableInfo = self::GetTableInfo($sTable);
  469. if (empty($aTableInfo)) return false;
  470. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  471. return true;
  472. }
  473. public static function IsNullAllowed($sTable, $sField)
  474. {
  475. $aTableInfo = self::GetTableInfo($sTable);
  476. if (empty($aTableInfo)) return false;
  477. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  478. $aFieldData = $aTableInfo["Fields"][$sField];
  479. return (strtolower($aFieldData["Null"]) == "yes");
  480. }
  481. public static function GetFieldType($sTable, $sField)
  482. {
  483. $aTableInfo = self::GetTableInfo($sTable);
  484. if (empty($aTableInfo)) return false;
  485. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  486. $aFieldData = $aTableInfo["Fields"][$sField];
  487. return ($aFieldData["Type"]);
  488. }
  489. public static function GetFieldSpec($sTable, $sField)
  490. {
  491. $aTableInfo = self::GetTableInfo($sTable);
  492. if (empty($aTableInfo)) return false;
  493. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  494. $aFieldData = $aTableInfo["Fields"][$sField];
  495. $sRet = $aFieldData["Type"];
  496. if ($aFieldData["Null"] == 'NO')
  497. {
  498. $sRet .= ' NOT NULL';
  499. }
  500. if (is_numeric($aFieldData["Default"]))
  501. {
  502. if (strtolower(substr($aFieldData["Type"], 0, 5)) == 'enum(')
  503. {
  504. // Force quotes to match the column declaration statement
  505. $sRet .= ' DEFAULT '.self::Quote($aFieldData["Default"], true);
  506. }
  507. else
  508. {
  509. $default = $aFieldData["Default"] + 0; // Coerce to a numeric variable
  510. $sRet .= ' DEFAULT '.self::Quote($default);
  511. }
  512. }
  513. elseif (is_string($aFieldData["Default"]) == 'string')
  514. {
  515. $sRet .= ' DEFAULT '.self::Quote($aFieldData["Default"]);
  516. }
  517. return $sRet;
  518. }
  519. public static function HasIndex($sTable, $sIndexId, $aFields = null)
  520. {
  521. $aTableInfo = self::GetTableInfo($sTable);
  522. if (empty($aTableInfo)) return false;
  523. if (!array_key_exists($sIndexId, $aTableInfo['Indexes'])) return false;
  524. if ($aFields == null)
  525. {
  526. // Just searching for the name
  527. return true;
  528. }
  529. // Compare the columns
  530. $sSearchedIndex = implode(',', $aFields);
  531. $sExistingIndex = implode(',', $aTableInfo['Indexes'][$sIndexId]);
  532. return ($sSearchedIndex == $sExistingIndex);
  533. }
  534. // Returns an array of (fieldname => array of field info)
  535. public static function GetTableFieldsList($sTable)
  536. {
  537. assert(!empty($sTable));
  538. $aTableInfo = self::GetTableInfo($sTable);
  539. if (empty($aTableInfo)) return array(); // #@# or an error ?
  540. return array_keys($aTableInfo["Fields"]);
  541. }
  542. // Cache the information about existing tables, and their fields
  543. private static $m_aTablesInfo = array();
  544. private static function _TablesInfoCacheReset()
  545. {
  546. self::$m_aTablesInfo = array();
  547. }
  548. private static function _TableInfoCacheInit($sTableName)
  549. {
  550. if (isset(self::$m_aTablesInfo[strtolower($sTableName)])
  551. && (self::$m_aTablesInfo[strtolower($sTableName)] != null)) return;
  552. try
  553. {
  554. // Check if the table exists
  555. $aFields = self::QueryToArray("SHOW COLUMNS FROM `$sTableName`");
  556. // Note: without backticks, you get an error with some table names (e.g. "group")
  557. foreach ($aFields as $aFieldData)
  558. {
  559. $sFieldName = $aFieldData["Field"];
  560. self::$m_aTablesInfo[strtolower($sTableName)]["Fields"][$sFieldName] =
  561. array
  562. (
  563. "Name"=>$aFieldData["Field"],
  564. "Type"=>$aFieldData["Type"],
  565. "Null"=>$aFieldData["Null"],
  566. "Key"=>$aFieldData["Key"],
  567. "Default"=>$aFieldData["Default"],
  568. "Extra"=>$aFieldData["Extra"]
  569. );
  570. }
  571. }
  572. catch(MySQLException $e)
  573. {
  574. // Table does not exist
  575. self::$m_aTablesInfo[strtolower($sTableName)] = null;
  576. }
  577. if (!is_null(self::$m_aTablesInfo[strtolower($sTableName)]))
  578. {
  579. $aIndexes = self::QueryToArray("SHOW INDEXES FROM `$sTableName`");
  580. $aMyIndexes = array();
  581. foreach ($aIndexes as $aIndexColumn)
  582. {
  583. $aMyIndexes[$aIndexColumn['Key_name']][$aIndexColumn['Seq_in_index']-1] = $aIndexColumn['Column_name'];
  584. }
  585. self::$m_aTablesInfo[strtolower($sTableName)]["Indexes"] = $aMyIndexes;
  586. }
  587. }
  588. //public static function EnumTables()
  589. //{
  590. // self::_TablesInfoCacheInit();
  591. // return array_keys(self::$m_aTablesInfo);
  592. //}
  593. public static function GetTableInfo($sTable)
  594. {
  595. self::_TableInfoCacheInit($sTable);
  596. // perform a case insensitive match because on Windows the table names become lowercase :-(
  597. //foreach(self::$m_aTablesInfo as $sTableName => $aInfo)
  598. //{
  599. // if (strtolower($sTableName) == strtolower($sTable))
  600. // {
  601. // return $aInfo;
  602. // }
  603. //}
  604. return self::$m_aTablesInfo[strtolower($sTable)];
  605. //return null;
  606. }
  607. public static function DumpTable($sTable)
  608. {
  609. $sSql = "SELECT * FROM `$sTable`";
  610. try
  611. {
  612. $oResult = self::$m_oMysqli->query($sSql);
  613. }
  614. catch(mysqli_sql_exception $e)
  615. {
  616. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql), $e);
  617. }
  618. if ($oResult === false)
  619. {
  620. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  621. }
  622. $aRows = array();
  623. while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC))
  624. {
  625. $aRows[] = $aRow;
  626. }
  627. $oResult->free();
  628. return $aRows;
  629. }
  630. /**
  631. * Returns the value of the specified server variable
  632. * @param string $sVarName Name of the server variable
  633. * @return mixed Current value of the variable
  634. */
  635. public static function GetServerVariable($sVarName)
  636. {
  637. $result = '';
  638. $sSql = "SELECT @@$sVarName as theVar";
  639. $aRows = self::QueryToArray($sSql);
  640. if (count($aRows) > 0)
  641. {
  642. $result = $aRows[0]['theVar'];
  643. }
  644. return $result;
  645. }
  646. /**
  647. * Returns the privileges of the current user
  648. * @return string privileges in a raw format
  649. */
  650. public static function GetRawPrivileges()
  651. {
  652. try
  653. {
  654. $oResult = self::Query('SHOW GRANTS'); // [ FOR CURRENT_USER()]
  655. }
  656. catch(MySQLException $e)
  657. {
  658. return "Current user not allowed to see his own privileges (could not access to the database 'mysql' - $iCode)";
  659. }
  660. $aRes = array();
  661. while ($aRow = $oResult->fetch_array(MYSQLI_NUM))
  662. {
  663. // so far, only one column...
  664. $aRes[] = implode('/', $aRow);
  665. }
  666. $oResult->free();
  667. // so far, only one line...
  668. return implode(', ', $aRes);
  669. }
  670. /**
  671. * Determine the slave status of the server
  672. * @return bool true if the server is slave
  673. */
  674. public static function IsSlaveServer()
  675. {
  676. try
  677. {
  678. $oResult = self::Query('SHOW SLAVE STATUS');
  679. }
  680. catch(MySQLException $e)
  681. {
  682. throw new CoreException("Current user not allowed to check the status", array('mysql_error' => $e->getMessage()));
  683. }
  684. if ($oResult->num_rows == 0)
  685. {
  686. return false;
  687. }
  688. // Returns one single row anytime
  689. $aRow = $oResult->fetch_array(MYSQLI_ASSOC);
  690. $oResult->free();
  691. if (!isset($aRow['Slave_IO_Running']))
  692. {
  693. return false;
  694. }
  695. if (!isset($aRow['Slave_SQL_Running']))
  696. {
  697. return false;
  698. }
  699. // If at least one slave thread is running, then we consider that the slave is enabled
  700. if ($aRow['Slave_IO_Running'] == 'Yes')
  701. {
  702. return true;
  703. }
  704. if ($aRow['Slave_SQL_Running'] == 'Yes')
  705. {
  706. return true;
  707. }
  708. return false;
  709. }
  710. }