Subs-Db-mysql.php 25 KB

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