errors.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. <?php
  2. /**
  3. * @file
  4. * Functions for error handling.
  5. */
  6. use Drupal\Component\Utility\SafeMarkup;
  7. use Drupal\Component\Utility\Xss;
  8. use Drupal\Core\Logger\RfcLogLevel;
  9. use Drupal\Core\Render\Markup;
  10. use Drupal\Core\Utility\Error;
  11. use Symfony\Component\HttpFoundation\Response;
  12. /**
  13. * Maps PHP error constants to watchdog severity levels.
  14. *
  15. * The error constants are documented at
  16. * http://php.net/manual/errorfunc.constants.php
  17. *
  18. * @ingroup logging_severity_levels
  19. */
  20. function drupal_error_levels() {
  21. $types = [
  22. E_ERROR => ['Error', RfcLogLevel::ERROR],
  23. E_WARNING => ['Warning', RfcLogLevel::WARNING],
  24. E_PARSE => ['Parse error', RfcLogLevel::ERROR],
  25. E_NOTICE => ['Notice', RfcLogLevel::NOTICE],
  26. E_CORE_ERROR => ['Core error', RfcLogLevel::ERROR],
  27. E_CORE_WARNING => ['Core warning', RfcLogLevel::WARNING],
  28. E_COMPILE_ERROR => ['Compile error', RfcLogLevel::ERROR],
  29. E_COMPILE_WARNING => ['Compile warning', RfcLogLevel::WARNING],
  30. E_USER_ERROR => ['User error', RfcLogLevel::ERROR],
  31. E_USER_WARNING => ['User warning', RfcLogLevel::WARNING],
  32. E_USER_NOTICE => ['User notice', RfcLogLevel::NOTICE],
  33. E_STRICT => ['Strict warning', RfcLogLevel::DEBUG],
  34. E_RECOVERABLE_ERROR => ['Recoverable fatal error', RfcLogLevel::ERROR],
  35. E_DEPRECATED => ['Deprecated function', RfcLogLevel::DEBUG],
  36. E_USER_DEPRECATED => ['User deprecated function', RfcLogLevel::DEBUG],
  37. ];
  38. return $types;
  39. }
  40. /**
  41. * Provides custom PHP error handling.
  42. *
  43. * @param $error_level
  44. * The level of the error raised.
  45. * @param $message
  46. * The error message.
  47. * @param $filename
  48. * The filename that the error was raised in.
  49. * @param $line
  50. * The line number the error was raised at.
  51. * @param $context
  52. * An array that points to the active symbol table at the point the error
  53. * occurred.
  54. */
  55. function _drupal_error_handler_real($error_level, $message, $filename, $line, $context) {
  56. if ($error_level & error_reporting()) {
  57. $types = drupal_error_levels();
  58. list($severity_msg, $severity_level) = $types[$error_level];
  59. $backtrace = debug_backtrace();
  60. $caller = Error::getLastCaller($backtrace);
  61. // We treat recoverable errors as fatal.
  62. $recoverable = $error_level == E_RECOVERABLE_ERROR;
  63. // As __toString() methods must not throw exceptions (recoverable errors)
  64. // in PHP, we allow them to trigger a fatal error by emitting a user error
  65. // using trigger_error().
  66. $to_string = $error_level == E_USER_ERROR && substr($caller['function'], -strlen('__toString()')) == '__toString()';
  67. _drupal_log_error([
  68. '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
  69. // The standard PHP error handler considers that the error messages
  70. // are HTML. We mimick this behavior here.
  71. '@message' => Markup::create(Xss::filterAdmin($message)),
  72. '%function' => $caller['function'],
  73. '%file' => $caller['file'],
  74. '%line' => $caller['line'],
  75. 'severity_level' => $severity_level,
  76. 'backtrace' => $backtrace,
  77. '@backtrace_string' => (new \Exception())->getTraceAsString(),
  78. ], $recoverable || $to_string);
  79. }
  80. // If the site is a test site then fail for user deprecations so they can be
  81. // caught by the deprecation error handler.
  82. elseif (DRUPAL_TEST_IN_CHILD_SITE && $error_level === E_USER_DEPRECATED) {
  83. $backtrace = debug_backtrace();
  84. $caller = Error::getLastCaller($backtrace);
  85. _drupal_error_header(
  86. Markup::create(Xss::filterAdmin($message)),
  87. 'User deprecated function',
  88. $caller['function'],
  89. $caller['file'],
  90. $caller['line']
  91. );
  92. }
  93. }
  94. /**
  95. * Determines whether an error should be displayed.
  96. *
  97. * When in maintenance mode or when error_level is ERROR_REPORTING_DISPLAY_ALL,
  98. * all errors should be displayed. For ERROR_REPORTING_DISPLAY_SOME, $error
  99. * will be examined to determine if it should be displayed.
  100. *
  101. * @param $error
  102. * Optional error to examine for ERROR_REPORTING_DISPLAY_SOME.
  103. *
  104. * @return
  105. * TRUE if an error should be displayed.
  106. */
  107. function error_displayable($error = NULL) {
  108. if (defined('MAINTENANCE_MODE')) {
  109. return TRUE;
  110. }
  111. $error_level = _drupal_get_error_level();
  112. if ($error_level == ERROR_REPORTING_DISPLAY_ALL || $error_level == ERROR_REPORTING_DISPLAY_VERBOSE) {
  113. return TRUE;
  114. }
  115. if ($error_level == ERROR_REPORTING_DISPLAY_SOME && isset($error)) {
  116. return $error['%type'] != 'Notice' && $error['%type'] != 'Strict warning';
  117. }
  118. return FALSE;
  119. }
  120. /**
  121. * Logs a PHP error or exception and displays an error page in fatal cases.
  122. *
  123. * @param $error
  124. * An array with the following keys: %type, @message, %function, %file,
  125. * %line, @backtrace_string, severity_level, and backtrace. All the parameters
  126. * are plain-text, with the exception of @message, which needs to be an HTML
  127. * string, and backtrace, which is a standard PHP backtrace.
  128. * @param bool $fatal
  129. * TRUE for:
  130. * - An exception is thrown and not caught by something else.
  131. * - A recoverable fatal error, which is a fatal error.
  132. * Non-recoverable fatal errors cannot be logged by Drupal.
  133. */
  134. function _drupal_log_error($error, $fatal = FALSE) {
  135. $is_installer = drupal_installation_attempted();
  136. // Backtrace array is not a valid replacement value for t().
  137. $backtrace = $error['backtrace'];
  138. unset($error['backtrace']);
  139. // When running inside the testing framework, we relay the errors
  140. // to the tested site by the way of HTTP headers.
  141. if (DRUPAL_TEST_IN_CHILD_SITE && !headers_sent() && (!defined('SIMPLETEST_COLLECT_ERRORS') || SIMPLETEST_COLLECT_ERRORS)) {
  142. _drupal_error_header($error['@message'], $error['%type'], $error['%function'], $error['%file'], $error['%line']);
  143. }
  144. $response = new Response();
  145. // Only call the logger if there is a logger factory available. This can occur
  146. // if there is an error while rebuilding the container or during the
  147. // installer.
  148. if (\Drupal::hasService('logger.factory')) {
  149. try {
  150. // Provide the PHP backtrace to logger implementations.
  151. \Drupal::logger('php')->log($error['severity_level'], '%type: @message in %function (line %line of %file) @backtrace_string.', $error + ['backtrace' => $backtrace]);
  152. }
  153. catch (\Exception $e) {
  154. // We can't log, for example because the database connection is not
  155. // available. At least try to log to PHP error log.
  156. error_log(strtr('Failed to log error: %type: @message in %function (line %line of %file). @backtrace_string', $error));
  157. }
  158. }
  159. // Log fatal errors, so developers can find and debug them.
  160. if ($fatal) {
  161. error_log(sprintf('%s: %s in %s on line %d %s', $error['%type'], $error['@message'], $error['%file'], $error['%line'], $error['@backtrace_string']));
  162. }
  163. if (PHP_SAPI === 'cli') {
  164. if ($fatal) {
  165. // When called from CLI, simply output a plain text message.
  166. // Should not translate the string to avoid errors producing more errors.
  167. $response->setContent(html_entity_decode(strip_tags(SafeMarkup::format('%type: @message in %function (line %line of %file).', $error))) . "\n");
  168. $response->send();
  169. exit;
  170. }
  171. }
  172. if (\Drupal::hasRequest() && \Drupal::request()->isXmlHttpRequest()) {
  173. if ($fatal) {
  174. if (error_displayable($error)) {
  175. // When called from JavaScript, simply output the error message.
  176. // Should not translate the string to avoid errors producing more errors.
  177. $response->setContent(SafeMarkup::format('%type: @message in %function (line %line of %file).', $error));
  178. $response->send();
  179. }
  180. exit;
  181. }
  182. }
  183. else {
  184. // Display the message if the current error reporting level allows this type
  185. // of message to be displayed, and unconditionally in update.php.
  186. $message = '';
  187. $class = NULL;
  188. if (error_displayable($error)) {
  189. $class = 'error';
  190. // If error type is 'User notice' then treat it as debug information
  191. // instead of an error message.
  192. // @see debug()
  193. if ($error['%type'] == 'User notice') {
  194. $error['%type'] = 'Debug';
  195. $class = 'status';
  196. }
  197. // Attempt to reduce verbosity by removing DRUPAL_ROOT from the file path
  198. // in the message. This does not happen for (false) security.
  199. if (\Drupal::hasService('app.root')) {
  200. $root_length = strlen(\Drupal::root());
  201. if (substr($error['%file'], 0, $root_length) == \Drupal::root()) {
  202. $error['%file'] = substr($error['%file'], $root_length + 1);
  203. }
  204. }
  205. // Check if verbose error reporting is on.
  206. $error_level = _drupal_get_error_level();
  207. if ($error_level != ERROR_REPORTING_DISPLAY_VERBOSE) {
  208. // Without verbose logging, use a simple message.
  209. // We call SafeMarkup::format() directly here, rather than use t() since
  210. // we are in the middle of error handling, and we don't want t() to
  211. // cause further errors.
  212. $message = SafeMarkup::format('%type: @message in %function (line %line of %file).', $error);
  213. }
  214. else {
  215. // With verbose logging, we will also include a backtrace.
  216. // First trace is the error itself, already contained in the message.
  217. // While the second trace is the error source and also contained in the
  218. // message, the message doesn't contain argument values, so we output it
  219. // once more in the backtrace.
  220. array_shift($backtrace);
  221. // Generate a backtrace containing only scalar argument values.
  222. $error['@backtrace'] = Error::formatBacktrace($backtrace);
  223. $message = SafeMarkup::format('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $error);
  224. }
  225. }
  226. if ($fatal) {
  227. // We fallback to a maintenance page at this point, because the page generation
  228. // itself can generate errors.
  229. // Should not translate the string to avoid errors producing more errors.
  230. $message = 'The website encountered an unexpected error. Please try again later.' . '<br />' . $message;
  231. if ($is_installer) {
  232. // install_display_output() prints the output and ends script execution.
  233. $output = [
  234. '#title' => 'Error',
  235. '#markup' => $message,
  236. ];
  237. install_display_output($output, $GLOBALS['install_state'], $response->headers->all());
  238. exit;
  239. }
  240. $response->setContent($message);
  241. $response->setStatusCode(500, '500 Service unavailable (with message)');
  242. $response->send();
  243. // An exception must halt script execution.
  244. exit;
  245. }
  246. if ($message) {
  247. if (\Drupal::hasService('session')) {
  248. // Message display is dependent on sessions being available.
  249. drupal_set_message($message, $class, TRUE);
  250. }
  251. else {
  252. print $message;
  253. }
  254. }
  255. }
  256. }
  257. /**
  258. * Returns the current error level.
  259. *
  260. * This function should only be used to get the current error level prior to the
  261. * kernel being booted or before Drupal is installed. In all other situations
  262. * the following code is preferred:
  263. * @code
  264. * \Drupal::config('system.logging')->get('error_level');
  265. * @endcode
  266. *
  267. * @return string
  268. * The current error level.
  269. */
  270. function _drupal_get_error_level() {
  271. // Raise the error level to maximum for the installer, so users are able to
  272. // file proper bug reports for installer errors. The returned value is
  273. // different to the one below, because the installer actually has a
  274. // 'config.factory' service, which reads the default 'error_level' value from
  275. // System module's default configuration and the default value is not verbose.
  276. // @see error_displayable()
  277. if (drupal_installation_attempted()) {
  278. return ERROR_REPORTING_DISPLAY_VERBOSE;
  279. }
  280. $error_level = NULL;
  281. // Try to get the error level configuration from database. If this fails,
  282. // for example if the database connection is not there, try to read it from
  283. // settings.php.
  284. try {
  285. $error_level = \Drupal::config('system.logging')->get('error_level');
  286. }
  287. catch (\Exception $e) {
  288. $error_level = isset($GLOBALS['config']['system.logging']['error_level']) ? $GLOBALS['config']['system.logging']['error_level'] : ERROR_REPORTING_HIDE;
  289. }
  290. // If there is no container or if it has no config.factory service, we are
  291. // possibly in an edge-case error situation while trying to serve a regular
  292. // request on a public site, so use the non-verbose default value.
  293. return $error_level ?: ERROR_REPORTING_DISPLAY_ALL;
  294. }
  295. /**
  296. * Adds error information to headers so that tests can access it.
  297. *
  298. * @param $message
  299. * The error message.
  300. * @param $type
  301. * The type of error.
  302. * @param $function
  303. * The function that emitted the error.
  304. * @param $file
  305. * The file that emitted the error.
  306. * @param $line
  307. * The line number in file that emitted the error.
  308. */
  309. function _drupal_error_header($message, $type, $function, $file, $line) {
  310. // $number does not use drupal_static as it should not be reset
  311. // as it uniquely identifies each PHP error.
  312. static $number = 0;
  313. $assertion = [
  314. $message,
  315. $type,
  316. [
  317. 'function' => $function,
  318. 'file' => $file,
  319. 'line' => $line,
  320. ],
  321. ];
  322. // For non-fatal errors (e.g. PHP notices) _drupal_log_error can be called
  323. // multiple times per request. In that case the response is typically
  324. // generated outside of the error handler, e.g., in a controller. As a
  325. // result it is not possible to use a Response object here but instead the
  326. // headers need to be emitted directly.
  327. header('X-Drupal-Assertion-' . $number . ': ' . rawurlencode(serialize($assertion)));
  328. $number++;
  329. }