Mercurial > hg > vamp-website
comparison forum/Sources/Subs-Db-sqlite.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 | |
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, $db_in_transact, $sqlite_error; | |
28 | |
29 // Map some database specific functions, only do this once. | |
30 if (!isset($smcFunc['db_fetch_assoc']) || $smcFunc['db_fetch_assoc'] != 'sqlite_fetch_array') | |
31 $smcFunc += array( | |
32 'db_query' => 'smf_db_query', | |
33 'db_quote' => 'smf_db_quote', | |
34 'db_fetch_assoc' => 'sqlite_fetch_array', | |
35 'db_fetch_row' => 'smf_db_fetch_row', | |
36 'db_free_result' => 'smf_db_free_result', | |
37 'db_insert' => 'smf_db_insert', | |
38 'db_insert_id' => 'smf_db_insert_id', | |
39 'db_num_rows' => 'sqlite_num_rows', | |
40 'db_data_seek' => 'sqlite_seek', | |
41 'db_num_fields' => 'sqlite_num_fields', | |
42 'db_escape_string' => 'sqlite_escape_string', | |
43 'db_unescape_string' => 'smf_db_unescape_string', | |
44 'db_server_info' => 'smf_db_libversion', | |
45 'db_affected_rows' => 'smf_db_affected_rows', | |
46 'db_transaction' => 'smf_db_transaction', | |
47 'db_error' => 'smf_db_last_error', | |
48 'db_select_db' => '', | |
49 'db_title' => 'SQLite', | |
50 'db_sybase' => true, | |
51 'db_case_sensitive' => true, | |
52 'db_escape_wildcard_string' => 'smf_db_escape_wildcard_string', | |
53 ); | |
54 | |
55 if (substr($db_name, -3) != '.db') | |
56 $db_name .= '.db'; | |
57 | |
58 if (!empty($db_options['persist'])) | |
59 $connection = @sqlite_popen($db_name, 0666, $sqlite_error); | |
60 else | |
61 $connection = @sqlite_open($db_name, 0666, $sqlite_error); | |
62 | |
63 // Something's wrong, show an error if its fatal (which we assume it is) | |
64 if (!$connection) | |
65 { | |
66 if (!empty($db_options['non_fatal'])) | |
67 return null; | |
68 else | |
69 db_fatal_error(); | |
70 } | |
71 $db_in_transact = false; | |
72 | |
73 // This is frankly stupid - stop SQLite returning alias names! | |
74 @sqlite_query('PRAGMA short_column_names = 1', $connection); | |
75 | |
76 // Make some user defined functions! | |
77 sqlite_create_function($connection, 'unix_timestamp', 'smf_udf_unix_timestamp', 0); | |
78 sqlite_create_function($connection, 'inet_aton', 'smf_udf_inet_aton', 1); | |
79 sqlite_create_function($connection, 'inet_ntoa', 'smf_udf_inet_ntoa', 1); | |
80 sqlite_create_function($connection, 'find_in_set', 'smf_udf_find_in_set', 2); | |
81 sqlite_create_function($connection, 'year', 'smf_udf_year', 1); | |
82 sqlite_create_function($connection, 'month', 'smf_udf_month', 1); | |
83 sqlite_create_function($connection, 'dayofmonth', 'smf_udf_dayofmonth', 1); | |
84 sqlite_create_function($connection, 'concat', 'smf_udf_concat'); | |
85 sqlite_create_function($connection, 'locate', 'smf_udf_locate', 2); | |
86 sqlite_create_function($connection, 'regexp', 'smf_udf_regexp', 2); | |
87 | |
88 return $connection; | |
89 } | |
90 | |
91 // Extend the database functionality. | |
92 function db_extend($type = 'extra') | |
93 { | |
94 global $sourcedir, $db_type; | |
95 | |
96 require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-' . $db_type . '.php'); | |
97 $initFunc = 'db_' . $type . '_init'; | |
98 $initFunc(); | |
99 } | |
100 | |
101 // SQLite doesn't actually need this! | |
102 function db_fix_prefix(&$db_prefix, $db_name) | |
103 { | |
104 return false; | |
105 } | |
106 | |
107 function smf_db_replacement__callback($matches) | |
108 { | |
109 global $db_callback, $user_info, $db_prefix; | |
110 | |
111 list ($values, $connection) = $db_callback; | |
112 | |
113 if ($matches[1] === 'db_prefix') | |
114 return $db_prefix; | |
115 | |
116 if ($matches[1] === 'query_see_board') | |
117 return $user_info['query_see_board']; | |
118 | |
119 if ($matches[1] === 'query_wanna_see_board') | |
120 return $user_info['query_wanna_see_board']; | |
121 | |
122 if (!isset($matches[2])) | |
123 smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__); | |
124 | |
125 if (!isset($values[$matches[2]])) | |
126 smf_db_error_backtrace('The database value you\'re trying to insert does not exist: ' . htmlspecialchars($matches[2]), '', E_USER_ERROR, __FILE__, __LINE__); | |
127 | |
128 $replacement = $values[$matches[2]]; | |
129 | |
130 switch ($matches[1]) | |
131 { | |
132 case 'int': | |
133 if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement) | |
134 smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
135 return (string) (int) $replacement; | |
136 break; | |
137 | |
138 case 'string': | |
139 case 'text': | |
140 return sprintf('\'%1$s\'', sqlite_escape_string($replacement)); | |
141 break; | |
142 | |
143 case 'array_int': | |
144 if (is_array($replacement)) | |
145 { | |
146 if (empty($replacement)) | |
147 smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
148 | |
149 foreach ($replacement as $key => $value) | |
150 { | |
151 if (!is_numeric($value) || (string) $value !== (string) (int) $value) | |
152 smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
153 | |
154 $replacement[$key] = (string) (int) $value; | |
155 } | |
156 | |
157 return implode(', ', $replacement); | |
158 } | |
159 else | |
160 smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
161 | |
162 break; | |
163 | |
164 case 'array_string': | |
165 if (is_array($replacement)) | |
166 { | |
167 if (empty($replacement)) | |
168 smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
169 | |
170 foreach ($replacement as $key => $value) | |
171 $replacement[$key] = sprintf('\'%1$s\'', sqlite_escape_string($value)); | |
172 | |
173 return implode(', ', $replacement); | |
174 } | |
175 else | |
176 smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
177 break; | |
178 | |
179 case 'date': | |
180 if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1) | |
181 return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]); | |
182 else | |
183 smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
184 break; | |
185 | |
186 case 'float': | |
187 if (!is_numeric($replacement)) | |
188 smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__); | |
189 return (string) (float) $replacement; | |
190 break; | |
191 | |
192 case 'identifier': | |
193 return '`' . strtr($replacement, array('`' => '', '.' => '')) . '`'; | |
194 break; | |
195 | |
196 case 'raw': | |
197 return $replacement; | |
198 break; | |
199 | |
200 default: | |
201 smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__); | |
202 break; | |
203 } | |
204 } | |
205 | |
206 // Just like the db_query, escape and quote a string, but not executing the query. | |
207 function smf_db_quote($db_string, $db_values, $connection = null) | |
208 { | |
209 global $db_callback, $db_connection; | |
210 | |
211 // Only bother if there's something to replace. | |
212 if (strpos($db_string, '{') !== false) | |
213 { | |
214 // This is needed by the callback function. | |
215 $db_callback = array($db_values, $connection == null ? $db_connection : $connection); | |
216 | |
217 // Do the quoting and escaping | |
218 $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string); | |
219 | |
220 // Clear this global variable. | |
221 $db_callback = array(); | |
222 } | |
223 | |
224 return $db_string; | |
225 } | |
226 | |
227 // Do a query. Takes care of errors too. | |
228 function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null) | |
229 { | |
230 global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start; | |
231 global $db_unbuffered, $db_callback, $modSettings; | |
232 | |
233 // Decide which connection to use. | |
234 $connection = $connection == null ? $db_connection : $connection; | |
235 | |
236 // Special queries that need processing. | |
237 $replacements = array( | |
238 'birthday_array' => array( | |
239 '~DATE_FORMAT\(([^,]+),\s*([^\)]+)\s*\)~' => 'strftime($2, $1)' | |
240 ), | |
241 'substring' => array( | |
242 '~SUBSTRING~' => 'SUBSTR', | |
243 ), | |
244 'truncate_table' => array( | |
245 '~TRUNCATE~i' => 'DELETE FROM', | |
246 ), | |
247 'user_activity_by_time' => array( | |
248 '~HOUR\(FROM_UNIXTIME\((poster_time\s+\+\s+\{int:.+\})\)\)~' => 'strftime(\'%H\', datetime($1, \'unixepoch\'))', | |
249 ), | |
250 'unread_fetch_topic_count' => array( | |
251 '~\s*SELECT\sCOUNT\(DISTINCT\st\.id_topic\),\sMIN\(t\.id_last_msg\)(.+)$~is' => 'SELECT COUNT(id_topic), MIN(id_last_msg) FROM (SELECT DISTINCT t.id_topic, t.id_last_msg $1)', | |
252 ), | |
253 'alter_table_boards' => array( | |
254 '~(.+)~' => '', | |
255 ), | |
256 'get_random_number' => array( | |
257 '~RAND~' => 'RANDOM', | |
258 ), | |
259 'set_character_set' => array( | |
260 '~(.+)~' => '', | |
261 ), | |
262 'themes_count' => array( | |
263 '~\s*SELECT\sCOUNT\(DISTINCT\sid_member\)\sAS\svalue,\sid_theme.+FROM\s(.+themes)(.+)~is' => 'SELECT COUNT(id_member) AS value, id_theme FROM (SELECT DISTINCT id_member, id_theme, variable FROM $1) $2', | |
264 ), | |
265 'attach_download_increase' => array( | |
266 '~LOW_PRIORITY~' => '', | |
267 ), | |
268 'pm_conversation_list' => array( | |
269 '~ORDER BY id_pm~' => 'ORDER BY MAX(pm.id_pm)', | |
270 ), | |
271 'boardindex_fetch_boards' => array( | |
272 '~(.)$~' => '$1 ORDER BY b.board_order', | |
273 ), | |
274 'messageindex_fetch_boards' => array( | |
275 '~(.)$~' => '$1 ORDER BY b.board_order', | |
276 ), | |
277 'order_by_board_order' => array( | |
278 '~(.)$~' => '$1 ORDER BY b.board_order', | |
279 ), | |
280 'spider_check' => array( | |
281 '~(.)$~' => '$1 ORDER BY LENGTH(user_agent) DESC', | |
282 ), | |
283 ); | |
284 | |
285 if (isset($replacements[$identifier])) | |
286 $db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string); | |
287 | |
288 // SQLite doesn't support count(distinct). | |
289 $db_string = trim($db_string); | |
290 $db_string = preg_replace('~^\s*SELECT\s+?COUNT\(DISTINCT\s+?(.+?)\)(\s*AS\s*(.+?))*\s*(FROM.+)~is', 'SELECT COUNT(*) $2 FROM (SELECT DISTINCT $1 $4)', $db_string); | |
291 | |
292 // Or RLIKE. | |
293 $db_string = preg_replace('~AND\s*(.+?)\s*RLIKE\s*(\{string:.+?\})~', 'AND REGEXP(\1, \2)', $db_string); | |
294 | |
295 // INSTR? No support for that buddy :( | |
296 if (preg_match('~INSTR\((.+?),\s(.+?)\)~', $db_string, $matches) === 1) | |
297 { | |
298 $db_string = preg_replace('~INSTR\((.+?),\s(.+?)\)~', '$1 LIKE $2', $db_string); | |
299 list(, $search) = explode(':', substr($matches[2], 1, -1)); | |
300 $db_values[$search] = '%' . $db_values[$search] . '%'; | |
301 } | |
302 | |
303 // Lets remove ASC and DESC from GROUP BY clause. | |
304 if (preg_match('~GROUP BY .*? (?:ASC|DESC)~is', $db_string, $matches)) | |
305 { | |
306 $replace = str_replace(array('ASC', 'DESC'), '', $matches[0]); | |
307 $db_string = str_replace($matches[0], $replace, $db_string); | |
308 } | |
309 | |
310 // We need to replace the SUBSTRING in the sort identifier. | |
311 if ($identifier == 'substring_membergroups' && isset($db_values['sort'])) | |
312 $db_values['sort'] = preg_replace('~SUBSTRING~', 'SUBSTR', $db_values['sort']); | |
313 | |
314 // SQLite doesn't support TO_DAYS but has the julianday function which can be used in the same manner. But make sure it is being used to calculate a span. | |
315 $db_string = preg_replace('~\(TO_DAYS\(([^)]+)\) - TO_DAYS\(([^)]+)\)\) AS span~', '(julianday($1) - julianday($2)) AS span', $db_string); | |
316 | |
317 // One more query.... | |
318 $db_count = !isset($db_count) ? 1 : $db_count + 1; | |
319 | |
320 if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override'])) | |
321 smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__); | |
322 | |
323 if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false)) | |
324 { | |
325 // Pass some values to the global space for use in the callback function. | |
326 $db_callback = array($db_values, $connection); | |
327 | |
328 // Inject the values passed to this function. | |
329 $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string); | |
330 | |
331 // This shouldn't be residing in global space any longer. | |
332 $db_callback = array(); | |
333 } | |
334 | |
335 // Debugging. | |
336 if (isset($db_show_debug) && $db_show_debug === true) | |
337 { | |
338 // Get the file and line number this function was called. | |
339 list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__); | |
340 | |
341 // Initialize $db_cache if not already initialized. | |
342 if (!isset($db_cache)) | |
343 $db_cache = array(); | |
344 | |
345 if (!empty($_SESSION['debug_redirect'])) | |
346 { | |
347 $db_cache = array_merge($_SESSION['debug_redirect'], $db_cache); | |
348 $db_count = count($db_cache) + 1; | |
349 $_SESSION['debug_redirect'] = array(); | |
350 } | |
351 | |
352 $st = microtime(); | |
353 // Don't overload it. | |
354 $db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...'; | |
355 $db_cache[$db_count]['f'] = $file; | |
356 $db_cache[$db_count]['l'] = $line; | |
357 $db_cache[$db_count]['s'] = array_sum(explode(' ', $st)) - array_sum(explode(' ', $time_start)); | |
358 } | |
359 | |
360 $ret = @sqlite_query($db_string, $connection, SQLITE_BOTH, $err_msg); | |
361 if ($ret === false && empty($db_values['db_error_skip'])) | |
362 $ret = smf_db_error($db_string . '#!#' . $err_msg, $connection); | |
363 | |
364 // Debugging. | |
365 if (isset($db_show_debug) && $db_show_debug === true) | |
366 $db_cache[$db_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st)); | |
367 | |
368 return $ret; | |
369 } | |
370 | |
371 function smf_db_affected_rows($connection = null) | |
372 { | |
373 global $db_connection; | |
374 | |
375 return sqlite_changes($connection == null ? $db_connection : $connection); | |
376 } | |
377 | |
378 function smf_db_insert_id($table, $field = null, $connection = null) | |
379 { | |
380 global $db_connection, $db_prefix; | |
381 | |
382 $table = str_replace('{db_prefix}', $db_prefix, $table); | |
383 | |
384 // SQLite doesn't need the table or field information. | |
385 return sqlite_last_insert_rowid($connection == null ? $db_connection : $connection); | |
386 } | |
387 | |
388 // Keeps the connection handle. | |
389 function smf_db_last_error() | |
390 { | |
391 global $db_connection, $sqlite_error; | |
392 | |
393 $query_errno = sqlite_last_error($db_connection); | |
394 return $query_errno || empty($sqlite_error) ? sqlite_error_string($query_errno) : $sqlite_error; | |
395 } | |
396 | |
397 // Do a transaction. | |
398 function smf_db_transaction($type = 'commit', $connection = null) | |
399 { | |
400 global $db_connection, $db_in_transact; | |
401 | |
402 // Decide which connection to use | |
403 $connection = $connection == null ? $db_connection : $connection; | |
404 | |
405 if ($type == 'begin') | |
406 { | |
407 $db_in_transact = true; | |
408 return @sqlite_query('BEGIN', $connection); | |
409 } | |
410 elseif ($type == 'rollback') | |
411 { | |
412 $db_in_transact = false; | |
413 return @sqlite_query('ROLLBACK', $connection); | |
414 } | |
415 elseif ($type == 'commit') | |
416 { | |
417 $db_in_transact = false; | |
418 return @sqlite_query('COMMIT', $connection); | |
419 } | |
420 | |
421 return false; | |
422 } | |
423 | |
424 // Database error! | |
425 function smf_db_error($db_string, $connection = null) | |
426 { | |
427 global $txt, $context, $sourcedir, $webmaster_email, $modSettings; | |
428 global $forum_version, $db_connection, $db_last_error, $db_persist; | |
429 global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd; | |
430 global $smcFunc; | |
431 | |
432 // We'll try recovering the file and line number the original db query was called from. | |
433 list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__); | |
434 | |
435 // Decide which connection to use | |
436 $connection = $connection == null ? $db_connection : $connection; | |
437 | |
438 // This is the error message... | |
439 $query_errno = sqlite_last_error($connection); | |
440 $query_error = sqlite_error_string($query_errno); | |
441 | |
442 // Get the extra error message. | |
443 $errStart = strrpos($db_string, '#!#'); | |
444 $query_error .= '<br />' . substr($db_string, $errStart + 3); | |
445 $db_string = substr($db_string, 0, $errStart); | |
446 | |
447 // Log the error. | |
448 if (function_exists('log_error')) | |
449 log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n" .$db_string : ''), 'database', $file, $line); | |
450 | |
451 // Sqlite optimizing - the actual error message isn't helpful or user friendly. | |
452 if (strpos($query_error, 'no_access') !== false || strpos($query_error, 'database schema has changed') !== false) | |
453 { | |
454 if (!empty($context) && !empty($txt) && !empty($txt['error_sqlite_optimizing'])) | |
455 fatal_error($txt['error_sqlite_optimizing'], false); | |
456 else | |
457 { | |
458 // Don't cache this page! | |
459 header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); | |
460 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); | |
461 header('Cache-Control: no-cache'); | |
462 | |
463 // Send the right error codes. | |
464 header('HTTP/1.1 503 Service Temporarily Unavailable'); | |
465 header('Status: 503 Service Temporarily Unavailable'); | |
466 header('Retry-After: 3600'); | |
467 | |
468 die('Sqlite is optimizing the database, the forum can not be accessed until it has finished. Please try refreshing this page momentarily.'); | |
469 } | |
470 } | |
471 | |
472 // Nothing's defined yet... just die with it. | |
473 if (empty($context) || empty($txt)) | |
474 die($query_error); | |
475 | |
476 // Show an error message, if possible. | |
477 $context['error_title'] = $txt['database_error']; | |
478 if (allowedTo('admin_forum')) | |
479 $context['error_message'] = nl2br($query_error) . '<br />' . $txt['file'] . ': ' . $file . '<br />' . $txt['line'] . ': ' . $line; | |
480 else | |
481 $context['error_message'] = $txt['try_again']; | |
482 | |
483 // 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!) | |
484 if (allowedTo('admin_forum') && !empty($forum_version) && $forum_version != 'SMF ' . @$modSettings['smfVersion'] && strpos($forum_version, 'Demo') === false && strpos($forum_version, 'CVS') === false) | |
485 $context['error_message'] .= '<br /><br />' . sprintf($txt['database_error_versions'], $forum_version, $modSettings['smfVersion']); | |
486 | |
487 if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true) | |
488 { | |
489 $context['error_message'] .= '<br /><br />' . nl2br($db_string); | |
490 } | |
491 | |
492 // It's already been logged... don't log it again. | |
493 fatal_error($context['error_message'], false); | |
494 } | |
495 | |
496 // Insert some data... | |
497 function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null) | |
498 { | |
499 global $db_in_transact, $db_connection, $smcFunc, $db_prefix; | |
500 | |
501 $connection = $connection === null ? $db_connection : $connection; | |
502 | |
503 if (empty($data)) | |
504 return; | |
505 | |
506 if (!is_array($data[array_rand($data)])) | |
507 $data = array($data); | |
508 | |
509 // Replace the prefix holder with the actual prefix. | |
510 $table = str_replace('{db_prefix}', $db_prefix, $table); | |
511 | |
512 $priv_trans = false; | |
513 if (count($data) > 1 && !$db_in_transact && !$disable_trans) | |
514 { | |
515 $smcFunc['db_transaction']('begin', $connection); | |
516 $priv_trans = true; | |
517 } | |
518 | |
519 if (!empty($data)) | |
520 { | |
521 // Create the mold for a single row insert. | |
522 $insertData = '('; | |
523 foreach ($columns as $columnName => $type) | |
524 { | |
525 // Are we restricting the length? | |
526 if (strpos($type, 'string-') !== false) | |
527 $insertData .= sprintf('SUBSTR({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName); | |
528 else | |
529 $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName); | |
530 } | |
531 $insertData = substr($insertData, 0, -2) . ')'; | |
532 | |
533 // Create an array consisting of only the columns. | |
534 $indexed_columns = array_keys($columns); | |
535 | |
536 // Here's where the variables are injected to the query. | |
537 $insertRows = array(); | |
538 foreach ($data as $dataRow) | |
539 $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection); | |
540 | |
541 foreach ($insertRows as $entry) | |
542 // Do the insert. | |
543 $smcFunc['db_query']('', | |
544 (($method === 'replace') ? 'REPLACE' : (' INSERT' . ($method === 'ignore' ? ' OR IGNORE' : ''))) . ' INTO ' . $table . '(' . implode(', ', $indexed_columns) . ') | |
545 VALUES | |
546 ' . $entry, | |
547 array( | |
548 'security_override' => true, | |
549 'db_error_skip' => $table === $db_prefix . 'log_errors', | |
550 ), | |
551 $connection | |
552 ); | |
553 } | |
554 | |
555 if ($priv_trans) | |
556 $smcFunc['db_transaction']('commit', $connection); | |
557 } | |
558 | |
559 // Doesn't do anything on sqlite! | |
560 function smf_db_free_result($handle = false) | |
561 { | |
562 return true; | |
563 } | |
564 | |
565 // Make sure we return no string indexes! | |
566 function smf_db_fetch_row($handle) | |
567 { | |
568 return sqlite_fetch_array($handle, SQLITE_NUM); | |
569 } | |
570 | |
571 // Unescape an escaped string! | |
572 function smf_db_unescape_string($string) | |
573 { | |
574 return strtr($string, array('\'\'' => '\'')); | |
575 } | |
576 | |
577 // This function tries to work out additional error information from a back trace. | |
578 function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null) | |
579 { | |
580 if (empty($log_message)) | |
581 $log_message = $error_message; | |
582 | |
583 if (function_exists('debug_backtrace')) | |
584 { | |
585 foreach (debug_backtrace() as $step) | |
586 { | |
587 // Found it? | |
588 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) != '__') | |
589 { | |
590 $log_message .= '<br />Function: ' . $step['function']; | |
591 break; | |
592 } | |
593 | |
594 if (isset($step['line'])) | |
595 { | |
596 $file = $step['file']; | |
597 $line = $step['line']; | |
598 } | |
599 } | |
600 } | |
601 | |
602 // A special case - we want the file and line numbers for debugging. | |
603 if ($error_type == 'return') | |
604 return array($file, $line); | |
605 | |
606 // Is always a critical error. | |
607 if (function_exists('log_error')) | |
608 log_error($log_message, 'critical', $file, $line); | |
609 | |
610 if (function_exists('fatal_error')) | |
611 { | |
612 fatal_error($error_message, $error_type); | |
613 | |
614 // Cannot continue... | |
615 exit; | |
616 } | |
617 elseif ($error_type) | |
618 trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type); | |
619 else | |
620 trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : '')); | |
621 } | |
622 | |
623 // Emulate UNIX_TIMESTAMP. | |
624 function smf_udf_unix_timestamp() | |
625 { | |
626 return strftime('%s', 'now'); | |
627 } | |
628 | |
629 // Emulate INET_ATON. | |
630 function smf_udf_inet_aton($ip) | |
631 { | |
632 $chunks = explode('.', $ip); | |
633 return @$chunks[0] * pow(256, 3) + @$chunks[1] * pow(256, 2) + @$chunks[2] * 256 + @$chunks[3]; | |
634 } | |
635 | |
636 // Emulate INET_NTOA. | |
637 function smf_udf_inet_ntoa($n) | |
638 { | |
639 $t = array(0, 0, 0, 0); | |
640 $msk = 16777216.0; | |
641 $n += 0.0; | |
642 if ($n < 1) | |
643 return '0.0.0.0'; | |
644 | |
645 for ($i = 0; $i < 4; $i++) | |
646 { | |
647 $k = (int) ($n / $msk); | |
648 $n -= $msk * $k; | |
649 $t[$i] = $k; | |
650 $msk /= 256.0; | |
651 }; | |
652 | |
653 $a = join('.', $t); | |
654 return $a; | |
655 } | |
656 | |
657 // Emulate FIND_IN_SET. | |
658 function smf_udf_find_in_set($find, $groups) | |
659 { | |
660 foreach (explode(',', $groups) as $key => $group) | |
661 { | |
662 if ($group == $find) | |
663 return $key + 1; | |
664 } | |
665 | |
666 return 0; | |
667 } | |
668 | |
669 // Emulate YEAR. | |
670 function smf_udf_year($date) | |
671 { | |
672 return substr($date, 0, 4); | |
673 } | |
674 | |
675 // Emulate MONTH. | |
676 function smf_udf_month($date) | |
677 { | |
678 return substr($date, 5, 2); | |
679 } | |
680 | |
681 // Emulate DAYOFMONTH. | |
682 function smf_udf_dayofmonth($date) | |
683 { | |
684 return substr($date, 8, 2); | |
685 } | |
686 | |
687 // We need this since sqlite_libversion() doesn't take any parameters. | |
688 function smf_db_libversion($void = null) | |
689 { | |
690 return sqlite_libversion(); | |
691 } | |
692 | |
693 // This function uses variable argument lists so that it can handle more then two parameters. | |
694 // Emulates the CONCAT function. | |
695 function smf_udf_concat() | |
696 { | |
697 // Since we didn't specify any arguments we must get them from PHP. | |
698 $args = func_get_args(); | |
699 | |
700 // It really doesn't matter if there were 0 to 100 arguments, just slap them all together. | |
701 return implode('', $args); | |
702 } | |
703 | |
704 // We need to use PHP to locate the position in the string. | |
705 function smf_udf_locate($find, $string) | |
706 { | |
707 return strpos($string, $find); | |
708 } | |
709 | |
710 // This is used to replace RLIKE. | |
711 function smf_udf_regexp($exp, $search) | |
712 { | |
713 if (preg_match($exp, $match)) | |
714 return 1; | |
715 return 0; | |
716 } | |
717 | |
718 // Escape the LIKE wildcards so that they match the character and not the wildcard. | |
719 // The optional second parameter turns human readable wildcards into SQL wildcards. | |
720 function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false) | |
721 { | |
722 $replacements = array( | |
723 '%' => '\%', | |
724 '\\' => '\\\\', | |
725 ); | |
726 | |
727 if ($translate_human_wildcards) | |
728 $replacements += array( | |
729 '*' => '%', | |
730 ); | |
731 | |
732 return strtr($string, $replacements); | |
733 } | |
734 ?> |