Subs-Db-mysql.php 25 KB

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