cmdbsource.class.inc.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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, 'user'=>$sUser));
  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. echo "<pre>\n";
  171. print_r($aRow);
  172. echo "</pre>\n";
  173. return $iNextInsertId;
  174. }
  175. public static function GetInsertId()
  176. {
  177. return mysql_insert_id(self::$m_resDBLink);
  178. }
  179. public static function InsertInto($sSQLQuery)
  180. {
  181. if (self::Query($sSQLQuery))
  182. {
  183. return self::GetInsertId();
  184. }
  185. return false;
  186. }
  187. public static function QueryToArray($sSql)
  188. {
  189. $aData = array();
  190. $result = mysql_query($sSql, self::$m_resDBLink);
  191. if (!$result)
  192. {
  193. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  194. }
  195. while ($aRow = mysql_fetch_array($result, MYSQL_BOTH))
  196. {
  197. $aData[] = $aRow;
  198. }
  199. mysql_free_result($result);
  200. return $aData;
  201. }
  202. public static function QueryToCol($sSql, $col)
  203. {
  204. $aColumn = array();
  205. $aData = self::QueryToArray($sSql);
  206. foreach($aData as $aRow)
  207. {
  208. @$aColumn[] = $aRow[$col];
  209. }
  210. return $aColumn;
  211. }
  212. public static function ExplainQuery($sSql)
  213. {
  214. $aData = array();
  215. $result = mysql_query("EXPLAIN $sSql", self::$m_resDBLink);
  216. if (!$result)
  217. {
  218. throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
  219. }
  220. $aNames = array();
  221. for ($i = 0; $i < mysql_num_fields($result) ; $i++)
  222. {
  223. $meta = mysql_fetch_field($result, $i);
  224. if (!$meta)
  225. {
  226. throw new MySQLException('mysql_fetch_field: No information available', array('query'=>$sSql, 'i'=>$i));
  227. }
  228. else
  229. {
  230. $aNames[] = $meta->name;
  231. }
  232. }
  233. $aData[] = $aNames;
  234. while ($aRow = mysql_fetch_array($result, MYSQL_ASSOC))
  235. {
  236. $aData[] = $aRow;
  237. }
  238. mysql_free_result($result);
  239. return $aData;
  240. }
  241. public static function TestQuery($sSql)
  242. {
  243. $result = mysql_query("EXPLAIN $sSql", self::$m_resDBLink);
  244. if (!$result)
  245. {
  246. return mysql_error();
  247. }
  248. mysql_free_result($result);
  249. return '';
  250. }
  251. public static function NbRows($result)
  252. {
  253. return mysql_num_rows($result);
  254. }
  255. public static function FetchArray($result)
  256. {
  257. return mysql_fetch_array($result, MYSQL_ASSOC);
  258. }
  259. public static function Seek($result, $iRow)
  260. {
  261. return mysql_data_seek($result, $iRow);
  262. }
  263. public static function FreeResult($result)
  264. {
  265. return mysql_free_result($result);
  266. }
  267. public static function IsTable($sTable)
  268. {
  269. $aTableInfo = self::GetTableInfo($sTable);
  270. return (!empty($aTableInfo));
  271. }
  272. public static function IsKey($sTable, $iKey)
  273. {
  274. $aTableInfo = self::GetTableInfo($sTable);
  275. if (empty($aTableInfo)) return false;
  276. if (!array_key_exists($iKey, $aTableInfo["Fields"])) return false;
  277. $aFieldData = $aTableInfo["Fields"][$iKey];
  278. if (!array_key_exists("Key", $aFieldData)) return false;
  279. return ($aFieldData["Key"] == "PRI");
  280. }
  281. public static function IsAutoIncrement($sTable, $sField)
  282. {
  283. $aTableInfo = self::GetTableInfo($sTable);
  284. if (empty($aTableInfo)) return false;
  285. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  286. $aFieldData = $aTableInfo["Fields"][$sField];
  287. if (!array_key_exists("Extra", $aFieldData)) return false;
  288. //MyHelpers::debug_breakpoint($aFieldData);
  289. return (strstr($aFieldData["Extra"], "auto_increment"));
  290. }
  291. public static function IsField($sTable, $sField)
  292. {
  293. $aTableInfo = self::GetTableInfo($sTable);
  294. if (empty($aTableInfo)) return false;
  295. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  296. return true;
  297. }
  298. public static function IsNullAllowed($sTable, $sField)
  299. {
  300. $aTableInfo = self::GetTableInfo($sTable);
  301. if (empty($aTableInfo)) return false;
  302. if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
  303. $aFieldData = $aTableInfo["Fields"][$sField];
  304. return (strtolower($aFieldData["Null"]) == "yes");
  305. }
  306. // Returns an array of (fieldname => array of field info)
  307. public static function GetTableFieldsList($sTable)
  308. {
  309. assert(!empty($sTable));
  310. $aTableInfo = self::GetTableInfo($sTable);
  311. if (empty($aTableInfo)) return array(); // #@# or an error ?
  312. return array_keys($aTableInfo["Fields"]);
  313. }
  314. // Cache the information about existing tables, and their fields
  315. private static $m_aTablesInfo = array();
  316. private static function _TablesInfoCacheReset()
  317. {
  318. self::$m_aTablesInfo = array();
  319. }
  320. private static function _TableInfoCacheInit($sTableName)
  321. {
  322. if (isset(self::$m_aTablesInfo[strtolower($sTableName)])
  323. && (self::$m_aTablesInfo[strtolower($sTableName)] != null)) return;
  324. try
  325. {
  326. // Check if the table exists
  327. $aFields = self::QueryToArray("SHOW COLUMNS FROM `$sTableName`");
  328. // Note: without backticks, you get an error with some table names (e.g. "group")
  329. foreach ($aFields as $aFieldData)
  330. {
  331. $sFieldName = $aFieldData["Field"];
  332. self::$m_aTablesInfo[strtolower($sTableName)]["Fields"][$sFieldName] =
  333. array
  334. (
  335. "Name"=>$aFieldData["Field"],
  336. "Type"=>$aFieldData["Type"],
  337. "Null"=>$aFieldData["Null"],
  338. "Key"=>$aFieldData["Key"],
  339. "Default"=>$aFieldData["Default"],
  340. "Extra"=>$aFieldData["Extra"]
  341. );
  342. }
  343. }
  344. catch(MySQLException $e)
  345. {
  346. // Table does not exist
  347. self::$m_aTablesInfo[strtolower($sTableName)] = null;
  348. }
  349. }
  350. //public static function EnumTables()
  351. //{
  352. // self::_TablesInfoCacheInit();
  353. // return array_keys(self::$m_aTablesInfo);
  354. //}
  355. public static function GetTableInfo($sTable)
  356. {
  357. self::_TableInfoCacheInit($sTable);
  358. // perform a case insensitive match because on Windows the table names become lowercase :-(
  359. //foreach(self::$m_aTablesInfo as $sTableName => $aInfo)
  360. //{
  361. // if (strtolower($sTableName) == strtolower($sTable))
  362. // {
  363. // return $aInfo;
  364. // }
  365. //}
  366. return self::$m_aTablesInfo[strtolower($sTable)];
  367. //return null;
  368. }
  369. }
  370. ?>