Errors.php 15 KB

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