Subs-Db-mysqli.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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 2012 Simple Machines
  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. * @return null
  27. */
  28. function smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, $db_options = array())
  29. {
  30. global $smcFunc, $mysql_set_mode;
  31. // Map some database specific functions, only do this once.
  32. if (!isset($smcFunc['db_fetch_assoc']) || $smcFunc['db_fetch_assoc'] != 'mysqli_fetch_assoc')
  33. $smcFunc += array(
  34. 'db_query' => 'smf_db_query',
  35. 'db_quote' => 'smf_db_quote',
  36. 'db_fetch_assoc' => 'mysqli_fetch_assoc',
  37. 'db_fetch_row' => 'mysqli_fetch_row',
  38. 'db_free_result' => 'mysqli_free_result',
  39. 'db_insert' => 'smf_db_insert',
  40. 'db_insert_id' => 'smf_db_insert_id',
  41. 'db_num_rows' => 'mysqli_num_rows',
  42. 'db_data_seek' => 'mysqli_data_seek',
  43. 'db_num_fields' => 'mysqli_num_fields',
  44. 'db_escape_string' => 'addslashes',
  45. 'db_unescape_string' => 'stripslashes',
  46. 'db_server_info' => 'smf_db_get_server_info',
  47. 'db_affected_rows' => 'smf_db_affected_rows',
  48. 'db_transaction' => 'smf_db_transaction',
  49. 'db_error' => 'mysqli_error',
  50. 'db_select_db' => 'smf_db_select',
  51. 'db_title' => 'MySQLi',
  52. 'db_sybase' => false,
  53. 'db_case_sensitive' => false,
  54. 'db_escape_wildcard_string' => 'smf_db_escape_wildcard_string',
  55. );
  56. if (!empty($db_options['persist']))
  57. $db_server = 'p:' . $db_server;
  58. if (!empty($db_options['port']))
  59. $connection = @mysqli_connect($db_server, $db_user, $db_passwd, '', $db_options['port']);
  60. else
  61. $connection = @mysqli_connect($db_server, $db_user, $db_passwd);
  62. // Something's wrong, show an error if its fatal (which we assume it is)
  63. if (!$connection)
  64. {
  65. if (!empty($db_options['non_fatal']))
  66. return null;
  67. else
  68. display_db_error();
  69. }
  70. // Select the database, unless told not to
  71. if (empty($db_options['dont_select_db']) && !@mysqli_select_db($connection, $db_name) && empty($db_options['non_fatal']))
  72. display_db_error();
  73. // This makes it possible to have SMF automatically change the sql_mode and autocommit if needed.
  74. if (isset($mysql_set_mode) && $mysql_set_mode === true)
  75. $smcFunc['db_query']('', 'SET sql_mode = \'\', AUTOCOMMIT = 1',
  76. array(),
  77. false
  78. );
  79. return $connection;
  80. }
  81. /**
  82. * Extend the database functionality. It calls the respective file's init
  83. * to add the implementations in that file to $smcFunc array.
  84. *
  85. * @param string $type indicated which additional file to load. ('extra', 'packages')
  86. */
  87. function db_extend($type = 'extra')
  88. {
  89. global $sourcedir;
  90. // we force the MySQL files as nothing syntactically changes with MySQLi
  91. require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-mysql.php');
  92. $initFunc = 'db_' . $type . '_init';
  93. $initFunc();
  94. }
  95. /**
  96. * Fix up the prefix so it doesn't require the database to be selected.
  97. *
  98. * @param string &db_prefix
  99. * @param string $db_name
  100. */
  101. function db_fix_prefix(&$db_prefix, $db_name)
  102. {
  103. $db_prefix = is_numeric(substr($db_prefix, 0, 1)) ? $db_name . '.' . $db_prefix : '`' . $db_name . '`.' . $db_prefix;
  104. }
  105. /**
  106. * Wrap mysqli_select_db so the connection does not need to be specified
  107. *
  108. * @param string &database
  109. * @param object $connection
  110. */
  111. function smf_db_select($database, $connection = null)
  112. {
  113. global $db_connection;
  114. return mysqli_select_db($connection === null ? $db_connection : $connection, $database);
  115. }
  116. /**
  117. * Wrap mysqli_get_server_info so the connection does not need to be specified
  118. *
  119. * @param object $connection
  120. */
  121. function smf_db_get_server_info($connection = null)
  122. {
  123. global $db_connection;
  124. return mysqli_get_server_info($connection === null ? $db_connection : $connection);
  125. }
  126. /**
  127. * Callback for preg_replace_callback on the query.
  128. * It allows to replace on the fly a few pre-defined strings, for convenience ('query_see_board', 'query_wanna_see_board'), with
  129. * their current values from $user_info.
  130. * In addition, it performs checks and sanitization on the values sent to the database.
  131. *
  132. * @param $matches
  133. */
  134. function smf_db_replacement__callback($matches)
  135. {
  136. global $db_callback, $user_info, $db_prefix, $smcFunc;
  137. list ($values, $connection) = $db_callback;
  138. if (!is_object($connection))
  139. display_db_error();
  140. if ($matches[1] === 'db_prefix')
  141. return $db_prefix;
  142. if ($matches[1] === 'query_see_board')
  143. return $user_info['query_see_board'];
  144. if ($matches[1] === 'query_wanna_see_board')
  145. return $user_info['query_wanna_see_board'];
  146. if ($matches[1] === 'empty')
  147. return '\'\'';
  148. if (!isset($matches[2]))
  149. smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
  150. if ($matches[1] === 'literal')
  151. return '\'' . mysqli_real_escape_string($connection, $matches[2]) . '\'';
  152. if (!isset($values[$matches[2]]))
  153. 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__);
  154. $replacement = $values[$matches[2]];
  155. switch ($matches[1])
  156. {
  157. case 'int':
  158. if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
  159. smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  160. return (string) (int) $replacement;
  161. break;
  162. case 'string':
  163. case 'text':
  164. return sprintf('\'%1$s\'', mysqli_real_escape_string($connection, $replacement));
  165. break;
  166. case 'array_int':
  167. if (is_array($replacement))
  168. {
  169. if (empty($replacement))
  170. smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  171. foreach ($replacement as $key => $value)
  172. {
  173. if (!is_numeric($value) || (string) $value !== (string) (int) $value)
  174. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  175. $replacement[$key] = (string) (int) $value;
  176. }
  177. return implode(', ', $replacement);
  178. }
  179. else
  180. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  181. break;
  182. case 'array_string':
  183. if (is_array($replacement))
  184. {
  185. if (empty($replacement))
  186. smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  187. foreach ($replacement as $key => $value)
  188. $replacement[$key] = sprintf('\'%1$s\'', mysqli_real_escape_string($connection, $value));
  189. return implode(', ', $replacement);
  190. }
  191. else
  192. smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  193. break;
  194. case 'date':
  195. if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
  196. return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]);
  197. else
  198. smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  199. break;
  200. case 'float':
  201. if (!is_numeric($replacement))
  202. smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  203. return (string) (float) $replacement;
  204. break;
  205. case 'identifier':
  206. // Backticks inside identifiers are supported as of MySQL 4.1. We don't need them for SMF.
  207. return '`' . strtr($replacement, array('`' => '', '.' => '')) . '`';
  208. break;
  209. case 'raw':
  210. return $replacement;
  211. break;
  212. default:
  213. smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
  214. break;
  215. }
  216. }
  217. /**
  218. * Just like the db_query, escape and quote a string, but not executing the query.
  219. *
  220. * @param string $db_string
  221. * @param array $db_values
  222. * @param object $connection = null
  223. */
  224. function smf_db_quote($db_string, $db_values, $connection = null)
  225. {
  226. global $db_callback, $db_connection;
  227. // Only bother if there's something to replace.
  228. if (strpos($db_string, '{') !== false)
  229. {
  230. // This is needed by the callback function.
  231. $db_callback = array($db_values, $connection === null ? $db_connection : $connection);
  232. // Do the quoting and escaping
  233. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  234. // Clear this global variable.
  235. $db_callback = array();
  236. }
  237. return $db_string;
  238. }
  239. /**
  240. * Do a query. Takes care of errors too.
  241. *
  242. * @param string $identifier
  243. * @param string $db_string
  244. * @param array $db_values = array()
  245. * @param object $connection = null
  246. */
  247. function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
  248. {
  249. global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start;
  250. global $db_unbuffered, $db_callback, $modSettings;
  251. // Comments that are allowed in a query are preg_removed.
  252. static $allowed_comments_from = array(
  253. '~\s+~s',
  254. '~/\*!40001 SQL_NO_CACHE \*/~',
  255. '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
  256. '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
  257. );
  258. static $allowed_comments_to = array(
  259. ' ',
  260. '',
  261. '',
  262. '',
  263. );
  264. // Decide which connection to use.
  265. $connection = $connection === null ? $db_connection : $connection;
  266. // Get a connection if we are shutting down, sometimes the link is closed before sessions are written
  267. if (!is_object($connection))
  268. {
  269. global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd;
  270. // Are we in SSI mode? If so try that username and password first
  271. if (SMF == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd))
  272. {
  273. if (empty($db_persist))
  274. $db_connection = @mysqli_connect($db_server, $ssi_db_user, $ssi_db_passwd);
  275. else
  276. $db_connection = @mysqli_connect('p:' . $db_server, $ssi_db_user, $ssi_db_passwd);
  277. }
  278. // Fall back to the regular username and password if need be
  279. if (!$db_connection)
  280. {
  281. if (empty($db_persist))
  282. $db_connection = @mysqli_connect($db_server, $db_user, $db_passwd);
  283. else
  284. $db_connection = @mysqli_connect('p:' . $db_server, $db_user, $db_passwd);
  285. }
  286. if (!$db_connection || !@mysqli_select_db($db_connection, $db_name))
  287. $db_connection = false;
  288. $connection = $db_connection;
  289. }
  290. // One more query....
  291. $db_count = !isset($db_count) ? 1 : $db_count + 1;
  292. if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
  293. smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
  294. // Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By
  295. if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && strpos($db_string, 'INSERT INTO') === false)
  296. {
  297. // Add before LIMIT
  298. if ($pos = strpos($db_string, 'LIMIT '))
  299. $db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string));
  300. else
  301. // Append it.
  302. $db_string .= "\n\t\t\tORDER BY null";
  303. }
  304. if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
  305. {
  306. // Pass some values to the global space for use in the callback function.
  307. $db_callback = array($db_values, $connection);
  308. // Inject the values passed to this function.
  309. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  310. // This shouldn't be residing in global space any longer.
  311. $db_callback = array();
  312. }
  313. // Debugging.
  314. if (isset($db_show_debug) && $db_show_debug === true)
  315. {
  316. // Get the file and line number this function was called.
  317. list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
  318. // Initialize $db_cache if not already initialized.
  319. if (!isset($db_cache))
  320. $db_cache = array();
  321. if (!empty($_SESSION['debug_redirect']))
  322. {
  323. $db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
  324. $db_count = count($db_cache) + 1;
  325. $_SESSION['debug_redirect'] = array();
  326. }
  327. // Don't overload it.
  328. $st = microtime();
  329. $db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
  330. $db_cache[$db_count]['f'] = $file;
  331. $db_cache[$db_count]['l'] = $line;
  332. $db_cache[$db_count]['s'] = array_sum(explode(' ', $st)) - array_sum(explode(' ', $time_start));
  333. }
  334. // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
  335. if (empty($modSettings['disableQueryCheck']))
  336. {
  337. $clean = '';
  338. $old_pos = 0;
  339. $pos = -1;
  340. while (true)
  341. {
  342. $pos = strpos($db_string, '\'', $pos + 1);
  343. if ($pos === false)
  344. break;
  345. $clean .= substr($db_string, $old_pos, $pos - $old_pos);
  346. while (true)
  347. {
  348. $pos1 = strpos($db_string, '\'', $pos + 1);
  349. $pos2 = strpos($db_string, '\\', $pos + 1);
  350. if ($pos1 === false)
  351. break;
  352. elseif ($pos2 == false || $pos2 > $pos1)
  353. {
  354. $pos = $pos1;
  355. break;
  356. }
  357. $pos = $pos2 + 1;
  358. }
  359. $clean .= ' %s ';
  360. $old_pos = $pos + 1;
  361. }
  362. $clean .= substr($db_string, $old_pos);
  363. $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
  364. // Comments? We don't use comments in our queries, we leave 'em outside!
  365. if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
  366. $fail = true;
  367. // Trying to change passwords, slow us down, or something?
  368. elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
  369. $fail = true;
  370. elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
  371. $fail = true;
  372. if (!empty($fail) && function_exists('log_error'))
  373. smf_db_error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
  374. }
  375. if (empty($db_unbuffered))
  376. $ret = @mysqli_query($connection, $db_string);
  377. else
  378. $ret = @mysqli_query($connection, $db_string, MYSQLI_USE_RESULT);
  379. if ($ret === false && empty($db_values['db_error_skip']))
  380. $ret = smf_db_error($db_string, $connection);
  381. // Debugging.
  382. if (isset($db_show_debug) && $db_show_debug === true)
  383. $db_cache[$db_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
  384. return $ret;
  385. }
  386. /**
  387. * affected_rows
  388. * @param object $connection
  389. */
  390. function smf_db_affected_rows($connection = null)
  391. {
  392. global $db_connection;
  393. return mysqli_affected_rows($connection === null ? $db_connection : $connection);
  394. }
  395. /**
  396. * insert_id
  397. *
  398. * @param string $table
  399. * @param string $field = null
  400. * @param object $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. // MySQL doesn't need the table or field information.
  407. return mysqli_insert_id($connection === null ? $db_connection : $connection);
  408. }
  409. /**
  410. * Do a transaction.
  411. *
  412. * @param string $type - the step to perform (i.e. 'begin', 'commit', 'rollback')
  413. * @param object $connection = null
  414. */
  415. function smf_db_transaction($type = 'commit', $connection = null)
  416. {
  417. global $db_connection;
  418. // Decide which connection to use
  419. $connection = $connection === null ? $db_connection : $connection;
  420. if ($type == 'begin')
  421. return @mysqli_query($connection, 'BEGIN');
  422. elseif ($type == 'rollback')
  423. return @mysqli_query($connection, 'ROLLBACK');
  424. elseif ($type == 'commit')
  425. return @mysqli_query($connection, 'COMMIT');
  426. return false;
  427. }
  428. /**
  429. * Database error!
  430. * Backtrace, log, try to fix.
  431. *
  432. * @param string $db_string
  433. * @param object $connection = null
  434. */
  435. function smf_db_error($db_string, $connection = null)
  436. {
  437. global $txt, $context, $sourcedir, $webmaster_email, $modSettings;
  438. global $db_connection, $db_last_error, $db_persist;
  439. global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd;
  440. global $smcFunc;
  441. // Get the file and line numbers.
  442. list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
  443. // Decide which connection to use
  444. $connection = $connection === null ? $db_connection : $connection;
  445. // This is the error message...
  446. $query_error = mysqli_error($connection);
  447. $query_errno = mysqli_errno($connection);
  448. // Error numbers:
  449. // 1016: Can't open file '....MYI'
  450. // 1030: Got error ??? from table handler.
  451. // 1034: Incorrect key file for table.
  452. // 1035: Old key file for table.
  453. // 1205: Lock wait timeout exceeded.
  454. // 1213: Deadlock found.
  455. // 2006: Server has gone away.
  456. // 2013: Lost connection to server during query.
  457. // Log the error.
  458. if ($query_errno != 1213 && $query_errno != 1205 && function_exists('log_error'))
  459. log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n$db_string" : ''), 'database', $file, $line);
  460. // Database error auto fixing ;).
  461. if (function_exists('cache_get_data') && (!isset($modSettings['autoFixDatabase']) || $modSettings['autoFixDatabase'] == '1'))
  462. {
  463. // Force caching on, just for the error checking.
  464. $old_cache = @$modSettings['cache_enable'];
  465. $modSettings['cache_enable'] = '1';
  466. if (($temp = cache_get_data('db_last_error', 600)) !== null)
  467. $db_last_error = max(@$db_last_error, $temp);
  468. if (@$db_last_error < time() - 3600 * 24 * 3)
  469. {
  470. // We know there's a problem... but what? Try to auto detect.
  471. if ($query_errno == 1030 && strpos($query_error, ' 127 ') !== false)
  472. {
  473. preg_match_all('~(?:[\n\r]|^)[^\']+?(?:FROM|JOIN|UPDATE|TABLE) ((?:[^\n\r(]+?(?:, )?)*)~s', $db_string, $matches);
  474. $fix_tables = array();
  475. foreach ($matches[1] as $tables)
  476. {
  477. $tables = array_unique(explode(',', $tables));
  478. foreach ($tables as $table)
  479. {
  480. // Now, it's still theoretically possible this could be an injection. So backtick it!
  481. if (trim($table) != '')
  482. $fix_tables[] = '`' . strtr(trim($table), array('`' => '')) . '`';
  483. }
  484. }
  485. $fix_tables = array_unique($fix_tables);
  486. }
  487. // Table crashed. Let's try to fix it.
  488. elseif ($query_errno == 1016)
  489. {
  490. if (preg_match('~\'([^\.\']+)~', $query_error, $match) != 0)
  491. $fix_tables = array('`' . $match[1] . '`');
  492. }
  493. // Indexes crashed. Should be easy to fix!
  494. elseif ($query_errno == 1034 || $query_errno == 1035)
  495. {
  496. preg_match('~\'([^\']+?)\'~', $query_error, $match);
  497. $fix_tables = array('`' . $match[1] . '`');
  498. }
  499. }
  500. // Check for errors like 145... only fix it once every three days, and send an email. (can't use empty because it might not be set yet...)
  501. if (!empty($fix_tables))
  502. {
  503. // Subs-Admin.php for updateSettingsFile(), Subs-Post.php for sendmail().
  504. require_once($sourcedir . '/Subs-Admin.php');
  505. require_once($sourcedir . '/Subs-Post.php');
  506. // Make a note of the REPAIR...
  507. cache_put_data('db_last_error', time(), 600);
  508. if (($temp = cache_get_data('db_last_error', 600)) === null)
  509. updateSettingsFile(array('db_last_error' => time()));
  510. // Attempt to find and repair the broken table.
  511. foreach ($fix_tables as $table)
  512. $smcFunc['db_query']('', "
  513. REPAIR TABLE $table", false, false);
  514. // And send off an email!
  515. sendmail($webmaster_email, $txt['database_error'], $txt['tried_to_repair'], null, 'dberror');
  516. $modSettings['cache_enable'] = $old_cache;
  517. // Try the query again...?
  518. $ret = $smcFunc['db_query']('', $db_string, false, false);
  519. if ($ret !== false)
  520. return $ret;
  521. }
  522. else
  523. $modSettings['cache_enable'] = $old_cache;
  524. // Check for the "lost connection" or "deadlock found" errors - and try it just one more time.
  525. if (in_array($query_errno, array(1205, 1213, 2006, 2013)))
  526. {
  527. if (in_array($query_errno, array(2006, 2013)) && $db_connection == $connection)
  528. {
  529. // Are we in SSI mode? If so try that username and password first
  530. if (SMF == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd))
  531. {
  532. if (empty($db_persist))
  533. $db_connection = @mysqli_connect($db_server, $ssi_db_user, $ssi_db_passwd);
  534. else
  535. $db_connection = @mysqli_connect('p:' . $db_server, $ssi_db_user, $ssi_db_passwd);
  536. }
  537. // Fall back to the regular username and password if need be
  538. if (!$db_connection)
  539. {
  540. if (empty($db_persist))
  541. $db_connection = @mysqli_connect($db_server, $db_user, $db_passwd);
  542. else
  543. $db_connection = @mysqli_connect('p:' . $db_server, $db_user, $db_passwd);
  544. }
  545. if (!$db_connection || !@mysqli_select_db($db_connection, $db_name))
  546. $db_connection = false;
  547. }
  548. if ($db_connection)
  549. {
  550. // Try a deadlock more than once more.
  551. for ($n = 0; $n < 4; $n++)
  552. {
  553. $ret = $smcFunc['db_query']('', $db_string, false, false);
  554. $new_errno = mysqli_errno($db_connection);
  555. if ($ret !== false || in_array($new_errno, array(1205, 1213)))
  556. break;
  557. }
  558. // If it failed again, shucks to be you... we're not trying it over and over.
  559. if ($ret !== false)
  560. return $ret;
  561. }
  562. }
  563. // Are they out of space, perhaps?
  564. elseif ($query_errno == 1030 && (strpos($query_error, ' -1 ') !== false || strpos($query_error, ' 28 ') !== false || strpos($query_error, ' 12 ') !== false))
  565. {
  566. if (!isset($txt))
  567. $query_error .= ' - check database storage space.';
  568. else
  569. {
  570. if (!isset($txt['mysql_error_space']))
  571. loadLanguage('Errors');
  572. $query_error .= !isset($txt['mysql_error_space']) ? ' - check database storage space.' : $txt['mysql_error_space'];
  573. }
  574. }
  575. }
  576. // Nothing's defined yet... just die with it.
  577. if (empty($context) || empty($txt))
  578. die($query_error);
  579. // Show an error message, if possible.
  580. $context['error_title'] = $txt['database_error'];
  581. if (allowedTo('admin_forum'))
  582. $context['error_message'] = nl2br($query_error) . '<br>' . $txt['file'] . ': ' . $file . '<br>' . $txt['line'] . ': ' . $line;
  583. else
  584. $context['error_message'] = $txt['try_again'];
  585. if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
  586. {
  587. $context['error_message'] .= '<br><br>' . nl2br($db_string);
  588. }
  589. // It's already been logged... don't log it again.
  590. fatal_error($context['error_message'], false);
  591. }
  592. /**
  593. * insert
  594. *
  595. * @param string $method - options 'replace', 'ignore', 'insert'
  596. * @param $table
  597. * @param $columns
  598. * @param $data
  599. * @param $keys
  600. * @param bool $disable_trans = false
  601. * @param object $connection = null
  602. */
  603. function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null)
  604. {
  605. global $smcFunc, $db_connection, $db_prefix;
  606. $connection = $connection === null ? $db_connection : $connection;
  607. // With nothing to insert, simply return.
  608. if (empty($data))
  609. return;
  610. // Replace the prefix holder with the actual prefix.
  611. $table = str_replace('{db_prefix}', $db_prefix, $table);
  612. // Inserting data as a single row can be done as a single array.
  613. if (!is_array($data[array_rand($data)]))
  614. $data = array($data);
  615. // Create the mold for a single row insert.
  616. $insertData = '(';
  617. foreach ($columns as $columnName => $type)
  618. {
  619. // Are we restricting the length?
  620. if (strpos($type, 'string-') !== false)
  621. $insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
  622. else
  623. $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
  624. }
  625. $insertData = substr($insertData, 0, -2) . ')';
  626. // Create an array consisting of only the columns.
  627. $indexed_columns = array_keys($columns);
  628. // Here's where the variables are injected to the query.
  629. $insertRows = array();
  630. foreach ($data as $dataRow)
  631. $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
  632. // Determine the method of insertion.
  633. $queryTitle = $method == 'replace' ? 'REPLACE' : ($method == 'ignore' ? 'INSERT IGNORE' : 'INSERT');
  634. // Do the insert.
  635. $smcFunc['db_query']('', '
  636. ' . $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`)
  637. VALUES
  638. ' . implode(',
  639. ', $insertRows),
  640. array(
  641. 'security_override' => true,
  642. 'db_error_skip' => $table === $db_prefix . 'log_errors',
  643. ),
  644. $connection
  645. );
  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, false);
  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. * Escape the LIKE wildcards so that they match the character and not the wildcard.
  693. *
  694. * @param $string
  695. * @param bool $translate_human_wildcards = false, if true, turns human readable wildcards into SQL wildcards.
  696. */
  697. function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false)
  698. {
  699. $replacements = array(
  700. '%' => '\%',
  701. '_' => '\_',
  702. '\\' => '\\\\',
  703. );
  704. if ($translate_human_wildcards)
  705. $replacements += array(
  706. '*' => '%',
  707. );
  708. return strtr($string, $replacements);
  709. }
  710. ?>