PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/sources/database/Db-postgresql.subs.php

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