PageRenderTime 26ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/drupal-7.14/includes/errors.inc

#
Pascal | 299 lines | 143 code | 22 blank | 134 comment | 21 complexity | 6d6e34559ea705c0858bcbb4c63eb766 MD5 | raw file
Possible License(s): GPL-2.0
  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. // When called from JavaScript, simply output the error message.
  213. print t('%type: !message in %function (line %line of %file).', $error);
  214. exit;
  215. }
  216. }
  217. else {
  218. // Display the message if the current error reporting level allows this type
  219. // of message to be displayed, and unconditionnaly in update.php.
  220. if (error_displayable($error)) {
  221. $class = 'error';
  222. // If error type is 'User notice' then treat it as debug information
  223. // instead of an error message, see dd().
  224. if ($error['%type'] == 'User notice') {
  225. $error['%type'] = 'Debug';
  226. $class = 'status';
  227. }
  228. drupal_set_message(t('%type: !message in %function (line %line of %file).', $error), $class);
  229. }
  230. if ($fatal) {
  231. drupal_set_title(t('Error'));
  232. // We fallback to a maintenance page at this point, because the page generation
  233. // itself can generate errors.
  234. print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));
  235. exit;
  236. }
  237. }
  238. }
  239. /**
  240. * Gets the last caller from a backtrace.
  241. *
  242. * @param $backtrace
  243. * A standard PHP backtrace.
  244. *
  245. * @return
  246. * An associative array with keys 'file', 'line' and 'function'.
  247. */
  248. function _drupal_get_last_caller($backtrace) {
  249. // Errors that occur inside PHP internal functions do not generate
  250. // information about file and line. Ignore black listed functions.
  251. $blacklist = array('debug', '_drupal_error_handler', '_drupal_exception_handler');
  252. while (($backtrace && !isset($backtrace[0]['line'])) ||
  253. (isset($backtrace[1]['function']) && in_array($backtrace[1]['function'], $blacklist))) {
  254. array_shift($backtrace);
  255. }
  256. // The first trace is the call itself.
  257. // It gives us the line and the file of the last call.
  258. $call = $backtrace[0];
  259. // The second call give us the function where the call originated.
  260. if (isset($backtrace[1])) {
  261. if (isset($backtrace[1]['class'])) {
  262. $call['function'] = $backtrace[1]['class'] . $backtrace[1]['type'] . $backtrace[1]['function'] . '()';
  263. }
  264. else {
  265. $call['function'] = $backtrace[1]['function'] . '()';
  266. }
  267. }
  268. else {
  269. $call['function'] = 'main()';
  270. }
  271. return $call;
  272. }