errors.inc 11 KB

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