PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/sources/Errors.php

https://github.com/Arantor/Elkarte
PHP | 449 lines | 243 code | 67 blank | 139 comment | 84 complexity | 12e37816dea27b87714f7ffbc8742375 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0
  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * The purpose of this file is... errors. (hard to guess, I guess?) It takes
  16. * care of logging, error messages, error handling, database errors, and
  17. * error log administration.
  18. *
  19. */
  20. if (!defined('ELKARTE'))
  21. die('No access...');
  22. /**
  23. * Log an error, if the error logging is enabled.
  24. * filename and line should be __FILE__ and __LINE__, respectively.
  25. * Example use:
  26. * die(log_error($msg));
  27. *
  28. * @param string $error_message
  29. * @param string $error_type = 'general'
  30. * @param string $file = null
  31. * @param int $line = null
  32. * @return string, the error message
  33. */
  34. function log_error($error_message, $error_type = 'general', $file = null, $line = null)
  35. {
  36. global $txt, $modSettings, $sc, $user_info, $smcFunc, $scripturl, $last_error;
  37. static $tried_hook = false;
  38. // Check if error logging is actually on.
  39. if (empty($modSettings['enableErrorLogging']))
  40. return $error_message;
  41. // Basically, htmlspecialchars it minus &. (for entities!)
  42. $error_message = strtr($error_message, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
  43. $error_message = strtr($error_message, array('&lt;br /&gt;' => '<br />', '&lt;b&gt;' => '<strong>', '&lt;/b&gt;' => '</strong>', "\n" => '<br />'));
  44. // Add a file and line to the error message?
  45. // Don't use the actual txt entries for file and line but instead use %1$s for file and %2$s for line
  46. if ($file == null)
  47. $file = '';
  48. else
  49. // Window style slashes don't play well, lets convert them to the unix style.
  50. $file = str_replace('\\', '/', $file);
  51. if ($line == null)
  52. $line = 0;
  53. else
  54. $line = (int) $line;
  55. // Just in case there's no id_member or IP set yet.
  56. if (empty($user_info['id']))
  57. $user_info['id'] = 0;
  58. if (empty($user_info['ip']))
  59. $user_info['ip'] = '';
  60. // Find the best query string we can...
  61. $query_string = empty($_SERVER['QUERY_STRING']) ? (empty($_SERVER['REQUEST_URL']) ? '' : str_replace($scripturl, '', $_SERVER['REQUEST_URL'])) : $_SERVER['QUERY_STRING'];
  62. // Don't log the session hash in the url twice, it's a waste.
  63. $query_string = htmlspecialchars((ELKARTE == 'SSI' ? '' : '?') . preg_replace(array('~;sesc=[^&;]+~', '~' . session_name() . '=' . session_id() . '[&;]~'), array(';sesc', ''), $query_string));
  64. // Just so we know what board error messages are from.
  65. if (isset($_POST['board']) && !isset($_GET['board']))
  66. $query_string .= ($query_string == '' ? 'board=' : ';board=') . $_POST['board'];
  67. // What types of categories do we have?
  68. $known_error_types = array(
  69. 'general',
  70. 'critical',
  71. 'database',
  72. 'undefined_vars',
  73. 'user',
  74. 'template',
  75. 'debug',
  76. );
  77. // This prevents us from infinite looping if the hook or call produces an error.
  78. $other_error_types = array();
  79. if (empty($tried_hook))
  80. {
  81. $tried_hook = true;
  82. call_integration_hook('integrate_error_types', array($other_error_types));
  83. $known_error_types += $other_error_types;
  84. }
  85. // Make sure the category that was specified is a valid one
  86. $error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
  87. // Don't log the same error countless times, as we can get in a cycle of depression...
  88. $error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line);
  89. if (empty($last_error) || $last_error != $error_info)
  90. {
  91. // Insert the error into the database.
  92. $smcFunc['db_insert']('',
  93. '{db_prefix}log_errors',
  94. 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'),
  95. $error_info,
  96. array('id_error')
  97. );
  98. $last_error = $error_info;
  99. }
  100. // Return the message to make things simpler.
  101. return $error_message;
  102. }
  103. /**
  104. * An irrecoverable error. This function stops execution and displays an error message.
  105. * It logs the error message if $log is specified.
  106. *
  107. * @param string $error
  108. * @param string $log = 'general'
  109. */
  110. function fatal_error($error, $log = 'general')
  111. {
  112. global $txt, $context, $modSettings;
  113. // We don't have $txt yet, but that's okay...
  114. if (empty($txt))
  115. die($error);
  116. setup_fatal_error_context($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2) ? log_error($error, $log) : $error, $error);
  117. }
  118. /**
  119. * Shows a fatal error with a message stored in the language file.
  120. *
  121. * This function stops execution and displays an error message by key.
  122. * - uses the string with the error_message_key key.
  123. * - logs the error in the forum's default language while displaying the error
  124. * message in the user's language.
  125. * - uses Errors language file and applies the $sprintf information if specified.
  126. * - the information is logged if log is specified.
  127. *
  128. * @param $error
  129. * @param $log
  130. * @param $sprintf
  131. */
  132. function fatal_lang_error($error, $log = 'general', $sprintf = array())
  133. {
  134. global $txt, $language, $modSettings, $user_info, $context;
  135. static $fatal_error_called = false;
  136. // Try to load a theme if we don't have one.
  137. if (empty($context['theme_loaded']) && empty($fatal_error_called))
  138. {
  139. $fatal_error_called = true;
  140. loadTheme();
  141. }
  142. // If we have no theme stuff we can't have the language file...
  143. if (empty($context['theme_loaded']))
  144. die($error);
  145. $reload_lang_file = true;
  146. // Log the error in the forum's language, but don't waste the time if we aren't logging
  147. if ($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2))
  148. {
  149. loadLanguage('Errors', $language);
  150. $reload_lang_file = $language != $user_info['language'];
  151. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  152. log_error($error_message, $log);
  153. }
  154. // Load the language file, only if it needs to be reloaded
  155. if ($reload_lang_file)
  156. {
  157. loadLanguage('Errors');
  158. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  159. }
  160. setup_fatal_error_context($error_message, $error);
  161. }
  162. /**
  163. * Handler for standard error messages, standard PHP error handler replacement.
  164. * It dies with fatal_error() if the error_level matches with error_reporting.
  165. *
  166. * @param int $error_level
  167. * @param string $error_string
  168. * @param string $file
  169. * @param int $line
  170. */
  171. function error_handler($error_level, $error_string, $file, $line)
  172. {
  173. global $settings, $modSettings, $db_show_debug;
  174. // Ignore errors if we're ignoring them or they are strict notices from PHP 5 (which cannot be solved without breaking PHP 4.)
  175. if (error_reporting() == 0 || (defined('E_STRICT') && $error_level == E_STRICT && (empty($modSettings['enableErrorLogging']) || $modSettings['enableErrorLogging'] != 2)))
  176. return;
  177. if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
  178. {
  179. $array = debug_backtrace();
  180. for ($i = 0; $i < count($array); $i++)
  181. {
  182. if ($array[$i]['function'] != 'loadSubTemplate')
  183. continue;
  184. // This is a bug in PHP, with eval, it seems!
  185. if (empty($array[$i]['args']))
  186. $i++;
  187. break;
  188. }
  189. if (isset($array[$i]) && !empty($array[$i]['args']))
  190. $file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
  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 = stripos($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 output 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. /**
  227. * It is called by fatal_error() and fatal_lang_error().
  228. * @uses Errors template, fatal_error sub template, or Wireless template, error sub template.
  229. *
  230. * @param string $error_message
  231. * @param type $error_code
  232. */
  233. function setup_fatal_error_context($error_message, $error_code)
  234. {
  235. global $context, $txt, $ssi_on_error_method;
  236. static $level = 0;
  237. // Attempt to prevent a recursive loop.
  238. ++$level;
  239. if ($level > 1)
  240. return false;
  241. // Maybe they came from dlattach or similar?
  242. if (ELKARTE != 'SSI' && empty($context['theme_loaded']))
  243. loadTheme();
  244. // Don't bother indexing errors mate...
  245. $context['robot_no_index'] = true;
  246. if (!isset($context['error_title']))
  247. $context['error_title'] = $txt['error_occured'];
  248. $context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
  249. $context['error_code'] = isset($error_code) ? 'id="' . $error_code . '" ' : '';
  250. if (empty($context['page_title']))
  251. $context['page_title'] = $context['error_title'];
  252. // Load the template and set the sub template.
  253. loadTemplate('Errors');
  254. $context['sub_template'] = 'fatal_error';
  255. // If this is SSI, what do they want us to do?
  256. if (ELKARTE == '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 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. // Just check we're not in any buffers, just in case.
  311. while (@ob_get_level() > 0)
  312. @ob_end_clean();
  313. set_fatal_error_headers();
  314. // For our purposes, we're gonna want this on if at all possible.
  315. $modSettings['cache_enable'] = 1;
  316. if (($temp = cache_get_data('db_last_error', 600)) !== null)
  317. $db_last_error = max($db_last_error, $temp);
  318. if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
  319. {
  320. // Avoid writing to the Settings.php file if at all possible; use shared memory instead.
  321. cache_put_data('db_last_error', time(), 600);
  322. if (($temp = cache_get_data('db_last_error', 600)) === null)
  323. logLastDatabaseError();
  324. // Language files aren't loaded yet :(.
  325. $db_error = @$smcFunc['db_error']($db_connection);
  326. @mail($webmaster_email, $mbname . ': 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 the system could not connect to the database, contact your host if this continues.');
  327. }
  328. // What to do? Language files haven't and can't be loaded yet...
  329. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  330. <html xmlns="http://www.w3.org/1999/xhtml">
  331. <head>
  332. <meta name="robots" content="noindex" />
  333. <title>Connection Problems</title>
  334. </head>
  335. <body>
  336. <h3>Connection Problems</h3>
  337. Sorry, we were unable to connect to the database. This may be caused by the server being busy. Please try again later.
  338. </body>
  339. </html>';
  340. die();
  341. }
  342. /**
  343. * Show an error message for load average blocking problems.
  344. * It shows a complete page independent of language files or themes.
  345. * It is used only if the load averages are too high to continue execution.
  346. * It stops further execution of the script.
  347. */
  348. function display_loadavg_error()
  349. {
  350. // If this is a load average problem, display an appropriate message (but we still don't have language files!)
  351. set_fatal_error_headers();
  352. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  353. <html xmlns="http://www.w3.org/1999/xhtml">
  354. <head>
  355. <meta name="robots" content="noindex" />
  356. <title>Temporarily Unavailable</title>
  357. </head>
  358. <body>
  359. <h3>Temporarily Unavailable</h3>
  360. Due to high stress on the server the forum is temporarily unavailable. Please try again later.
  361. </body>
  362. </html>';
  363. die();
  364. }
  365. /**
  366. * Small utility function for fatal error pages.
  367. * Used by display_db_error(), display_loadavg_error(),
  368. * display_maintenance_message()
  369. */
  370. function set_fatal_error_headers()
  371. {
  372. // Don't cache this page!
  373. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  374. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  375. header('Cache-Control: no-cache');
  376. // Send the right error codes.
  377. header('HTTP/1.1 503 Service Temporarily Unavailable');
  378. header('Status: 503 Service Temporarily Unavailable');
  379. header('Retry-After: 3600');
  380. }