errors.inc 10 KB

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