6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
20 * Database Abstraction Layer
27 var $return_on_error = false;
28 var $transaction = false;
30 var $num_queries = array();
31 var $open_queries = array();
38 var $persistency = false;
43 // Set to true if error triggered
44 var $sql_error_triggered = false;
46 // Holding the last sql query on sql error
47 var $sql_error_sql = '';
48 // Holding the error information - only populated if sql_error_triggered is set
49 var $sql_error_returned = array();
51 // Holding transaction count
52 var $transactions = 0;
54 // Supports multi inserts?
55 var $multi_insert = false;
63 * Wildcards for matching any (%) or exactly one (_) character within LIKE expressions
69 * Exact version of the DBAL, directly queried
71 var $sql_server_version = false;
78 $this->num_queries = array(
84 // Fill default sql layer based on the class being called.
85 // This can be changed by the specified layer itself later if needed.
86 $this->sql_layer = substr(get_class($this), 5);
88 // Do not change this please! This variable is used to easy the use of it - and is hardcoded.
89 $this->any_char = chr(0) . '%';
90 $this->one_char = chr(0) . '_';
94 * return on error or display error message
96 function sql_return_on_error($fail = false)
98 $this->sql_error_triggered = false;
99 $this->sql_error_sql = '';
101 $this->return_on_error = $fail;
105 * Return number of sql queries and cached sql queries used
107 function sql_num_queries($cached = false)
109 return ($cached) ? $this->num_queries['cached'] : $this->num_queries['normal'];
115 function sql_add_num_queries($cached = false)
117 $this->num_queries['cached'] += ($cached !== false) ? 1 : 0;
118 $this->num_queries['normal'] += ($cached !== false) ? 0 : 1;
119 $this->num_queries['total'] += 1;
123 * DBAL garbage collection, close sql connection
127 if (!$this->db_connect_id)
132 if ($this->transaction)
136 $this->sql_transaction('commit');
138 while ($this->transaction);
141 foreach ($this->open_queries as $query_id)
143 $this->sql_freeresult($query_id);
146 // Connection closed correctly. Set db_connect_id to false to prevent errors
147 if ($result = $this->_sql_close())
149 $this->db_connect_id = false;
157 * Doing some validation here.
159 function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
166 // Never use a negative total or offset
167 $total = ($total < 0) ? 0 : $total;
168 $offset = ($offset < 0) ? 0 : $offset;
170 return $this->_sql_query_limit($query, $total, $offset, $cache_ttl);
176 function sql_fetchrowset($query_id = false)
178 if ($query_id === false)
180 $query_id = $this->query_result;
183 if ($query_id !== false)
186 while ($row = $this->sql_fetchrow($query_id))
199 * if rownum is false, the current row is used, else it is pointing to the row (zero-based)
201 function sql_fetchfield($field, $rownum = false, $query_id = false)
205 if ($query_id === false)
207 $query_id = $this->query_result;
210 if ($query_id !== false)
212 if ($rownum !== false)
214 $this->sql_rowseek($rownum, $query_id);
217 if (!is_object($query_id) && isset($cache->sql_rowset[$query_id]))
219 return $cache->sql_fetchfield($query_id, $field);
222 $row = $this->sql_fetchrow($query_id);
223 return (isset($row[$field])) ? $row[$field] : false;
230 * Correctly adjust LIKE expression for special characters
231 * Some DBMS are handling them in a different way
233 * @param string $expression The expression to use. Every wildcard is escaped, except $this->any_char and $this->one_char
234 * @return string LIKE expression including the keyword!
236 function sql_like_expression($expression)
238 $expression = utf8_str_replace(array('_', '%'), array("\_", "\%"), $expression);
239 $expression = utf8_str_replace(array(chr(0) . "\_", chr(0) . "\%"), array('_', '%'), $expression);
241 return $this->_sql_like_expression('LIKE \'' . $this->sql_escape($expression) . '\'');
245 * Returns whether results of a query need to be buffered to run a transaction while iterating over them.
247 * @return bool Whether buffering is required.
249 function sql_buffer_nested_transactions()
258 function sql_transaction($status = 'begin')
263 // If we are within a transaction we will not open another one, but enclose the current one to not loose data (prevening auto commit)
264 if ($this->transaction)
266 $this->transactions++;
270 $result = $this->_sql_transaction('begin');
277 $this->transaction = true;
281 // If there was a previously opened transaction we do not commit yet... but count back the number of inner transactions
282 if ($this->transaction && $this->transactions)
284 $this->transactions--;
288 // Check if there is a transaction (no transaction can happen if there was an error, with a combined rollback and error returning enabled)
289 // This implies we have transaction always set for autocommit db's
290 if (!$this->transaction)
295 $result = $this->_sql_transaction('commit');
302 $this->transaction = false;
303 $this->transactions = 0;
307 $result = $this->_sql_transaction('rollback');
308 $this->transaction = false;
309 $this->transactions = 0;
313 $result = $this->_sql_transaction($status);
321 * Build sql statement from array for insert/update/select statements
323 * Idea for this from Ikonboard
324 * Possible query values: INSERT, INSERT_SELECT, UPDATE, SELECT
327 function sql_build_array($query, $assoc_ary = false)
329 if (!is_array($assoc_ary))
334 $fields = $values = array();
336 if ($query == 'INSERT' || $query == 'INSERT_SELECT')
338 foreach ($assoc_ary as $key => $var)
342 if (is_array($var) && is_string($var[0]))
344 // This is used for INSERT_SELECT(s)
349 $values[] = $this->_sql_validate_value($var);
353 $query = ($query == 'INSERT') ? ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')' : ' (' . implode(', ', $fields) . ') SELECT ' . implode(', ', $values) . ' ';
355 else if ($query == 'MULTI_INSERT')
357 trigger_error('The MULTI_INSERT query value is no longer supported. Please use sql_multi_insert() instead.', E_USER_ERROR);
359 else if ($query == 'UPDATE' || $query == 'SELECT')
362 foreach ($assoc_ary as $key => $var)
364 $values[] = "$key = " . $this->_sql_validate_value($var);
366 $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
373 * Build IN or NOT IN sql comparison string, uses <> or = on single element
374 * arrays to improve comparison speed
377 * @param string $field name of the sql column that shall be compared
378 * @param array $array array of values that are allowed (IN) or not allowed (NOT IN)
379 * @param bool $negate true for NOT IN (), false for IN () (default)
380 * @param bool $allow_empty_set If true, allow $array to be empty, this function will return 1=1 or 1=0 then. Default to false.
382 function sql_in_set($field, $array, $negate = false, $allow_empty_set = false)
386 if (!$allow_empty_set)
388 // Print the backtrace to help identifying the location of the problematic code
389 $this->sql_error('No values specified for SQL IN comparison');
393 // NOT IN () actually means everything so use a tautology
398 // IN () actually means nothing so use a contradiction
406 if (!is_array($array))
408 $array = array($array);
411 if (sizeof($array) == 1)
414 $var = current($array);
416 return $field . ($negate ? ' <> ' : ' = ') . $this->_sql_validate_value($var);
420 return $field . ($negate ? ' NOT IN ' : ' IN ') . '(' . implode(', ', array_map(array($this, '_sql_validate_value'), $array)) . ')';
425 * Run binary AND operator on DB column.
426 * Results in sql statement: "{$column_name} & (1 << {$bit}) {$compare}"
428 * @param string $column_name The column name to use
429 * @param int $bit The value to use for the AND operator, will be converted to (1 << $bit). Is used by options, using the number schema... 0, 1, 2...29
430 * @param string $compare Any custom SQL code after the check (for example "= 0")
432 function sql_bit_and($column_name, $bit, $compare = '')
434 if (method_exists($this, '_sql_bit_and'))
436 return $this->_sql_bit_and($column_name, $bit, $compare);
439 return $column_name . ' & ' . (1 << $bit) . (($compare) ? ' ' . $compare : '');
443 * Run binary OR operator on DB column.
444 * Results in sql statement: "{$column_name} | (1 << {$bit}) {$compare}"
446 * @param string $column_name The column name to use
447 * @param int $bit The value to use for the OR operator, will be converted to (1 << $bit). Is used by options, using the number schema... 0, 1, 2...29
448 * @param string $compare Any custom SQL code after the check (for example "= 0")
450 function sql_bit_or($column_name, $bit, $compare = '')
452 if (method_exists($this, '_sql_bit_or'))
454 return $this->_sql_bit_or($column_name, $bit, $compare);
457 return $column_name . ' | ' . (1 << $bit) . (($compare) ? ' ' . $compare : '');
461 * Run more than one insert statement.
463 * @param string $table table name to run the statements on
464 * @param array &$sql_ary multi-dimensional array holding the statement data.
466 * @return bool false if no statements were executed.
469 function sql_multi_insert($table, &$sql_ary)
471 if (!sizeof($sql_ary))
476 if ($this->multi_insert)
479 foreach ($sql_ary as $id => $_sql_ary)
481 // If by accident the sql array is only one-dimensional we build a normal insert statement
482 if (!is_array($_sql_ary))
484 return $this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('INSERT', $sql_ary));
488 foreach ($_sql_ary as $key => $var)
490 $values[] = $this->_sql_validate_value($var);
492 $ary[] = '(' . implode(', ', $values) . ')';
495 return $this->sql_query('INSERT INTO ' . $table . ' ' . ' (' . implode(', ', array_keys($sql_ary[0])) . ') VALUES ' . implode(', ', $ary));
499 foreach ($sql_ary as $ary)
506 $result = $this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('INSERT', $ary));
519 * Function for validating values
522 function _sql_validate_value($var)
528 else if (is_string($var))
530 return "'" . $this->sql_escape($var) . "'";
534 return (is_bool($var)) ? intval($var) : $var;
539 * Build sql statement from array for select and select distinct statements
541 * Possible query values: SELECT, SELECT_DISTINCT
543 function sql_build_query($query, $array)
549 case 'SELECT_DISTINCT';
551 $sql = str_replace('_', ' ', $query) . ' ' . $array['SELECT'] . ' FROM ';
553 // Build table array. We also build an alias array for later checks.
554 $table_array = $aliases = array();
555 $used_multi_alias = false;
557 foreach ($array['FROM'] as $table_name => $alias)
559 if (is_array($alias))
561 $used_multi_alias = true;
563 foreach ($alias as $multi_alias)
565 $table_array[] = $table_name . ' ' . $multi_alias;
566 $aliases[] = $multi_alias;
571 $table_array[] = $table_name . ' ' . $alias;
576 // We run the following code to determine if we need to re-order the table array. ;)
577 // The reason for this is that for multi-aliased tables (two equal tables) in the FROM statement the last table need to match the first comparison.
578 // DBMS who rely on this: Oracle, PostgreSQL and MSSQL. For all other DBMS it makes absolutely no difference in which order the table is.
579 if (!empty($array['LEFT_JOIN']) && sizeof($array['FROM']) > 1 && $used_multi_alias !== false)
581 // Take first LEFT JOIN
582 $join = current($array['LEFT_JOIN']);
584 // Determine the table used there (even if there are more than one used, we only want to have one
585 preg_match('/(' . implode('|', $aliases) . ')\.[^\s]+/U', str_replace(array('(', ')', 'AND', 'OR', ' '), '', $join['ON']), $matches);
587 // If there is a first join match, we need to make sure the table order is correct
588 if (!empty($matches[1]))
590 $first_join_match = trim($matches[1]);
591 $table_array = $last = array();
593 foreach ($array['FROM'] as $table_name => $alias)
595 if (is_array($alias))
597 foreach ($alias as $multi_alias)
599 ($multi_alias === $first_join_match) ? $last[] = $table_name . ' ' . $multi_alias : $table_array[] = $table_name . ' ' . $multi_alias;
604 ($alias === $first_join_match) ? $last[] = $table_name . ' ' . $alias : $table_array[] = $table_name . ' ' . $alias;
608 $table_array = array_merge($table_array, $last);
612 $sql .= $this->_sql_custom_build('FROM', implode(' CROSS JOIN ', $table_array));
614 if (!empty($array['LEFT_JOIN']))
616 foreach ($array['LEFT_JOIN'] as $join)
618 $sql .= ' LEFT JOIN ' . key($join['FROM']) . ' ' . current($join['FROM']) . ' ON (' . $join['ON'] . ')';
622 if (!empty($array['WHERE']))
624 $sql .= ' WHERE ' . $this->_sql_custom_build('WHERE', $array['WHERE']);
627 if (!empty($array['GROUP_BY']))
629 $sql .= ' GROUP BY ' . $array['GROUP_BY'];
632 if (!empty($array['ORDER_BY']))
634 $sql .= ' ORDER BY ' . $array['ORDER_BY'];
644 * display sql error page
646 function sql_error($sql = '')
648 global $auth, $user, $config;
650 // Set var to retrieve errored status
651 $this->sql_error_triggered = true;
652 $this->sql_error_sql = $sql;
654 $this->sql_error_returned = $this->_sql_error();
656 if (!$this->return_on_error)
658 $message = 'SQL ERROR [ ' . $this->sql_layer . ' ]<br /><br />' . $this->sql_error_returned['message'] . ' [' . $this->sql_error_returned['code'] . ']';
660 // Show complete SQL error and path to administrators only
661 // Additionally show complete error on installation or if extended debug mode is enabled
662 // The DEBUG_EXTRA constant is for development only!
663 if ((isset($auth) && $auth->acl_get('a_')) || defined('IN_INSTALL') || defined('DEBUG_EXTRA'))
665 // Print out a nice backtrace...
666 $backtrace = get_backtrace();
668 $message .= ($sql) ? '<br /><br />SQL<br /><br />' . htmlspecialchars($sql) : '';
669 $message .= ($backtrace) ? '<br /><br />BACKTRACE<br />' . $backtrace : '';
670 $message .= '<br />';
674 // If error occurs in initiating the session we need to use a pre-defined language string
675 // This could happen if the connection could not be established for example (then we are not able to grab the default language)
676 if (!isset($user->lang['SQL_ERROR_OCCURRED']))
678 $message .= '<br /><br />An sql error occurred while fetching this page. Please contact an administrator if this problem persists.';
682 if (!empty($config['board_contact']))
684 $message .= '<br /><br />' . sprintf($user->lang['SQL_ERROR_OCCURRED'], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
688 $message .= '<br /><br />' . sprintf($user->lang['SQL_ERROR_OCCURRED'], '', '');
693 if ($this->transaction)
695 $this->sql_transaction('rollback');
698 if (strlen($message) > 1024)
700 // We need to define $msg_long_text here to circumvent text stripping.
701 global $msg_long_text;
702 $msg_long_text = $message;
704 trigger_error(false, E_USER_ERROR);
707 trigger_error($message, E_USER_ERROR);
710 if ($this->transaction)
712 $this->sql_transaction('rollback');
715 return $this->sql_error_returned;
721 function sql_report($mode, $query = '')
723 global $cache, $starttime, $phpbb_root_path, $user;
725 if (empty($_REQUEST['explain']))
730 if (!$query && $this->query_hold != '')
732 $query = $this->query_hold;
744 $mtime = explode(' ', microtime());
745 $totaltime = $mtime[0] + $mtime[1] - $starttime;
747 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
748 <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
750 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
751 <meta http-equiv="Content-Style-Type" content="text/css" />
752 <meta http-equiv="imagetoolbar" content="no" />
753 <title>SQL Report</title>
754 <link href="' . $phpbb_root_path . 'adm/style/admin.css" rel="stylesheet" type="text/css" media="screen" />
756 <body id="errorpage">
758 <div id="page-header">
759 <a href="' . build_url('explain') . '">Return to previous page</a>
764 <span class="corners-top"><span></span></span>
768 <p><b>Page generated in ' . round($totaltime, 4) . " seconds with {$this->num_queries['normal']} queries" . (($this->num_queries['cached']) ? " + {$this->num_queries['cached']} " . (($this->num_queries['cached'] == 1) ? 'query' : 'queries') . ' returning data from cache' : '') . '</b></p>
770 <p>Time spent on ' . $this->sql_layer . ' queries: <b>' . round($this->sql_time, 5) . 's</b> | Time spent on PHP: <b>' . round($totaltime - $this->sql_time, 5) . 's</b></p>
773 ' . $this->sql_report . '
775 <span class="corners-bottom"><span></span></span>
779 <div id="page-footer">
780 Powered by <a href="http://www.phpbb.com/">phpBB</a>® Forum Software © phpBB Group
791 $endtime = explode(' ', microtime());
792 $endtime = $endtime[0] + $endtime[1];
794 $this->sql_report .= '
796 <table cellspacing="1">
799 <th>Query #' . $this->num_queries['total'] . '</th>
804 <td class="row3"><textarea style="font-family:\'Courier New\',monospace;width:99%" rows="5" cols="10">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td>
809 ' . $this->html_hold . '
811 <p style="text-align: center;">
814 if ($this->query_result)
816 if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query))
818 $this->sql_report .= 'Affected rows: <b>' . $this->sql_affectedrows($this->query_result) . '</b> | ';
820 $this->sql_report .= 'Before: ' . sprintf('%.5f', $this->curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $this->curtime) . 's</b>';
824 $error = $this->sql_error();
825 $this->sql_report .= '<b style="color: red">FAILED</b> - ' . $this->sql_layer . ' Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']);
828 $this->sql_report .= '</p><br /><br />';
830 $this->sql_time += $endtime - $this->curtime;
834 $this->query_hold = $query;
835 $this->html_hold = '';
837 $this->_sql_report($mode, $query);
839 $this->curtime = explode(' ', microtime());
840 $this->curtime = $this->curtime[0] + $this->curtime[1];
844 case 'add_select_row':
846 $html_table = func_get_arg(2);
847 $row = func_get_arg(3);
849 if (!$html_table && sizeof($row))
852 $this->html_hold .= '<table cellspacing="1"><tr>';
854 foreach (array_keys($row) as $val)
856 $this->html_hold .= '<th>' . (($val) ? ucwords(str_replace('_', ' ', $val)) : ' ') . '</th>';
858 $this->html_hold .= '</tr>';
860 $this->html_hold .= '<tr>';
863 foreach (array_values($row) as $val)
865 $class = ($class == 'row1') ? 'row2' : 'row1';
866 $this->html_hold .= '<td class="' . $class . '">' . (($val) ? $val : ' ') . '</td>';
868 $this->html_hold .= '</tr>';
876 $this->_sql_report($mode, $query);
880 case 'record_fromcache':
882 $endtime = func_get_arg(2);
883 $splittime = func_get_arg(3);
885 $time_cache = $endtime - $this->curtime;
886 $time_db = $splittime - $endtime;
887 $color = ($time_db > $time_cache) ? 'green' : 'red';
889 $this->sql_report .= '<table cellspacing="1"><thead><tr><th>Query results obtained from the cache</th></tr></thead><tbody><tr>';
890 $this->sql_report .= '<td class="row3"><textarea style="font-family:\'Courier New\',monospace;width:99%" rows="5" cols="10">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></tbody></table>';
891 $this->sql_report .= '<p style="text-align: center;">';
892 $this->sql_report .= 'Before: ' . sprintf('%.5f', $this->curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed [cache]: <b style="color: ' . $color . '">' . sprintf('%.5f', ($time_cache)) . 's</b> | Elapsed [db]: <b>' . sprintf('%.5f', $time_db) . 's</b></p><br /><br />';
894 // Pad the start time to not interfere with page timing
895 $starttime += $time_db;
901 $this->_sql_report($mode, $query);
911 * This variable holds the class name to use later
913 $sql_db = (!empty($dbms)) ? 'dbal_' . basename($dbms) : 'dbal';