Subs-Db-mysql.php 23 KB

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