Chris@76: 'smf_db_query', Chris@76: 'db_quote' => 'smf_db_quote', Chris@76: 'db_insert' => 'smf_db_insert', Chris@76: 'db_insert_id' => 'smf_db_insert_id', Chris@76: 'db_fetch_assoc' => 'smf_db_fetch_assoc', Chris@76: 'db_fetch_row' => 'smf_db_fetch_row', Chris@76: 'db_free_result' => 'pg_free_result', Chris@76: 'db_num_rows' => 'pg_num_rows', Chris@76: 'db_data_seek' => 'smf_db_data_seek', Chris@76: 'db_num_fields' => 'pg_num_fields', Chris@76: 'db_escape_string' => 'pg_escape_string', Chris@76: 'db_unescape_string' => 'smf_db_unescape_string', Chris@76: 'db_server_info' => 'smf_db_version', Chris@76: 'db_affected_rows' => 'smf_db_affected_rows', Chris@76: 'db_transaction' => 'smf_db_transaction', Chris@76: 'db_error' => 'pg_last_error', Chris@76: 'db_select_db' => 'smf_db_select_db', Chris@76: 'db_title' => 'PostgreSQL', 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 (!empty($db_options['persist'])) Chris@76: $connection = @pg_pconnect('host=' . $db_server . ' dbname=' . $db_name . ' user=\'' . $db_user . '\' password=\'' . $db_passwd . '\''); Chris@76: else Chris@76: $connection = @pg_connect( 'host=' . $db_server . ' dbname=' . $db_name . ' user=\'' . $db_user . '\' password=\'' . $db_passwd . '\''); 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: { Chris@76: return null; Chris@76: } Chris@76: else Chris@76: { Chris@76: db_fatal_error(); Chris@76: } Chris@76: } 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: // Do nothing on postgreSQL Chris@76: function db_fix_prefix (&$db_prefix, $db_name) Chris@76: { Chris@76: return; 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 (!is_resource($connection)) Chris@76: db_fatal_error(); 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\'', pg_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\'', pg_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, $db_last_result, $db_replace_result, $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: 'alter_table_boards' => array( Chris@76: '~(.+)~' => '', Chris@76: ), Chris@76: 'alter_table_icons' => array( Chris@76: '~(.+)~' => '', Chris@76: ), Chris@76: 'alter_table_smileys' => array( Chris@76: '~(.+)~' => '', Chris@76: ), Chris@76: 'alter_table_spiders' => array( Chris@76: '~(.+)~' => '', Chris@76: ), Chris@76: 'ban_suggest_error_ips' => array( Chris@76: '~RLIKE~' => '~', Chris@76: '~\\.~' => '\.', Chris@76: ), Chris@76: 'ban_suggest_message_ips' => array( Chris@76: '~RLIKE~' => '~', Chris@76: '~\\.~' => '\.', Chris@76: ), Chris@76: 'consolidate_spider_stats' => array( Chris@76: '~MONTH\(log_time\), DAYOFMONTH\(log_time\)~' => 'MONTH(CAST(CAST(log_time AS abstime) AS timestamp)), DAYOFMONTH(CAST(CAST(log_time AS abstime) AS timestamp))', Chris@76: ), Chris@76: 'delete_subscription' => array( Chris@76: '~LIMIT 1~' => '', Chris@76: ), Chris@76: 'display_get_post_poster' => array( Chris@76: '~GROUP BY id_msg\s+HAVING~' => 'AND', Chris@76: ), Chris@76: 'attach_download_increase' => array( Chris@76: '~LOW_PRIORITY~' => '', Chris@76: ), Chris@76: 'boardindex_fetch_boards' => array( Chris@76: '~IFNULL\(lb.id_msg, 0\) >= b.id_msg_updated~' => 'CASE WHEN IFNULL(lb.id_msg, 0) >= b.id_msg_updated THEN 1 ELSE 0 END', Chris@76: '~(.)$~' => '$1 ORDER BY b.board_order', Chris@76: ), Chris@76: 'get_random_number' => array( Chris@76: '~RAND~' => 'RANDOM', Chris@76: ), Chris@76: 'insert_log_search_topics' => array( Chris@76: '~NOT RLIKE~' => '!~', Chris@76: ), Chris@76: 'insert_log_search_results_no_index' => array( Chris@76: '~NOT RLIKE~' => '!~', Chris@76: ), Chris@76: 'insert_log_search_results_subject' => array( Chris@76: '~NOT RLIKE~' => '!~', Chris@76: ), Chris@76: 'messageindex_fetch_boards' => array( Chris@76: '~(.)$~' => '$1 ORDER BY b.board_order', Chris@76: ), Chris@76: 'select_message_icons' => array( Chris@76: '~(.)$~' => '$1 ORDER BY icon_order', Chris@76: ), Chris@76: 'set_character_set' => array( Chris@76: '~SET\\s+NAMES\\s([a-zA-Z0-9\\-_]+)~' => 'SET NAMES \'$1\'', Chris@76: ), Chris@76: 'pm_conversation_list' => array( Chris@76: '~ORDER\\s+BY\\s+\\{raw:sort\\}~' => 'ORDER BY ' . (isset($db_values['sort']) ? ($db_values['sort'] === 'pm.id_pm' ? 'MAX(pm.id_pm)' : $db_values['sort']) : ''), Chris@76: ), Chris@76: 'top_topic_starters' => array( Chris@76: '~ORDER BY FIND_IN_SET\(id_member,(.+?)\)~' => 'ORDER BY STRPOS(\',\' || $1 || \',\', \',\' || id_member|| \',\')', 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: 'unread_replies' => array( Chris@76: '~SELECT\\s+DISTINCT\\s+t.id_topic~' => 'SELECT t.id_topic, {raw:sort}', Chris@76: ), Chris@76: 'profile_board_stats' => array( Chris@76: '~COUNT\(\*\) \/ MAX\(b.num_posts\)~' => 'CAST(COUNT(*) AS DECIMAL) / CAST(b.num_posts AS DECIMAL)', Chris@76: ), Chris@76: 'set_smiley_order' => array( Chris@76: '~(.+)~' => '', 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: // Limits need to be a little different. Chris@76: $db_string = preg_replace('~\sLIMIT\s(\d+|{int:.+}),\s*(\d+|{int:.+})\s*$~i', 'LIMIT $2 OFFSET $1', $db_string); Chris@76: Chris@76: if (trim($db_string) == '') Chris@76: return false; Chris@76: Chris@76: // Comments that are allowed in a query are preg_removed. Chris@76: static $allowed_comments_from = array( Chris@76: '~\s+~s', Chris@76: '~/\*!40001 SQL_NO_CACHE \*/~', Chris@76: '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~', Chris@76: '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~', Chris@76: ); Chris@76: static $allowed_comments_to = array( Chris@76: ' ', Chris@76: '', Chris@76: '', Chris@76: '', Chris@76: ); Chris@76: Chris@76: // One more query.... Chris@76: $db_count = !isset($db_count) ? 1 : $db_count + 1; Chris@76: $db_replace_result = 0; 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: // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over. Chris@76: if (empty($modSettings['disableQueryCheck'])) Chris@76: { Chris@76: $clean = ''; Chris@76: $old_pos = 0; Chris@76: $pos = -1; Chris@76: while (true) Chris@76: { Chris@76: $pos = strpos($db_string, '\'', $pos + 1); Chris@76: if ($pos === false) Chris@76: break; Chris@76: $clean .= substr($db_string, $old_pos, $pos - $old_pos); Chris@76: Chris@76: while (true) Chris@76: { Chris@76: $pos1 = strpos($db_string, '\'', $pos + 1); Chris@76: $pos2 = strpos($db_string, '\\', $pos + 1); Chris@76: if ($pos1 === false) Chris@76: break; Chris@76: elseif ($pos2 == false || $pos2 > $pos1) Chris@76: { Chris@76: $pos = $pos1; Chris@76: break; Chris@76: } Chris@76: Chris@76: $pos = $pos2 + 1; Chris@76: } Chris@76: $clean .= ' %s '; Chris@76: Chris@76: $old_pos = $pos + 1; Chris@76: } Chris@76: $clean .= substr($db_string, $old_pos); Chris@76: $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean))); Chris@76: Chris@76: // We don't use UNION in SMF, at least so far. But it's useful for injections. Chris@76: if (strpos($clean, 'union') !== false && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0) Chris@76: $fail = true; Chris@76: // Comments? We don't use comments in our queries, we leave 'em outside! Chris@76: elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false) Chris@76: $fail = true; Chris@76: // Trying to change passwords, slow us down, or something? Chris@76: elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0) Chris@76: $fail = true; Chris@76: elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) Chris@76: $fail = true; Chris@76: // Sub selects? We don't use those either. Chris@76: elseif (preg_match('~\([^)]*?select~s', $clean) != 0) Chris@76: $fail = true; Chris@76: Chris@76: if (!empty($fail) && function_exists('log_error')) Chris@76: smf_db_error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__); Chris@76: } Chris@76: Chris@76: $db_last_result = @pg_query($connection, $db_string); Chris@76: Chris@76: if ($db_last_result === false && empty($db_values['db_error_skip'])) Chris@76: $db_last_result = smf_db_error($db_string, $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 $db_last_result; Chris@76: } Chris@76: Chris@76: function smf_db_affected_rows($result = null) Chris@76: { Chris@76: global $db_last_result, $db_replace_result; Chris@76: Chris@76: if ($db_replace_result) Chris@76: return $db_replace_result; Chris@76: elseif ($result == null && !$db_last_result) Chris@76: return 0; Chris@76: Chris@76: return pg_affected_rows($result == null ? $db_last_result : $result); Chris@76: } Chris@76: Chris@76: function smf_db_insert_id($table, $field = null, $connection = null) Chris@76: { Chris@76: global $db_connection, $smcFunc, $db_prefix; Chris@76: Chris@76: $table = str_replace('{db_prefix}', $db_prefix, $table); Chris@76: Chris@76: if ($connection === false) Chris@76: $connection = $db_connection; Chris@76: Chris@76: // Try get the last ID for the auto increment field. Chris@76: $request = $smcFunc['db_query']('', 'SELECT CURRVAL(\'' . $table . '_seq\') AS insertID', Chris@76: array( Chris@76: ) Chris@76: ); Chris@76: if (!$request) Chris@76: return false; Chris@76: list ($lastID) = $smcFunc['db_fetch_row']($request); Chris@76: $smcFunc['db_free_result']($request); Chris@76: Chris@76: return $lastID; 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; 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: return @pg_query($connection, 'BEGIN'); Chris@76: elseif ($type == 'rollback') Chris@76: return @pg_query($connection, 'ROLLBACK'); Chris@76: elseif ($type == 'commit') Chris@76: return @pg_query($connection, 'COMMIT'); 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_error = @pg_last_error($connection); 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: // 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: // A PostgreSQL specific function for tracking the current row... Chris@76: function smf_db_fetch_row($request, $counter = false) Chris@76: { Chris@76: global $db_row_count; Chris@76: Chris@76: if ($counter !== false) Chris@76: return pg_fetch_row($request, $counter); Chris@76: Chris@76: // Reset the row counter... Chris@76: if (!isset($db_row_count[(int) $request])) Chris@76: $db_row_count[(int) $request] = 0; Chris@76: Chris@76: // Return the right row. Chris@76: return @pg_fetch_row($request, $db_row_count[(int) $request]++); Chris@76: } Chris@76: Chris@76: // Get an associative array Chris@76: function smf_db_fetch_assoc($request, $counter = false) Chris@76: { Chris@76: global $db_row_count; Chris@76: Chris@76: if ($counter !== false) Chris@76: return pg_fetch_assoc($request, $counter); Chris@76: Chris@76: // Reset the row counter... Chris@76: if (!isset($db_row_count[(int) $request])) Chris@76: $db_row_count[(int) $request] = 0; Chris@76: Chris@76: // Return the right row. Chris@76: return @pg_fetch_assoc($request, $db_row_count[(int) $request]++); Chris@76: } Chris@76: Chris@76: // Reset the pointer... Chris@76: function smf_db_data_seek($request, $counter) Chris@76: { Chris@76: global $db_row_count; Chris@76: Chris@76: $db_row_count[(int) $request] = $counter; Chris@76: Chris@76: return true; 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: // For inserting data in a special way... Chris@76: function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null) Chris@76: { Chris@76: global $db_replace_result, $db_in_transact, $smcFunc, $db_connection, $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 || $method == 'replace') && !$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: // PostgreSQL doesn't support replace: we implement a MySQL-compatible behavior instead Chris@76: if ($method == 'replace') Chris@76: { Chris@76: $count = 0; Chris@76: $where = ''; 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: $actualType = sprintf($columnName . ' = SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $count); Chris@76: else Chris@76: $actualType = sprintf($columnName . ' = {%1$s:%2$s}, ', $type, $count); Chris@76: Chris@76: // A key? That's what we were looking for. Chris@76: if (in_array($columnName, $keys)) Chris@76: $where .= (empty($where) ? '' : ' AND ') . substr($actualType, 0, -2); Chris@76: $count++; Chris@76: } Chris@76: Chris@76: // Make it so. Chris@76: if (!empty($where) && !empty($data)) Chris@76: { Chris@76: foreach ($data as $k => $entry) Chris@76: { Chris@76: $smcFunc['db_query']('', ' Chris@76: DELETE FROM ' . $table . Chris@76: ' WHERE ' . $where, Chris@76: $entry, $connection Chris@76: ); Chris@76: } Chris@76: } 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('SUBSTRING({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: INSERT INTO ' . $table . '("' . implode('", "', $indexed_columns) . '") Chris@76: VALUES Chris@76: ' . $entry, Chris@76: array( Chris@76: 'security_override' => true, Chris@76: 'db_error_skip' => $method == 'ignore' || $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: // Dummy function really. Chris@76: function smf_db_select_db($db_name, $db_connection) Chris@76: { Chris@76: return true; Chris@76: } Chris@76: Chris@76: // Get the current version. Chris@76: function smf_db_version() Chris@76: { Chris@76: $version = pg_version(); Chris@76: Chris@76: return $version['client']; 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: // 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: 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: Chris@76: ?>