Errors.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <?php
  2. /**
  3. * The purpose of this file is... errors. (hard to guess, I guess?) It takes
  4. * care of logging, error messages, error handling, database errors, and
  5. * error log administration.
  6. *
  7. * Simple Machines Forum (SMF)
  8. *
  9. * @package SMF
  10. * @author Simple Machines http://www.simplemachines.org
  11. * @copyright 2014 Simple Machines and individual contributors
  12. * @license http://www.simplemachines.org/about/smf/license.php BSD
  13. *
  14. * @version 2.1 Alpha 1
  15. */
  16. if (!defined('SMF'))
  17. die('No direct access...');
  18. /**
  19. * Log an error, if the error logging is enabled.
  20. * filename and line should be __FILE__ and __LINE__, respectively.
  21. * Example use:
  22. * die(log_error($msg));
  23. *
  24. * @param string $error_message The message to log
  25. * @param string $error_type The type of error
  26. * @param string $file The name of the file where this error occurred
  27. * @param int $line The line where the error occurred
  28. * @return string The message that was logged
  29. */
  30. function log_error($error_message, $error_type = 'general', $file = null, $line = null)
  31. {
  32. global $modSettings, $sc, $user_info, $smcFunc, $scripturl, $last_error;
  33. static $tried_hook = false;
  34. // Check if error logging is actually on.
  35. if (empty($modSettings['enableErrorLogging']))
  36. return $error_message;
  37. // Basically, htmlspecialchars it minus &. (for entities!)
  38. $error_message = strtr($error_message, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
  39. $error_message = strtr($error_message, array('&lt;br /&gt;' => '<br>', '&lt;br&gt;' => '<br>', '&lt;b&gt;' => '<strong>', '&lt;/b&gt;' => '</strong>', "\n" => '<br>'));
  40. // Add a file and line to the error message?
  41. // Don't use the actual txt entries for file and line but instead use %1$s for file and %2$s for line
  42. if ($file == null)
  43. $file = '';
  44. else
  45. // Window style slashes don't play well, lets convert them to the unix style.
  46. $file = str_replace('\\', '/', $file);
  47. if ($line == null)
  48. $line = 0;
  49. else
  50. $line = (int) $line;
  51. // Just in case there's no id_member or IP set yet.
  52. if (empty($user_info['id']))
  53. $user_info['id'] = 0;
  54. if (empty($user_info['ip']))
  55. $user_info['ip'] = '';
  56. // Find the best query string we can...
  57. $query_string = empty($_SERVER['QUERY_STRING']) ? (empty($_SERVER['REQUEST_URL']) ? '' : str_replace($scripturl, '', $_SERVER['REQUEST_URL'])) : $_SERVER['QUERY_STRING'];
  58. // Don't log the session hash in the url twice, it's a waste.
  59. $query_string = $smcFunc['htmlspecialchars']((SMF == 'SSI' || SMF == 'BACKGROUND' ? '' : '?') . preg_replace(array('~;sesc=[^&;]+~', '~' . session_name() . '=' . session_id() . '[&;]~'), array(';sesc', ''), $query_string));
  60. // Just so we know what board error messages are from.
  61. if (isset($_POST['board']) && !isset($_GET['board']))
  62. $query_string .= ($query_string == '' ? 'board=' : ';board=') . $_POST['board'];
  63. // What types of categories do we have?
  64. $known_error_types = array(
  65. 'general',
  66. 'critical',
  67. 'database',
  68. 'undefined_vars',
  69. 'user',
  70. 'ban',
  71. 'template',
  72. 'debug',
  73. 'cron',
  74. 'paidsubs',
  75. );
  76. // This prevents us from infinite looping if the hook or call produces an error.
  77. $other_error_types = array();
  78. if (empty($tried_hook))
  79. {
  80. $tried_hook = true;
  81. call_integration_hook('integrate_error_types', array(&$other_error_types));
  82. $known_error_types += $other_error_types;
  83. }
  84. // Make sure the category that was specified is a valid one
  85. $error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
  86. // Don't log the same error countless times, as we can get in a cycle of depression...
  87. $error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line);
  88. if (empty($last_error) || $last_error != $error_info)
  89. {
  90. // Insert the error into the database.
  91. $smcFunc['db_insert']('',
  92. '{db_prefix}log_errors',
  93. array('id_member' => 'int', 'log_time' => 'int', 'ip' => 'string-16', 'url' => 'string-65534', 'message' => 'string-65534', 'session' => 'string', 'error_type' => 'string', 'file' => 'string-255', 'line' => 'int'),
  94. $error_info,
  95. array('id_error')
  96. );
  97. $last_error = $error_info;
  98. }
  99. // Return the message to make things simpler.
  100. return $error_message;
  101. }
  102. /**
  103. * An irrecoverable error. This function stops execution and displays an error message.
  104. * It logs the error message if $log is specified.
  105. * @param string $error The error message
  106. * @param string $log = 'general' What type of error to log this as (false to not log it))
  107. */
  108. function fatal_error($error, $log = 'general')
  109. {
  110. global $txt;
  111. // We don't have $txt yet, but that's okay...
  112. if (empty($txt))
  113. die($error);
  114. setup_fatal_error_context($log ? log_error($error, $log) : $error, $error);
  115. }
  116. /**
  117. * Shows a fatal error with a message stored in the language file.
  118. *
  119. * This function stops execution and displays an error message by key.
  120. * - uses the string with the error_message_key key.
  121. * - logs the error in the forum's default language while displaying the error
  122. * message in the user's language.
  123. * - uses Errors language file and applies the $sprintf information if specified.
  124. * - the information is logged if log is specified.
  125. *
  126. * @param string $error The error message
  127. * @param string $log The type of error, or false to not log it
  128. * @param array $sprintf An array of data to be sprintf()'d into the specified message
  129. */
  130. function fatal_lang_error($error, $log = 'general', $sprintf = array())
  131. {
  132. global $txt, $language, $user_info, $context;
  133. static $fatal_error_called = false;
  134. // Try to load a theme if we don't have one.
  135. if (empty($context['theme_loaded']) && empty($fatal_error_called))
  136. {
  137. $fatal_error_called = true;
  138. loadTheme();
  139. }
  140. // If we have no theme stuff we can't have the language file...
  141. if (empty($context['theme_loaded']))
  142. die($error);
  143. $reload_lang_file = true;
  144. // Log the error in the forum's language, but don't waste the time if we aren't logging
  145. if ($log)
  146. {
  147. loadLanguage('Errors', $language);
  148. $reload_lang_file = $language != $user_info['language'];
  149. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  150. log_error($error_message, $log);
  151. }
  152. // Load the language file, only if it needs to be reloaded
  153. if ($reload_lang_file)
  154. {
  155. loadLanguage('Errors');
  156. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  157. }
  158. setup_fatal_error_context($error_message, $error);
  159. }
  160. /**
  161. * Handler for standard error messages, standard PHP error handler replacement.
  162. * It dies with fatal_error() if the error_level matches with error_reporting.
  163. * @param int $error_level A pre-defined error-handling constant (see {@link http://www.php.net/errorfunc.constants})
  164. * @param string $error_string The error message
  165. * @param string $file The file where the error occurred
  166. * @param int $line The line where the error occurred
  167. */
  168. function error_handler($error_level, $error_string, $file, $line)
  169. {
  170. global $settings, $modSettings, $db_show_debug;
  171. // Ignore errors if we're ignoring them or they are strict notices from PHP 5 (which cannot be solved without breaking PHP 4.)
  172. if (error_reporting() == 0 || (defined('E_STRICT') && $error_level == E_STRICT && !empty($modSettings['enableErrorLogging'])))
  173. return;
  174. if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
  175. {
  176. $array = debug_backtrace();
  177. for ($i = 0; $i < count($array); $i++)
  178. {
  179. if ($array[$i]['function'] != 'loadSubTemplate')
  180. continue;
  181. // This is a bug in PHP, with eval, it seems!
  182. if (empty($array[$i]['args']))
  183. $i++;
  184. break;
  185. }
  186. if (isset($array[$i]) && !empty($array[$i]['args']))
  187. $file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
  188. else
  189. $file = realpath($settings['current_include_filename']) . ' (eval?)';
  190. }
  191. if (isset($db_show_debug) && $db_show_debug === true)
  192. {
  193. // Commonly, undefined indexes will occur inside attributes; try to show them anyway!
  194. if ($error_level % 255 != E_ERROR)
  195. {
  196. $temporary = ob_get_contents();
  197. if (substr($temporary, -2) == '="')
  198. echo '"';
  199. }
  200. // Debugging! This should look like a PHP error message.
  201. echo '<br>
  202. <strong>', $error_level % 255 == E_ERROR ? 'Error' : ($error_level % 255 == E_WARNING ? 'Warning' : 'Notice'), '</strong>: ', $error_string, ' in <strong>', $file, '</strong> on line <strong>', $line, '</strong><br>';
  203. }
  204. $error_type = stripos($error_string, 'undefined') !== false ? 'undefined_vars' : 'general';
  205. $message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
  206. // Let's give integrations a chance to ouput a bit differently
  207. call_integration_hook('integrate_output_error', array($message, $error_type, $error_level, $file, $line));
  208. // Dying on these errors only causes MORE problems (blank pages!)
  209. if ($file == 'Unknown')
  210. return;
  211. // If this is an E_ERROR or E_USER_ERROR.... die. Violently so.
  212. if ($error_level % 255 == E_ERROR)
  213. obExit(false);
  214. else
  215. return;
  216. // If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die. Violently so.
  217. if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
  218. fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
  219. // We should NEVER get to this point. Any fatal error MUST quit, or very bad things can happen.
  220. if ($error_level % 255 == E_ERROR)
  221. die('No direct access...');
  222. }
  223. /**
  224. * It is called by {@link fatal_error()} and {@link fatal_lang_error()}.
  225. * @uses Errors template, fatal_error sub template, or Wireless template, error sub template.
  226. *
  227. * @param string $error_message The error message
  228. * @param string $error_code An error code
  229. */
  230. function setup_fatal_error_context($error_message, $error_code)
  231. {
  232. global $context, $txt, $ssi_on_error_method;
  233. static $level = 0;
  234. // Attempt to prevent a recursive loop.
  235. ++$level;
  236. if ($level > 1)
  237. return false;
  238. // Maybe they came from dlattach or similar?
  239. if (SMF != 'SSI' && SMF != 'BACKGROUND' && empty($context['theme_loaded']))
  240. loadTheme();
  241. // Don't bother indexing errors mate...
  242. $context['robot_no_index'] = true;
  243. if (!isset($context['error_title']))
  244. $context['error_title'] = $txt['error_occured'];
  245. $context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
  246. $context['error_code'] = isset($error_code) ? 'id="' . $error_code . '" ' : '';
  247. if (empty($context['page_title']))
  248. $context['page_title'] = $context['error_title'];
  249. // Display the error message - wireless?
  250. if (defined('WIRELESS') && WIRELESS)
  251. $context['sub_template'] = WIRELESS_PROTOCOL . '_error';
  252. // Load the template and set the sub template.
  253. else
  254. {
  255. loadTemplate('Errors');
  256. $context['sub_template'] = 'fatal_error';
  257. }
  258. // If this is SSI, what do they want us to do?
  259. if (SMF == 'SSI')
  260. {
  261. if (!empty($ssi_on_error_method) && $ssi_on_error_method !== true && is_callable($ssi_on_error_method))
  262. $ssi_on_error_method();
  263. elseif (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
  264. loadSubTemplate('fatal_error');
  265. // No layers?
  266. if (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
  267. exit;
  268. }
  269. // Alternatively from the cron call?
  270. elseif (SMF == 'BACKGROUND')
  271. {
  272. // We can't rely on even having language files available.
  273. if (defined('FROM_CLI') && FROM_CLI)
  274. echo 'cron error: ', $context['error_message'];
  275. else
  276. echo 'An error occurred. More information may be available in your logs.';
  277. exit;
  278. }
  279. // We want whatever for the header, and a footer. (footer includes sub template!)
  280. obExit(null, true, false, true);
  281. /* DO NOT IGNORE:
  282. If you are creating a bridge to SMF or modifying this function, you MUST
  283. make ABSOLUTELY SURE that this function quits and DOES NOT RETURN TO NORMAL
  284. PROGRAM FLOW. Otherwise, security error messages will not be shown, and
  285. your forum will be in a very easily hackable state.
  286. */
  287. trigger_error('Hacking attempt...', E_USER_ERROR);
  288. }
  289. /**
  290. * Show a message for the (full block) maintenance mode.
  291. * It shows a complete page independent of language files or themes.
  292. * It is used only if $maintenance = 2 in Settings.php.
  293. * It stops further execution of the script.
  294. */
  295. function display_maintenance_message()
  296. {
  297. global $maintenance, $mtitle, $mmessage;
  298. set_fatal_error_headers();
  299. if (!empty($maintenance))
  300. echo '<!DOCTYPE html>
  301. <html>
  302. <head>
  303. <meta name="robots" content="noindex">
  304. <title>', $mtitle, '</title>
  305. </head>
  306. <body>
  307. <h3>', $mtitle, '</h3>
  308. ', $mmessage, '
  309. </body>
  310. </html>';
  311. die();
  312. }
  313. /**
  314. * Show an error message for the connection problems.
  315. * It shows a complete page independent of language files or themes.
  316. * It is used only if there's no way to connect to the database.
  317. * It stops further execution of the script.
  318. */
  319. function display_db_error()
  320. {
  321. global $mbname, $modSettings, $maintenance;
  322. global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc, $sourcedir;
  323. require_once($sourcedir . '/Logging.php');
  324. set_fatal_error_headers();
  325. // For our purposes, we're gonna want this on if at all possible.
  326. $modSettings['cache_enable'] = '1';
  327. if (($temp = cache_get_data('db_last_error', 600)) !== null)
  328. $db_last_error = max($db_last_error, $temp);
  329. if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
  330. {
  331. // Avoid writing to the Settings.php file if at all possible; use shared memory instead.
  332. cache_put_data('db_last_error', time(), 600);
  333. if (($temp = cache_get_data('db_last_error', 600)) === null)
  334. logLastDatabaseError();
  335. // Language files aren't loaded yet :(.
  336. $db_error = @$smcFunc['db_error']($db_connection);
  337. @mail($webmaster_email, $mbname . ': SMF Database Error!', 'There has been a problem with the database!' . ($db_error == '' ? '' : "\n" . $smcFunc['db_title'] . ' reported:' . "\n" . $db_error) . "\n\n" . 'This is a notice email to let you know that SMF could not connect to the database, contact your host if this continues.');
  338. }
  339. // What to do? Language files haven't and can't be loaded yet...
  340. echo '<!DOCTYPE html>
  341. <html>
  342. <head>
  343. <meta name="robots" content="noindex">
  344. <title>Connection Problems</title>
  345. </head>
  346. <body>
  347. <h3>Connection Problems</h3>
  348. Sorry, SMF was unable to connect to the database. This may be caused by the server being busy. Please try again later.
  349. </body>
  350. </html>';
  351. die();
  352. }
  353. /**
  354. * Show an error message for load average blocking problems.
  355. * It shows a complete page independent of language files or themes.
  356. * It is used only if the load averages are too high to continue execution.
  357. * It stops further execution of the script.
  358. */
  359. function display_loadavg_error()
  360. {
  361. // If this is a load average problem, display an appropriate message (but we still don't have language files!)
  362. set_fatal_error_headers();
  363. echo '<!DOCTYPE html>
  364. <html>
  365. <head>
  366. <meta name="robots" content="noindex">
  367. <title>Temporarily Unavailable</title>
  368. </head>
  369. <body>
  370. <h3>Temporarily Unavailable</h3>
  371. Due to high stress on the server the forum is temporarily unavailable. Please try again later.
  372. </body>
  373. </html>';
  374. die();
  375. }
  376. /**
  377. * Small utility function for fatal error pages.
  378. * Used by display_db_error(), display_loadavg_error(),
  379. * display_maintenance_message()
  380. */
  381. function set_fatal_error_headers()
  382. {
  383. // Don't cache this page!
  384. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  385. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  386. header('Cache-Control: no-cache');
  387. // Send the right error codes.
  388. header('HTTP/1.1 503 Service Temporarily Unavailable');
  389. header('Status: 503 Service Temporarily Unavailable');
  390. header('Retry-After: 3600');
  391. }
  392. ?>