PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/sources/database/Db-sqlite.subs.php

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