2
0

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