Subs-Db-postgresql.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file has all the main functions in it that relate to the database.
  15. smf_db_initiate() maps the implementations in this file (smf_db_function_name)
  16. to the $smcFunc['db_function_name'] variable.
  17. */
  18. // Initialize the database settings
  19. function smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, &$db_prefix, $db_options = array())
  20. {
  21. global $smcFunc, $mysql_set_mode;
  22. // Map some database specific functions, only do this once.
  23. if (!isset($smcFunc['db_fetch_assoc']) || $smcFunc['db_fetch_assoc'] != 'postg_fetch_assoc')
  24. $smcFunc += array(
  25. 'db_query' => 'smf_db_query',
  26. 'db_quote' => 'smf_db_quote',
  27. 'db_insert' => 'smf_db_insert',
  28. 'db_insert_id' => 'smf_db_insert_id',
  29. 'db_fetch_assoc' => 'smf_db_fetch_assoc',
  30. 'db_fetch_row' => 'smf_db_fetch_row',
  31. 'db_free_result' => 'pg_free_result',
  32. 'db_num_rows' => 'pg_num_rows',
  33. 'db_data_seek' => 'smf_db_data_seek',
  34. 'db_num_fields' => 'pg_num_fields',
  35. 'db_escape_string' => 'pg_escape_string',
  36. 'db_unescape_string' => 'smf_db_unescape_string',
  37. 'db_server_info' => 'smf_db_version',
  38. 'db_affected_rows' => 'smf_db_affected_rows',
  39. 'db_transaction' => 'smf_db_transaction',
  40. 'db_error' => 'pg_last_error',
  41. 'db_select_db' => 'smf_db_select_db',
  42. 'db_title' => 'PostgreSQL',
  43. 'db_sybase' => true,
  44. 'db_case_sensitive' => true,
  45. 'db_escape_wildcard_string' => 'smf_db_escape_wildcard_string',
  46. );
  47. if (!empty($db_options['persist']))
  48. $connection = @pg_pconnect('host=' . $db_server . ' dbname=' . $db_name . ' user=\'' . $db_user . '\' password=\'' . $db_passwd . '\'');
  49. else
  50. $connection = @pg_connect( 'host=' . $db_server . ' dbname=' . $db_name . ' user=\'' . $db_user . '\' password=\'' . $db_passwd . '\'');
  51. // Something's wrong, show an error if its fatal (which we assume it is)
  52. if (!$connection)
  53. {
  54. if (!empty($db_options['non_fatal']))
  55. {
  56. return null;
  57. }
  58. else
  59. {
  60. db_fatal_error();
  61. }
  62. }
  63. return $connection;
  64. }
  65. // Extend the database functionality.
  66. function db_extend ($type = 'extra')
  67. {
  68. global $sourcedir, $db_type;
  69. require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-' . $db_type . '.php');
  70. $initFunc = 'db_' . $type . '_init';
  71. $initFunc();
  72. }
  73. // Do nothing on postgreSQL
  74. function db_fix_prefix (&$db_prefix, $db_name)
  75. {
  76. return;
  77. }
  78. function smf_db_replacement__callback($matches)
  79. {
  80. global $db_callback, $user_info, $db_prefix;
  81. list ($values, $connection) = $db_callback;
  82. if ($matches[1] === 'db_prefix')
  83. return $db_prefix;
  84. if ($matches[1] === 'query_see_board')
  85. return $user_info['query_see_board'];
  86. if ($matches[1] === 'query_wanna_see_board')
  87. return $user_info['query_wanna_see_board'];
  88. if (!isset($matches[2]))
  89. smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
  90. if (!isset($values[$matches[2]]))
  91. smf_db_error_backtrace('The database value you\'re trying to insert does not exist: ' . htmlspecialchars($matches[2]), '', E_USER_ERROR, __FILE__, __LINE__);
  92. $replacement = $values[$matches[2]];
  93. switch ($matches[1])
  94. {
  95. case 'int':
  96. if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
  97. smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  98. return (string) (int) $replacement;
  99. break;
  100. case 'string':
  101. case 'text':
  102. return sprintf('\'%1$s\'', pg_escape_string($replacement));
  103. break;
  104. case 'array_int':
  105. if (is_array($replacement))
  106. {
  107. if (empty($replacement))
  108. smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  109. foreach ($replacement as $key => $value)
  110. {
  111. if (!is_numeric($value) || (string) $value !== (string) (int) $value)
  112. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  113. $replacement[$key] = (string) (int) $value;
  114. }
  115. return implode(', ', $replacement);
  116. }
  117. else
  118. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  119. break;
  120. case 'array_string':
  121. if (is_array($replacement))
  122. {
  123. if (empty($replacement))
  124. smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  125. foreach ($replacement as $key => $value)
  126. $replacement[$key] = sprintf('\'%1$s\'', pg_escape_string($value));
  127. return implode(', ', $replacement);
  128. }
  129. else
  130. smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  131. break;
  132. case 'date':
  133. if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
  134. return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]);
  135. else
  136. smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  137. break;
  138. case 'float':
  139. if (!is_numeric($replacement))
  140. smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  141. return (string) (float) $replacement;
  142. break;
  143. case 'identifier':
  144. return '`' . strtr($replacement, array('`' => '', '.' => '')) . '`';
  145. break;
  146. case 'raw':
  147. return $replacement;
  148. break;
  149. default:
  150. smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
  151. break;
  152. }
  153. }
  154. // Just like the db_query, escape and quote a string, but not executing the query.
  155. function smf_db_quote($db_string, $db_values, $connection = null)
  156. {
  157. global $db_callback, $db_connection;
  158. // Only bother if there's something to replace.
  159. if (strpos($db_string, '{') !== false)
  160. {
  161. // This is needed by the callback function.
  162. $db_callback = array($db_values, $connection == null ? $db_connection : $connection);
  163. // Do the quoting and escaping
  164. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  165. // Clear this global variable.
  166. $db_callback = array();
  167. }
  168. return $db_string;
  169. }
  170. // Do a query. Takes care of errors too.
  171. function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
  172. {
  173. global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start;
  174. global $db_unbuffered, $db_callback, $db_last_result, $db_replace_result, $modSettings;
  175. // Decide which connection to use.
  176. $connection = $connection == null ? $db_connection : $connection;
  177. // Special queries that need processing.
  178. $replacements = array(
  179. 'alter_table_boards' => array(
  180. '~(.+)~' => '',
  181. ),
  182. 'alter_table_icons' => array(
  183. '~(.+)~' => '',
  184. ),
  185. 'alter_table_smileys' => array(
  186. '~(.+)~' => '',
  187. ),
  188. 'alter_table_spiders' => array(
  189. '~(.+)~' => '',
  190. ),
  191. 'ban_suggest_error_ips' => array(
  192. '~RLIKE~' => '~',
  193. '~\\.~' => '\.',
  194. ),
  195. 'ban_suggest_message_ips' => array(
  196. '~RLIKE~' => '~',
  197. '~\\.~' => '\.',
  198. ),
  199. 'consolidate_spider_stats' => array(
  200. '~MONTH\(log_time\), DAYOFMONTH\(log_time\)~' => 'MONTH(CAST(CAST(log_time AS abstime) AS timestamp)), DAYOFMONTH(CAST(CAST(log_time AS abstime) AS timestamp))',
  201. ),
  202. 'delete_subscription' => array(
  203. '~LIMIT 1~' => '',
  204. ),
  205. 'display_get_post_poster' => array(
  206. '~GROUP BY id_msg\s+HAVING~' => 'AND',
  207. ),
  208. 'attach_download_increase' => array(
  209. '~LOW_PRIORITY~' => '',
  210. ),
  211. 'boardindex_fetch_boards' => array(
  212. '~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',
  213. '~(.)$~' => '$1 ORDER BY b.board_order',
  214. ),
  215. 'get_random_number' => array(
  216. '~RAND~' => 'RANDOM',
  217. ),
  218. 'insert_log_search_topics' => array(
  219. '~NOT RLIKE~' => '!~',
  220. ),
  221. 'insert_log_search_results_no_index' => array(
  222. '~NOT RLIKE~' => '!~',
  223. ),
  224. 'insert_log_search_results_subject' => array(
  225. '~NOT RLIKE~' => '!~',
  226. ),
  227. 'messageindex_fetch_boards' => array(
  228. '~(.)$~' => '$1 ORDER BY b.board_order',
  229. ),
  230. 'select_message_icons' => array(
  231. '~(.)$~' => '$1 ORDER BY icon_order',
  232. ),
  233. 'set_character_set' => array(
  234. '~SET\\s+NAMES\\s([a-zA-Z0-9\\-_]+)~' => 'SET NAMES \'$1\'',
  235. ),
  236. 'pm_conversation_list' => array(
  237. '~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']) : ''),
  238. ),
  239. 'top_topic_starters' => array(
  240. '~ORDER BY FIND_IN_SET\(id_member,(.+?)\)~' => 'ORDER BY STRPOS(\',\' || $1 || \',\', \',\' || id_member|| \',\')',
  241. ),
  242. 'order_by_board_order' => array(
  243. '~(.)$~' => '$1 ORDER BY b.board_order',
  244. ),
  245. 'spider_check' => array(
  246. '~(.)$~' => '$1 ORDER BY LENGTH(user_agent) DESC',
  247. ),
  248. 'unread_replies' => array(
  249. '~SELECT\\s+DISTINCT\\s+t.id_topic~' => 'SELECT t.id_topic, {raw:sort}',
  250. ),
  251. 'profile_board_stats' => array(
  252. '~COUNT\(\*\) \/ MAX\(b.num_posts\)~' => 'CAST(COUNT(*) AS DECIMAL) / CAST(b.num_posts AS DECIMAL)',
  253. ),
  254. 'set_smiley_order' => array(
  255. '~(.+)~' => '',
  256. ),
  257. );
  258. if (isset($replacements[$identifier]))
  259. $db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
  260. // Limits need to be a little different.
  261. $db_string = preg_replace('~\sLIMIT\s(\d+|{int:.+}),\s*(\d+|{int:.+})\s*$~i', 'LIMIT $2 OFFSET $1', $db_string);
  262. if (trim($db_string) == '')
  263. return false;
  264. // Comments that are allowed in a query are preg_removed.
  265. static $allowed_comments_from = array(
  266. '~\s+~s',
  267. '~/\*!40001 SQL_NO_CACHE \*/~',
  268. '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
  269. '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
  270. );
  271. static $allowed_comments_to = array(
  272. ' ',
  273. '',
  274. '',
  275. '',
  276. );
  277. // One more query....
  278. $db_count = !isset($db_count) ? 1 : $db_count + 1;
  279. $db_replace_result = 0;
  280. if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
  281. smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
  282. if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
  283. {
  284. // Pass some values to the global space for use in the callback function.
  285. $db_callback = array($db_values, $connection);
  286. // Inject the values passed to this function.
  287. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  288. // This shouldn't be residing in global space any longer.
  289. $db_callback = array();
  290. }
  291. // Debugging.
  292. if (isset($db_show_debug) && $db_show_debug === true)
  293. {
  294. // Get the file and line number this function was called.
  295. list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
  296. // Initialize $db_cache if not already initialized.
  297. if (!isset($db_cache))
  298. $db_cache = array();
  299. if (!empty($_SESSION['debug_redirect']))
  300. {
  301. $db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
  302. $db_count = count($db_cache) + 1;
  303. $_SESSION['debug_redirect'] = array();
  304. }
  305. $st = microtime();
  306. // Don't overload it.
  307. $db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
  308. $db_cache[$db_count]['f'] = $file;
  309. $db_cache[$db_count]['l'] = $line;
  310. $db_cache[$db_count]['s'] = array_sum(explode(' ', $st)) - array_sum(explode(' ', $time_start));
  311. }
  312. // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
  313. if (empty($modSettings['disableQueryCheck']))
  314. {
  315. $clean = '';
  316. $old_pos = 0;
  317. $pos = -1;
  318. while (true)
  319. {
  320. $pos = strpos($db_string, '\'', $pos + 1);
  321. if ($pos === false)
  322. break;
  323. $clean .= substr($db_string, $old_pos, $pos - $old_pos);
  324. while (true)
  325. {
  326. $pos1 = strpos($db_string, '\'', $pos + 1);
  327. $pos2 = strpos($db_string, '\\', $pos + 1);
  328. if ($pos1 === false)
  329. break;
  330. elseif ($pos2 == false || $pos2 > $pos1)
  331. {
  332. $pos = $pos1;
  333. break;
  334. }
  335. $pos = $pos2 + 1;
  336. }
  337. $clean .= ' %s ';
  338. $old_pos = $pos + 1;
  339. }
  340. $clean .= substr($db_string, $old_pos);
  341. $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
  342. // We don't use UNION in SMF, at least so far. But it's useful for injections.
  343. if (strpos($clean, 'union') !== false && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0)
  344. $fail = true;
  345. // Comments? We don't use comments in our queries, we leave 'em outside!
  346. elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
  347. $fail = true;
  348. // Trying to change passwords, slow us down, or something?
  349. elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
  350. $fail = true;
  351. elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
  352. $fail = true;
  353. // Sub selects? We don't use those either.
  354. elseif (preg_match('~\([^)]*?select~s', $clean) != 0)
  355. $fail = true;
  356. if (!empty($fail) && function_exists('log_error'))
  357. smf_db_error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
  358. }
  359. $db_last_result = @pg_query($connection, $db_string);
  360. if ($db_last_result === false && empty($db_values['db_error_skip']))
  361. $db_last_result = smf_db_error($db_string, $connection);
  362. // Debugging.
  363. if (isset($db_show_debug) && $db_show_debug === true)
  364. $db_cache[$db_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
  365. return $db_last_result;
  366. }
  367. function smf_db_affected_rows($result = null)
  368. {
  369. global $db_last_result, $db_replace_result;
  370. if ($db_replace_result)
  371. return $db_replace_result;
  372. elseif ($result == null && !$db_last_result)
  373. return 0;
  374. return pg_affected_rows($result == null ? $db_last_result : $result);
  375. }
  376. function smf_db_insert_id($table, $field = null, $connection = null)
  377. {
  378. global $db_connection, $smcFunc, $db_prefix;
  379. $table = str_replace('{db_prefix}', $db_prefix, $table);
  380. if ($connection === false)
  381. $connection = $db_connection;
  382. // Try get the last ID for the auto increment field.
  383. $request = $smcFunc['db_query']('', 'SELECT CURRVAL(\'' . $table . '_seq\') AS insertID',
  384. array(
  385. )
  386. );
  387. if (!$request)
  388. return false;
  389. list ($lastID) = $smcFunc['db_fetch_row']($request);
  390. $smcFunc['db_free_result']($request);
  391. return $lastID;
  392. }
  393. // Do a transaction.
  394. function smf_db_transaction($type = 'commit', $connection = null)
  395. {
  396. global $db_connection;
  397. // Decide which connection to use
  398. $connection = $connection == null ? $db_connection : $connection;
  399. if ($type == 'begin')
  400. return @pg_query($connection, 'BEGIN');
  401. elseif ($type == 'rollback')
  402. return @pg_query($connection, 'ROLLBACK');
  403. elseif ($type == 'commit')
  404. return @pg_query($connection, 'COMMIT');
  405. return false;
  406. }
  407. // Database error!
  408. function smf_db_error($db_string, $connection = null)
  409. {
  410. global $txt, $context, $sourcedir, $webmaster_email, $modSettings;
  411. global $forum_version, $db_connection, $db_last_error, $db_persist;
  412. global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd;
  413. global $smcFunc;
  414. // We'll try recovering the file and line number the original db query was called from.
  415. list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
  416. // Decide which connection to use
  417. $connection = $connection == null ? $db_connection : $connection;
  418. // This is the error message...
  419. $query_error = @pg_last_error($connection);
  420. // Log the error.
  421. if (function_exists('log_error'))
  422. log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n" .$db_string : ''), 'database', $file, $line);
  423. // Nothing's defined yet... just die with it.
  424. if (empty($context) || empty($txt))
  425. die($query_error);
  426. // Show an error message, if possible.
  427. $context['error_title'] = $txt['database_error'];
  428. if (allowedTo('admin_forum'))
  429. $context['error_message'] = nl2br($query_error) . '<br />' . $txt['file'] . ': ' . $file . '<br />' . $txt['line'] . ': ' . $line;
  430. else
  431. $context['error_message'] = $txt['try_again'];
  432. // 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!)
  433. if (allowedTo('admin_forum') && !empty($forum_version) && $forum_version != 'SMF ' . @$modSettings['smfVersion'] && strpos($forum_version, 'Demo') === false && strpos($forum_version, 'CVS') === false)
  434. $context['error_message'] .= '<br /><br />' . sprintf($txt['database_error_versions'], $forum_version, $modSettings['smfVersion']);
  435. if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
  436. {
  437. $context['error_message'] .= '<br /><br />' . nl2br($db_string);
  438. }
  439. // It's already been logged... don't log it again.
  440. fatal_error($context['error_message'], false);
  441. }
  442. // A PostgreSQL specific function for tracking the current row...
  443. function smf_db_fetch_row($request, $counter = false)
  444. {
  445. global $db_row_count;
  446. if ($counter !== false)
  447. return pg_fetch_row($request, $counter);
  448. // Reset the row counter...
  449. if (!isset($db_row_count[(int) $request]))
  450. $db_row_count[(int) $request] = 0;
  451. // Return the right row.
  452. return @pg_fetch_row($request, $db_row_count[(int) $request]++);
  453. }
  454. // Get an associative array
  455. function smf_db_fetch_assoc($request, $counter = false)
  456. {
  457. global $db_row_count;
  458. if ($counter !== false)
  459. return pg_fetch_assoc($request, $counter);
  460. // Reset the row counter...
  461. if (!isset($db_row_count[(int) $request]))
  462. $db_row_count[(int) $request] = 0;
  463. // Return the right row.
  464. return @pg_fetch_assoc($request, $db_row_count[(int) $request]++);
  465. }
  466. // Reset the pointer...
  467. function smf_db_data_seek($request, $counter)
  468. {
  469. global $db_row_count;
  470. $db_row_count[(int) $request] = $counter;
  471. return true;
  472. }
  473. // Unescape an escaped string!
  474. function smf_db_unescape_string($string)
  475. {
  476. return strtr($string, array('\'\'' => '\''));
  477. }
  478. // For inserting data in a special way...
  479. function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null)
  480. {
  481. global $db_replace_result, $db_in_transact, $smcFunc, $db_connection, $db_prefix;
  482. $connection = $connection === null ? $db_connection : $connection;
  483. if (empty($data))
  484. return;
  485. if (!is_array($data[array_rand($data)]))
  486. $data = array($data);
  487. // Replace the prefix holder with the actual prefix.
  488. $table = str_replace('{db_prefix}', $db_prefix, $table);
  489. $priv_trans = false;
  490. if ((count($data) > 1 || $method == 'replace') && !$db_in_transact && !$disable_trans)
  491. {
  492. $smcFunc['db_transaction']('begin', $connection);
  493. $priv_trans = true;
  494. }
  495. // PostgreSQL doesn't support replace: we implement a MySQL-compatible behavior instead
  496. if ($method == 'replace')
  497. {
  498. $count = 0;
  499. $where = '';
  500. foreach ($columns as $columnName => $type)
  501. {
  502. // Are we restricting the length?
  503. if (strpos($type, 'string-') !== false)
  504. $actualType = sprintf($columnName . ' = SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $count);
  505. else
  506. $actualType = sprintf($columnName . ' = {%1$s:%2$s}, ', $type, $count);
  507. // A key? That's what we were looking for.
  508. if (in_array($columnName, $keys))
  509. $where .= (empty($where) ? '' : ' AND ') . substr($actualType, 0, -2);
  510. $count++;
  511. }
  512. // Make it so.
  513. if (!empty($where) && !empty($data))
  514. {
  515. foreach ($data as $k => $entry)
  516. {
  517. $smcFunc['db_query']('', '
  518. DELETE FROM ' . $table .
  519. ' WHERE ' . $where,
  520. $entry, $connection
  521. );
  522. }
  523. }
  524. }
  525. if (!empty($data))
  526. {
  527. // Create the mold for a single row insert.
  528. $insertData = '(';
  529. foreach ($columns as $columnName => $type)
  530. {
  531. // Are we restricting the length?
  532. if (strpos($type, 'string-') !== false)
  533. $insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
  534. else
  535. $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
  536. }
  537. $insertData = substr($insertData, 0, -2) . ')';
  538. // Create an array consisting of only the columns.
  539. $indexed_columns = array_keys($columns);
  540. // Here's where the variables are injected to the query.
  541. $insertRows = array();
  542. foreach ($data as $dataRow)
  543. $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
  544. foreach ($insertRows as $entry)
  545. // Do the insert.
  546. $smcFunc['db_query']('', '
  547. INSERT INTO ' . $table . '("' . implode('", "', $indexed_columns) . '")
  548. VALUES
  549. ' . $entry,
  550. array(
  551. 'security_override' => true,
  552. 'db_error_skip' => $method == 'ignore' || $table === $db_prefix . 'log_errors',
  553. ),
  554. $connection
  555. );
  556. }
  557. if ($priv_trans)
  558. $smcFunc['db_transaction']('commit', $connection);
  559. }
  560. // Dummy function really.
  561. function smf_db_select_db($db_name, $db_connection)
  562. {
  563. return true;
  564. }
  565. // Get the current version.
  566. function smf_db_version()
  567. {
  568. $version = pg_version();
  569. return $version['client'];
  570. }
  571. // This function tries to work out additional error information from a back trace.
  572. function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
  573. {
  574. if (empty($log_message))
  575. $log_message = $error_message;
  576. if (function_exists('debug_backtrace'))
  577. {
  578. foreach (debug_backtrace() as $step)
  579. {
  580. // Found it?
  581. 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) != '__')
  582. {
  583. $log_message .= '<br />Function: ' . $step['function'];
  584. break;
  585. }
  586. if (isset($step['line']))
  587. {
  588. $file = $step['file'];
  589. $line = $step['line'];
  590. }
  591. }
  592. }
  593. // A special case - we want the file and line numbers for debugging.
  594. if ($error_type == 'return')
  595. return array($file, $line);
  596. // Is always a critical error.
  597. if (function_exists('log_error'))
  598. log_error($log_message, 'critical', $file, $line);
  599. if (function_exists('fatal_error'))
  600. {
  601. fatal_error($error_message, $error_type);
  602. // Cannot continue...
  603. exit;
  604. }
  605. elseif ($error_type)
  606. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type);
  607. else
  608. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
  609. }
  610. // Escape the LIKE wildcards so that they match the character and not the wildcard.
  611. // The optional second parameter turns human readable wildcards into SQL wildcards.
  612. function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false)
  613. {
  614. $replacements = array(
  615. '%' => '\%',
  616. '_' => '\_',
  617. '\\' => '\\\\',
  618. );
  619. if ($translate_human_wildcards)
  620. $replacements += array(
  621. '*' => '%',
  622. );
  623. return strtr($string, $replacements);
  624. }
  625. ?>