Subs-Db-mysql.php 25 KB

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