cmdbsource.class.inc.php 20 KB

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