Subs-Db-sqlite.php 25 KB

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