Subs-Db-mysql.php 25 KB

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