Subs-Db-sqlite3.php 27 KB

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