Subs-Db-sqlite.php 25 KB

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