PageRenderTime 42ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/db/mysql.php

https://bitbucket.org/jablonski/yebood
PHP | 562 lines | 353 code | 84 blank | 125 comment | 70 complexity | adcbb6f4d7dec3bc310f73525200031f MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /**
  3. *
  4. * @package dbal
  5. * @version $Id$
  6. * @copyright (c) 2005 phpBB Group
  7. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  8. *
  9. */
  10. /**
  11. * @ignore
  12. */
  13. if (!defined('IN_PHPBB'))
  14. {
  15. exit;
  16. }
  17. include_once($phpbb_root_path . 'includes/db/dbal.' . $phpEx);
  18. /**
  19. * MySQL4 Database Abstraction Layer
  20. * Compatible with:
  21. * MySQL 3.23+
  22. * MySQL 4.0+
  23. * MySQL 4.1+
  24. * MySQL 5.0+
  25. * @package dbal
  26. */
  27. class dbal_mysql extends dbal
  28. {
  29. var $multi_insert = true;
  30. /**
  31. * Connect to server
  32. * @access public
  33. */
  34. function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
  35. {
  36. $this->persistency = $persistency;
  37. $this->user = $sqluser;
  38. $this->server = $sqlserver . (($port) ? ':' . $port : '');
  39. $this->dbname = $database;
  40. $this->sql_layer = 'mysql4';
  41. $this->db_connect_id = ($this->persistency) ? @mysql_pconnect($this->server, $this->user, $sqlpassword) : @mysql_connect($this->server, $this->user, $sqlpassword, $new_link);
  42. if ($this->db_connect_id && $this->dbname != '')
  43. {
  44. if (@mysql_select_db($this->dbname, $this->db_connect_id))
  45. {
  46. // Determine what version we are using and if it natively supports UNICODE
  47. if (version_compare($this->sql_server_info(true), '4.1.0', '>='))
  48. {
  49. @mysql_query("SET NAMES 'utf8'", $this->db_connect_id);
  50. // enforce strict mode on databases that support it
  51. if (version_compare($this->sql_server_info(true), '5.0.2', '>='))
  52. {
  53. $result = @mysql_query('SELECT @@session.sql_mode AS sql_mode', $this->db_connect_id);
  54. $row = @mysql_fetch_assoc($result);
  55. @mysql_free_result($result);
  56. $modes = array_map('trim', explode(',', $row['sql_mode']));
  57. // TRADITIONAL includes STRICT_ALL_TABLES and STRICT_TRANS_TABLES
  58. if (!in_array('TRADITIONAL', $modes))
  59. {
  60. if (!in_array('STRICT_ALL_TABLES', $modes))
  61. {
  62. $modes[] = 'STRICT_ALL_TABLES';
  63. }
  64. if (!in_array('STRICT_TRANS_TABLES', $modes))
  65. {
  66. $modes[] = 'STRICT_TRANS_TABLES';
  67. }
  68. }
  69. $mode = implode(',', $modes);
  70. @mysql_query("SET SESSION sql_mode='{$mode}'", $this->db_connect_id);
  71. }
  72. }
  73. else if (version_compare($this->sql_server_info(true), '4.0.0', '<'))
  74. {
  75. $this->sql_layer = 'mysql';
  76. }
  77. return $this->db_connect_id;
  78. }
  79. }
  80. return $this->sql_error('');
  81. }
  82. /**
  83. * Version information about used database
  84. * @param bool $raw if true, only return the fetched sql_server_version
  85. * @param bool $use_cache If true, it is safe to retrieve the value from the cache
  86. * @return string sql server version
  87. */
  88. function sql_server_info($raw = false, $use_cache = true)
  89. {
  90. global $cache;
  91. if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mysql_version')) === false)
  92. {
  93. $result = @mysql_query('SELECT VERSION() AS version', $this->db_connect_id);
  94. $row = @mysql_fetch_assoc($result);
  95. @mysql_free_result($result);
  96. $this->sql_server_version = $row['version'];
  97. if (!empty($cache) && $use_cache)
  98. {
  99. $cache->put('mysql_version', $this->sql_server_version);
  100. }
  101. }
  102. return ($raw) ? $this->sql_server_version : 'MySQL ' . $this->sql_server_version;
  103. }
  104. /**
  105. * SQL Transaction
  106. * @access private
  107. */
  108. function _sql_transaction($status = 'begin')
  109. {
  110. switch ($status)
  111. {
  112. case 'begin':
  113. return @mysql_query('BEGIN', $this->db_connect_id);
  114. break;
  115. case 'commit':
  116. return @mysql_query('COMMIT', $this->db_connect_id);
  117. break;
  118. case 'rollback':
  119. return @mysql_query('ROLLBACK', $this->db_connect_id);
  120. break;
  121. }
  122. return true;
  123. }
  124. /**
  125. * Base query method
  126. *
  127. * @param string $query Contains the SQL query which shall be executed
  128. * @param int $cache_ttl Either 0 to avoid caching or the time in seconds which the result shall be kept in cache
  129. * @return mixed When casted to bool the returned value returns true on success and false on failure
  130. *
  131. * @access public
  132. */
  133. function sql_query($query = '', $cache_ttl = 0)
  134. {
  135. if ($query != '')
  136. {
  137. global $cache;
  138. // EXPLAIN only in extra debug mode
  139. if (defined('DEBUG_EXTRA'))
  140. {
  141. $this->sql_report('start', $query);
  142. }
  143. $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
  144. $this->sql_add_num_queries($this->query_result);
  145. if ($this->query_result === false)
  146. {
  147. if (($this->query_result = @mysql_query($query, $this->db_connect_id)) === false)
  148. {
  149. $this->sql_error($query);
  150. }
  151. if (defined('DEBUG_EXTRA'))
  152. {
  153. $this->sql_report('stop', $query);
  154. }
  155. if ($cache_ttl && method_exists($cache, 'sql_save'))
  156. {
  157. $this->open_queries[(int) $this->query_result] = $this->query_result;
  158. $cache->sql_save($query, $this->query_result, $cache_ttl);
  159. }
  160. else if (strpos($query, 'SELECT') === 0 && $this->query_result)
  161. {
  162. $this->open_queries[(int) $this->query_result] = $this->query_result;
  163. }
  164. }
  165. else if (defined('DEBUG_EXTRA'))
  166. {
  167. $this->sql_report('fromcache', $query);
  168. }
  169. }
  170. else
  171. {
  172. return false;
  173. }
  174. return $this->query_result;
  175. }
  176. /**
  177. * Build LIMIT query
  178. */
  179. function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
  180. {
  181. $this->query_result = false;
  182. // if $total is set to 0 we do not want to limit the number of rows
  183. if ($total == 0)
  184. {
  185. // Having a value of -1 was always a bug
  186. $total = '18446744073709551615';
  187. }
  188. $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total);
  189. return $this->sql_query($query, $cache_ttl);
  190. }
  191. /**
  192. * Return number of affected rows
  193. */
  194. function sql_affectedrows()
  195. {
  196. return ($this->db_connect_id) ? @mysql_affected_rows($this->db_connect_id) : false;
  197. }
  198. /**
  199. * Fetch current row
  200. */
  201. function sql_fetchrow($query_id = false)
  202. {
  203. global $cache;
  204. if ($query_id === false)
  205. {
  206. $query_id = $this->query_result;
  207. }
  208. if (isset($cache->sql_rowset[$query_id]))
  209. {
  210. return $cache->sql_fetchrow($query_id);
  211. }
  212. return ($query_id !== false) ? @mysql_fetch_assoc($query_id) : false;
  213. }
  214. /**
  215. * Seek to given row number
  216. * rownum is zero-based
  217. */
  218. function sql_rowseek($rownum, &$query_id)
  219. {
  220. global $cache;
  221. if ($query_id === false)
  222. {
  223. $query_id = $this->query_result;
  224. }
  225. if (isset($cache->sql_rowset[$query_id]))
  226. {
  227. return $cache->sql_rowseek($rownum, $query_id);
  228. }
  229. return ($query_id !== false) ? @mysql_data_seek($query_id, $rownum) : false;
  230. }
  231. /**
  232. * Get last inserted id after insert statement
  233. */
  234. function sql_nextid()
  235. {
  236. return ($this->db_connect_id) ? @mysql_insert_id($this->db_connect_id) : false;
  237. }
  238. /**
  239. * Free sql result
  240. */
  241. function sql_freeresult($query_id = false)
  242. {
  243. global $cache;
  244. if ($query_id === false)
  245. {
  246. $query_id = $this->query_result;
  247. }
  248. if (isset($cache->sql_rowset[$query_id]))
  249. {
  250. return $cache->sql_freeresult($query_id);
  251. }
  252. if (isset($this->open_queries[(int) $query_id]))
  253. {
  254. unset($this->open_queries[(int) $query_id]);
  255. return @mysql_free_result($query_id);
  256. }
  257. return false;
  258. }
  259. /**
  260. * Escape string used in sql query
  261. */
  262. function sql_escape($msg)
  263. {
  264. if (!$this->db_connect_id)
  265. {
  266. return @mysql_real_escape_string($msg);
  267. }
  268. return @mysql_real_escape_string($msg, $this->db_connect_id);
  269. }
  270. /**
  271. * Gets the estimated number of rows in a specified table.
  272. *
  273. * @param string $table_name Table name
  274. *
  275. * @return string Number of rows in $table_name.
  276. * Prefixed with ~ if estimated (otherwise exact).
  277. *
  278. * @access public
  279. */
  280. function get_estimated_row_count($table_name)
  281. {
  282. $table_status = $this->get_table_status($table_name);
  283. if (isset($table_status['Engine']))
  284. {
  285. if ($table_status['Engine'] === 'MyISAM')
  286. {
  287. return $table_status['Rows'];
  288. }
  289. else if ($table_status['Engine'] === 'InnoDB' && $table_status['Rows'] > 100000)
  290. {
  291. return '~' . $table_status['Rows'];
  292. }
  293. }
  294. return parent::get_row_count($table_name);
  295. }
  296. /**
  297. * Gets the exact number of rows in a specified table.
  298. *
  299. * @param string $table_name Table name
  300. *
  301. * @return string Exact number of rows in $table_name.
  302. *
  303. * @access public
  304. */
  305. function get_row_count($table_name)
  306. {
  307. $table_status = $this->get_table_status($table_name);
  308. if (isset($table_status['Engine']) && $table_status['Engine'] === 'MyISAM')
  309. {
  310. return $table_status['Rows'];
  311. }
  312. return parent::get_row_count($table_name);
  313. }
  314. /**
  315. * Gets some information about the specified table.
  316. *
  317. * @param string $table_name Table name
  318. *
  319. * @return array
  320. *
  321. * @access protected
  322. */
  323. function get_table_status($table_name)
  324. {
  325. $sql = "SHOW TABLE STATUS
  326. LIKE '" . $this->sql_escape($table_name) . "'";
  327. $result = $this->sql_query($sql);
  328. $table_status = $this->sql_fetchrow($result);
  329. $this->sql_freeresult($result);
  330. return $table_status;
  331. }
  332. /**
  333. * Build LIKE expression
  334. * @access private
  335. */
  336. function _sql_like_expression($expression)
  337. {
  338. return $expression;
  339. }
  340. /**
  341. * Build db-specific query data
  342. * @access private
  343. */
  344. function _sql_custom_build($stage, $data)
  345. {
  346. switch ($stage)
  347. {
  348. case 'FROM':
  349. $data = '(' . $data . ')';
  350. break;
  351. }
  352. return $data;
  353. }
  354. /**
  355. * return sql error array
  356. * @access private
  357. */
  358. function _sql_error()
  359. {
  360. if (!$this->db_connect_id)
  361. {
  362. return array(
  363. 'message' => @mysql_error(),
  364. 'code' => @mysql_errno()
  365. );
  366. }
  367. return array(
  368. 'message' => @mysql_error($this->db_connect_id),
  369. 'code' => @mysql_errno($this->db_connect_id)
  370. );
  371. }
  372. /**
  373. * Close sql connection
  374. * @access private
  375. */
  376. function _sql_close()
  377. {
  378. return @mysql_close($this->db_connect_id);
  379. }
  380. /**
  381. * Build db-specific report
  382. * @access private
  383. */
  384. function _sql_report($mode, $query = '')
  385. {
  386. static $test_prof;
  387. // current detection method, might just switch to see the existance of INFORMATION_SCHEMA.PROFILING
  388. if ($test_prof === null)
  389. {
  390. $test_prof = false;
  391. if (version_compare($this->sql_server_info(true), '5.0.37', '>=') && version_compare($this->sql_server_info(true), '5.1', '<'))
  392. {
  393. $test_prof = true;
  394. }
  395. }
  396. switch ($mode)
  397. {
  398. case 'start':
  399. $explain_query = $query;
  400. if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
  401. {
  402. $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
  403. }
  404. else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
  405. {
  406. $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
  407. }
  408. if (preg_match('/^SELECT/', $explain_query))
  409. {
  410. $html_table = false;
  411. // begin profiling
  412. if ($test_prof)
  413. {
  414. @mysql_query('SET profiling = 1;', $this->db_connect_id);
  415. }
  416. if ($result = @mysql_query("EXPLAIN $explain_query", $this->db_connect_id))
  417. {
  418. while ($row = @mysql_fetch_assoc($result))
  419. {
  420. $html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
  421. }
  422. }
  423. @mysql_free_result($result);
  424. if ($html_table)
  425. {
  426. $this->html_hold .= '</table>';
  427. }
  428. if ($test_prof)
  429. {
  430. $html_table = false;
  431. // get the last profile
  432. if ($result = @mysql_query('SHOW PROFILE ALL;', $this->db_connect_id))
  433. {
  434. $this->html_hold .= '<br />';
  435. while ($row = @mysql_fetch_assoc($result))
  436. {
  437. // make <unknown> HTML safe
  438. if (!empty($row['Source_function']))
  439. {
  440. $row['Source_function'] = str_replace(array('<', '>'), array('&lt;', '&gt;'), $row['Source_function']);
  441. }
  442. // remove unsupported features
  443. foreach ($row as $key => $val)
  444. {
  445. if ($val === null)
  446. {
  447. unset($row[$key]);
  448. }
  449. }
  450. $html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
  451. }
  452. }
  453. @mysql_free_result($result);
  454. if ($html_table)
  455. {
  456. $this->html_hold .= '</table>';
  457. }
  458. @mysql_query('SET profiling = 0;', $this->db_connect_id);
  459. }
  460. }
  461. break;
  462. case 'fromcache':
  463. $endtime = explode(' ', microtime());
  464. $endtime = $endtime[0] + $endtime[1];
  465. $result = @mysql_query($query, $this->db_connect_id);
  466. while ($void = @mysql_fetch_assoc($result))
  467. {
  468. // Take the time spent on parsing rows into account
  469. }
  470. @mysql_free_result($result);
  471. $splittime = explode(' ', microtime());
  472. $splittime = $splittime[0] + $splittime[1];
  473. $this->sql_report('record_fromcache', $query, $endtime, $splittime);
  474. break;
  475. }
  476. }
  477. }
  478. ?>