Subs-Db-postgresql.php 25 KB

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