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