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