Errors.php 15 KB

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