errors.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. }
  81. /**
  82. * Determines whether an error should be displayed.
  83. *
  84. * When in maintenance mode or when error_level is ERROR_REPORTING_DISPLAY_ALL,
  85. * all errors should be displayed. For ERROR_REPORTING_DISPLAY_SOME, $error
  86. * will be examined to determine if it should be displayed.
  87. *
  88. * @param $error
  89. * Optional error to examine for ERROR_REPORTING_DISPLAY_SOME.
  90. *
  91. * @return
  92. * TRUE if an error should be displayed.
  93. */
  94. function error_displayable($error = NULL) {
  95. if (defined('MAINTENANCE_MODE')) {
  96. return TRUE;
  97. }
  98. $error_level = _drupal_get_error_level();
  99. if ($error_level == ERROR_REPORTING_DISPLAY_ALL || $error_level == ERROR_REPORTING_DISPLAY_VERBOSE) {
  100. return TRUE;
  101. }
  102. if ($error_level == ERROR_REPORTING_DISPLAY_SOME && isset($error)) {
  103. return $error['%type'] != 'Notice' && $error['%type'] != 'Strict warning';
  104. }
  105. return FALSE;
  106. }
  107. /**
  108. * Logs a PHP error or exception and displays an error page in fatal cases.
  109. *
  110. * @param $error
  111. * An array with the following keys: %type, @message, %function, %file,
  112. * %line, @backtrace_string, severity_level, and backtrace. All the parameters
  113. * are plain-text, with the exception of @message, which needs to be an HTML
  114. * string, and backtrace, which is a standard PHP backtrace.
  115. * @param bool $fatal
  116. * TRUE for:
  117. * - An exception is thrown and not caught by something else.
  118. * - A recoverable fatal error, which is a fatal error.
  119. * Non-recoverable fatal errors cannot be logged by Drupal.
  120. */
  121. function _drupal_log_error($error, $fatal = FALSE) {
  122. $is_installer = drupal_installation_attempted();
  123. // Backtrace array is not a valid replacement value for t().
  124. $backtrace = $error['backtrace'];
  125. unset($error['backtrace']);
  126. // When running inside the testing framework, we relay the errors
  127. // to the tested site by the way of HTTP headers.
  128. if (DRUPAL_TEST_IN_CHILD_SITE && !headers_sent() && (!defined('SIMPLETEST_COLLECT_ERRORS') || SIMPLETEST_COLLECT_ERRORS)) {
  129. // $number does not use drupal_static as it should not be reset
  130. // as it uniquely identifies each PHP error.
  131. static $number = 0;
  132. $assertion = [
  133. $error['@message'],
  134. $error['%type'],
  135. [
  136. 'function' => $error['%function'],
  137. 'file' => $error['%file'],
  138. 'line' => $error['%line'],
  139. ],
  140. ];
  141. // For non-fatal errors (e.g. PHP notices) _drupal_log_error can be called
  142. // multiple times per request. In that case the response is typically
  143. // generated outside of the error handler, e.g., in a controller. As a
  144. // result it is not possible to use a Response object here but instead the
  145. // headers need to be emitted directly.
  146. header('X-Drupal-Assertion-' . $number . ': ' . rawurlencode(serialize($assertion)));
  147. $number++;
  148. }
  149. $response = new Response();
  150. // Only call the logger if there is a logger factory available. This can occur
  151. // if there is an error while rebuilding the container or during the
  152. // installer.
  153. if (\Drupal::hasService('logger.factory')) {
  154. try {
  155. \Drupal::logger('php')->log($error['severity_level'], '%type: @message in %function (line %line of %file) @backtrace_string.', $error);
  156. }
  157. catch (\Exception $e) {
  158. // We can't log, for example because the database connection is not
  159. // available. At least try to log to PHP error log.
  160. error_log(strtr('Failed to log error: %type: @message in %function (line %line of %file). @backtrace_string', $error));
  161. }
  162. }
  163. // Log fatal errors, so developers can find and debug them.
  164. if ($fatal) {
  165. error_log(sprintf('%s: %s in %s on line %d %s', $error['%type'], $error['@message'], $error['%file'], $error['%line'], $error['@backtrace_string']));
  166. }
  167. if (PHP_SAPI === 'cli') {
  168. if ($fatal) {
  169. // When called from CLI, simply output a plain text message.
  170. // Should not translate the string to avoid errors producing more errors.
  171. $response->setContent(html_entity_decode(strip_tags(SafeMarkup::format('%type: @message in %function (line %line of %file).', $error))) . "\n");
  172. $response->send();
  173. exit;
  174. }
  175. }
  176. if (\Drupal::hasRequest() && \Drupal::request()->isXmlHttpRequest()) {
  177. if ($fatal) {
  178. if (error_displayable($error)) {
  179. // When called from JavaScript, simply output the error message.
  180. // Should not translate the string to avoid errors producing more errors.
  181. $response->setContent(SafeMarkup::format('%type: @message in %function (line %line of %file).', $error));
  182. $response->send();
  183. }
  184. exit;
  185. }
  186. }
  187. else {
  188. // Display the message if the current error reporting level allows this type
  189. // of message to be displayed, and unconditionally in update.php.
  190. $message = '';
  191. $class = NULL;
  192. if (error_displayable($error)) {
  193. $class = 'error';
  194. // If error type is 'User notice' then treat it as debug information
  195. // instead of an error message.
  196. // @see debug()
  197. if ($error['%type'] == 'User notice') {
  198. $error['%type'] = 'Debug';
  199. $class = 'status';
  200. }
  201. // Attempt to reduce verbosity by removing DRUPAL_ROOT from the file path
  202. // in the message. This does not happen for (false) security.
  203. if (\Drupal::hasService('app.root')) {
  204. $root_length = strlen(\Drupal::root());
  205. if (substr($error['%file'], 0, $root_length) == \Drupal::root()) {
  206. $error['%file'] = substr($error['%file'], $root_length + 1);
  207. }
  208. }
  209. // Check if verbose error reporting is on.
  210. $error_level = _drupal_get_error_level();
  211. if ($error_level != ERROR_REPORTING_DISPLAY_VERBOSE) {
  212. // Without verbose logging, use a simple message.
  213. // We call SafeMarkup::format() directly here, rather than use t() since
  214. // we are in the middle of error handling, and we don't want t() to
  215. // cause further errors.
  216. $message = SafeMarkup::format('%type: @message in %function (line %line of %file).', $error);
  217. }
  218. else {
  219. // With verbose logging, we will also include a backtrace.
  220. // First trace is the error itself, already contained in the message.
  221. // While the second trace is the error source and also contained in the
  222. // message, the message doesn't contain argument values, so we output it
  223. // once more in the backtrace.
  224. array_shift($backtrace);
  225. // Generate a backtrace containing only scalar argument values.
  226. $error['@backtrace'] = Error::formatBacktrace($backtrace);
  227. $message = SafeMarkup::format('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $error);
  228. }
  229. }
  230. if ($fatal) {
  231. // We fallback to a maintenance page at this point, because the page generation
  232. // itself can generate errors.
  233. // Should not translate the string to avoid errors producing more errors.
  234. $message = 'The website encountered an unexpected error. Please try again later.' . '<br />' . $message;
  235. if ($is_installer) {
  236. // install_display_output() prints the output and ends script execution.
  237. $output = [
  238. '#title' => 'Error',
  239. '#markup' => $message,
  240. ];
  241. install_display_output($output, $GLOBALS['install_state'], $response->headers->all());
  242. exit;
  243. }
  244. $response->setContent($message);
  245. $response->setStatusCode(500, '500 Service unavailable (with message)');
  246. $response->send();
  247. // An exception must halt script execution.
  248. exit;
  249. }
  250. if ($message) {
  251. if (\Drupal::hasService('session')) {
  252. // Message display is dependent on sessions being available.
  253. drupal_set_message($message, $class, TRUE);
  254. }
  255. else {
  256. print $message;
  257. }
  258. }
  259. }
  260. }
  261. /**
  262. * Returns the current error level.
  263. *
  264. * This function should only be used to get the current error level prior to the
  265. * kernel being booted or before Drupal is installed. In all other situations
  266. * the following code is preferred:
  267. * @code
  268. * \Drupal::config('system.logging')->get('error_level');
  269. * @endcode
  270. *
  271. * @return string
  272. * The current error level.
  273. */
  274. function _drupal_get_error_level() {
  275. // Raise the error level to maximum for the installer, so users are able to
  276. // file proper bug reports for installer errors. The returned value is
  277. // different to the one below, because the installer actually has a
  278. // 'config.factory' service, which reads the default 'error_level' value from
  279. // System module's default configuration and the default value is not verbose.
  280. // @see error_displayable()
  281. if (drupal_installation_attempted()) {
  282. return ERROR_REPORTING_DISPLAY_VERBOSE;
  283. }
  284. $error_level = NULL;
  285. // Try to get the error level configuration from database. If this fails,
  286. // for example if the database connection is not there, try to read it from
  287. // settings.php.
  288. try {
  289. $error_level = \Drupal::config('system.logging')->get('error_level');
  290. }
  291. catch (\Exception $e) {
  292. $error_level = isset($GLOBALS['config']['system.logging']['error_level']) ? $GLOBALS['config']['system.logging']['error_level'] : ERROR_REPORTING_HIDE;
  293. }
  294. // If there is no container or if it has no config.factory service, we are
  295. // possibly in an edge-case error situation while trying to serve a regular
  296. // request on a public site, so use the non-verbose default value.
  297. return $error_level ?: ERROR_REPORTING_DISPLAY_ALL;
  298. }