cmdbsource.class.inc.php 13 KB

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