Subs-Db-sqlite.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. <?php
  2. /**
  3. * This file has all the main functions in it that relate to the database.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2012 Simple Machines contributors
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * Maps the implementations in this file (smf_db_function_name)
  18. * to the $smcFunc['db_function_name'] variable.
  19. *
  20. * @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. // 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!)
  463. if (allowedTo('admin_forum') && !empty($forum_version) && $forum_version != 'SMF ' . @$modSettings['smfVersion'] && strpos($forum_version, 'Demo') === false && strpos($forum_version, 'CVS') === false)
  464. $context['error_message'] .= '<br /><br />' . sprintf($txt['database_error_versions'], $forum_version, $modSettings['smfVersion']);
  465. if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
  466. {
  467. $context['error_message'] .= '<br /><br />' . nl2br($db_string);
  468. }
  469. // It's already been logged... don't log it again.
  470. fatal_error($context['error_message'], false);
  471. }
  472. /**
  473. * insert
  474. *
  475. * @param string $method, options 'replace', 'ignore', 'insert'
  476. * @param $table
  477. * @param $columns
  478. * @param $data
  479. * @param $keys
  480. * @param bool $disable_trans = false
  481. * @param resource $connection = null
  482. */
  483. function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null)
  484. {
  485. global $db_in_transact, $db_connection, $smcFunc, $db_prefix;
  486. $connection = $connection === null ? $db_connection : $connection;
  487. if (empty($data))
  488. return;
  489. if (!is_array($data[array_rand($data)]))
  490. $data = array($data);
  491. // Replace the prefix holder with the actual prefix.
  492. $table = str_replace('{db_prefix}', $db_prefix, $table);
  493. $priv_trans = false;
  494. if (count($data) > 1 && !$db_in_transact && !$disable_trans)
  495. {
  496. $smcFunc['db_transaction']('begin', $connection);
  497. $priv_trans = true;
  498. }
  499. if (!empty($data))
  500. {
  501. // Create the mold for a single row insert.
  502. $insertData = '(';
  503. foreach ($columns as $columnName => $type)
  504. {
  505. // Are we restricting the length?
  506. if (strpos($type, 'string-') !== false)
  507. $insertData .= sprintf('SUBSTR({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
  508. else
  509. $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
  510. }
  511. $insertData = substr($insertData, 0, -2) . ')';
  512. // Create an array consisting of only the columns.
  513. $indexed_columns = array_keys($columns);
  514. // Here's where the variables are injected to the query.
  515. $insertRows = array();
  516. foreach ($data as $dataRow)
  517. $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
  518. foreach ($insertRows as $entry)
  519. // Do the insert.
  520. $smcFunc['db_query']('',
  521. (($method === 'replace') ? 'REPLACE' : (' INSERT' . ($method === 'ignore' ? ' OR IGNORE' : ''))) . ' INTO ' . $table . '(' . implode(', ', $indexed_columns) . ')
  522. VALUES
  523. ' . $entry,
  524. array(
  525. 'security_override' => true,
  526. 'db_error_skip' => $table === $db_prefix . 'log_errors',
  527. ),
  528. $connection
  529. );
  530. }
  531. if ($priv_trans)
  532. $smcFunc['db_transaction']('commit', $connection);
  533. }
  534. /**
  535. * free_result. Doesn't do anything on sqlite!
  536. *
  537. * @param resource $handle = false
  538. */
  539. function smf_db_free_result($handle = false)
  540. {
  541. return true;
  542. }
  543. /**
  544. * fetch_row
  545. * Make sure we return no string indexes!
  546. *
  547. * @param $handle
  548. */
  549. function smf_db_fetch_row($handle)
  550. {
  551. return sqlite_fetch_array($handle, SQLITE_NUM);
  552. }
  553. /**
  554. * Unescape an escaped string!
  555. *
  556. * @param $string
  557. */
  558. function smf_db_unescape_string($string)
  559. {
  560. return strtr($string, array('\'\'' => '\''));
  561. }
  562. /**
  563. * This function tries to work out additional error information from a back trace.
  564. *
  565. * @param $error_message
  566. * @param $log_message
  567. * @param $error_type
  568. * @param $file
  569. * @param $line
  570. */
  571. function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
  572. {
  573. if (empty($log_message))
  574. $log_message = $error_message;
  575. foreach (debug_backtrace() as $step)
  576. {
  577. // Found it?
  578. 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)
  579. {
  580. $log_message .= '<br />Function: ' . $step['function'];
  581. break;
  582. }
  583. if (isset($step['line']))
  584. {
  585. $file = $step['file'];
  586. $line = $step['line'];
  587. }
  588. }
  589. // A special case - we want the file and line numbers for debugging.
  590. if ($error_type == 'return')
  591. return array($file, $line);
  592. // Is always a critical error.
  593. if (function_exists('log_error'))
  594. log_error($log_message, 'critical', $file, $line);
  595. if (function_exists('fatal_error'))
  596. {
  597. fatal_error($error_message, $error_type);
  598. // Cannot continue...
  599. exit;
  600. }
  601. elseif ($error_type)
  602. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type);
  603. else
  604. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
  605. }
  606. /**
  607. * Emulate UNIX_TIMESTAMP.
  608. */
  609. function smf_udf_unix_timestamp()
  610. {
  611. return strftime('%s', 'now');
  612. }
  613. /**
  614. * Emulate INET_ATON.
  615. *
  616. * @param $ip
  617. */
  618. function smf_udf_inet_aton($ip)
  619. {
  620. $chunks = explode('.', $ip);
  621. return @$chunks[0] * pow(256, 3) + @$chunks[1] * pow(256, 2) + @$chunks[2] * 256 + @$chunks[3];
  622. }
  623. /**
  624. * Emulate INET_NTOA.
  625. *
  626. * @param $n
  627. */
  628. function smf_udf_inet_ntoa($n)
  629. {
  630. $t = array(0, 0, 0, 0);
  631. $msk = 16777216.0;
  632. $n += 0.0;
  633. if ($n < 1)
  634. return '0.0.0.0';
  635. for ($i = 0; $i < 4; $i++)
  636. {
  637. $k = (int) ($n / $msk);
  638. $n -= $msk * $k;
  639. $t[$i] = $k;
  640. $msk /= 256.0;
  641. };
  642. $a = join('.', $t);
  643. return $a;
  644. }
  645. /**
  646. * Emulate FIND_IN_SET.
  647. *
  648. * @param $find
  649. * @param $groups
  650. */
  651. function smf_udf_find_in_set($find, $groups)
  652. {
  653. foreach (explode(',', $groups) as $key => $group)
  654. {
  655. if ($group == $find)
  656. return $key + 1;
  657. }
  658. return 0;
  659. }
  660. /**
  661. * Emulate YEAR.
  662. *
  663. * @param $date
  664. */
  665. function smf_udf_year($date)
  666. {
  667. return substr($date, 0, 4);
  668. }
  669. /**
  670. * Emulate MONTH.
  671. *
  672. * @param $date
  673. */
  674. function smf_udf_month($date)
  675. {
  676. return substr($date, 5, 2);
  677. }
  678. /**
  679. * Emulate DAYOFMONTH.
  680. *
  681. * @param $date
  682. */
  683. function smf_udf_dayofmonth($date)
  684. {
  685. return substr($date, 8, 2);
  686. }
  687. /**
  688. * We need this since sqlite_libversion() doesn't take any parameters.
  689. *
  690. * @param $void
  691. */
  692. function smf_db_libversion($void = null)
  693. {
  694. return sqlite_libversion();
  695. }
  696. /**
  697. * This function uses variable argument lists so that it can handle more then two parameters.
  698. * Emulates the CONCAT function.
  699. */
  700. function smf_udf_concat()
  701. {
  702. // Since we didn't specify any arguments we must get them from PHP.
  703. $args = func_get_args();
  704. // It really doesn't matter if there were 0 to 100 arguments, just slap them all together.
  705. return implode('', $args);
  706. }
  707. /**
  708. * We need to use PHP to locate the position in the string.
  709. *
  710. * @param string $find
  711. * @param string $string
  712. */
  713. function smf_udf_locate($find, $string)
  714. {
  715. return strpos($string, $find);
  716. }
  717. /**
  718. * This is used to replace RLIKE.
  719. *
  720. * @param string $exp
  721. * @param string $search
  722. */
  723. function smf_udf_regexp($exp, $search)
  724. {
  725. if (preg_match($exp, $match))
  726. return 1;
  727. return 0;
  728. }
  729. /**
  730. * Escape the LIKE wildcards so that they match the character and not the wildcard.
  731. * The optional second parameter turns human readable wildcards into SQL wildcards.
  732. */
  733. function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false)
  734. {
  735. $replacements = array(
  736. '%' => '\%',
  737. '\\' => '\\\\',
  738. );
  739. if ($translate_human_wildcards)
  740. $replacements += array(
  741. '*' => '%',
  742. );
  743. return strtr($string, $replacements);
  744. }
  745. ?>