Subs-Db-sqlite3.php 26 KB

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