cmdbsource.class.inc.php 11 KB

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