cmdbsource.class.inc.php 15 KB

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