Subs-Db-sqlite.php 25 KB

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