cmdbsource.class.inc.php 14 KB

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