Subs-Db-sqlite.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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 2013 Simple Machines and individual 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('No direct access...');
  16. /**
  17. * Maps the implementations in this file (smf_db_function_name)
  18. * to the $smcFunc['db_function_name'] variable.
  19. *
  20. * @param string $db_server
  21. * @param string $db_name
  22. * @param string $db_user
  23. * @param string $db_passwd
  24. * @param string $db_prefix
  25. * @param array $db_options
  26. */
  27. function smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, $db_options = array())
  28. {
  29. global $smcFunc, $mysql_set_mode, $db_in_transact, $sqlite_error;
  30. // Map some database specific functions, only do this once.
  31. if (!isset($smcFunc['db_fetch_assoc']) || $smcFunc['db_fetch_assoc'] != 'sqlite_fetch_array')
  32. $smcFunc += array(
  33. 'db_query' => 'smf_db_query',
  34. 'db_quote' => 'smf_db_quote',
  35. 'db_fetch_assoc' => 'sqlite_fetch_array',
  36. 'db_fetch_row' => 'smf_db_fetch_row',
  37. 'db_free_result' => 'smf_db_free_result',
  38. 'db_insert' => 'smf_db_insert',
  39. 'db_insert_id' => 'smf_db_insert_id',
  40. 'db_num_rows' => 'sqlite_num_rows',
  41. 'db_data_seek' => 'sqlite_seek',
  42. 'db_num_fields' => 'sqlite_num_fields',
  43. 'db_escape_string' => 'sqlite_escape_string',
  44. 'db_unescape_string' => 'smf_db_unescape_string',
  45. 'db_server_info' => 'smf_db_libversion',
  46. 'db_affected_rows' => 'smf_db_affected_rows',
  47. 'db_transaction' => 'smf_db_transaction',
  48. 'db_error' => 'smf_db_last_error',
  49. 'db_select_db' => '',
  50. 'db_title' => 'SQLite',
  51. 'db_sybase' => true,
  52. 'db_case_sensitive' => true,
  53. 'db_escape_wildcard_string' => 'smf_db_escape_wildcard_string',
  54. );
  55. if (substr($db_name, -3) != '.db')
  56. $db_name .= '.db';
  57. if (!empty($db_options['persist']))
  58. $connection = @sqlite_popen($db_name, 0666, $sqlite_error);
  59. else
  60. $connection = @sqlite_open($db_name, 0666, $sqlite_error);
  61. // Something's wrong, show an error if its fatal (which we assume it is)
  62. if (!$connection)
  63. {
  64. if (!empty($db_options['non_fatal']))
  65. return null;
  66. else
  67. display_db_error();
  68. }
  69. $db_in_transact = false;
  70. // This is frankly stupid - stop SQLite returning alias names!
  71. @sqlite_query('PRAGMA short_column_names = 1', $connection);
  72. // Make some user defined functions!
  73. sqlite_create_function($connection, 'unix_timestamp', 'smf_udf_unix_timestamp', 0);
  74. sqlite_create_function($connection, 'inet_aton', 'smf_udf_inet_aton', 1);
  75. sqlite_create_function($connection, 'inet_ntoa', 'smf_udf_inet_ntoa', 1);
  76. sqlite_create_function($connection, 'find_in_set', 'smf_udf_find_in_set', 2);
  77. sqlite_create_function($connection, 'year', 'smf_udf_year', 1);
  78. sqlite_create_function($connection, 'month', 'smf_udf_month', 1);
  79. sqlite_create_function($connection, 'dayofmonth', 'smf_udf_dayofmonth', 1);
  80. sqlite_create_function($connection, 'concat', 'smf_udf_concat');
  81. sqlite_create_function($connection, 'locate', 'smf_udf_locate', 2);
  82. sqlite_create_function($connection, 'regexp', 'smf_udf_regexp', 2);
  83. return $connection;
  84. }
  85. /**
  86. * Extend the database functionality. It calls the respective file's init
  87. * to add the implementations in that file to $smcFunc array.
  88. *
  89. * @param string $type indicated which additional file to load. ('extra', 'packages')
  90. */
  91. function db_extend($type = 'extra')
  92. {
  93. global $sourcedir, $db_type;
  94. require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-' . $db_type . '.php');
  95. $initFunc = 'db_' . $type . '_init';
  96. $initFunc();
  97. }
  98. /**
  99. * Fix db prefix if necessary.
  100. * SQLite doesn't actually need this!
  101. *
  102. * @param type $db_prefix
  103. * @param type $db_name
  104. */
  105. function db_fix_prefix(&$db_prefix, $db_name)
  106. {
  107. return false;
  108. }
  109. /**
  110. * Callback for preg_replace_calback on the query.
  111. * It allows to replace on the fly a few pre-defined strings, for
  112. * convenience ('query_see_board', 'query_wanna_see_board'), with
  113. * their current values from $user_info.
  114. * In addition, it performs checks and sanitization on the values
  115. * sent to the database.
  116. *
  117. * @param $matches
  118. */
  119. function smf_db_replacement__callback($matches)
  120. {
  121. global $db_callback, $user_info, $db_prefix, $smcFunc;
  122. list ($values, $connection) = $db_callback;
  123. if ($matches[1] === 'db_prefix')
  124. return $db_prefix;
  125. if ($matches[1] === 'query_see_board')
  126. return $user_info['query_see_board'];
  127. if ($matches[1] === 'query_wanna_see_board')
  128. return $user_info['query_wanna_see_board'];
  129. if ($matches[1] === 'empty')
  130. return '\'\'';
  131. if (!isset($matches[2]))
  132. smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
  133. if ($matches[1] === 'literal')
  134. return '\'' . sqlite_escape_string($matches[2]) . '\'';
  135. if (!isset($values[$matches[2]]))
  136. smf_db_error_backtrace('The database value you\'re trying to insert does not exist: ' . (isset($smcFunc['htmlspecialchars']) ? $smcFunc['htmlspecialchars']($matches[2]) : htmlspecialchars($matches[2])), '', E_USER_ERROR, __FILE__, __LINE__);
  137. $replacement = $values[$matches[2]];
  138. switch ($matches[1])
  139. {
  140. case 'int':
  141. if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
  142. smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  143. return (string) (int) $replacement;
  144. break;
  145. case 'string':
  146. case 'text':
  147. return sprintf('\'%1$s\'', sqlite_escape_string($replacement));
  148. break;
  149. case 'array_int':
  150. if (is_array($replacement))
  151. {
  152. if (empty($replacement))
  153. smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  154. foreach ($replacement as $key => $value)
  155. {
  156. if (!is_numeric($value) || (string) $value !== (string) (int) $value)
  157. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  158. $replacement[$key] = (string) (int) $value;
  159. }
  160. return implode(', ', $replacement);
  161. }
  162. else
  163. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  164. break;
  165. case 'array_string':
  166. if (is_array($replacement))
  167. {
  168. if (empty($replacement))
  169. smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  170. foreach ($replacement as $key => $value)
  171. $replacement[$key] = sprintf('\'%1$s\'', sqlite_escape_string($value));
  172. return implode(', ', $replacement);
  173. }
  174. else
  175. smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  176. break;
  177. case 'date':
  178. if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
  179. return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]);
  180. else
  181. smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  182. break;
  183. case 'float':
  184. if (!is_numeric($replacement))
  185. smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  186. return (string) (float) $replacement;
  187. break;
  188. case 'identifier':
  189. return '`' . strtr($replacement, array('`' => '', '.' => '')) . '`';
  190. break;
  191. case 'raw':
  192. return $replacement;
  193. break;
  194. default:
  195. smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
  196. break;
  197. }
  198. }
  199. /**
  200. * Just like the db_query, escape and quote a string,
  201. * but not executing the query.
  202. *
  203. * @param string $db_string
  204. * @param string $db_values
  205. * @param resource $connection
  206. */
  207. function smf_db_quote($db_string, $db_values, $connection = null)
  208. {
  209. global $db_callback, $db_connection;
  210. // Only bother if there's something to replace.
  211. if (strpos($db_string, '{') !== false)
  212. {
  213. // This is needed by the callback function.
  214. $db_callback = array($db_values, $connection === null ? $db_connection : $connection);
  215. // Do the quoting and escaping
  216. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  217. // Clear this global variable.
  218. $db_callback = array();
  219. }
  220. return $db_string;
  221. }
  222. /**
  223. * Do a query. Takes care of errors too.
  224. *
  225. * @param string $identifier
  226. * @param string $db_string
  227. * @param string $db_values
  228. * @param resource $connection
  229. */
  230. function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
  231. {
  232. global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start;
  233. global $db_unbuffered, $db_callback, $modSettings;
  234. // Decide which connection to use.
  235. $connection = $connection === null ? $db_connection : $connection;
  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. if (isset($replacements[$identifier]))
  285. $db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
  286. // SQLite doesn't support count(distinct).
  287. $db_string = trim($db_string);
  288. $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);
  289. // Or RLIKE.
  290. $db_string = preg_replace('~AND\s*(.+?)\s*RLIKE\s*(\{string:.+?\})~', 'AND REGEXP(\1, \2)', $db_string);
  291. // INSTR? No support for that buddy :(
  292. if (preg_match('~INSTR\((.+?),\s(.+?)\)~', $db_string, $matches) === 1)
  293. {
  294. $db_string = preg_replace('~INSTR\((.+?),\s(.+?)\)~', '$1 LIKE $2', $db_string);
  295. list(, $search) = explode(':', substr($matches[2], 1, -1));
  296. $db_values[$search] = '%' . $db_values[$search] . '%';
  297. }
  298. // Lets remove ASC and DESC from GROUP BY clause.
  299. if (preg_match('~GROUP BY .*? (?:ASC|DESC)~is', $db_string, $matches))
  300. {
  301. $replace = str_replace(array('ASC', 'DESC'), '', $matches[0]);
  302. $db_string = str_replace($matches[0], $replace, $db_string);
  303. }
  304. // We need to replace the SUBSTRING in the sort identifier.
  305. if ($identifier == 'substring_membergroups' && isset($db_values['sort']))
  306. $db_values['sort'] = preg_replace('~SUBSTRING~', 'SUBSTR', $db_values['sort']);
  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();
  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'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $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, $sourcedir, $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. if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
  467. {
  468. $context['error_message'] .= '<br /><br />' . nl2br($db_string);
  469. }
  470. // It's already been logged... don't log it again.
  471. fatal_error($context['error_message'], false);
  472. }
  473. /**
  474. * insert
  475. *
  476. * @param string $method, options 'replace', 'ignore', 'insert'
  477. * @param $table
  478. * @param $columns
  479. * @param $data
  480. * @param $keys
  481. * @param bool $disable_trans = false
  482. * @param resource $connection = null
  483. */
  484. function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null)
  485. {
  486. global $db_in_transact, $db_connection, $smcFunc, $db_prefix;
  487. $connection = $connection === null ? $db_connection : $connection;
  488. if (empty($data))
  489. return;
  490. if (!is_array($data[array_rand($data)]))
  491. $data = array($data);
  492. // Replace the prefix holder with the actual prefix.
  493. $table = str_replace('{db_prefix}', $db_prefix, $table);
  494. $priv_trans = false;
  495. if (count($data) > 1 && !$db_in_transact && !$disable_trans)
  496. {
  497. $smcFunc['db_transaction']('begin', $connection);
  498. $priv_trans = true;
  499. }
  500. if (!empty($data))
  501. {
  502. // Create the mold for a single row insert.
  503. $insertData = '(';
  504. foreach ($columns as $columnName => $type)
  505. {
  506. // Are we restricting the length?
  507. if (strpos($type, 'string-') !== false)
  508. $insertData .= sprintf('SUBSTR({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
  509. else
  510. $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
  511. }
  512. $insertData = substr($insertData, 0, -2) . ')';
  513. // Create an array consisting of only the columns.
  514. $indexed_columns = array_keys($columns);
  515. // Here's where the variables are injected to the query.
  516. $insertRows = array();
  517. foreach ($data as $dataRow)
  518. $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
  519. foreach ($insertRows as $entry)
  520. // Do the insert.
  521. $smcFunc['db_query']('',
  522. (($method === 'replace') ? 'REPLACE' : (' INSERT' . ($method === 'ignore' ? ' OR IGNORE' : ''))) . ' INTO ' . $table . '(' . implode(', ', $indexed_columns) . ')
  523. VALUES
  524. ' . $entry,
  525. array(
  526. 'security_override' => true,
  527. 'db_error_skip' => $table === $db_prefix . 'log_errors',
  528. ),
  529. $connection
  530. );
  531. }
  532. if ($priv_trans)
  533. $smcFunc['db_transaction']('commit', $connection);
  534. }
  535. /**
  536. * free_result. Doesn't do anything on sqlite!
  537. *
  538. * @param resource $handle = false
  539. */
  540. function smf_db_free_result($handle = false)
  541. {
  542. return true;
  543. }
  544. /**
  545. * fetch_row
  546. * Make sure we return no string indexes!
  547. *
  548. * @param $handle
  549. */
  550. function smf_db_fetch_row($handle)
  551. {
  552. return sqlite_fetch_array($handle, SQLITE_NUM);
  553. }
  554. /**
  555. * Unescape an escaped string!
  556. *
  557. * @param $string
  558. */
  559. function smf_db_unescape_string($string)
  560. {
  561. return strtr($string, array('\'\'' => '\''));
  562. }
  563. /**
  564. * This function tries to work out additional error information from a back trace.
  565. *
  566. * @param $error_message
  567. * @param $log_message
  568. * @param $error_type
  569. * @param $file
  570. * @param $line
  571. */
  572. function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
  573. {
  574. if (empty($log_message))
  575. $log_message = $error_message;
  576. foreach (debug_backtrace() as $step)
  577. {
  578. // Found it?
  579. 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)
  580. {
  581. $log_message .= '<br />Function: ' . $step['function'];
  582. break;
  583. }
  584. if (isset($step['line']))
  585. {
  586. $file = $step['file'];
  587. $line = $step['line'];
  588. }
  589. }
  590. // A special case - we want the file and line numbers for debugging.
  591. if ($error_type == 'return')
  592. return array($file, $line);
  593. // Is always a critical error.
  594. if (function_exists('log_error'))
  595. log_error($log_message, 'critical', $file, $line);
  596. if (function_exists('fatal_error'))
  597. {
  598. fatal_error($error_message, $error_type);
  599. // Cannot continue...
  600. exit;
  601. }
  602. elseif ($error_type)
  603. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type);
  604. else
  605. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
  606. }
  607. /**
  608. * Emulate UNIX_TIMESTAMP.
  609. */
  610. function smf_udf_unix_timestamp()
  611. {
  612. return strftime('%s', 'now');
  613. }
  614. /**
  615. * Emulate INET_ATON.
  616. *
  617. * @param $ip
  618. */
  619. function smf_udf_inet_aton($ip)
  620. {
  621. $chunks = explode('.', $ip);
  622. return @$chunks[0] * pow(256, 3) + @$chunks[1] * pow(256, 2) + @$chunks[2] * 256 + @$chunks[3];
  623. }
  624. /**
  625. * Emulate INET_NTOA.
  626. *
  627. * @param $n
  628. */
  629. function smf_udf_inet_ntoa($n)
  630. {
  631. $t = array(0, 0, 0, 0);
  632. $msk = 16777216.0;
  633. $n += 0.0;
  634. if ($n < 1)
  635. return '0.0.0.0';
  636. for ($i = 0; $i < 4; $i++)
  637. {
  638. $k = (int) ($n / $msk);
  639. $n -= $msk * $k;
  640. $t[$i] = $k;
  641. $msk /= 256.0;
  642. };
  643. $a = join('.', $t);
  644. return $a;
  645. }
  646. /**
  647. * Emulate FIND_IN_SET.
  648. *
  649. * @param $find
  650. * @param $groups
  651. */
  652. function smf_udf_find_in_set($find, $groups)
  653. {
  654. foreach (explode(',', $groups) as $key => $group)
  655. {
  656. if ($group == $find)
  657. return $key + 1;
  658. }
  659. return 0;
  660. }
  661. /**
  662. * Emulate YEAR.
  663. *
  664. * @param $date
  665. */
  666. function smf_udf_year($date)
  667. {
  668. return substr($date, 0, 4);
  669. }
  670. /**
  671. * Emulate MONTH.
  672. *
  673. * @param $date
  674. */
  675. function smf_udf_month($date)
  676. {
  677. return substr($date, 5, 2);
  678. }
  679. /**
  680. * Emulate DAYOFMONTH.
  681. *
  682. * @param $date
  683. */
  684. function smf_udf_dayofmonth($date)
  685. {
  686. return substr($date, 8, 2);
  687. }
  688. /**
  689. * We need this since sqlite_libversion() doesn't take any parameters.
  690. *
  691. * @param $void
  692. */
  693. function smf_db_libversion($void = null)
  694. {
  695. return sqlite_libversion();
  696. }
  697. /**
  698. * This function uses variable argument lists so that it can handle more then two parameters.
  699. * Emulates the CONCAT function.
  700. */
  701. function smf_udf_concat()
  702. {
  703. // Since we didn't specify any arguments we must get them from PHP.
  704. $args = func_get_args();
  705. // It really doesn't matter if there were 0 to 100 arguments, just slap them all together.
  706. return implode('', $args);
  707. }
  708. /**
  709. * We need to use PHP to locate the position in the string.
  710. *
  711. * @param string $find
  712. * @param string $string
  713. */
  714. function smf_udf_locate($find, $string)
  715. {
  716. return strpos($string, $find);
  717. }
  718. /**
  719. * This is used to replace RLIKE.
  720. *
  721. * @param string $exp
  722. * @param string $search
  723. */
  724. function smf_udf_regexp($exp, $search)
  725. {
  726. if (preg_match($exp, $match))
  727. return 1;
  728. return 0;
  729. }
  730. /**
  731. * Escape the LIKE wildcards so that they match the character and not the wildcard.
  732. * The optional second parameter turns human readable wildcards into SQL wildcards.
  733. */
  734. function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false)
  735. {
  736. $replacements = array(
  737. '%' => '\%',
  738. '\\' => '\\\\',
  739. );
  740. if ($translate_human_wildcards)
  741. $replacements += array(
  742. '*' => '%',
  743. );
  744. return strtr($string, $replacements);
  745. }
  746. ?>