Chris@76: 'smf_db_query',
Chris@76: 'db_quote' => 'smf_db_quote',
Chris@76: 'db_fetch_assoc' => 'sqlite_fetch_array',
Chris@76: 'db_fetch_row' => 'smf_db_fetch_row',
Chris@76: 'db_free_result' => 'smf_db_free_result',
Chris@76: 'db_insert' => 'smf_db_insert',
Chris@76: 'db_insert_id' => 'smf_db_insert_id',
Chris@76: 'db_num_rows' => 'sqlite_num_rows',
Chris@76: 'db_data_seek' => 'sqlite_seek',
Chris@76: 'db_num_fields' => 'sqlite_num_fields',
Chris@76: 'db_escape_string' => 'sqlite_escape_string',
Chris@76: 'db_unescape_string' => 'smf_db_unescape_string',
Chris@76: 'db_server_info' => 'smf_db_libversion',
Chris@76: 'db_affected_rows' => 'smf_db_affected_rows',
Chris@76: 'db_transaction' => 'smf_db_transaction',
Chris@76: 'db_error' => 'smf_db_last_error',
Chris@76: 'db_select_db' => '',
Chris@76: 'db_title' => 'SQLite',
Chris@76: 'db_sybase' => true,
Chris@76: 'db_case_sensitive' => true,
Chris@76: 'db_escape_wildcard_string' => 'smf_db_escape_wildcard_string',
Chris@76: );
Chris@76:
Chris@76: if (substr($db_name, -3) != '.db')
Chris@76: $db_name .= '.db';
Chris@76:
Chris@76: if (!empty($db_options['persist']))
Chris@76: $connection = @sqlite_popen($db_name, 0666, $sqlite_error);
Chris@76: else
Chris@76: $connection = @sqlite_open($db_name, 0666, $sqlite_error);
Chris@76:
Chris@76: // Something's wrong, show an error if its fatal (which we assume it is)
Chris@76: if (!$connection)
Chris@76: {
Chris@76: if (!empty($db_options['non_fatal']))
Chris@76: return null;
Chris@76: else
Chris@76: db_fatal_error();
Chris@76: }
Chris@76: $db_in_transact = false;
Chris@76:
Chris@76: // This is frankly stupid - stop SQLite returning alias names!
Chris@76: @sqlite_query('PRAGMA short_column_names = 1', $connection);
Chris@76:
Chris@76: // Make some user defined functions!
Chris@76: sqlite_create_function($connection, 'unix_timestamp', 'smf_udf_unix_timestamp', 0);
Chris@76: sqlite_create_function($connection, 'inet_aton', 'smf_udf_inet_aton', 1);
Chris@76: sqlite_create_function($connection, 'inet_ntoa', 'smf_udf_inet_ntoa', 1);
Chris@76: sqlite_create_function($connection, 'find_in_set', 'smf_udf_find_in_set', 2);
Chris@76: sqlite_create_function($connection, 'year', 'smf_udf_year', 1);
Chris@76: sqlite_create_function($connection, 'month', 'smf_udf_month', 1);
Chris@76: sqlite_create_function($connection, 'dayofmonth', 'smf_udf_dayofmonth', 1);
Chris@76: sqlite_create_function($connection, 'concat', 'smf_udf_concat');
Chris@76: sqlite_create_function($connection, 'locate', 'smf_udf_locate', 2);
Chris@76: sqlite_create_function($connection, 'regexp', 'smf_udf_regexp', 2);
Chris@76:
Chris@76: return $connection;
Chris@76: }
Chris@76:
Chris@76: // Extend the database functionality.
Chris@76: function db_extend($type = 'extra')
Chris@76: {
Chris@76: global $sourcedir, $db_type;
Chris@76:
Chris@76: require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-' . $db_type . '.php');
Chris@76: $initFunc = 'db_' . $type . '_init';
Chris@76: $initFunc();
Chris@76: }
Chris@76:
Chris@76: // SQLite doesn't actually need this!
Chris@76: function db_fix_prefix(&$db_prefix, $db_name)
Chris@76: {
Chris@76: return false;
Chris@76: }
Chris@76:
Chris@76: function smf_db_replacement__callback($matches)
Chris@76: {
Chris@76: global $db_callback, $user_info, $db_prefix;
Chris@76:
Chris@76: list ($values, $connection) = $db_callback;
Chris@76:
Chris@76: if ($matches[1] === 'db_prefix')
Chris@76: return $db_prefix;
Chris@76:
Chris@76: if ($matches[1] === 'query_see_board')
Chris@76: return $user_info['query_see_board'];
Chris@76:
Chris@76: if ($matches[1] === 'query_wanna_see_board')
Chris@76: return $user_info['query_wanna_see_board'];
Chris@76:
Chris@76: if (!isset($matches[2]))
Chris@76: smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76:
Chris@76: if (!isset($values[$matches[2]]))
Chris@76: smf_db_error_backtrace('The database value you\'re trying to insert does not exist: ' . htmlspecialchars($matches[2]), '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76:
Chris@76: $replacement = $values[$matches[2]];
Chris@76:
Chris@76: switch ($matches[1])
Chris@76: {
Chris@76: case 'int':
Chris@76: if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
Chris@76: smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76: return (string) (int) $replacement;
Chris@76: break;
Chris@76:
Chris@76: case 'string':
Chris@76: case 'text':
Chris@76: return sprintf('\'%1$s\'', sqlite_escape_string($replacement));
Chris@76: break;
Chris@76:
Chris@76: case 'array_int':
Chris@76: if (is_array($replacement))
Chris@76: {
Chris@76: if (empty($replacement))
Chris@76: smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76:
Chris@76: foreach ($replacement as $key => $value)
Chris@76: {
Chris@76: if (!is_numeric($value) || (string) $value !== (string) (int) $value)
Chris@76: smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76:
Chris@76: $replacement[$key] = (string) (int) $value;
Chris@76: }
Chris@76:
Chris@76: return implode(', ', $replacement);
Chris@76: }
Chris@76: else
Chris@76: smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76:
Chris@76: break;
Chris@76:
Chris@76: case 'array_string':
Chris@76: if (is_array($replacement))
Chris@76: {
Chris@76: if (empty($replacement))
Chris@76: smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76:
Chris@76: foreach ($replacement as $key => $value)
Chris@76: $replacement[$key] = sprintf('\'%1$s\'', sqlite_escape_string($value));
Chris@76:
Chris@76: return implode(', ', $replacement);
Chris@76: }
Chris@76: else
Chris@76: smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76: break;
Chris@76:
Chris@76: case 'date':
Chris@76: if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
Chris@76: return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]);
Chris@76: else
Chris@76: smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76: break;
Chris@76:
Chris@76: case 'float':
Chris@76: if (!is_numeric($replacement))
Chris@76: smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
Chris@76: return (string) (float) $replacement;
Chris@76: break;
Chris@76:
Chris@76: case 'identifier':
Chris@76: return '`' . strtr($replacement, array('`' => '', '.' => '')) . '`';
Chris@76: break;
Chris@76:
Chris@76: case 'raw':
Chris@76: return $replacement;
Chris@76: break;
Chris@76:
Chris@76: default:
Chris@76: smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
Chris@76: break;
Chris@76: }
Chris@76: }
Chris@76:
Chris@76: // Just like the db_query, escape and quote a string, but not executing the query.
Chris@76: function smf_db_quote($db_string, $db_values, $connection = null)
Chris@76: {
Chris@76: global $db_callback, $db_connection;
Chris@76:
Chris@76: // Only bother if there's something to replace.
Chris@76: if (strpos($db_string, '{') !== false)
Chris@76: {
Chris@76: // This is needed by the callback function.
Chris@76: $db_callback = array($db_values, $connection == null ? $db_connection : $connection);
Chris@76:
Chris@76: // Do the quoting and escaping
Chris@76: $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
Chris@76:
Chris@76: // Clear this global variable.
Chris@76: $db_callback = array();
Chris@76: }
Chris@76:
Chris@76: return $db_string;
Chris@76: }
Chris@76:
Chris@76: // Do a query. Takes care of errors too.
Chris@76: function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
Chris@76: {
Chris@76: global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start;
Chris@76: global $db_unbuffered, $db_callback, $modSettings;
Chris@76:
Chris@76: // Decide which connection to use.
Chris@76: $connection = $connection == null ? $db_connection : $connection;
Chris@76:
Chris@76: // Special queries that need processing.
Chris@76: $replacements = array(
Chris@76: 'birthday_array' => array(
Chris@76: '~DATE_FORMAT\(([^,]+),\s*([^\)]+)\s*\)~' => 'strftime($2, $1)'
Chris@76: ),
Chris@76: 'substring' => array(
Chris@76: '~SUBSTRING~' => 'SUBSTR',
Chris@76: ),
Chris@76: 'truncate_table' => array(
Chris@76: '~TRUNCATE~i' => 'DELETE FROM',
Chris@76: ),
Chris@76: 'user_activity_by_time' => array(
Chris@76: '~HOUR\(FROM_UNIXTIME\((poster_time\s+\+\s+\{int:.+\})\)\)~' => 'strftime(\'%H\', datetime($1, \'unixepoch\'))',
Chris@76: ),
Chris@76: 'unread_fetch_topic_count' => array(
Chris@76: '~\s*SELECT\sCOUNT\(DISTINCT\st\.id_topic\),\sMIN\(t\.id_last_msg\)(.+)$~is' => 'SELECT COUNT(id_topic), MIN(id_last_msg) FROM (SELECT DISTINCT t.id_topic, t.id_last_msg $1)',
Chris@76: ),
Chris@76: 'alter_table_boards' => array(
Chris@76: '~(.+)~' => '',
Chris@76: ),
Chris@76: 'get_random_number' => array(
Chris@76: '~RAND~' => 'RANDOM',
Chris@76: ),
Chris@76: 'set_character_set' => array(
Chris@76: '~(.+)~' => '',
Chris@76: ),
Chris@76: 'themes_count' => array(
Chris@76: '~\s*SELECT\sCOUNT\(DISTINCT\sid_member\)\sAS\svalue,\sid_theme.+FROM\s(.+themes)(.+)~is' => 'SELECT COUNT(id_member) AS value, id_theme FROM (SELECT DISTINCT id_member, id_theme, variable FROM $1) $2',
Chris@76: ),
Chris@76: 'attach_download_increase' => array(
Chris@76: '~LOW_PRIORITY~' => '',
Chris@76: ),
Chris@76: 'pm_conversation_list' => array(
Chris@76: '~ORDER BY id_pm~' => 'ORDER BY MAX(pm.id_pm)',
Chris@76: ),
Chris@76: 'boardindex_fetch_boards' => array(
Chris@76: '~(.)$~' => '$1 ORDER BY b.board_order',
Chris@76: ),
Chris@76: 'messageindex_fetch_boards' => array(
Chris@76: '~(.)$~' => '$1 ORDER BY b.board_order',
Chris@76: ),
Chris@76: 'order_by_board_order' => array(
Chris@76: '~(.)$~' => '$1 ORDER BY b.board_order',
Chris@76: ),
Chris@76: 'spider_check' => array(
Chris@76: '~(.)$~' => '$1 ORDER BY LENGTH(user_agent) DESC',
Chris@76: ),
Chris@76: );
Chris@76:
Chris@76: if (isset($replacements[$identifier]))
Chris@76: $db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
Chris@76:
Chris@76: // SQLite doesn't support count(distinct).
Chris@76: $db_string = trim($db_string);
Chris@76: $db_string = preg_replace('~^\s*SELECT\s+?COUNT\(DISTINCT\s+?(.+?)\)(\s*AS\s*(.+?))*\s*(FROM.+)~is', 'SELECT COUNT(*) $2 FROM (SELECT DISTINCT $1 $4)', $db_string);
Chris@76:
Chris@76: // Or RLIKE.
Chris@76: $db_string = preg_replace('~AND\s*(.+?)\s*RLIKE\s*(\{string:.+?\})~', 'AND REGEXP(\1, \2)', $db_string);
Chris@76:
Chris@76: // INSTR? No support for that buddy :(
Chris@76: if (preg_match('~INSTR\((.+?),\s(.+?)\)~', $db_string, $matches) === 1)
Chris@76: {
Chris@76: $db_string = preg_replace('~INSTR\((.+?),\s(.+?)\)~', '$1 LIKE $2', $db_string);
Chris@76: list(, $search) = explode(':', substr($matches[2], 1, -1));
Chris@76: $db_values[$search] = '%' . $db_values[$search] . '%';
Chris@76: }
Chris@76:
Chris@76: // Lets remove ASC and DESC from GROUP BY clause.
Chris@76: if (preg_match('~GROUP BY .*? (?:ASC|DESC)~is', $db_string, $matches))
Chris@76: {
Chris@76: $replace = str_replace(array('ASC', 'DESC'), '', $matches[0]);
Chris@76: $db_string = str_replace($matches[0], $replace, $db_string);
Chris@76: }
Chris@76:
Chris@76: // We need to replace the SUBSTRING in the sort identifier.
Chris@76: if ($identifier == 'substring_membergroups' && isset($db_values['sort']))
Chris@76: $db_values['sort'] = preg_replace('~SUBSTRING~', 'SUBSTR', $db_values['sort']);
Chris@76:
Chris@76: // SQLite doesn't support TO_DAYS but has the julianday function which can be used in the same manner. But make sure it is being used to calculate a span.
Chris@76: $db_string = preg_replace('~\(TO_DAYS\(([^)]+)\) - TO_DAYS\(([^)]+)\)\) AS span~', '(julianday($1) - julianday($2)) AS span', $db_string);
Chris@76:
Chris@76: // One more query....
Chris@76: $db_count = !isset($db_count) ? 1 : $db_count + 1;
Chris@76:
Chris@76: if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
Chris@76: smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
Chris@76:
Chris@76: if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
Chris@76: {
Chris@76: // Pass some values to the global space for use in the callback function.
Chris@76: $db_callback = array($db_values, $connection);
Chris@76:
Chris@76: // Inject the values passed to this function.
Chris@76: $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
Chris@76:
Chris@76: // This shouldn't be residing in global space any longer.
Chris@76: $db_callback = array();
Chris@76: }
Chris@76:
Chris@76: // Debugging.
Chris@76: if (isset($db_show_debug) && $db_show_debug === true)
Chris@76: {
Chris@76: // Get the file and line number this function was called.
Chris@76: list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
Chris@76:
Chris@76: // Initialize $db_cache if not already initialized.
Chris@76: if (!isset($db_cache))
Chris@76: $db_cache = array();
Chris@76:
Chris@76: if (!empty($_SESSION['debug_redirect']))
Chris@76: {
Chris@76: $db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
Chris@76: $db_count = count($db_cache) + 1;
Chris@76: $_SESSION['debug_redirect'] = array();
Chris@76: }
Chris@76:
Chris@76: $st = microtime();
Chris@76: // Don't overload it.
Chris@76: $db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
Chris@76: $db_cache[$db_count]['f'] = $file;
Chris@76: $db_cache[$db_count]['l'] = $line;
Chris@76: $db_cache[$db_count]['s'] = array_sum(explode(' ', $st)) - array_sum(explode(' ', $time_start));
Chris@76: }
Chris@76:
Chris@76: $ret = @sqlite_query($db_string, $connection, SQLITE_BOTH, $err_msg);
Chris@76: if ($ret === false && empty($db_values['db_error_skip']))
Chris@76: $ret = smf_db_error($db_string . '#!#' . $err_msg, $connection);
Chris@76:
Chris@76: // Debugging.
Chris@76: if (isset($db_show_debug) && $db_show_debug === true)
Chris@76: $db_cache[$db_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
Chris@76:
Chris@76: return $ret;
Chris@76: }
Chris@76:
Chris@76: function smf_db_affected_rows($connection = null)
Chris@76: {
Chris@76: global $db_connection;
Chris@76:
Chris@76: return sqlite_changes($connection == null ? $db_connection : $connection);
Chris@76: }
Chris@76:
Chris@76: function smf_db_insert_id($table, $field = null, $connection = null)
Chris@76: {
Chris@76: global $db_connection, $db_prefix;
Chris@76:
Chris@76: $table = str_replace('{db_prefix}', $db_prefix, $table);
Chris@76:
Chris@76: // SQLite doesn't need the table or field information.
Chris@76: return sqlite_last_insert_rowid($connection == null ? $db_connection : $connection);
Chris@76: }
Chris@76:
Chris@76: // Keeps the connection handle.
Chris@76: function smf_db_last_error()
Chris@76: {
Chris@76: global $db_connection, $sqlite_error;
Chris@76:
Chris@76: $query_errno = sqlite_last_error($db_connection);
Chris@76: return $query_errno || empty($sqlite_error) ? sqlite_error_string($query_errno) : $sqlite_error;
Chris@76: }
Chris@76:
Chris@76: // Do a transaction.
Chris@76: function smf_db_transaction($type = 'commit', $connection = null)
Chris@76: {
Chris@76: global $db_connection, $db_in_transact;
Chris@76:
Chris@76: // Decide which connection to use
Chris@76: $connection = $connection == null ? $db_connection : $connection;
Chris@76:
Chris@76: if ($type == 'begin')
Chris@76: {
Chris@76: $db_in_transact = true;
Chris@76: return @sqlite_query('BEGIN', $connection);
Chris@76: }
Chris@76: elseif ($type == 'rollback')
Chris@76: {
Chris@76: $db_in_transact = false;
Chris@76: return @sqlite_query('ROLLBACK', $connection);
Chris@76: }
Chris@76: elseif ($type == 'commit')
Chris@76: {
Chris@76: $db_in_transact = false;
Chris@76: return @sqlite_query('COMMIT', $connection);
Chris@76: }
Chris@76:
Chris@76: return false;
Chris@76: }
Chris@76:
Chris@76: // Database error!
Chris@76: function smf_db_error($db_string, $connection = null)
Chris@76: {
Chris@76: global $txt, $context, $sourcedir, $webmaster_email, $modSettings;
Chris@76: global $forum_version, $db_connection, $db_last_error, $db_persist;
Chris@76: global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd;
Chris@76: global $smcFunc;
Chris@76:
Chris@76: // We'll try recovering the file and line number the original db query was called from.
Chris@76: list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
Chris@76:
Chris@76: // Decide which connection to use
Chris@76: $connection = $connection == null ? $db_connection : $connection;
Chris@76:
Chris@76: // This is the error message...
Chris@76: $query_errno = sqlite_last_error($connection);
Chris@76: $query_error = sqlite_error_string($query_errno);
Chris@76:
Chris@76: // Get the extra error message.
Chris@76: $errStart = strrpos($db_string, '#!#');
Chris@76: $query_error .= '
' . substr($db_string, $errStart + 3);
Chris@76: $db_string = substr($db_string, 0, $errStart);
Chris@76:
Chris@76: // Log the error.
Chris@76: if (function_exists('log_error'))
Chris@76: log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n" .$db_string : ''), 'database', $file, $line);
Chris@76:
Chris@76: // Sqlite optimizing - the actual error message isn't helpful or user friendly.
Chris@76: if (strpos($query_error, 'no_access') !== false || strpos($query_error, 'database schema has changed') !== false)
Chris@76: {
Chris@76: if (!empty($context) && !empty($txt) && !empty($txt['error_sqlite_optimizing']))
Chris@76: fatal_error($txt['error_sqlite_optimizing'], false);
Chris@76: else
Chris@76: {
Chris@76: // Don't cache this page!
Chris@76: header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
Chris@76: header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
Chris@76: header('Cache-Control: no-cache');
Chris@76:
Chris@76: // Send the right error codes.
Chris@76: header('HTTP/1.1 503 Service Temporarily Unavailable');
Chris@76: header('Status: 503 Service Temporarily Unavailable');
Chris@76: header('Retry-After: 3600');
Chris@76:
Chris@76: die('Sqlite is optimizing the database, the forum can not be accessed until it has finished. Please try refreshing this page momentarily.');
Chris@76: }
Chris@76: }
Chris@76:
Chris@76: // Nothing's defined yet... just die with it.
Chris@76: if (empty($context) || empty($txt))
Chris@76: die($query_error);
Chris@76:
Chris@76: // Show an error message, if possible.
Chris@76: $context['error_title'] = $txt['database_error'];
Chris@76: if (allowedTo('admin_forum'))
Chris@76: $context['error_message'] = nl2br($query_error) . '
' . $txt['file'] . ': ' . $file . '
' . $txt['line'] . ': ' . $line;
Chris@76: else
Chris@76: $context['error_message'] = $txt['try_again'];
Chris@76:
Chris@76: // A database error is often the sign of a database in need of updgrade. Check forum versions, and if not identical suggest an upgrade... (not for Demo/CVS versions!)
Chris@76: if (allowedTo('admin_forum') && !empty($forum_version) && $forum_version != 'SMF ' . @$modSettings['smfVersion'] && strpos($forum_version, 'Demo') === false && strpos($forum_version, 'CVS') === false)
Chris@76: $context['error_message'] .= '
' . sprintf($txt['database_error_versions'], $forum_version, $modSettings['smfVersion']);
Chris@76:
Chris@76: if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
Chris@76: {
Chris@76: $context['error_message'] .= '
' . nl2br($db_string);
Chris@76: }
Chris@76:
Chris@76: // It's already been logged... don't log it again.
Chris@76: fatal_error($context['error_message'], false);
Chris@76: }
Chris@76:
Chris@76: // Insert some data...
Chris@76: function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null)
Chris@76: {
Chris@76: global $db_in_transact, $db_connection, $smcFunc, $db_prefix;
Chris@76:
Chris@76: $connection = $connection === null ? $db_connection : $connection;
Chris@76:
Chris@76: if (empty($data))
Chris@76: return;
Chris@76:
Chris@76: if (!is_array($data[array_rand($data)]))
Chris@76: $data = array($data);
Chris@76:
Chris@76: // Replace the prefix holder with the actual prefix.
Chris@76: $table = str_replace('{db_prefix}', $db_prefix, $table);
Chris@76:
Chris@76: $priv_trans = false;
Chris@76: if (count($data) > 1 && !$db_in_transact && !$disable_trans)
Chris@76: {
Chris@76: $smcFunc['db_transaction']('begin', $connection);
Chris@76: $priv_trans = true;
Chris@76: }
Chris@76:
Chris@76: if (!empty($data))
Chris@76: {
Chris@76: // Create the mold for a single row insert.
Chris@76: $insertData = '(';
Chris@76: foreach ($columns as $columnName => $type)
Chris@76: {
Chris@76: // Are we restricting the length?
Chris@76: if (strpos($type, 'string-') !== false)
Chris@76: $insertData .= sprintf('SUBSTR({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
Chris@76: else
Chris@76: $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
Chris@76: }
Chris@76: $insertData = substr($insertData, 0, -2) . ')';
Chris@76:
Chris@76: // Create an array consisting of only the columns.
Chris@76: $indexed_columns = array_keys($columns);
Chris@76:
Chris@76: // Here's where the variables are injected to the query.
Chris@76: $insertRows = array();
Chris@76: foreach ($data as $dataRow)
Chris@76: $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
Chris@76:
Chris@76: foreach ($insertRows as $entry)
Chris@76: // Do the insert.
Chris@76: $smcFunc['db_query']('',
Chris@76: (($method === 'replace') ? 'REPLACE' : (' INSERT' . ($method === 'ignore' ? ' OR IGNORE' : ''))) . ' INTO ' . $table . '(' . implode(', ', $indexed_columns) . ')
Chris@76: VALUES
Chris@76: ' . $entry,
Chris@76: array(
Chris@76: 'security_override' => true,
Chris@76: 'db_error_skip' => $table === $db_prefix . 'log_errors',
Chris@76: ),
Chris@76: $connection
Chris@76: );
Chris@76: }
Chris@76:
Chris@76: if ($priv_trans)
Chris@76: $smcFunc['db_transaction']('commit', $connection);
Chris@76: }
Chris@76:
Chris@76: // Doesn't do anything on sqlite!
Chris@76: function smf_db_free_result($handle = false)
Chris@76: {
Chris@76: return true;
Chris@76: }
Chris@76:
Chris@76: // Make sure we return no string indexes!
Chris@76: function smf_db_fetch_row($handle)
Chris@76: {
Chris@76: return sqlite_fetch_array($handle, SQLITE_NUM);
Chris@76: }
Chris@76:
Chris@76: // Unescape an escaped string!
Chris@76: function smf_db_unescape_string($string)
Chris@76: {
Chris@76: return strtr($string, array('\'\'' => '\''));
Chris@76: }
Chris@76:
Chris@76: // This function tries to work out additional error information from a back trace.
Chris@76: function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
Chris@76: {
Chris@76: if (empty($log_message))
Chris@76: $log_message = $error_message;
Chris@76:
Chris@76: if (function_exists('debug_backtrace'))
Chris@76: {
Chris@76: foreach (debug_backtrace() as $step)
Chris@76: {
Chris@76: // Found it?
Chris@76: if (strpos($step['function'], 'query') === false && !in_array(substr($step['function'], 0, 7), array('smf_db_', 'preg_re', 'db_erro', 'call_us')) && substr($step['function'], 0, 2) != '__')
Chris@76: {
Chris@76: $log_message .= '
Function: ' . $step['function'];
Chris@76: break;
Chris@76: }
Chris@76:
Chris@76: if (isset($step['line']))
Chris@76: {
Chris@76: $file = $step['file'];
Chris@76: $line = $step['line'];
Chris@76: }
Chris@76: }
Chris@76: }
Chris@76:
Chris@76: // A special case - we want the file and line numbers for debugging.
Chris@76: if ($error_type == 'return')
Chris@76: return array($file, $line);
Chris@76:
Chris@76: // Is always a critical error.
Chris@76: if (function_exists('log_error'))
Chris@76: log_error($log_message, 'critical', $file, $line);
Chris@76:
Chris@76: if (function_exists('fatal_error'))
Chris@76: {
Chris@76: fatal_error($error_message, $error_type);
Chris@76:
Chris@76: // Cannot continue...
Chris@76: exit;
Chris@76: }
Chris@76: elseif ($error_type)
Chris@76: trigger_error($error_message . ($line !== null ? '(' . basename($file) . '-' . $line . ')' : ''), $error_type);
Chris@76: else
Chris@76: trigger_error($error_message . ($line !== null ? '(' . basename($file) . '-' . $line . ')' : ''));
Chris@76: }
Chris@76:
Chris@76: // Emulate UNIX_TIMESTAMP.
Chris@76: function smf_udf_unix_timestamp()
Chris@76: {
Chris@76: return strftime('%s', 'now');
Chris@76: }
Chris@76:
Chris@76: // Emulate INET_ATON.
Chris@76: function smf_udf_inet_aton($ip)
Chris@76: {
Chris@76: $chunks = explode('.', $ip);
Chris@76: return @$chunks[0] * pow(256, 3) + @$chunks[1] * pow(256, 2) + @$chunks[2] * 256 + @$chunks[3];
Chris@76: }
Chris@76:
Chris@76: // Emulate INET_NTOA.
Chris@76: function smf_udf_inet_ntoa($n)
Chris@76: {
Chris@76: $t = array(0, 0, 0, 0);
Chris@76: $msk = 16777216.0;
Chris@76: $n += 0.0;
Chris@76: if ($n < 1)
Chris@76: return '0.0.0.0';
Chris@76:
Chris@76: for ($i = 0; $i < 4; $i++)
Chris@76: {
Chris@76: $k = (int) ($n / $msk);
Chris@76: $n -= $msk * $k;
Chris@76: $t[$i] = $k;
Chris@76: $msk /= 256.0;
Chris@76: };
Chris@76:
Chris@76: $a = join('.', $t);
Chris@76: return $a;
Chris@76: }
Chris@76:
Chris@76: // Emulate FIND_IN_SET.
Chris@76: function smf_udf_find_in_set($find, $groups)
Chris@76: {
Chris@76: foreach (explode(',', $groups) as $key => $group)
Chris@76: {
Chris@76: if ($group == $find)
Chris@76: return $key + 1;
Chris@76: }
Chris@76:
Chris@76: return 0;
Chris@76: }
Chris@76:
Chris@76: // Emulate YEAR.
Chris@76: function smf_udf_year($date)
Chris@76: {
Chris@76: return substr($date, 0, 4);
Chris@76: }
Chris@76:
Chris@76: // Emulate MONTH.
Chris@76: function smf_udf_month($date)
Chris@76: {
Chris@76: return substr($date, 5, 2);
Chris@76: }
Chris@76:
Chris@76: // Emulate DAYOFMONTH.
Chris@76: function smf_udf_dayofmonth($date)
Chris@76: {
Chris@76: return substr($date, 8, 2);
Chris@76: }
Chris@76:
Chris@76: // We need this since sqlite_libversion() doesn't take any parameters.
Chris@76: function smf_db_libversion($void = null)
Chris@76: {
Chris@76: return sqlite_libversion();
Chris@76: }
Chris@76:
Chris@76: // This function uses variable argument lists so that it can handle more then two parameters.
Chris@76: // Emulates the CONCAT function.
Chris@76: function smf_udf_concat()
Chris@76: {
Chris@76: // Since we didn't specify any arguments we must get them from PHP.
Chris@76: $args = func_get_args();
Chris@76:
Chris@76: // It really doesn't matter if there were 0 to 100 arguments, just slap them all together.
Chris@76: return implode('', $args);
Chris@76: }
Chris@76:
Chris@76: // We need to use PHP to locate the position in the string.
Chris@76: function smf_udf_locate($find, $string)
Chris@76: {
Chris@76: return strpos($string, $find);
Chris@76: }
Chris@76:
Chris@76: // This is used to replace RLIKE.
Chris@76: function smf_udf_regexp($exp, $search)
Chris@76: {
Chris@76: if (preg_match($exp, $match))
Chris@76: return 1;
Chris@76: return 0;
Chris@76: }
Chris@76:
Chris@76: // Escape the LIKE wildcards so that they match the character and not the wildcard.
Chris@76: // The optional second parameter turns human readable wildcards into SQL wildcards.
Chris@76: function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false)
Chris@76: {
Chris@76: $replacements = array(
Chris@76: '%' => '\%',
Chris@76: '\\' => '\\\\',
Chris@76: );
Chris@76:
Chris@76: if ($translate_human_wildcards)
Chris@76: $replacements += array(
Chris@76: '*' => '%',
Chris@76: );
Chris@76:
Chris@76: return strtr($string, $replacements);
Chris@76: }
Chris@76: ?>