cmdbsource.class.inc.php 11 KB

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