Subs-Db-postgresql.php 25 KB

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