errors.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. /**
  3. * @file
  4. * Functions for error handling.
  5. */
  6. /**
  7. * Maps PHP error constants to watchdog severity levels.
  8. *
  9. * The error constants are documented at
  10. * http://php.net/manual/errorfunc.constants.php
  11. *
  12. * @ingroup logging_severity_levels
  13. */
  14. function drupal_error_levels() {
  15. $types = array(
  16. E_ERROR => array('Error', WATCHDOG_ERROR),
  17. E_WARNING => array('Warning', WATCHDOG_WARNING),
  18. E_PARSE => array('Parse error', WATCHDOG_ERROR),
  19. E_NOTICE => array('Notice', WATCHDOG_NOTICE),
  20. E_CORE_ERROR => array('Core error', WATCHDOG_ERROR),
  21. E_CORE_WARNING => array('Core warning', WATCHDOG_WARNING),
  22. E_COMPILE_ERROR => array('Compile error', WATCHDOG_ERROR),
  23. E_COMPILE_WARNING => array('Compile warning', WATCHDOG_WARNING),
  24. E_USER_ERROR => array('User error', WATCHDOG_ERROR),
  25. E_USER_WARNING => array('User warning', WATCHDOG_WARNING),
  26. E_USER_NOTICE => array('User notice', WATCHDOG_NOTICE),
  27. E_STRICT => array('Strict warning', WATCHDOG_DEBUG),
  28. E_RECOVERABLE_ERROR => array('Recoverable fatal error', WATCHDOG_ERROR),
  29. );
  30. // E_DEPRECATED and E_USER_DEPRECATED were added in PHP 5.3.0.
  31. if (defined('E_DEPRECATED')) {
  32. $types[E_DEPRECATED] = array('Deprecated function', WATCHDOG_DEBUG);
  33. $types[E_USER_DEPRECATED] = array('User deprecated function', WATCHDOG_DEBUG);
  34. }
  35. return $types;
  36. }
  37. /**
  38. * Provides custom PHP error handling.
  39. *
  40. * @param $error_level
  41. * The level of the error raised.
  42. * @param $message
  43. * The error message.
  44. * @param $filename
  45. * The filename that the error was raised in.
  46. * @param $line
  47. * The line number the error was raised at.
  48. */
  49. function _drupal_error_handler_real($error_level, $message, $filename, $line) {
  50. if ($error_level & error_reporting()) {
  51. $types = drupal_error_levels();
  52. list($severity_msg, $severity_level) = $types[$error_level];
  53. $caller = _drupal_get_last_caller(debug_backtrace());
  54. if (!function_exists('filter_xss_admin')) {
  55. require_once DRUPAL_ROOT . '/includes/common.inc';
  56. }
  57. // We treat recoverable errors as fatal, and also allow fatal errors to be
  58. // explicitly triggered by drupal_trigger_fatal_error().
  59. _drupal_log_error(array(
  60. '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
  61. // The standard PHP error handler considers that the error messages
  62. // are HTML. We mimic this behavior here.
  63. '!message' => filter_xss_admin($message),
  64. '%function' => $caller['function'],
  65. '%file' => $caller['file'],
  66. '%line' => $caller['line'],
  67. 'severity_level' => $severity_level,
  68. ), $error_level == E_RECOVERABLE_ERROR || drupal_static('drupal_trigger_fatal_error'));
  69. }
  70. }
  71. /**
  72. * Decodes an exception and retrieves the correct caller.
  73. *
  74. * @param $exception
  75. * The exception object that was thrown.
  76. *
  77. * @return
  78. * An error in the format expected by _drupal_log_error().
  79. */
  80. function _drupal_decode_exception($exception) {
  81. $message = $exception->getMessage();
  82. $backtrace = $exception->getTrace();
  83. // Add the line throwing the exception to the backtrace.
  84. array_unshift($backtrace, array('line' => $exception->getLine(), 'file' => $exception->getFile()));
  85. // For PDOException errors, we try to return the initial caller,
  86. // skipping internal functions of the database layer.
  87. if ($exception instanceof PDOException) {
  88. // The first element in the stack is the call, the second element gives us the caller.
  89. // We skip calls that occurred in one of the classes of the database layer
  90. // or in one of its global functions.
  91. $db_functions = array('db_query', 'db_query_range');
  92. while (!empty($backtrace[1]) && ($caller = $backtrace[1]) &&
  93. ((isset($caller['class']) && (strpos($caller['class'], 'Query') !== FALSE || strpos($caller['class'], 'Database') !== FALSE || strpos($caller['class'], 'PDO') !== FALSE)) ||
  94. in_array($caller['function'], $db_functions))) {
  95. // We remove that call.
  96. array_shift($backtrace);
  97. }
  98. if (isset($exception->errorInfo['query_string'], $exception->errorInfo['args'])) {
  99. $message .= ": " . $exception->errorInfo['query_string'] . "; " . print_r($exception->errorInfo['args'], TRUE);
  100. }
  101. }
  102. $caller = _drupal_get_last_caller($backtrace);
  103. return array(
  104. '%type' => get_class($exception),
  105. // The standard PHP exception handler considers that the exception message
  106. // is plain-text. We mimic this behavior here.
  107. '!message' => check_plain($message),
  108. '%function' => $caller['function'],
  109. '%file' => $caller['file'],
  110. '%line' => $caller['line'],
  111. 'severity_level' => WATCHDOG_ERROR,
  112. );
  113. }
  114. /**
  115. * Renders an exception error message without further exceptions.
  116. *
  117. * @param $exception
  118. * The exception object that was thrown.
  119. * @return
  120. * An error message.
  121. */
  122. function _drupal_render_exception_safe($exception) {
  123. return check_plain(strtr('%type: !message in %function (line %line of %file).', _drupal_decode_exception($exception)));
  124. }
  125. /**
  126. * Determines whether an error should be displayed.
  127. *
  128. * When in maintenance mode or when error_level is ERROR_REPORTING_DISPLAY_ALL,
  129. * all errors should be displayed. For ERROR_REPORTING_DISPLAY_SOME, $error
  130. * will be examined to determine if it should be displayed.
  131. *
  132. * @param $error
  133. * Optional error to examine for ERROR_REPORTING_DISPLAY_SOME.
  134. *
  135. * @return
  136. * TRUE if an error should be displayed.
  137. */
  138. function error_displayable($error = NULL) {
  139. $error_level = variable_get('error_level', ERROR_REPORTING_DISPLAY_ALL);
  140. $updating = (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update');
  141. $all_errors_displayed = ($error_level == ERROR_REPORTING_DISPLAY_ALL);
  142. $error_needs_display = ($error_level == ERROR_REPORTING_DISPLAY_SOME &&
  143. isset($error) && $error['%type'] != 'Notice' && $error['%type'] != 'Strict warning');
  144. return ($updating || $all_errors_displayed || $error_needs_display);
  145. }
  146. /**
  147. * Logs a PHP error or exception and displays an error page in fatal cases.
  148. *
  149. * @param $error
  150. * An array with the following keys: %type, !message, %function, %file, %line
  151. * and severity_level. All the parameters are plain-text, with the exception
  152. * of !message, which needs to be a safe HTML string.
  153. * @param $fatal
  154. * TRUE if the error is fatal.
  155. */
  156. function _drupal_log_error($error, $fatal = FALSE) {
  157. // Initialize a maintenance theme if the bootstrap was not complete.
  158. // Do it early because drupal_set_message() triggers a drupal_theme_initialize().
  159. if ($fatal && (drupal_get_bootstrap_phase() != DRUPAL_BOOTSTRAP_FULL)) {
  160. unset($GLOBALS['theme']);
  161. if (!defined('MAINTENANCE_MODE')) {
  162. define('MAINTENANCE_MODE', 'error');
  163. }
  164. drupal_maintenance_theme();
  165. }
  166. // When running inside the testing framework, we relay the errors
  167. // to the tested site by the way of HTTP headers.
  168. $test_info = &$GLOBALS['drupal_test_info'];
  169. if (!empty($test_info['in_child_site']) && !headers_sent() && (!defined('SIMPLETEST_COLLECT_ERRORS') || SIMPLETEST_COLLECT_ERRORS)) {
  170. // $number does not use drupal_static as it should not be reset
  171. // as it uniquely identifies each PHP error.
  172. static $number = 0;
  173. $assertion = array(
  174. $error['!message'],
  175. $error['%type'],
  176. array(
  177. 'function' => $error['%function'],
  178. 'file' => $error['%file'],
  179. 'line' => $error['%line'],
  180. ),
  181. );
  182. header('X-Drupal-Assertion-' . $number . ': ' . rawurlencode(serialize($assertion)));
  183. $number++;
  184. }
  185. // Log the error immediately, unless this is a non-fatal error which has been
  186. // triggered via drupal_trigger_error_with_delayed_logging(); in that case
  187. // trigger it in a shutdown function. Fatal errors are always triggered
  188. // immediately since for a fatal error the page request will end here anyway.
  189. if (!$fatal && drupal_static('_drupal_trigger_error_with_delayed_logging')) {
  190. drupal_register_shutdown_function('watchdog', 'php', '%type: !message in %function (line %line of %file).', $error, $error['severity_level']);
  191. }
  192. else {
  193. watchdog('php', '%type: !message in %function (line %line of %file).', $error, $error['severity_level']);
  194. }
  195. if ($fatal) {
  196. drupal_add_http_header('Status', '500 Service unavailable (with message)');
  197. }
  198. if (drupal_is_cli()) {
  199. if ($fatal) {
  200. // When called from CLI, simply output a plain text message.
  201. print html_entity_decode(strip_tags(t('%type: !message in %function (line %line of %file).', $error))). "\n";
  202. exit(1);
  203. }
  204. }
  205. if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
  206. if ($fatal) {
  207. if (error_displayable($error)) {
  208. // When called from JavaScript, simply output the error message.
  209. print t('%type: !message in %function (line %line of %file).', $error);
  210. }
  211. exit;
  212. }
  213. }
  214. else {
  215. // Display the message if the current error reporting level allows this type
  216. // of message to be displayed, and unconditionally in update.php.
  217. if (error_displayable($error)) {
  218. $class = 'error';
  219. // If error type is 'User notice' then treat it as debug information
  220. // instead of an error message, see dd().
  221. if ($error['%type'] == 'User notice') {
  222. $error['%type'] = 'Debug';
  223. $class = 'status';
  224. }
  225. drupal_set_message(t('%type: !message in %function (line %line of %file).', $error), $class);
  226. }
  227. if ($fatal) {
  228. drupal_set_title(t('Error'));
  229. // We fallback to a maintenance page at this point, because the page generation
  230. // itself can generate errors.
  231. print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));
  232. exit;
  233. }
  234. }
  235. }
  236. /**
  237. * Gets the last caller from a backtrace.
  238. *
  239. * @param $backtrace
  240. * A standard PHP backtrace.
  241. *
  242. * @return
  243. * An associative array with keys 'file', 'line' and 'function'.
  244. */
  245. function _drupal_get_last_caller($backtrace) {
  246. // Errors that occur inside PHP internal functions do not generate
  247. // information about file and line. Ignore black listed functions.
  248. $blacklist = array('debug', '_drupal_error_handler', '_drupal_exception_handler', 'drupal_trigger_fatal_error');
  249. while (($backtrace && !isset($backtrace[0]['line'])) ||
  250. (isset($backtrace[1]['function']) && in_array($backtrace[1]['function'], $blacklist))) {
  251. array_shift($backtrace);
  252. }
  253. // The first trace is the call itself.
  254. // It gives us the line and the file of the last call.
  255. $call = $backtrace[0];
  256. // The second call give us the function where the call originated.
  257. if (isset($backtrace[1])) {
  258. if (isset($backtrace[1]['class'])) {
  259. $call['function'] = $backtrace[1]['class'] . $backtrace[1]['type'] . $backtrace[1]['function'] . '()';
  260. }
  261. else {
  262. $call['function'] = $backtrace[1]['function'] . '()';
  263. }
  264. }
  265. else {
  266. $call['function'] = 'main()';
  267. }
  268. return $call;
  269. }