Subs-Db-sqlite3.php 26 KB

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