Subs-Db-sqlite.php 25 KB

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