2
0

Subs-Db-sqlite.php 25 KB

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