Mercurial > hg > vamp-website
comparison forum/Sources/Subs-Db-mysql.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'] != 'mysql_fetch_assoc') | |
31 $smcFunc += array( | |
32 'db_query' => 'smf_db_query', | |
33 'db_quote' => 'smf_db_quote', | |
34 'db_fetch_assoc' => 'mysql_fetch_assoc', | |
35 'db_fetch_row' => 'mysql_fetch_row', | |
36 'db_free_result' => 'mysql_free_result', | |
37 'db_insert' => 'smf_db_insert', | |
38 'db_insert_id' => 'smf_db_insert_id', | |
39 'db_num_rows' => 'mysql_num_rows', | |
40 'db_data_seek' => 'mysql_data_seek', | |
41 'db_num_fields' => 'mysql_num_fields', | |
42 'db_escape_string' => 'addslashes', | |
43 'db_unescape_string' => 'stripslashes', | |
44 'db_server_info' => 'mysql_get_server_info', | |
45 'db_affected_rows' => 'smf_db_affected_rows', | |
46 'db_transaction' => 'smf_db_transaction', | |
47 'db_error' => 'mysql_error', | |
48 'db_select_db' => 'mysql_select_db', | |
49 'db_title' => 'MySQL', | |
50 'db_sybase' => false, | |
51 'db_case_sensitive' => false, | |
52 'db_escape_wildcard_string' => 'smf_db_escape_wildcard_string', | |
53 ); | |
54 | |
55 if (!empty($db_options['persist'])) | |
56 $connection = @mysql_pconnect($db_server, $db_user, $db_passwd); | |
57 else | |
58 $connection = @mysql_connect($db_server, $db_user, $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 return null; | |
65 else | |
66 db_fatal_error(); | |
67 } | |
68 | |
69 // Select the database, unless told not to | |
70 if (empty($db_options['dont_select_db']) && !@mysql_select_db($db_name, $connection) && empty($db_options['non_fatal'])) | |
71 db_fatal_error(); | |
72 | |
73 // This makes it possible to have SMF automatically change the sql_mode and autocommit if needed. | |
74 if (isset($mysql_set_mode) && $mysql_set_mode === true) | |
75 $smcFunc['db_query']('', 'SET sql_mode = \'\', AUTOCOMMIT = 1', | |
76 array(), | |
77 false | |
78 ); | |
79 | |
80 return $connection; | |
81 } | |
82 | |
83 // Extend the database functionality. | |
84 function db_extend($type = 'extra') | |
85 { | |
86 global $sourcedir, $db_type; | |
87 | |
88 require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-' . $db_type . '.php'); | |
89 $initFunc = 'db_' . $type . '_init'; | |
90 $initFunc(); | |
91 } | |
92 | |
93 // Fix up the prefix so it doesn't require the database to be selected. | |
94 function db_fix_prefix(&$db_prefix, $db_name) | |
95 { | |
96 $db_prefix = is_numeric(substr($db_prefix, 0, 1)) ? $db_name . '.' . $db_prefix : '`' . $db_name . '`.' . $db_prefix; | |
97 } | |
98 | |
99 function smf_db_replacement__callback($matches) | |
100 { | |
101 global $db_callback, $user_info, $db_prefix; | |
102 | |
103 list ($values, $connection) = $db_callback; | |
104 | |
105 if (!is_resource($connection)) | |
106 db_fatal_error(); | |
107 | |
108 if ($matches[1] === 'db_prefix') | |
109 return $db_prefix; | |
110 | |
111 if ($matches[1] === 'query_see_board') | |
112 return $user_info['query_see_board']; | |
113 | |
114 if ($matches[1] === 'query_wanna_see_board') | |
115 return $user_info['query_wanna_see_board']; | |
116 | |
117 if (!isset($matches[2])) | |
118 smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__); | |
119 | |
120 if (!isset($values[$matches[2]])) | |
121 smf_db_error_backtrace('The database value you\'re trying to insert does not exist: ' . htmlspecialchars($matches[2]), '', E_USER_ERROR, __FILE__, __LINE__); | |
122 | |
123 $replacement = $values[$matches[2]]; | |
124 | |
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 | |
133 case 'string': | |
134 case 'text': | |
135 return sprintf('\'%1$s\'', mysql_real_escape_string($replacement, $connection)); | |
136 break; | |
137 | |
138 case 'array_int': | |
139 if (is_array($replacement)) | |
140 { | |
141 if (empty($replacement)) | |
142 smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
143 | |
144 foreach ($replacement as $key => $value) | |
145 { | |
146 if (!is_numeric($value) || (string) $value !== (string) (int) $value) | |
147 smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
148 | |
149 $replacement[$key] = (string) (int) $value; | |
150 } | |
151 | |
152 return implode(', ', $replacement); | |
153 } | |
154 else | |
155 smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
156 | |
157 break; | |
158 | |
159 case 'array_string': | |
160 if (is_array($replacement)) | |
161 { | |
162 if (empty($replacement)) | |
163 smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
164 | |
165 foreach ($replacement as $key => $value) | |
166 $replacement[$key] = sprintf('\'%1$s\'', mysql_real_escape_string($value, $connection)); | |
167 | |
168 return implode(', ', $replacement); | |
169 } | |
170 else | |
171 smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
172 break; | |
173 | |
174 case 'date': | |
175 if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1) | |
176 return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]); | |
177 else | |
178 smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
179 break; | |
180 | |
181 case 'float': | |
182 if (!is_numeric($replacement)) | |
183 smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
184 return (string) (float) $replacement; | |
185 break; | |
186 | |
187 case 'identifier': | |
188 // Backticks inside identifiers are supported as of MySQL 4.1. We don't need them for SMF. | |
189 return '`' . strtr($replacement, array('`' => '', '.' => '')) . '`'; | |
190 break; | |
191 | |
192 case 'raw': | |
193 return $replacement; | |
194 break; | |
195 | |
196 default: | |
197 smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__); | |
198 break; | |
199 } | |
200 } | |
201 | |
202 // Just like the db_query, escape and quote a string, but not executing the query. | |
203 function smf_db_quote($db_string, $db_values, $connection = null) | |
204 { | |
205 global $db_callback, $db_connection; | |
206 | |
207 // Only bother if there's something to replace. | |
208 if (strpos($db_string, '{') !== false) | |
209 { | |
210 // This is needed by the callback function. | |
211 $db_callback = array($db_values, $connection == null ? $db_connection : $connection); | |
212 | |
213 // Do the quoting and escaping | |
214 $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string); | |
215 | |
216 // Clear this global variable. | |
217 $db_callback = array(); | |
218 } | |
219 | |
220 return $db_string; | |
221 } | |
222 | |
223 // Do a query. Takes care of errors too. | |
224 function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null) | |
225 { | |
226 global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start; | |
227 global $db_unbuffered, $db_callback, $modSettings; | |
228 | |
229 // Comments that are allowed in a query are preg_removed. | |
230 static $allowed_comments_from = array( | |
231 '~\s+~s', | |
232 '~/\*!40001 SQL_NO_CACHE \*/~', | |
233 '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~', | |
234 '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~', | |
235 ); | |
236 static $allowed_comments_to = array( | |
237 ' ', | |
238 '', | |
239 '', | |
240 '', | |
241 ); | |
242 | |
243 // Decide which connection to use. | |
244 $connection = $connection == null ? $db_connection : $connection; | |
245 | |
246 // One more query.... | |
247 $db_count = !isset($db_count) ? 1 : $db_count + 1; | |
248 | |
249 if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override'])) | |
250 smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__); | |
251 | |
252 // Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By | |
253 if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && strpos($db_string, 'INSERT INTO') === false) | |
254 { | |
255 // Add before LIMIT | |
256 if ($pos = strpos($db_string, 'LIMIT ')) | |
257 $db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string)); | |
258 else | |
259 // Append it. | |
260 $db_string .= "\n\t\t\tORDER BY null"; | |
261 } | |
262 | |
263 if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false)) | |
264 { | |
265 // Pass some values to the global space for use in the callback function. | |
266 $db_callback = array($db_values, $connection); | |
267 | |
268 // Inject the values passed to this function. | |
269 $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string); | |
270 | |
271 // This shouldn't be residing in global space any longer. | |
272 $db_callback = array(); | |
273 } | |
274 | |
275 // Debugging. | |
276 if (isset($db_show_debug) && $db_show_debug === true) | |
277 { | |
278 // Get the file and line number this function was called. | |
279 list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__); | |
280 | |
281 // Initialize $db_cache if not already initialized. | |
282 if (!isset($db_cache)) | |
283 $db_cache = array(); | |
284 | |
285 if (!empty($_SESSION['debug_redirect'])) | |
286 { | |
287 $db_cache = array_merge($_SESSION['debug_redirect'], $db_cache); | |
288 $db_count = count($db_cache) + 1; | |
289 $_SESSION['debug_redirect'] = array(); | |
290 } | |
291 | |
292 $st = microtime(); | |
293 // Don't overload it. | |
294 $db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...'; | |
295 $db_cache[$db_count]['f'] = $file; | |
296 $db_cache[$db_count]['l'] = $line; | |
297 $db_cache[$db_count]['s'] = array_sum(explode(' ', $st)) - array_sum(explode(' ', $time_start)); | |
298 } | |
299 | |
300 // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over. | |
301 if (empty($modSettings['disableQueryCheck'])) | |
302 { | |
303 $clean = ''; | |
304 $old_pos = 0; | |
305 $pos = -1; | |
306 while (true) | |
307 { | |
308 $pos = strpos($db_string, '\'', $pos + 1); | |
309 if ($pos === false) | |
310 break; | |
311 $clean .= substr($db_string, $old_pos, $pos - $old_pos); | |
312 | |
313 while (true) | |
314 { | |
315 $pos1 = strpos($db_string, '\'', $pos + 1); | |
316 $pos2 = strpos($db_string, '\\', $pos + 1); | |
317 if ($pos1 === false) | |
318 break; | |
319 elseif ($pos2 == false || $pos2 > $pos1) | |
320 { | |
321 $pos = $pos1; | |
322 break; | |
323 } | |
324 | |
325 $pos = $pos2 + 1; | |
326 } | |
327 $clean .= ' %s '; | |
328 | |
329 $old_pos = $pos + 1; | |
330 } | |
331 $clean .= substr($db_string, $old_pos); | |
332 $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean))); | |
333 | |
334 // We don't use UNION in SMF, at least so far. But it's useful for injections. | |
335 if (strpos($clean, 'union') !== false && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0) | |
336 $fail = true; | |
337 // Comments? We don't use comments in our queries, we leave 'em outside! | |
338 elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false) | |
339 $fail = true; | |
340 // Trying to change passwords, slow us down, or something? | |
341 elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0) | |
342 $fail = true; | |
343 elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) | |
344 $fail = true; | |
345 // Sub selects? We don't use those either. | |
346 elseif (preg_match('~\([^)]*?select~s', $clean) != 0) | |
347 $fail = true; | |
348 | |
349 if (!empty($fail) && function_exists('log_error')) | |
350 smf_db_error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__); | |
351 } | |
352 | |
353 if (empty($db_unbuffered)) | |
354 $ret = @mysql_query($db_string, $connection); | |
355 else | |
356 $ret = @mysql_unbuffered_query($db_string, $connection); | |
357 if ($ret === false && empty($db_values['db_error_skip'])) | |
358 $ret = smf_db_error($db_string, $connection); | |
359 | |
360 // Debugging. | |
361 if (isset($db_show_debug) && $db_show_debug === true) | |
362 $db_cache[$db_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st)); | |
363 | |
364 return $ret; | |
365 } | |
366 | |
367 function smf_db_affected_rows($connection = null) | |
368 { | |
369 global $db_connection; | |
370 | |
371 return mysql_affected_rows($connection == null ? $db_connection : $connection); | |
372 } | |
373 | |
374 function smf_db_insert_id($table, $field = null, $connection = null) | |
375 { | |
376 global $db_connection, $db_prefix; | |
377 | |
378 $table = str_replace('{db_prefix}', $db_prefix, $table); | |
379 | |
380 // MySQL doesn't need the table or field information. | |
381 return mysql_insert_id($connection == null ? $db_connection : $connection); | |
382 } | |
383 | |
384 // Do a transaction. | |
385 function smf_db_transaction($type = 'commit', $connection = null) | |
386 { | |
387 global $db_connection; | |
388 | |
389 // Decide which connection to use | |
390 $connection = $connection == null ? $db_connection : $connection; | |
391 | |
392 if ($type == 'begin') | |
393 return @mysql_query('BEGIN', $connection); | |
394 elseif ($type == 'rollback') | |
395 return @mysql_query('ROLLBACK', $connection); | |
396 elseif ($type == 'commit') | |
397 return @mysql_query('COMMIT', $connection); | |
398 | |
399 return false; | |
400 } | |
401 | |
402 // Database error! | |
403 function smf_db_error($db_string, $connection = null) | |
404 { | |
405 global $txt, $context, $sourcedir, $webmaster_email, $modSettings; | |
406 global $forum_version, $db_connection, $db_last_error, $db_persist; | |
407 global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd; | |
408 global $smcFunc; | |
409 | |
410 // Get the file and line numbers. | |
411 list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__); | |
412 | |
413 // Decide which connection to use | |
414 $connection = $connection == null ? $db_connection : $connection; | |
415 | |
416 // This is the error message... | |
417 $query_error = mysql_error($connection); | |
418 $query_errno = mysql_errno($connection); | |
419 | |
420 // Error numbers: | |
421 // 1016: Can't open file '....MYI' | |
422 // 1030: Got error ??? from table handler. | |
423 // 1034: Incorrect key file for table. | |
424 // 1035: Old key file for table. | |
425 // 1205: Lock wait timeout exceeded. | |
426 // 1213: Deadlock found. | |
427 // 2006: Server has gone away. | |
428 // 2013: Lost connection to server during query. | |
429 | |
430 // Log the error. | |
431 if ($query_errno != 1213 && $query_errno != 1205 && function_exists('log_error')) | |
432 log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n$db_string" : ''), 'database', $file, $line); | |
433 | |
434 // Database error auto fixing ;). | |
435 if (function_exists('cache_get_data') && (!isset($modSettings['autoFixDatabase']) || $modSettings['autoFixDatabase'] == '1')) | |
436 { | |
437 // Force caching on, just for the error checking. | |
438 $old_cache = @$modSettings['cache_enable']; | |
439 $modSettings['cache_enable'] = '1'; | |
440 | |
441 if (($temp = cache_get_data('db_last_error', 600)) !== null) | |
442 $db_last_error = max(@$db_last_error, $temp); | |
443 | |
444 if (@$db_last_error < time() - 3600 * 24 * 3) | |
445 { | |
446 // We know there's a problem... but what? Try to auto detect. | |
447 if ($query_errno == 1030 && strpos($query_error, ' 127 ') !== false) | |
448 { | |
449 preg_match_all('~(?:[\n\r]|^)[^\']+?(?:FROM|JOIN|UPDATE|TABLE) ((?:[^\n\r(]+?(?:, )?)*)~s', $db_string, $matches); | |
450 | |
451 $fix_tables = array(); | |
452 foreach ($matches[1] as $tables) | |
453 { | |
454 $tables = array_unique(explode(',', $tables)); | |
455 foreach ($tables as $table) | |
456 { | |
457 // Now, it's still theoretically possible this could be an injection. So backtick it! | |
458 if (trim($table) != '') | |
459 $fix_tables[] = '`' . strtr(trim($table), array('`' => '')) . '`'; | |
460 } | |
461 } | |
462 | |
463 $fix_tables = array_unique($fix_tables); | |
464 } | |
465 // Table crashed. Let's try to fix it. | |
466 elseif ($query_errno == 1016) | |
467 { | |
468 if (preg_match('~\'([^\.\']+)~', $query_error, $match) != 0) | |
469 $fix_tables = array('`' . $match[1] . '`'); | |
470 } | |
471 // Indexes crashed. Should be easy to fix! | |
472 elseif ($query_errno == 1034 || $query_errno == 1035) | |
473 { | |
474 preg_match('~\'([^\']+?)\'~', $query_error, $match); | |
475 $fix_tables = array('`' . $match[1] . '`'); | |
476 } | |
477 } | |
478 | |
479 // Check for errors like 145... only fix it once every three days, and send an email. (can't use empty because it might not be set yet...) | |
480 if (!empty($fix_tables)) | |
481 { | |
482 // Subs-Admin.php for updateSettingsFile(), Subs-Post.php for sendmail(). | |
483 require_once($sourcedir . '/Subs-Admin.php'); | |
484 require_once($sourcedir . '/Subs-Post.php'); | |
485 | |
486 // Make a note of the REPAIR... | |
487 cache_put_data('db_last_error', time(), 600); | |
488 if (($temp = cache_get_data('db_last_error', 600)) === null) | |
489 updateSettingsFile(array('db_last_error' => time())); | |
490 | |
491 // Attempt to find and repair the broken table. | |
492 foreach ($fix_tables as $table) | |
493 $smcFunc['db_query']('', " | |
494 REPAIR TABLE $table", false, false); | |
495 | |
496 // And send off an email! | |
497 sendmail($webmaster_email, $txt['database_error'], $txt['tried_to_repair']); | |
498 | |
499 $modSettings['cache_enable'] = $old_cache; | |
500 | |
501 // Try the query again...? | |
502 $ret = $smcFunc['db_query']('', $db_string, false, false); | |
503 if ($ret !== false) | |
504 return $ret; | |
505 } | |
506 else | |
507 $modSettings['cache_enable'] = $old_cache; | |
508 | |
509 // Check for the "lost connection" or "deadlock found" errors - and try it just one more time. | |
510 if (in_array($query_errno, array(1205, 1213, 2006, 2013))) | |
511 { | |
512 if (in_array($query_errno, array(2006, 2013)) && $db_connection == $connection) | |
513 { | |
514 // Are we in SSI mode? If so try that username and password first | |
515 if (SMF == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd)) | |
516 { | |
517 if (empty($db_persist)) | |
518 $db_connection = @mysql_connect($db_server, $ssi_db_user, $ssi_db_passwd); | |
519 else | |
520 $db_connection = @mysql_pconnect($db_server, $ssi_db_user, $ssi_db_passwd); | |
521 } | |
522 // Fall back to the regular username and password if need be | |
523 if (!$db_connection) | |
524 { | |
525 if (empty($db_persist)) | |
526 $db_connection = @mysql_connect($db_server, $db_user, $db_passwd); | |
527 else | |
528 $db_connection = @mysql_pconnect($db_server, $db_user, $db_passwd); | |
529 } | |
530 | |
531 if (!$db_connection || !@mysql_select_db($db_name, $db_connection)) | |
532 $db_connection = false; | |
533 } | |
534 | |
535 if ($db_connection) | |
536 { | |
537 // Try a deadlock more than once more. | |
538 for ($n = 0; $n < 4; $n++) | |
539 { | |
540 $ret = $smcFunc['db_query']('', $db_string, false, false); | |
541 | |
542 $new_errno = mysql_errno($db_connection); | |
543 if ($ret !== false || in_array($new_errno, array(1205, 1213))) | |
544 break; | |
545 } | |
546 | |
547 // If it failed again, shucks to be you... we're not trying it over and over. | |
548 if ($ret !== false) | |
549 return $ret; | |
550 } | |
551 } | |
552 // Are they out of space, perhaps? | |
553 elseif ($query_errno == 1030 && (strpos($query_error, ' -1 ') !== false || strpos($query_error, ' 28 ') !== false || strpos($query_error, ' 12 ') !== false)) | |
554 { | |
555 if (!isset($txt)) | |
556 $query_error .= ' - check database storage space.'; | |
557 else | |
558 { | |
559 if (!isset($txt['mysql_error_space'])) | |
560 loadLanguage('Errors'); | |
561 | |
562 $query_error .= !isset($txt['mysql_error_space']) ? ' - check database storage space.' : $txt['mysql_error_space']; | |
563 } | |
564 } | |
565 } | |
566 | |
567 // Nothing's defined yet... just die with it. | |
568 if (empty($context) || empty($txt)) | |
569 die($query_error); | |
570 | |
571 // Show an error message, if possible. | |
572 $context['error_title'] = $txt['database_error']; | |
573 if (allowedTo('admin_forum')) | |
574 $context['error_message'] = nl2br($query_error) . '<br />' . $txt['file'] . ': ' . $file . '<br />' . $txt['line'] . ': ' . $line; | |
575 else | |
576 $context['error_message'] = $txt['try_again']; | |
577 | |
578 // A database error is often the sign of a database in need of upgrade. Check forum versions, and if not identical suggest an upgrade... (not for Demo/CVS versions!) | |
579 if (allowedTo('admin_forum') && !empty($forum_version) && $forum_version != 'SMF ' . @$modSettings['smfVersion'] && strpos($forum_version, 'Demo') === false && strpos($forum_version, 'CVS') === false) | |
580 $context['error_message'] .= '<br /><br />' . sprintf($txt['database_error_versions'], $forum_version, $modSettings['smfVersion']); | |
581 | |
582 if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true) | |
583 { | |
584 $context['error_message'] .= '<br /><br />' . nl2br($db_string); | |
585 } | |
586 | |
587 // It's already been logged... don't log it again. | |
588 fatal_error($context['error_message'], false); | |
589 } | |
590 | |
591 // Insert some data... | |
592 function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null) | |
593 { | |
594 global $smcFunc, $db_connection, $db_prefix; | |
595 | |
596 $connection = $connection === null ? $db_connection : $connection; | |
597 | |
598 // With nothing to insert, simply return. | |
599 if (empty($data)) | |
600 return; | |
601 | |
602 // Replace the prefix holder with the actual prefix. | |
603 $table = str_replace('{db_prefix}', $db_prefix, $table); | |
604 | |
605 // Inserting data as a single row can be done as a single array. | |
606 if (!is_array($data[array_rand($data)])) | |
607 $data = array($data); | |
608 | |
609 // Create the mold for a single row insert. | |
610 $insertData = '('; | |
611 foreach ($columns as $columnName => $type) | |
612 { | |
613 // Are we restricting the length? | |
614 if (strpos($type, 'string-') !== false) | |
615 $insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName); | |
616 else | |
617 $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName); | |
618 } | |
619 $insertData = substr($insertData, 0, -2) . ')'; | |
620 | |
621 // Create an array consisting of only the columns. | |
622 $indexed_columns = array_keys($columns); | |
623 | |
624 // Here's where the variables are injected to the query. | |
625 $insertRows = array(); | |
626 foreach ($data as $dataRow) | |
627 $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection); | |
628 | |
629 // Determine the method of insertion. | |
630 $queryTitle = $method == 'replace' ? 'REPLACE' : ($method == 'ignore' ? 'INSERT IGNORE' : 'INSERT'); | |
631 | |
632 // Do the insert. | |
633 $smcFunc['db_query']('', ' | |
634 ' . $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`) | |
635 VALUES | |
636 ' . implode(', | |
637 ', $insertRows), | |
638 array( | |
639 'security_override' => true, | |
640 'db_error_skip' => $table === $db_prefix . 'log_errors', | |
641 ), | |
642 $connection | |
643 ); | |
644 } | |
645 | |
646 // This function tries to work out additional error information from a back trace. | |
647 function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null) | |
648 { | |
649 if (empty($log_message)) | |
650 $log_message = $error_message; | |
651 | |
652 if (function_exists('debug_backtrace')) | |
653 { | |
654 foreach (debug_backtrace() as $step) | |
655 { | |
656 // Found it? | |
657 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) != '__') | |
658 { | |
659 $log_message .= '<br />Function: ' . $step['function']; | |
660 break; | |
661 } | |
662 | |
663 if (isset($step['line'])) | |
664 { | |
665 $file = $step['file']; | |
666 $line = $step['line']; | |
667 } | |
668 } | |
669 } | |
670 | |
671 // A special case - we want the file and line numbers for debugging. | |
672 if ($error_type == 'return') | |
673 return array($file, $line); | |
674 | |
675 // Is always a critical error. | |
676 if (function_exists('log_error')) | |
677 log_error($log_message, 'critical', $file, $line); | |
678 | |
679 if (function_exists('fatal_error')) | |
680 { | |
681 fatal_error($error_message, false); | |
682 | |
683 // Cannot continue... | |
684 exit; | |
685 } | |
686 elseif ($error_type) | |
687 trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type); | |
688 else | |
689 trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : '')); | |
690 } | |
691 | |
692 // Escape the LIKE wildcards so that they match the character and not the wildcard. | |
693 // The optional second parameter turns human readable wildcards into SQL wildcards. | |
694 function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false) | |
695 { | |
696 $replacements = array( | |
697 '%' => '\%', | |
698 '_' => '\_', | |
699 '\\' => '\\\\', | |
700 ); | |
701 | |
702 if ($translate_human_wildcards) | |
703 $replacements += array( | |
704 '*' => '%', | |
705 ); | |
706 | |
707 return strtr($string, $replacements); | |
708 } | |
709 ?> |