Errors.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* The purpose of this file is... errors. (hard to guess, huh?) It takes
  15. care of logging, error messages, error handling, database errors, and
  16. error log administration. It does this with:
  17. bool db_fatal_error(bool loadavg = false)
  18. - calls show_db_error().
  19. - this is used for database connection error handling.
  20. - loadavg means this is a load average problem, not a database error.
  21. string log_error(string error_message, string error_type = general,
  22. string filename = none, int line = none)
  23. - logs an error, if error logging is enabled.
  24. - depends on the enableErrorLogging setting.
  25. - filename and line should be __FILE__ and __LINE__, respectively.
  26. - returns the error message. (ie. die(log_error($msg));)
  27. void fatal_error(string error_message, mixed (bool or string) log = general)
  28. - stops execution and displays an error message.
  29. - logs the error message if log is missing or true.
  30. void fatal_lang_error(string error_message_key, mixed (bool or string) log = general,
  31. array sprintf = array())
  32. - stops execution and displays an error message by key.
  33. - uses the string with the error_message_key key.
  34. - loads the Errors language file.
  35. - applies the sprintf information if specified.
  36. - the information is logged if log is true or missing.
  37. - logs the error in the forum's default language while displaying the error
  38. message in the user's language
  39. void error_handler(int error_level, string error_string, string filename,
  40. int line)
  41. - this is a standard PHP error handler replacement.
  42. - dies with fatal_error() if the error_level matches with
  43. error_reporting.
  44. void setup_fatal_error_context(string error_message)
  45. - uses the fatal_error sub template of the Errors template - or the
  46. error sub template in the Wireless template.
  47. - used by fatal_error() and fatal_lang_error()
  48. void show_db_error(bool loadavg = false)
  49. - called by db_fatal_error() function
  50. - shows a complete page independent of language files or themes.
  51. - used only if there's no way to connect to the database or the
  52. load averages are too high to do so.
  53. - loadavg means this is a load average problem, not a database error.
  54. - stops further execution of the script.
  55. */
  56. // Handle fatal errors - like connection errors or load average problems
  57. function db_fatal_error($loadavg = false)
  58. {
  59. global $sourcedir;
  60. show_db_error($loadavg);
  61. // Since we use "or db_fatal_error();" this is needed...
  62. return false;
  63. }
  64. // Log an error, if the option is on.
  65. function log_error($error_message, $error_type = 'general', $file = null, $line = null)
  66. {
  67. global $txt, $modSettings, $sc, $user_info, $smcFunc, $scripturl, $last_error;
  68. // Check if error logging is actually on.
  69. if (empty($modSettings['enableErrorLogging']))
  70. return $error_message;
  71. // Basically, htmlspecialchars it minus &. (for entities!)
  72. $error_message = strtr($error_message, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
  73. $error_message = strtr($error_message, array('&lt;br /&gt;' => '<br />', '&lt;b&gt;' => '<strong>', '&lt;/b&gt;' => '</strong>', "\n" => '<br />'));
  74. // Add a file and line to the error message?
  75. // Don't use the actual txt entries for file and line but instead use %1$s for file and %2$s for line
  76. if ($file == null)
  77. $file = '';
  78. else
  79. // Window style slashes don't play well, lets convert them to the unix style.
  80. $file = str_replace('\\', '/', $file);
  81. if ($line == null)
  82. $line = 0;
  83. else
  84. $line = (int) $line;
  85. // Just in case there's no id_member or IP set yet.
  86. if (empty($user_info['id']))
  87. $user_info['id'] = 0;
  88. if (empty($user_info['ip']))
  89. $user_info['ip'] = '';
  90. // Find the best query string we can...
  91. $query_string = empty($_SERVER['QUERY_STRING']) ? (empty($_SERVER['REQUEST_URL']) ? '' : str_replace($scripturl, '', $_SERVER['REQUEST_URL'])) : $_SERVER['QUERY_STRING'];
  92. // Don't log the session hash in the url twice, it's a waste.
  93. $query_string = htmlspecialchars((SMF == 'SSI' ? '' : '?') . preg_replace(array('~;sesc=[^&;]+~', '~' . session_name() . '=' . session_id() . '[&;]~'), array(';sesc', ''), $query_string));
  94. // Just so we know what board error messages are from.
  95. if (isset($_POST['board']) && !isset($_GET['board']))
  96. $query_string .= ($query_string == '' ? 'board=' : ';board=') . $_POST['board'];
  97. // What types of categories do we have?
  98. $known_error_types = array(
  99. 'general',
  100. 'critical',
  101. 'database',
  102. 'undefined_vars',
  103. 'user',
  104. 'template',
  105. 'debug',
  106. );
  107. // Make sure the category that was specified is a valid one
  108. $error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
  109. // Don't log the same error countless times, as we can get in a cycle of depression...
  110. $error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line);
  111. if (empty($last_error) || $last_error != $error_info)
  112. {
  113. // Insert the error into the database.
  114. $smcFunc['db_insert']('',
  115. '{db_prefix}log_errors',
  116. 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'),
  117. $error_info,
  118. array('id_error')
  119. );
  120. $last_error = $error_info;
  121. }
  122. // Return the message to make things simpler.
  123. return $error_message;
  124. }
  125. // An irrecoverable error.
  126. function fatal_error($error, $log = 'general')
  127. {
  128. global $txt, $context, $modSettings;
  129. // We don't have $txt yet, but that's okay...
  130. if (empty($txt))
  131. die($error);
  132. setup_fatal_error_context($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2) ? log_error($error, $log) : $error);
  133. }
  134. // A fatal error with a message stored in the language file.
  135. function fatal_lang_error($error, $log = 'general', $sprintf = array())
  136. {
  137. global $txt, $language, $modSettings, $user_info, $context;
  138. static $fatal_error_called = false;
  139. // Try to load a theme if we don't have one.
  140. if (empty($context['theme_loaded']) && empty($fatal_error_called))
  141. {
  142. $fatal_error_called = true;
  143. loadTheme();
  144. }
  145. // If we have no theme stuff we can't have the language file...
  146. if (empty($context['theme_loaded']))
  147. die($error);
  148. $reload_lang_file = true;
  149. // Log the error in the forum's language, but don't waste the time if we aren't logging
  150. if ($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2))
  151. {
  152. loadLanguage('Errors', $language);
  153. $reload_lang_file = $language != $user_info['language'];
  154. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  155. log_error($error_message, $log);
  156. }
  157. // Load the language file, only if it needs to be reloaded
  158. if ($reload_lang_file)
  159. {
  160. loadLanguage('Errors');
  161. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  162. }
  163. setup_fatal_error_context($error_message);
  164. }
  165. // Handler for standard error messages.
  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. if (function_exists('debug_backtrace'))
  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. else
  192. $file = realpath($settings['current_include_filename']) . ' (eval?)';
  193. }
  194. if (isset($db_show_debug) && $db_show_debug === true)
  195. {
  196. // Commonly, undefined indexes will occur inside attributes; try to show them anyway!
  197. if ($error_level % 255 != E_ERROR)
  198. {
  199. $temporary = ob_get_contents();
  200. if (substr($temporary, -2) == '="')
  201. echo '"';
  202. }
  203. // Debugging! This should look like a PHP error message.
  204. echo '<br />
  205. <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 />';
  206. }
  207. $error_type = strpos(strtolower($error_string), 'undefined') !== false ? 'undefined_vars' : 'general';
  208. $message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
  209. // Let's give integrations a chance to ouput a bit differently
  210. call_integration_hook('integrate_output_error', array($message, $error_type, $error_level, $file, $line));
  211. // Dying on these errors only causes MORE problems (blank pages!)
  212. if ($file == 'Unknown')
  213. return;
  214. // If this is an E_ERROR or E_USER_ERROR.... die. Violently so.
  215. if ($error_level % 255 == E_ERROR)
  216. obExit(false);
  217. else
  218. return;
  219. // If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die. Violently so.
  220. if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
  221. fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
  222. // We should NEVER get to this point. Any fatal error MUST quit, or very bad things can happen.
  223. if ($error_level % 255 == E_ERROR)
  224. die('Hacking attempt...');
  225. }
  226. function setup_fatal_error_context($error_message)
  227. {
  228. global $context, $txt, $ssi_on_error_method;
  229. static $level = 0;
  230. // Attempt to prevent a recursive loop.
  231. ++$level;
  232. if ($level > 1)
  233. return false;
  234. // Maybe they came from dlattach or similar?
  235. if (SMF != 'SSI' && empty($context['theme_loaded']))
  236. loadTheme();
  237. // Don't bother indexing errors mate...
  238. $context['robot_no_index'] = true;
  239. if (!isset($context['error_title']))
  240. $context['error_title'] = $txt['error_occured'];
  241. $context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
  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. // Show an error message for the connection problems.
  275. function show_db_error($loadavg = false)
  276. {
  277. global $sourcedir, $mbname, $maintenance, $mtitle, $mmessage, $modSettings;
  278. global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc;
  279. // Don't cache this page!
  280. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  281. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  282. header('Cache-Control: no-cache');
  283. // Send the right error codes.
  284. header('HTTP/1.1 503 Service Temporarily Unavailable');
  285. header('Status: 503 Service Temporarily Unavailable');
  286. header('Retry-After: 3600');
  287. if ($loadavg == false)
  288. {
  289. // For our purposes, we're gonna want this on if at all possible.
  290. $modSettings['cache_enable'] = '1';
  291. if (($temp = cache_get_data('db_last_error', 600)) !== null)
  292. $db_last_error = max($db_last_error, $temp);
  293. if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
  294. {
  295. require_once($sourcedir . '/Subs-Admin.php');
  296. // Avoid writing to the Settings.php file if at all possible; use shared memory instead.
  297. cache_put_data('db_last_error', time(), 600);
  298. if (($temp = cache_get_data('db_last_error', 600)) == null)
  299. updateLastDatabaseError();
  300. // Language files aren't loaded yet :(.
  301. $db_error = @$smcFunc['db_error']($db_connection);
  302. @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.');
  303. }
  304. }
  305. if (!empty($maintenance))
  306. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  307. <html xmlns="http://www.w3.org/1999/xhtml">
  308. <head>
  309. <meta name="robots" content="noindex" />
  310. <title>', $mtitle, '</title>
  311. </head>
  312. <body>
  313. <h3>', $mtitle, '</h3>
  314. ', $mmessage, '
  315. </body>
  316. </html>';
  317. // If this is a load average problem, display an appropriate message (but we still don't have language files!)
  318. elseif ($loadavg)
  319. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  320. <html xmlns="http://www.w3.org/1999/xhtml">
  321. <head>
  322. <meta name="robots" content="noindex" />
  323. <title>Temporarily Unavailable</title>
  324. </head>
  325. <body>
  326. <h3>Temporarily Unavailable</h3>
  327. Due to high stress on the server the forum is temporarily unavailable. Please try again later.
  328. </body>
  329. </html>';
  330. // What to do? Language files haven't and can't be loaded yet...
  331. else
  332. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  333. <html xmlns="http://www.w3.org/1999/xhtml">
  334. <head>
  335. <meta name="robots" content="noindex" />
  336. <title>Connection Problems</title>
  337. </head>
  338. <body>
  339. <h3>Connection Problems</h3>
  340. Sorry, SMF was unable to connect to the database. This may be caused by the server being busy. Please try again later.
  341. </body>
  342. </html>';
  343. die;
  344. }
  345. ?>