errors.inc 11 KB

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