Errors.php 15 KB

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