cmdbsource.class.inc.php 10 KB

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