Subs-Db-mysqli.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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. $connection = @mysqli_connect('p:' . $db_server, $db_user, $db_passwd);
  58. else
  59. $connection = @mysqli_connect($db_server, $db_user, $db_passwd);
  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. // Select the database, unless told not to
  69. if (empty($db_options['dont_select_db']) && !@mysqli_select_db($connection, $db_name) && empty($db_options['non_fatal']))
  70. display_db_error();
  71. // This makes it possible to have SMF automatically change the sql_mode and autocommit if needed.
  72. if (isset($mysql_set_mode) && $mysql_set_mode === true)
  73. $smcFunc['db_query']('', 'SET sql_mode = \'\', AUTOCOMMIT = 1',
  74. array(),
  75. false
  76. );
  77. return $connection;
  78. }
  79. /**
  80. * Extend the database functionality. It calls the respective file's init
  81. * to add the implementations in that file to $smcFunc array.
  82. *
  83. * @param string $type indicated which additional file to load. ('extra', 'packages')
  84. */
  85. function db_extend($type = 'extra')
  86. {
  87. global $sourcedir;
  88. // we force the MySQL files as nothing syntactically changes with MySQLi
  89. require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-mysql.php');
  90. $initFunc = 'db_' . $type . '_init';
  91. $initFunc();
  92. }
  93. /**
  94. * Fix up the prefix so it doesn't require the database to be selected.
  95. *
  96. * @param string &db_prefix
  97. * @param string $db_name
  98. */
  99. function db_fix_prefix(&$db_prefix, $db_name)
  100. {
  101. $db_prefix = is_numeric(substr($db_prefix, 0, 1)) ? $db_name . '.' . $db_prefix : '`' . $db_name . '`.' . $db_prefix;
  102. }
  103. /**
  104. * Wrap mysqli_select_db so the connection does not need to be specified
  105. *
  106. * @param string &database
  107. * @param object $connection
  108. */
  109. function smf_db_select($database, $connection = null)
  110. {
  111. global $db_connection;
  112. return mysqli_select_db($connection === null ? $db_connection : $connection, $database);
  113. }
  114. /**
  115. * Wrap mysqli_get_server_info so the connection does not need to be specified
  116. *
  117. * @param object $connection
  118. */
  119. function smf_db_get_server_info($connection = null)
  120. {
  121. global $db_connection;
  122. return mysqli_get_server_info($connection === null ? $db_connection : $connection);
  123. }
  124. /**
  125. * Callback for preg_replace_callback on the query.
  126. * It allows to replace on the fly a few pre-defined strings, for convenience ('query_see_board', 'query_wanna_see_board'), with
  127. * their current values from $user_info.
  128. * In addition, it performs checks and sanitization on the values sent to the database.
  129. *
  130. * @param $matches
  131. */
  132. function smf_db_replacement__callback($matches)
  133. {
  134. global $db_callback, $user_info, $db_prefix;
  135. list ($values, $connection) = $db_callback;
  136. if (!is_object($connection))
  137. display_db_error();
  138. if ($matches[1] === 'db_prefix')
  139. return $db_prefix;
  140. if ($matches[1] === 'query_see_board')
  141. return $user_info['query_see_board'];
  142. if ($matches[1] === 'query_wanna_see_board')
  143. return $user_info['query_wanna_see_board'];
  144. if (!isset($matches[2]))
  145. smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
  146. if (!isset($values[$matches[2]]))
  147. smf_db_error_backtrace('The database value you\'re trying to insert does not exist: ' . htmlspecialchars($matches[2]), '', E_USER_ERROR, __FILE__, __LINE__);
  148. $replacement = $values[$matches[2]];
  149. switch ($matches[1])
  150. {
  151. case 'int':
  152. if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
  153. smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  154. return (string) (int) $replacement;
  155. break;
  156. case 'string':
  157. case 'text':
  158. return sprintf('\'%1$s\'', mysqli_real_escape_string($connection, $replacement));
  159. break;
  160. case 'array_int':
  161. if (is_array($replacement))
  162. {
  163. if (empty($replacement))
  164. smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  165. foreach ($replacement as $key => $value)
  166. {
  167. if (!is_numeric($value) || (string) $value !== (string) (int) $value)
  168. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  169. $replacement[$key] = (string) (int) $value;
  170. }
  171. return implode(', ', $replacement);
  172. }
  173. else
  174. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  175. break;
  176. case 'array_string':
  177. if (is_array($replacement))
  178. {
  179. if (empty($replacement))
  180. smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  181. foreach ($replacement as $key => $value)
  182. $replacement[$key] = sprintf('\'%1$s\'', mysqli_real_escape_string($connection, $value));
  183. return implode(', ', $replacement);
  184. }
  185. else
  186. smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  187. break;
  188. case 'date':
  189. if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
  190. return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]);
  191. else
  192. smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  193. break;
  194. case 'float':
  195. if (!is_numeric($replacement))
  196. smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  197. return (string) (float) $replacement;
  198. break;
  199. case 'identifier':
  200. // Backticks inside identifiers are supported as of MySQL 4.1. We don't need them for SMF.
  201. return '`' . strtr($replacement, array('`' => '', '.' => '')) . '`';
  202. break;
  203. case 'raw':
  204. return $replacement;
  205. break;
  206. default:
  207. smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
  208. break;
  209. }
  210. }
  211. /**
  212. * Just like the db_query, escape and quote a string, but not executing the query.
  213. *
  214. * @param string $db_string
  215. * @param array $db_values
  216. * @param object $connection = null
  217. */
  218. function smf_db_quote($db_string, $db_values, $connection = null)
  219. {
  220. global $db_callback, $db_connection;
  221. // Only bother if there's something to replace.
  222. if (strpos($db_string, '{') !== false)
  223. {
  224. // This is needed by the callback function.
  225. $db_callback = array($db_values, $connection === null ? $db_connection : $connection);
  226. // Do the quoting and escaping
  227. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  228. // Clear this global variable.
  229. $db_callback = array();
  230. }
  231. return $db_string;
  232. }
  233. /**
  234. * Do a query. Takes care of errors too.
  235. *
  236. * @param string $identifier
  237. * @param string $db_string
  238. * @param array $db_values = array()
  239. * @param object $connection = null
  240. */
  241. function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
  242. {
  243. global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start;
  244. global $db_unbuffered, $db_callback, $modSettings;
  245. // Comments that are allowed in a query are preg_removed.
  246. static $allowed_comments_from = array(
  247. '~\s+~s',
  248. '~/\*!40001 SQL_NO_CACHE \*/~',
  249. '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
  250. '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
  251. );
  252. static $allowed_comments_to = array(
  253. ' ',
  254. '',
  255. '',
  256. '',
  257. );
  258. // Decide which connection to use.
  259. $connection = $connection === null ? $db_connection : $connection;
  260. // Get a connection if we are shutting down, sometimes the link is closed before sessions are written
  261. if (!is_object($connection))
  262. {
  263. global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd;
  264. // Are we in SSI mode? If so try that username and password first
  265. if (SMF == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd))
  266. {
  267. if (empty($db_persist))
  268. $db_connection = @mysqli_connect($db_server, $ssi_db_user, $ssi_db_passwd);
  269. else
  270. $db_connection = @mysqli_connect('p:' . $db_server, $ssi_db_user, $ssi_db_passwd);
  271. }
  272. // Fall back to the regular username and password if need be
  273. if (!$db_connection)
  274. {
  275. if (empty($db_persist))
  276. $db_connection = @mysqli_connect($db_server, $db_user, $db_passwd);
  277. else
  278. $db_connection = @mysqli_connect('p:' . $db_server, $db_user, $db_passwd);
  279. }
  280. if (!$db_connection || !@mysqli_select_db($db_connection, $db_name))
  281. $db_connection = false;
  282. $connection = $db_connection;
  283. }
  284. // One more query....
  285. $db_count = !isset($db_count) ? 1 : $db_count + 1;
  286. if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
  287. smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
  288. // Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By
  289. if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && strpos($db_string, 'INSERT INTO') === false)
  290. {
  291. // Add before LIMIT
  292. if ($pos = strpos($db_string, 'LIMIT '))
  293. $db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string));
  294. else
  295. // Append it.
  296. $db_string .= "\n\t\t\tORDER BY null";
  297. }
  298. if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
  299. {
  300. // Pass some values to the global space for use in the callback function.
  301. $db_callback = array($db_values, $connection);
  302. // Inject the values passed to this function.
  303. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  304. // This shouldn't be residing in global space any longer.
  305. $db_callback = array();
  306. }
  307. // Debugging.
  308. if (isset($db_show_debug) && $db_show_debug === true)
  309. {
  310. // Get the file and line number this function was called.
  311. list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
  312. // Initialize $db_cache if not already initialized.
  313. if (!isset($db_cache))
  314. $db_cache = array();
  315. if (!empty($_SESSION['debug_redirect']))
  316. {
  317. $db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
  318. $db_count = count($db_cache) + 1;
  319. $_SESSION['debug_redirect'] = array();
  320. }
  321. // Don't overload it.
  322. $st = microtime();
  323. $db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
  324. $db_cache[$db_count]['f'] = $file;
  325. $db_cache[$db_count]['l'] = $line;
  326. $db_cache[$db_count]['s'] = array_sum(explode(' ', $st)) - array_sum(explode(' ', $time_start));
  327. }
  328. // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
  329. if (empty($modSettings['disableQueryCheck']))
  330. {
  331. $clean = '';
  332. $old_pos = 0;
  333. $pos = -1;
  334. while (true)
  335. {
  336. $pos = strpos($db_string, '\'', $pos + 1);
  337. if ($pos === false)
  338. break;
  339. $clean .= substr($db_string, $old_pos, $pos - $old_pos);
  340. while (true)
  341. {
  342. $pos1 = strpos($db_string, '\'', $pos + 1);
  343. $pos2 = strpos($db_string, '\\', $pos + 1);
  344. if ($pos1 === false)
  345. break;
  346. elseif ($pos2 == false || $pos2 > $pos1)
  347. {
  348. $pos = $pos1;
  349. break;
  350. }
  351. $pos = $pos2 + 1;
  352. }
  353. $clean .= ' %s ';
  354. $old_pos = $pos + 1;
  355. }
  356. $clean .= substr($db_string, $old_pos);
  357. $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
  358. // We don't use UNION in SMF, at least so far. But it's useful for injections.
  359. if (strpos($clean, 'union') !== false && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0)
  360. $fail = true;
  361. // Comments? We don't use comments in our queries, we leave 'em outside!
  362. elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
  363. $fail = true;
  364. // Trying to change passwords, slow us down, or something?
  365. elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
  366. $fail = true;
  367. elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
  368. $fail = true;
  369. // Sub selects? We don't use those either.
  370. elseif (preg_match('~\([^)]*?select~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 $forum_version, $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']);
  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. // A database error is often the sign of a database in need of upgrade. Check forum versions, and if not identical suggest an upgrade... (not for Demo/CVS versions!)
  586. if (allowedTo('admin_forum') && !empty($forum_version) && $forum_version != 'SMF ' . @$modSettings['smfVersion'] && strpos($forum_version, 'Demo') === false && strpos($forum_version, 'CVS') === false)
  587. $context['error_message'] .= '<br /><br />' . sprintf($txt['database_error_versions'], $forum_version, $modSettings['smfVersion']);
  588. if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
  589. {
  590. $context['error_message'] .= '<br /><br />' . nl2br($db_string);
  591. }
  592. // It's already been logged... don't log it again.
  593. fatal_error($context['error_message'], false);
  594. }
  595. /**
  596. * insert
  597. *
  598. * @param string $method - options 'replace', 'ignore', 'insert'
  599. * @param $table
  600. * @param $columns
  601. * @param $data
  602. * @param $keys
  603. * @param bool $disable_trans = false
  604. * @param object $connection = null
  605. */
  606. function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null)
  607. {
  608. global $smcFunc, $db_connection, $db_prefix;
  609. $connection = $connection === null ? $db_connection : $connection;
  610. // With nothing to insert, simply return.
  611. if (empty($data))
  612. return;
  613. // Replace the prefix holder with the actual prefix.
  614. $table = str_replace('{db_prefix}', $db_prefix, $table);
  615. // Inserting data as a single row can be done as a single array.
  616. if (!is_array($data[array_rand($data)]))
  617. $data = array($data);
  618. // Create the mold for a single row insert.
  619. $insertData = '(';
  620. foreach ($columns as $columnName => $type)
  621. {
  622. // Are we restricting the length?
  623. if (strpos($type, 'string-') !== false)
  624. $insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
  625. else
  626. $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
  627. }
  628. $insertData = substr($insertData, 0, -2) . ')';
  629. // Create an array consisting of only the columns.
  630. $indexed_columns = array_keys($columns);
  631. // Here's where the variables are injected to the query.
  632. $insertRows = array();
  633. foreach ($data as $dataRow)
  634. $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
  635. // Determine the method of insertion.
  636. $queryTitle = $method == 'replace' ? 'REPLACE' : ($method == 'ignore' ? 'INSERT IGNORE' : 'INSERT');
  637. // Do the insert.
  638. $smcFunc['db_query']('', '
  639. ' . $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`)
  640. VALUES
  641. ' . implode(',
  642. ', $insertRows),
  643. array(
  644. 'security_override' => true,
  645. 'db_error_skip' => $table === $db_prefix . 'log_errors',
  646. ),
  647. $connection
  648. );
  649. }
  650. /**
  651. * This function tries to work out additional error information from a back trace.
  652. *
  653. * @param $error_message
  654. * @param $log_message
  655. * @param $error_type
  656. * @param $file
  657. * @param $line
  658. */
  659. function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
  660. {
  661. if (empty($log_message))
  662. $log_message = $error_message;
  663. foreach (debug_backtrace() as $step)
  664. {
  665. // Found it?
  666. if (strpos($step['function'], 'query') === false && !in_array(substr($step['function'], 0, 7), array('smf_db_', 'preg_re', 'db_erro', 'call_us')) && strpos($step['function'], '__') !== 0)
  667. {
  668. $log_message .= '<br />Function: ' . $step['function'];
  669. break;
  670. }
  671. if (isset($step['line']))
  672. {
  673. $file = $step['file'];
  674. $line = $step['line'];
  675. }
  676. }
  677. // A special case - we want the file and line numbers for debugging.
  678. if ($error_type == 'return')
  679. return array($file, $line);
  680. // Is always a critical error.
  681. if (function_exists('log_error'))
  682. log_error($log_message, 'critical', $file, $line);
  683. if (function_exists('fatal_error'))
  684. {
  685. fatal_error($error_message, false);
  686. // Cannot continue...
  687. exit;
  688. }
  689. elseif ($error_type)
  690. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type);
  691. else
  692. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
  693. }
  694. /**
  695. * Escape the LIKE wildcards so that they match the character and not the wildcard.
  696. *
  697. * @param $string
  698. * @param bool $translate_human_wildcards = false, if true, turns human readable wildcards into SQL wildcards.
  699. */
  700. function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false)
  701. {
  702. $replacements = array(
  703. '%' => '\%',
  704. '_' => '\_',
  705. '\\' => '\\\\',
  706. );
  707. if ($translate_human_wildcards)
  708. $replacements += array(
  709. '*' => '%',
  710. );
  711. return strtr($string, $replacements);
  712. }
  713. ?>