Errors.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 2012 Simple Machines
  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('Hacking attempt...');
  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
  25. * @param string $error_type = 'general'
  26. * @param string $file = null
  27. * @param int $line = null
  28. * @return string, the error message
  29. */
  30. function log_error($error_message, $error_type = 'general', $file = null, $line = null)
  31. {
  32. global $txt, $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;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 = htmlspecialchars((SMF == 'SSI' ? '' : '?') . 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. 'template',
  71. 'debug',
  72. );
  73. // This prevents us from infinite looping if the hook or call produces an error.
  74. $other_error_types = array();
  75. if (empty($tried_hook))
  76. {
  77. $tried_hook = true;
  78. call_integration_hook('integrate_error_types', array(&$other_error_types));
  79. $known_error_types += $other_error_types;
  80. }
  81. // Make sure the category that was specified is a valid one
  82. $error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
  83. // Don't log the same error countless times, as we can get in a cycle of depression...
  84. $error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line);
  85. if (empty($last_error) || $last_error != $error_info)
  86. {
  87. // Insert the error into the database.
  88. $smcFunc['db_insert']('',
  89. '{db_prefix}log_errors',
  90. 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'),
  91. $error_info,
  92. array('id_error')
  93. );
  94. $last_error = $error_info;
  95. }
  96. // Return the message to make things simpler.
  97. return $error_message;
  98. }
  99. /**
  100. * An irrecoverable error. This function stops execution and displays an error message.
  101. * It logs the error message if $log is specified.
  102. * @param string $error
  103. * @param string $log = 'general'
  104. */
  105. function fatal_error($error, $log = 'general')
  106. {
  107. global $txt, $context, $modSettings;
  108. // We don't have $txt yet, but that's okay...
  109. if (empty($txt))
  110. die($error);
  111. setup_fatal_error_context($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2) ? log_error($error, $log) : $error, $error);
  112. }
  113. /**
  114. * Shows a fatal error with a message stored in the language file.
  115. *
  116. * This function stops execution and displays an error message by key.
  117. * - uses the string with the error_message_key key.
  118. * - logs the error in the forum's default language while displaying the error
  119. * message in the user's language.
  120. * - uses Errors language file and applies the $sprintf information if specified.
  121. * - the information is logged if log is specified.
  122. *
  123. * @param $error
  124. * @param $log
  125. * @param $sprintf
  126. */
  127. function fatal_lang_error($error, $log = 'general', $sprintf = array())
  128. {
  129. global $txt, $language, $modSettings, $user_info, $context;
  130. static $fatal_error_called = false;
  131. // Try to load a theme if we don't have one.
  132. if (empty($context['theme_loaded']) && empty($fatal_error_called))
  133. {
  134. $fatal_error_called = true;
  135. loadTheme();
  136. }
  137. // If we have no theme stuff we can't have the language file...
  138. if (empty($context['theme_loaded']))
  139. die($error);
  140. $reload_lang_file = true;
  141. // Log the error in the forum's language, but don't waste the time if we aren't logging
  142. if ($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2))
  143. {
  144. loadLanguage('Errors', $language);
  145. $reload_lang_file = $language != $user_info['language'];
  146. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  147. log_error($error_message, $log);
  148. }
  149. // Load the language file, only if it needs to be reloaded
  150. if ($reload_lang_file)
  151. {
  152. loadLanguage('Errors');
  153. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  154. }
  155. setup_fatal_error_context($error_message, $error);
  156. }
  157. /**
  158. * Handler for standard error messages, standard PHP error handler replacement.
  159. * It dies with fatal_error() if the error_level matches with error_reporting.
  160. * @param int $error_level
  161. * @param string $error_string
  162. * @param string $file
  163. * @param int $line
  164. */
  165. function error_handler($error_level, $error_string, $file, $line)
  166. {
  167. global $settings, $modSettings, $db_show_debug;
  168. // Ignore errors if we're ignoring them or they are strict notices from PHP 5 (which cannot be solved without breaking PHP 4.)
  169. if (error_reporting() == 0 || (defined('E_STRICT') && $error_level == E_STRICT && (empty($modSettings['enableErrorLogging']) || $modSettings['enableErrorLogging'] != 2)))
  170. return;
  171. if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
  172. {
  173. $array = debug_backtrace();
  174. for ($i = 0; $i < count($array); $i++)
  175. {
  176. if ($array[$i]['function'] != 'loadSubTemplate')
  177. continue;
  178. // This is a bug in PHP, with eval, it seems!
  179. if (empty($array[$i]['args']))
  180. $i++;
  181. break;
  182. }
  183. if (isset($array[$i]) && !empty($array[$i]['args']))
  184. $file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
  185. else
  186. $file = realpath($settings['current_include_filename']) . ' (eval?)';
  187. }
  188. if (isset($db_show_debug) && $db_show_debug === true)
  189. {
  190. // Commonly, undefined indexes will occur inside attributes; try to show them anyway!
  191. if ($error_level % 255 != E_ERROR)
  192. {
  193. $temporary = ob_get_contents();
  194. if (substr($temporary, -2) == '="')
  195. echo '"';
  196. }
  197. // Debugging! This should look like a PHP error message.
  198. echo '<br />
  199. <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 />';
  200. }
  201. $error_type = stripos($error_string, 'undefined') !== false ? 'undefined_vars' : 'general';
  202. $message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
  203. // Let's give integrations a chance to ouput a bit differently
  204. call_integration_hook('integrate_output_error', array(&$message, &$error_type, &$error_level, &$file, &$line));
  205. // Dying on these errors only causes MORE problems (blank pages!)
  206. if ($file == 'Unknown')
  207. return;
  208. // If this is an E_ERROR or E_USER_ERROR.... die. Violently so.
  209. if ($error_level % 255 == E_ERROR)
  210. obExit(false);
  211. else
  212. return;
  213. // If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die. Violently so.
  214. if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
  215. fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
  216. // We should NEVER get to this point. Any fatal error MUST quit, or very bad things can happen.
  217. if ($error_level % 255 == E_ERROR)
  218. die('Hacking attempt...');
  219. }
  220. /**
  221. * It is called by fatal_error() and fatal_lang_error().
  222. * @uses Errors template, fatal_error sub template, or Wireless template, error sub template.
  223. *
  224. * @param string $error_message
  225. * @param type $error_code
  226. */
  227. function setup_fatal_error_context($error_message, $error_code)
  228. {
  229. global $context, $txt, $ssi_on_error_method;
  230. static $level = 0;
  231. // Attempt to prevent a recursive loop.
  232. ++$level;
  233. if ($level > 1)
  234. return false;
  235. // Maybe they came from dlattach or similar?
  236. if (SMF != 'SSI' && empty($context['theme_loaded']))
  237. loadTheme();
  238. // Don't bother indexing errors mate...
  239. $context['robot_no_index'] = true;
  240. if (!isset($context['error_title']))
  241. $context['error_title'] = $txt['error_occured'];
  242. $context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
  243. $context['error_code'] = isset($error_code) ? 'id="' . $error_code . '" ' : '';
  244. if (empty($context['page_title']))
  245. $context['page_title'] = $context['error_title'];
  246. // Display the error message - wireless?
  247. if (defined('WIRELESS') && WIRELESS)
  248. $context['sub_template'] = WIRELESS_PROTOCOL . '_error';
  249. // Load the template and set the sub template.
  250. else
  251. {
  252. loadTemplate('Errors');
  253. $context['sub_template'] = 'fatal_error';
  254. }
  255. // If this is SSI, what do they want us to do?
  256. if (SMF == 'SSI')
  257. {
  258. if (!empty($ssi_on_error_method) && $ssi_on_error_method !== true && is_callable($ssi_on_error_method))
  259. $ssi_on_error_method();
  260. elseif (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
  261. loadSubTemplate('fatal_error');
  262. // No layers?
  263. if (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
  264. exit;
  265. }
  266. // We want whatever for the header, and a footer. (footer includes sub template!)
  267. obExit(null, true, false, true);
  268. /* DO NOT IGNORE:
  269. If you are creating a bridge to SMF or modifying this function, you MUST
  270. make ABSOLUTELY SURE that this function quits and DOES NOT RETURN TO NORMAL
  271. PROGRAM FLOW. Otherwise, security error messages will not be shown, and
  272. your forum will be in a very easily hackable state.
  273. */
  274. trigger_error('Hacking attempt...', E_USER_ERROR);
  275. }
  276. /**
  277. * Show a message for the (full block) maintenance mode.
  278. * It shows a complete page independent of language files or themes.
  279. * It is used only if $maintenance = 2 in Settings.php.
  280. * It stops further execution of the script.
  281. */
  282. function display_maintenance_message()
  283. {
  284. global $maintenance, $mtitle, $mmessage;
  285. set_fatal_error_headers();
  286. if (!empty($maintenance))
  287. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  288. <html xmlns="http://www.w3.org/1999/xhtml">
  289. <head>
  290. <meta name="robots" content="noindex" />
  291. <title>', $mtitle, '</title>
  292. </head>
  293. <body>
  294. <h3>', $mtitle, '</h3>
  295. ', $mmessage, '
  296. </body>
  297. </html>';
  298. die();
  299. }
  300. /**
  301. * Show an error message for the connection problems.
  302. * It shows a complete page independent of language files or themes.
  303. * It is used only if there's no way to connect to the database.
  304. * It stops further execution of the script.
  305. */
  306. function display_db_error()
  307. {
  308. global $mbname, $modSettings, $maintenance;
  309. global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc;
  310. set_fatal_error_headers();
  311. // For our purposes, we're gonna want this on if at all possible.
  312. $modSettings['cache_enable'] = '1';
  313. if (($temp = cache_get_data('db_last_error', 600)) !== null)
  314. $db_last_error = max($db_last_error, $temp);
  315. if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
  316. {
  317. // Avoid writing to the Settings.php file if at all possible; use shared memory instead.
  318. cache_put_data('db_last_error', time(), 600);
  319. if (($temp = cache_get_data('db_last_error', 600)) === null)
  320. logLastDatabaseError();
  321. // Language files aren't loaded yet :(.
  322. $db_error = @$smcFunc['db_error']($db_connection);
  323. @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.');
  324. }
  325. // What to do? Language files haven't and can't be loaded yet...
  326. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  327. <html xmlns="http://www.w3.org/1999/xhtml">
  328. <head>
  329. <meta name="robots" content="noindex" />
  330. <title>Connection Problems</title>
  331. </head>
  332. <body>
  333. <h3>Connection Problems</h3>
  334. Sorry, SMF was unable to connect to the database. This may be caused by the server being busy. Please try again later.
  335. </body>
  336. </html>';
  337. die();
  338. }
  339. /**
  340. * Show an error message for load average blocking problems.
  341. * It shows a complete page independent of language files or themes.
  342. * It is used only if the load averages are too high to continue execution.
  343. * It stops further execution of the script.
  344. */
  345. function display_loadavg_error()
  346. {
  347. // If this is a load average problem, display an appropriate message (but we still don't have language files!)
  348. set_fatal_error_headers();
  349. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  350. <html xmlns="http://www.w3.org/1999/xhtml">
  351. <head>
  352. <meta name="robots" content="noindex" />
  353. <title>Temporarily Unavailable</title>
  354. </head>
  355. <body>
  356. <h3>Temporarily Unavailable</h3>
  357. Due to high stress on the server the forum is temporarily unavailable. Please try again later.
  358. </body>
  359. </html>';
  360. die();
  361. }
  362. /**
  363. * Small utility function for fatal error pages.
  364. * Used by display_db_error(), display_loadavg_error(),
  365. * display_maintenance_message()
  366. */
  367. function set_fatal_error_headers()
  368. {
  369. // Don't cache this page!
  370. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  371. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  372. header('Cache-Control: no-cache');
  373. // Send the right error codes.
  374. header('HTTP/1.1 503 Service Temporarily Unavailable');
  375. header('Status: 503 Service Temporarily Unavailable');
  376. header('Retry-After: 3600');
  377. }
  378. ?>