Subs-Db-mysqli.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 ($matches[1] === 'empty')
  145. return '\'\'';
  146. if (!isset($matches[2]))
  147. smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
  148. if ($matches[1] === 'literal')
  149. return mysqli_real_escape_string($connection, $matches[2]);
  150. if (!isset($values[$matches[2]]))
  151. smf_db_error_backtrace('The database value you\'re trying to insert does not exist: ' . htmlspecialchars($matches[2]), '', E_USER_ERROR, __FILE__, __LINE__);
  152. $replacement = $values[$matches[2]];
  153. switch ($matches[1])
  154. {
  155. case 'int':
  156. if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
  157. smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  158. return (string) (int) $replacement;
  159. break;
  160. case 'string':
  161. case 'text':
  162. return sprintf('\'%1$s\'', mysqli_real_escape_string($connection, $replacement));
  163. break;
  164. case 'array_int':
  165. if (is_array($replacement))
  166. {
  167. if (empty($replacement))
  168. smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  169. foreach ($replacement as $key => $value)
  170. {
  171. if (!is_numeric($value) || (string) $value !== (string) (int) $value)
  172. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  173. $replacement[$key] = (string) (int) $value;
  174. }
  175. return implode(', ', $replacement);
  176. }
  177. else
  178. smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  179. break;
  180. case 'array_string':
  181. if (is_array($replacement))
  182. {
  183. if (empty($replacement))
  184. smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  185. foreach ($replacement as $key => $value)
  186. $replacement[$key] = sprintf('\'%1$s\'', mysqli_real_escape_string($connection, $value));
  187. return implode(', ', $replacement);
  188. }
  189. else
  190. smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  191. break;
  192. case 'date':
  193. if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
  194. return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]);
  195. else
  196. smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  197. break;
  198. case 'float':
  199. if (!is_numeric($replacement))
  200. smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
  201. return (string) (float) $replacement;
  202. break;
  203. case 'identifier':
  204. // Backticks inside identifiers are supported as of MySQL 4.1. We don't need them for SMF.
  205. return '`' . strtr($replacement, array('`' => '', '.' => '')) . '`';
  206. break;
  207. case 'raw':
  208. return $replacement;
  209. break;
  210. default:
  211. smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
  212. break;
  213. }
  214. }
  215. /**
  216. * Just like the db_query, escape and quote a string, but not executing the query.
  217. *
  218. * @param string $db_string
  219. * @param array $db_values
  220. * @param object $connection = null
  221. */
  222. function smf_db_quote($db_string, $db_values, $connection = null)
  223. {
  224. global $db_callback, $db_connection;
  225. // Only bother if there's something to replace.
  226. if (strpos($db_string, '{') !== false)
  227. {
  228. // This is needed by the callback function.
  229. $db_callback = array($db_values, $connection === null ? $db_connection : $connection);
  230. // Do the quoting and escaping
  231. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  232. // Clear this global variable.
  233. $db_callback = array();
  234. }
  235. return $db_string;
  236. }
  237. /**
  238. * Do a query. Takes care of errors too.
  239. *
  240. * @param string $identifier
  241. * @param string $db_string
  242. * @param array $db_values = array()
  243. * @param object $connection = null
  244. */
  245. function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
  246. {
  247. global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start;
  248. global $db_unbuffered, $db_callback, $modSettings;
  249. // Comments that are allowed in a query are preg_removed.
  250. static $allowed_comments_from = array(
  251. '~\s+~s',
  252. '~/\*!40001 SQL_NO_CACHE \*/~',
  253. '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
  254. '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
  255. );
  256. static $allowed_comments_to = array(
  257. ' ',
  258. '',
  259. '',
  260. '',
  261. );
  262. // Decide which connection to use.
  263. $connection = $connection === null ? $db_connection : $connection;
  264. // Get a connection if we are shutting down, sometimes the link is closed before sessions are written
  265. if (!is_object($connection))
  266. {
  267. global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd;
  268. // Are we in SSI mode? If so try that username and password first
  269. if (SMF == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd))
  270. {
  271. if (empty($db_persist))
  272. $db_connection = @mysqli_connect($db_server, $ssi_db_user, $ssi_db_passwd);
  273. else
  274. $db_connection = @mysqli_connect('p:' . $db_server, $ssi_db_user, $ssi_db_passwd);
  275. }
  276. // Fall back to the regular username and password if need be
  277. if (!$db_connection)
  278. {
  279. if (empty($db_persist))
  280. $db_connection = @mysqli_connect($db_server, $db_user, $db_passwd);
  281. else
  282. $db_connection = @mysqli_connect('p:' . $db_server, $db_user, $db_passwd);
  283. }
  284. if (!$db_connection || !@mysqli_select_db($db_connection, $db_name))
  285. $db_connection = false;
  286. $connection = $db_connection;
  287. }
  288. // One more query....
  289. $db_count = !isset($db_count) ? 1 : $db_count + 1;
  290. if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
  291. smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
  292. // Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By
  293. if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && strpos($db_string, 'INSERT INTO') === false)
  294. {
  295. // Add before LIMIT
  296. if ($pos = strpos($db_string, 'LIMIT '))
  297. $db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string));
  298. else
  299. // Append it.
  300. $db_string .= "\n\t\t\tORDER BY null";
  301. }
  302. if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
  303. {
  304. // Pass some values to the global space for use in the callback function.
  305. $db_callback = array($db_values, $connection);
  306. // Inject the values passed to this function.
  307. $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
  308. // This shouldn't be residing in global space any longer.
  309. $db_callback = array();
  310. }
  311. // Debugging.
  312. if (isset($db_show_debug) && $db_show_debug === true)
  313. {
  314. // Get the file and line number this function was called.
  315. list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
  316. // Initialize $db_cache if not already initialized.
  317. if (!isset($db_cache))
  318. $db_cache = array();
  319. if (!empty($_SESSION['debug_redirect']))
  320. {
  321. $db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
  322. $db_count = count($db_cache) + 1;
  323. $_SESSION['debug_redirect'] = array();
  324. }
  325. // Don't overload it.
  326. $st = microtime();
  327. $db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
  328. $db_cache[$db_count]['f'] = $file;
  329. $db_cache[$db_count]['l'] = $line;
  330. $db_cache[$db_count]['s'] = array_sum(explode(' ', $st)) - array_sum(explode(' ', $time_start));
  331. }
  332. // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
  333. if (empty($modSettings['disableQueryCheck']))
  334. {
  335. $clean = '';
  336. $old_pos = 0;
  337. $pos = -1;
  338. while (true)
  339. {
  340. $pos = strpos($db_string, '\'', $pos + 1);
  341. if ($pos === false)
  342. break;
  343. $clean .= substr($db_string, $old_pos, $pos - $old_pos);
  344. while (true)
  345. {
  346. $pos1 = strpos($db_string, '\'', $pos + 1);
  347. $pos2 = strpos($db_string, '\\', $pos + 1);
  348. if ($pos1 === false)
  349. break;
  350. elseif ($pos2 == false || $pos2 > $pos1)
  351. {
  352. $pos = $pos1;
  353. break;
  354. }
  355. $pos = $pos2 + 1;
  356. }
  357. $clean .= ' %s ';
  358. $old_pos = $pos + 1;
  359. }
  360. $clean .= substr($db_string, $old_pos);
  361. $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
  362. // We don't use UNION in SMF, at least so far. But it's useful for injections.
  363. if (strpos($clean, 'union') !== false && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0)
  364. $fail = true;
  365. // Comments? We don't use comments in our queries, we leave 'em outside!
  366. elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
  367. $fail = true;
  368. // Trying to change passwords, slow us down, or something?
  369. elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
  370. $fail = true;
  371. elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
  372. $fail = true;
  373. // Sub selects? We don't use those either.
  374. elseif (preg_match('~\([^)]*?select~s', $clean) != 0)
  375. $fail = true;
  376. if (!empty($fail) && function_exists('log_error'))
  377. smf_db_error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
  378. }
  379. if (empty($db_unbuffered))
  380. $ret = @mysqli_query($connection, $db_string);
  381. else
  382. $ret = @mysqli_query($connection, $db_string, MYSQLI_USE_RESULT);
  383. if ($ret === false && empty($db_values['db_error_skip']))
  384. $ret = smf_db_error($db_string, $connection);
  385. // Debugging.
  386. if (isset($db_show_debug) && $db_show_debug === true)
  387. $db_cache[$db_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
  388. return $ret;
  389. }
  390. /**
  391. * affected_rows
  392. * @param object $connection
  393. */
  394. function smf_db_affected_rows($connection = null)
  395. {
  396. global $db_connection;
  397. return mysqli_affected_rows($connection === null ? $db_connection : $connection);
  398. }
  399. /**
  400. * insert_id
  401. *
  402. * @param string $table
  403. * @param string $field = null
  404. * @param object $connection = null
  405. */
  406. function smf_db_insert_id($table, $field = null, $connection = null)
  407. {
  408. global $db_connection, $db_prefix;
  409. $table = str_replace('{db_prefix}', $db_prefix, $table);
  410. // MySQL doesn't need the table or field information.
  411. return mysqli_insert_id($connection === null ? $db_connection : $connection);
  412. }
  413. /**
  414. * Do a transaction.
  415. *
  416. * @param string $type - the step to perform (i.e. 'begin', 'commit', 'rollback')
  417. * @param object $connection = null
  418. */
  419. function smf_db_transaction($type = 'commit', $connection = null)
  420. {
  421. global $db_connection;
  422. // Decide which connection to use
  423. $connection = $connection === null ? $db_connection : $connection;
  424. if ($type == 'begin')
  425. return @mysqli_query($connection, 'BEGIN');
  426. elseif ($type == 'rollback')
  427. return @mysqli_query($connection, 'ROLLBACK');
  428. elseif ($type == 'commit')
  429. return @mysqli_query($connection, 'COMMIT');
  430. return false;
  431. }
  432. /**
  433. * Database error!
  434. * Backtrace, log, try to fix.
  435. *
  436. * @param string $db_string
  437. * @param object $connection = null
  438. */
  439. function smf_db_error($db_string, $connection = null)
  440. {
  441. global $txt, $context, $sourcedir, $webmaster_email, $modSettings;
  442. global $forum_version, $db_connection, $db_last_error, $db_persist;
  443. global $db_server, $db_user, $db_passwd, $db_name, $db_show_debug, $ssi_db_user, $ssi_db_passwd;
  444. global $smcFunc;
  445. // Get the file and line numbers.
  446. list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
  447. // Decide which connection to use
  448. $connection = $connection === null ? $db_connection : $connection;
  449. // This is the error message...
  450. $query_error = mysqli_error($connection);
  451. $query_errno = mysqli_errno($connection);
  452. // Error numbers:
  453. // 1016: Can't open file '....MYI'
  454. // 1030: Got error ??? from table handler.
  455. // 1034: Incorrect key file for table.
  456. // 1035: Old key file for table.
  457. // 1205: Lock wait timeout exceeded.
  458. // 1213: Deadlock found.
  459. // 2006: Server has gone away.
  460. // 2013: Lost connection to server during query.
  461. // Log the error.
  462. if ($query_errno != 1213 && $query_errno != 1205 && function_exists('log_error'))
  463. log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n$db_string" : ''), 'database', $file, $line);
  464. // Database error auto fixing ;).
  465. if (function_exists('cache_get_data') && (!isset($modSettings['autoFixDatabase']) || $modSettings['autoFixDatabase'] == '1'))
  466. {
  467. // Force caching on, just for the error checking.
  468. $old_cache = @$modSettings['cache_enable'];
  469. $modSettings['cache_enable'] = '1';
  470. if (($temp = cache_get_data('db_last_error', 600)) !== null)
  471. $db_last_error = max(@$db_last_error, $temp);
  472. if (@$db_last_error < time() - 3600 * 24 * 3)
  473. {
  474. // We know there's a problem... but what? Try to auto detect.
  475. if ($query_errno == 1030 && strpos($query_error, ' 127 ') !== false)
  476. {
  477. preg_match_all('~(?:[\n\r]|^)[^\']+?(?:FROM|JOIN|UPDATE|TABLE) ((?:[^\n\r(]+?(?:, )?)*)~s', $db_string, $matches);
  478. $fix_tables = array();
  479. foreach ($matches[1] as $tables)
  480. {
  481. $tables = array_unique(explode(',', $tables));
  482. foreach ($tables as $table)
  483. {
  484. // Now, it's still theoretically possible this could be an injection. So backtick it!
  485. if (trim($table) != '')
  486. $fix_tables[] = '`' . strtr(trim($table), array('`' => '')) . '`';
  487. }
  488. }
  489. $fix_tables = array_unique($fix_tables);
  490. }
  491. // Table crashed. Let's try to fix it.
  492. elseif ($query_errno == 1016)
  493. {
  494. if (preg_match('~\'([^\.\']+)~', $query_error, $match) != 0)
  495. $fix_tables = array('`' . $match[1] . '`');
  496. }
  497. // Indexes crashed. Should be easy to fix!
  498. elseif ($query_errno == 1034 || $query_errno == 1035)
  499. {
  500. preg_match('~\'([^\']+?)\'~', $query_error, $match);
  501. $fix_tables = array('`' . $match[1] . '`');
  502. }
  503. }
  504. // 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...)
  505. if (!empty($fix_tables))
  506. {
  507. // Subs-Admin.php for updateSettingsFile(), Subs-Post.php for sendmail().
  508. require_once($sourcedir . '/Subs-Admin.php');
  509. require_once($sourcedir . '/Subs-Post.php');
  510. // Make a note of the REPAIR...
  511. cache_put_data('db_last_error', time(), 600);
  512. if (($temp = cache_get_data('db_last_error', 600)) === null)
  513. updateSettingsFile(array('db_last_error' => time()));
  514. // Attempt to find and repair the broken table.
  515. foreach ($fix_tables as $table)
  516. $smcFunc['db_query']('', "
  517. REPAIR TABLE $table", false, false);
  518. // And send off an email!
  519. sendmail($webmaster_email, $txt['database_error'], $txt['tried_to_repair']);
  520. $modSettings['cache_enable'] = $old_cache;
  521. // Try the query again...?
  522. $ret = $smcFunc['db_query']('', $db_string, false, false);
  523. if ($ret !== false)
  524. return $ret;
  525. }
  526. else
  527. $modSettings['cache_enable'] = $old_cache;
  528. // Check for the "lost connection" or "deadlock found" errors - and try it just one more time.
  529. if (in_array($query_errno, array(1205, 1213, 2006, 2013)))
  530. {
  531. if (in_array($query_errno, array(2006, 2013)) && $db_connection == $connection)
  532. {
  533. // Are we in SSI mode? If so try that username and password first
  534. if (SMF == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd))
  535. {
  536. if (empty($db_persist))
  537. $db_connection = @mysqli_connect($db_server, $ssi_db_user, $ssi_db_passwd);
  538. else
  539. $db_connection = @mysqli_connect('p:' . $db_server, $ssi_db_user, $ssi_db_passwd);
  540. }
  541. // Fall back to the regular username and password if need be
  542. if (!$db_connection)
  543. {
  544. if (empty($db_persist))
  545. $db_connection = @mysqli_connect($db_server, $db_user, $db_passwd);
  546. else
  547. $db_connection = @mysqli_connect('p:' . $db_server, $db_user, $db_passwd);
  548. }
  549. if (!$db_connection || !@mysqli_select_db($db_connection, $db_name))
  550. $db_connection = false;
  551. }
  552. if ($db_connection)
  553. {
  554. // Try a deadlock more than once more.
  555. for ($n = 0; $n < 4; $n++)
  556. {
  557. $ret = $smcFunc['db_query']('', $db_string, false, false);
  558. $new_errno = mysqli_errno($db_connection);
  559. if ($ret !== false || in_array($new_errno, array(1205, 1213)))
  560. break;
  561. }
  562. // If it failed again, shucks to be you... we're not trying it over and over.
  563. if ($ret !== false)
  564. return $ret;
  565. }
  566. }
  567. // Are they out of space, perhaps?
  568. elseif ($query_errno == 1030 && (strpos($query_error, ' -1 ') !== false || strpos($query_error, ' 28 ') !== false || strpos($query_error, ' 12 ') !== false))
  569. {
  570. if (!isset($txt))
  571. $query_error .= ' - check database storage space.';
  572. else
  573. {
  574. if (!isset($txt['mysql_error_space']))
  575. loadLanguage('Errors');
  576. $query_error .= !isset($txt['mysql_error_space']) ? ' - check database storage space.' : $txt['mysql_error_space'];
  577. }
  578. }
  579. }
  580. // Nothing's defined yet... just die with it.
  581. if (empty($context) || empty($txt))
  582. die($query_error);
  583. // Show an error message, if possible.
  584. $context['error_title'] = $txt['database_error'];
  585. if (allowedTo('admin_forum'))
  586. $context['error_message'] = nl2br($query_error) . '<br />' . $txt['file'] . ': ' . $file . '<br />' . $txt['line'] . ': ' . $line;
  587. else
  588. $context['error_message'] = $txt['try_again'];
  589. if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
  590. {
  591. $context['error_message'] .= '<br /><br />' . nl2br($db_string);
  592. }
  593. // It's already been logged... don't log it again.
  594. fatal_error($context['error_message'], false);
  595. }
  596. /**
  597. * insert
  598. *
  599. * @param string $method - options 'replace', 'ignore', 'insert'
  600. * @param $table
  601. * @param $columns
  602. * @param $data
  603. * @param $keys
  604. * @param bool $disable_trans = false
  605. * @param object $connection = null
  606. */
  607. function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null)
  608. {
  609. global $smcFunc, $db_connection, $db_prefix;
  610. $connection = $connection === null ? $db_connection : $connection;
  611. // With nothing to insert, simply return.
  612. if (empty($data))
  613. return;
  614. // Replace the prefix holder with the actual prefix.
  615. $table = str_replace('{db_prefix}', $db_prefix, $table);
  616. // Inserting data as a single row can be done as a single array.
  617. if (!is_array($data[array_rand($data)]))
  618. $data = array($data);
  619. // Create the mold for a single row insert.
  620. $insertData = '(';
  621. foreach ($columns as $columnName => $type)
  622. {
  623. // Are we restricting the length?
  624. if (strpos($type, 'string-') !== false)
  625. $insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
  626. else
  627. $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
  628. }
  629. $insertData = substr($insertData, 0, -2) . ')';
  630. // Create an array consisting of only the columns.
  631. $indexed_columns = array_keys($columns);
  632. // Here's where the variables are injected to the query.
  633. $insertRows = array();
  634. foreach ($data as $dataRow)
  635. $insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
  636. // Determine the method of insertion.
  637. $queryTitle = $method == 'replace' ? 'REPLACE' : ($method == 'ignore' ? 'INSERT IGNORE' : 'INSERT');
  638. // Do the insert.
  639. $smcFunc['db_query']('', '
  640. ' . $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`)
  641. VALUES
  642. ' . implode(',
  643. ', $insertRows),
  644. array(
  645. 'security_override' => true,
  646. 'db_error_skip' => $table === $db_prefix . 'log_errors',
  647. ),
  648. $connection
  649. );
  650. }
  651. /**
  652. * This function tries to work out additional error information from a back trace.
  653. *
  654. * @param $error_message
  655. * @param $log_message
  656. * @param $error_type
  657. * @param $file
  658. * @param $line
  659. */
  660. function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
  661. {
  662. if (empty($log_message))
  663. $log_message = $error_message;
  664. foreach (debug_backtrace() as $step)
  665. {
  666. // Found it?
  667. 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)
  668. {
  669. $log_message .= '<br />Function: ' . $step['function'];
  670. break;
  671. }
  672. if (isset($step['line']))
  673. {
  674. $file = $step['file'];
  675. $line = $step['line'];
  676. }
  677. }
  678. // A special case - we want the file and line numbers for debugging.
  679. if ($error_type == 'return')
  680. return array($file, $line);
  681. // Is always a critical error.
  682. if (function_exists('log_error'))
  683. log_error($log_message, 'critical', $file, $line);
  684. if (function_exists('fatal_error'))
  685. {
  686. fatal_error($error_message, false);
  687. // Cannot continue...
  688. exit;
  689. }
  690. elseif ($error_type)
  691. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type);
  692. else
  693. trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
  694. }
  695. /**
  696. * Escape the LIKE wildcards so that they match the character and not the wildcard.
  697. *
  698. * @param $string
  699. * @param bool $translate_human_wildcards = false, if true, turns human readable wildcards into SQL wildcards.
  700. */
  701. function smf_db_escape_wildcard_string($string, $translate_human_wildcards=false)
  702. {
  703. $replacements = array(
  704. '%' => '\%',
  705. '_' => '\_',
  706. '\\' => '\\\\',
  707. );
  708. if ($translate_human_wildcards)
  709. $replacements += array(
  710. '*' => '%',
  711. );
  712. return strtr($string, $replacements);
  713. }
  714. ?>