errors.inc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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/en/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 mimick 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 mimick 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 boostrap 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. watchdog('php', '%type: !message in %function (line %line of %file).', $error, $error['severity_level']);
  188. if ($fatal) {
  189. drupal_add_http_header('Status', '500 Service unavailable (with message)');
  190. }
  191. if (drupal_is_cli()) {
  192. if ($fatal) {
  193. // When called from CLI, simply output a plain text message.
  194. print html_entity_decode(strip_tags(t('%type: !message in %function (line %line of %file).', $error))). "\n";
  195. exit;
  196. }
  197. }
  198. if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
  199. if ($fatal) {
  200. if (error_displayable($error)) {
  201. // When called from JavaScript, simply output the error message.
  202. print t('%type: !message in %function (line %line of %file).', $error);
  203. }
  204. exit;
  205. }
  206. }
  207. else {
  208. // Display the message if the current error reporting level allows this type
  209. // of message to be displayed, and unconditionnaly in update.php.
  210. if (error_displayable($error)) {
  211. $class = 'error';
  212. // If error type is 'User notice' then treat it as debug information
  213. // instead of an error message, see dd().
  214. if ($error['%type'] == 'User notice') {
  215. $error['%type'] = 'Debug';
  216. $class = 'status';
  217. }
  218. drupal_set_message(t('%type: !message in %function (line %line of %file).', $error), $class);
  219. }
  220. if ($fatal) {
  221. drupal_set_title(t('Error'));
  222. // We fallback to a maintenance page at this point, because the page generation
  223. // itself can generate errors.
  224. print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));
  225. exit;
  226. }
  227. }
  228. }
  229. /**
  230. * Gets the last caller from a backtrace.
  231. *
  232. * @param $backtrace
  233. * A standard PHP backtrace.
  234. *
  235. * @return
  236. * An associative array with keys 'file', 'line' and 'function'.
  237. */
  238. function _drupal_get_last_caller($backtrace) {
  239. // Errors that occur inside PHP internal functions do not generate
  240. // information about file and line. Ignore black listed functions.
  241. $blacklist = array('debug', '_drupal_error_handler', '_drupal_exception_handler');
  242. while (($backtrace && !isset($backtrace[0]['line'])) ||
  243. (isset($backtrace[1]['function']) && in_array($backtrace[1]['function'], $blacklist))) {
  244. array_shift($backtrace);
  245. }
  246. // The first trace is the call itself.
  247. // It gives us the line and the file of the last call.
  248. $call = $backtrace[0];
  249. // The second call give us the function where the call originated.
  250. if (isset($backtrace[1])) {
  251. if (isset($backtrace[1]['class'])) {
  252. $call['function'] = $backtrace[1]['class'] . $backtrace[1]['type'] . $backtrace[1]['function'] . '()';
  253. }
  254. else {
  255. $call['function'] = $backtrace[1]['function'] . '()';
  256. }
  257. }
  258. else {
  259. $call['function'] = 'main()';
  260. }
  261. return $call;
  262. }