PageRenderTime 47ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/sources/database/Db-mysql.subs.php

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