Subs-Db-sqlite.php 23 KB

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