Subs-Db-postgresql.php 25 KB

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