ExceptionController.php 17 KB
Newer Older
1 2
<?php

Crell's avatar
Crell committed
3 4
/**
 * @file
5
 * Contains \Drupal\Core\Controller\ExceptionController.
Crell's avatar
Crell committed
6
 */
7

8
namespace Drupal\Core\Controller;
9

10
use Drupal\Core\Page\DefaultHtmlPageRenderer;
11
use Drupal\Core\Page\HtmlFragmentRendererInterface;
12
use Drupal\Core\Page\HtmlPageRendererInterface;
13
use Drupal\Core\Routing\UrlGeneratorInterface;
14 15
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
16 17
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\HttpFoundation\JsonResponse;
19
use Symfony\Component\HttpKernel\HttpKernelInterface;
20
use Drupal\Component\Utility\String;
21
use Symfony\Component\Debug\Exception\FlattenException;
22
use Drupal\Core\ContentNegotiation;
23
use Drupal\Core\Utility\Error;
24 25
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
26

27
/**
Crell's avatar
Crell committed
28
 * This controller handles HTTP errors generated by the routing system.
29
 */
30
class ExceptionController extends HtmlControllerBase implements ContainerAwareInterface {
31
  use StringTranslationTrait;
Crell's avatar
Crell committed
32 33

  /**
34
   * The content negotiation library.
Crell's avatar
Crell committed
35
   *
36
   * @var \Drupal\Core\ContentNegotiation
Crell's avatar
Crell committed
37
   */
38 39
  protected $negotiation;

40 41 42 43 44 45 46 47 48 49 50 51
  /**
   * The service container.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

  /**
   * The page rendering service.
   *
   * @var \Drupal\Core\Page\HtmlPageRendererInterface
   */
52 53 54 55 56 57 58 59
  protected $htmlPageRenderer;

  /**
   * The fragment rendering service.
   *
   * @var \Drupal\Core\Page\HtmlFragmentRendererInterface
   */
  protected $fragmentRenderer;
60

Crell's avatar
Crell committed
61
  /**
62
   * Constructor.
63
   *
64
   * @param \Drupal\Core\ContentNegotiation $negotiation
Crell's avatar
Crell committed
65 66
   *   The content negotiation library to use to determine the correct response
   *   format.
67 68 69 70
   * @param \Drupal\Core\Controller\TitleResolverInterface $title_resolver
   *   The title resolver.
   * @param \Drupal\Core\Page\HtmlPageRendererInterface $renderer
   *   The page renderer.
71 72
   * @param \Drupal\Core\Page\HtmlFragmentRendererInterface $fragment_renderer
   *   The fragment rendering service.
73 74 75
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The url generator.
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
Crell's avatar
Crell committed
76
   */
77 78
  public function __construct(ContentNegotiation $negotiation, TitleResolverInterface $title_resolver, HtmlPageRendererInterface $renderer, HtmlFragmentRendererInterface $fragment_renderer, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator) {
    parent::__construct($title_resolver, $url_generator);
79
    $this->negotiation = $negotiation;
80 81
    $this->htmlPageRenderer = $renderer;
    $this->fragmentRenderer = $fragment_renderer;
82
    $this->stringTranslation = $string_translation;
83 84 85 86 87 88 89 90 91 92 93 94
  }

  /**
   * Sets the Container associated with this Controller.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   A ContainerInterface instance.
   *
   * @api
   */
  public function setContainer(ContainerInterface $container = NULL) {
    $this->container = $container;
95 96
  }

Crell's avatar
Crell committed
97 98 99
  /**
   * Handles an exception on a request.
   *
100
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
Crell's avatar
Crell committed
101
   *   The flattened exception.
102
   * @param \Symfony\Component\HttpFoundation\Request $request
Crell's avatar
Crell committed
103
   *   The request that generated the exception.
104
   *
105
   * @return \Symfony\Component\HttpFoundation\Response
106
   *   A response object.
Crell's avatar
Crell committed
107
   */
108 109 110 111 112 113 114
  public function execute(FlattenException $exception, Request $request) {
    $method = 'on' . $exception->getStatusCode() . $this->negotiation->getContentType($request);

    if (method_exists($this, $method)) {
      return $this->$method($exception, $request);
    }

115
    return new Response('A fatal error occurred: ' . $exception->getMessage(), $exception->getStatusCode(), $exception->getHeaders());
116 117 118 119 120
  }

  /**
   * Processes a MethodNotAllowed exception into an HTTP 405 response.
   *
121
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
122
   *   The flattened exception.
123
   * @param \Symfony\Component\HttpFoundation\Request $request
124
   *   The request object that triggered this exception.
125 126 127
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   A response object.
128 129
   */
  public function on405Html(FlattenException $exception, Request $request) {
130
    return new Response('Method Not Allowed', 405);
131 132 133 134 135
  }

  /**
   * Processes an AccessDenied exception into an HTTP 403 response.
   *
136
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
137
   *   The flattened exception.
138
   * @param \Symfony\Component\HttpFoundation\Request $request
139
   *   The request object that triggered this exception.
140 141 142
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   A response object.
143 144
   */
  public function on403Html(FlattenException $exception, Request $request) {
145
    $system_path = $request->attributes->get('_system_path');
146
    watchdog('access denied', $system_path, array(), WATCHDOG_WARNING);
147

148
    $system_config = $this->container->get('config.factory')->get('system.site');
149
    $path = $this->container->get('path.alias_manager')->getPathByAlias($system_config->get('page.403'));
150
    if ($path && $path != $system_path) {
151 152 153 154 155 156
      if ($request->getMethod() === 'POST') {
        $subrequest = Request::create($request->getBaseUrl() . '/' . $path, 'POST', array('destination' => $system_path, '_exception_statuscode' => 403) + $request->request->all(), $request->cookies->all(), array(), $request->server->all());
      }
      else {
        $subrequest = Request::create($request->getBaseUrl() . '/' . $path, 'GET', array('destination' => $system_path, '_exception_statuscode' => 403), $request->cookies->all(), array(), $request->server->all());
      }
157

158
      $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
159 160 161
      $response->setStatusCode(403, 'Access denied');
    }
    else {
162
      $page_content = array(
163 164
        '#markup' => $this->t('You are not authorized to access this page.'),
        '#title' => $this->t('Access denied'),
165
      );
166

167
      $fragment = $this->createHtmlFragment($page_content, $request);
168 169
      $page = $this->fragmentRenderer->render($fragment, 403);
      $response = new Response($this->htmlPageRenderer->render($page), $page->getStatusCode());
170
      return $response;
171 172 173
    }

    return $response;
174 175
  }

176
  /**
177
   * Processes a NotFound exception into an HTTP 404 response.
178
   *
179
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
180
   *   The flattened exception.
181
   * @param \Symfony\Component\HttpFoundation\Request $request
182
   *   The request object that triggered this exception.
183 184 185
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   A response object.
186 187
   */
  public function on404Html(FlattenException $exception, Request $request) {
188
    watchdog('page not found', String::checkPlain($request->attributes->get('_system_path')), array(), WATCHDOG_WARNING);
189 190

    // Check for and return a fast 404 page if configured.
191
    $config = \Drupal::config('system.performance');
192

193 194 195
    $exclude_paths = $config->get('fast_404.exclude_paths');
    if ($config->get('fast_404.enabled') && $exclude_paths && !preg_match($exclude_paths, $request->getPathInfo())) {
      $fast_paths = $config->get('fast_404.paths');
196
      if ($fast_paths && preg_match($fast_paths, $request->getPathInfo())) {
197
        $fast_404_html = $config->get('fast_404.html');
198
        $fast_404_html = strtr($fast_404_html, array('@path' => String::checkPlain($request->getUri())));
199 200 201
        return new Response($fast_404_html, 404);
      }
    }
202

203
    $system_path = $request->attributes->get('_system_path');
204

205
    $path = $this->container->get('path.alias_manager')->getPathByAlias(\Drupal::config('system.site')->get('page.404'));
206 207 208 209 210
    if ($path && $path != $system_path) {
      // @todo Um, how do I specify an override URL again? Totally not clear. Do
      //   that and sub-call the kernel rather than using meah().
      // @todo The create() method expects a slash-prefixed path, but we store a
      //   normal system path in the site_404 variable.
211 212 213 214 215 216
      if ($request->getMethod() === 'POST') {
        $subrequest = Request::create($request->getBaseUrl() . '/' . $path, 'POST', array('destination' => $system_path, '_exception_statuscode' => 404) + $request->request->all(), $request->cookies->all(), array(), $request->server->all());
      }
      else {
        $subrequest = Request::create($request->getBaseUrl() . '/' . $path, 'GET', array('destination' => $system_path, '_exception_statuscode' => 404), $request->cookies->all(), array(), $request->server->all());
      }
217

218
      $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
219 220 221
      $response->setStatusCode(404, 'Not Found');
    }
    else {
222
      $page_content = array(
223 224
        '#markup' => $this->t('The requested page "@path" could not be found.', array('@path' => $request->getPathInfo())),
        '#title' => $this->t('Page not found'),
225 226 227
      );

      $fragment = $this->createHtmlFragment($page_content, $request);
228 229
      $page = $this->fragmentRenderer->render($fragment, 404);
      $response = new Response($this->htmlPageRenderer->render($page), $page->getStatusCode());
230
      return $response;
231 232 233 234 235
    }

    return $response;
  }

236 237 238
  /**
   * Processes a generic exception into an HTTP 500 response.
   *
239
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
240
   *   Metadata about the exception that was thrown.
241
   * @param \Symfony\Component\HttpFoundation\Request $request
242
   *   The request object that triggered this exception.
243 244 245
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   A response object.
246 247 248 249 250 251 252 253 254 255 256
   */
  public function on500Html(FlattenException $exception, Request $request) {
    $error = $this->decodeException($exception);

    // Because the kernel doesn't run until full bootstrap, we know that
    // most subsystems are already initialized.

    $headers = array();

    // When running inside the testing framework, we relay the errors
    // to the tested site by the way of HTTP headers.
257
    if (DRUPAL_TEST_IN_CHILD_SITE && !headers_sent() && (!defined('SIMPLETEST_COLLECT_ERRORS') || SIMPLETEST_COLLECT_ERRORS)) {
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      // $number does not use drupal_static as it should not be reset
      // as it uniquely identifies each PHP error.
      static $number = 0;
      $assertion = array(
        $error['!message'],
        $error['%type'],
        array(
          'function' => $error['%function'],
          'file' => $error['%file'],
          'line' => $error['%line'],
        ),
      );
      $headers['X-Drupal-Assertion-' . $number] = rawurlencode(serialize($assertion));
      $number++;
    }

    watchdog('php', '%type: !message in %function (line %line of %file).', $error, $error['severity_level']);

    // Display the message if the current error reporting level allows this type
    // of message to be displayed, and unconditionnaly in update.php.
    if (error_displayable($error)) {
      $class = 'error';

      // If error type is 'User notice' then treat it as debug information
282 283
      // instead of an error message.
      // @see debug()
284 285 286 287 288
      if ($error['%type'] == 'User notice') {
        $error['%type'] = 'Debug';
        $class = 'status';
      }

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
      // Attempt to reduce verbosity by removing DRUPAL_ROOT from the file path
      // in the message. This does not happen for (false) security.
      $root_length = strlen(DRUPAL_ROOT);
      if (substr($error['%file'], 0, $root_length) == DRUPAL_ROOT) {
        $error['%file'] = substr($error['%file'], $root_length + 1);
      }
      // Should not translate the string to avoid errors producing more errors.
      $message = String::format('%type: !message in %function (line %line of %file).', $error);

      // Check if verbose error reporting is on.
      $error_level = $this->container->get('config.factory')->get('system.logging')->get('error_level');

      if ($error_level == ERROR_REPORTING_DISPLAY_VERBOSE) {
        $backtrace_exception = $exception;
        while ($backtrace_exception->getPrevious()) {
          $backtrace_exception = $backtrace_exception->getPrevious();
        }
        $backtrace = $backtrace_exception->getTrace();
        // First trace is the error itself, already contained in the message.
        // While the second trace is the error source and also contained in the
        // message, the message doesn't contain argument values, so we output it
        // once more in the backtrace.
        array_shift($backtrace);
        // Generate a backtrace containing only scalar argument values.
        $message .= '<pre class="backtrace">' . Error::formatFlattenedBacktrace($backtrace) . '</pre>';
      }
      drupal_set_message($message, $class, TRUE);
316 317
    }

318 319
    $content = $this->t('The website has encountered an error. Please try again later.');
    $output = DefaultHtmlPageRenderer::renderPage($content, $this->t('Error'));
320
    $response = new Response($output);
321 322 323 324 325
    $response->setStatusCode(500, '500 Service unavailable (with message)');

    return $response;
  }

326
  /**
327
   * Processes an AccessDenied exception that occurred on a JSON request.
328
   *
329
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
330
   *   The flattened exception.
331
   * @param \Symfony\Component\HttpFoundation\Request $request
332
   *   The request object that triggered this exception.
333 334 335
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response object.
336 337 338 339 340 341 342 343
   */
  public function on403Json(FlattenException $exception, Request $request) {
    $response = new JsonResponse();
    $response->setStatusCode(403, 'Access Denied');
    return $response;
  }

  /**
344
   * Processes a NotFound exception that occurred on a JSON request.
345
   *
346
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
347
   *   The flattened exception.
348
   * @param \Symfony\Component\HttpFoundation\Request $request
349
   *   The request object that triggered this exception.
350 351 352
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response object.
353 354 355 356 357 358 359 360
   */
  public function on404Json(FlattenException $exception, Request $request) {
    $response = new JsonResponse();
    $response->setStatusCode(404, 'Not Found');
    return $response;
  }

  /**
361
   * Processes a MethodNotAllowed exception that occurred on a JSON request.
362
   *
363
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
364
   *   The flattened exception.
365
   * @param \Symfony\Component\HttpFoundation\Request $request
366
   *   The request object that triggered this exception.
367 368 369
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response object.
370 371 372 373 374 375 376 377
   */
  public function on405Json(FlattenException $exception, Request $request) {
    $response = new JsonResponse();
    $response->setStatusCode(405, 'Method Not Allowed');
    return $response;
  }


378 379 380
  /**
   * This method is a temporary port of _drupal_decode_exception().
   *
381 382
   * @todo This should get refactored. FlattenException could use some
   *   improvement as well.
383
   *
384 385 386
   * @param \Symfony\Component\Debug\Exception\FlattenException $exception
   *  The flattened exception.
   *
387
   * @return array
388 389
   *   An array of string-substitution tokens for formatting a message about the
   *   exception.
390 391 392 393 394 395 396 397 398 399
   */
  protected function decodeException(FlattenException $exception) {
    $message = $exception->getMessage();

    $backtrace = $exception->getTrace();

    // This value is missing from the stack for some reason in the
    // FlattenException version of the backtrace.
    $backtrace[0]['line'] = $exception->getLine();

400
    // For database errors, we try to return the initial caller,
401
    // skipping internal functions of the database layer.
402 403 404 405 406 407 408
    if (strpos($exception->getClass(), 'DatabaseExceptionWrapper') !== FALSE) {
      // A DatabaseExceptionWrapper exception is actually just a courier for
      // the original PDOException.  It's the stack trace from that exception
      // that we care about.
      $backtrace = $exception->getPrevious()->getTrace();
      $backtrace[0]['line'] = $exception->getLine();

409 410 411 412 413
      // The first element in the stack is the call, the second element gives us the caller.
      // We skip calls that occurred in one of the classes of the database layer
      // or in one of its global functions.
      $db_functions = array('db_query',  'db_query_range');
      while (!empty($backtrace[1]) && ($caller = $backtrace[1]) &&
414 415
          ((strpos($caller['namespace'], 'Drupal\Core\Database') !== FALSE || strpos($caller['class'], 'PDO') !== FALSE)) ||
          in_array($caller['function'], $db_functions)) {
416 417 418 419
        // We remove that call.
        array_shift($backtrace);
      }
    }
420 421

    $caller = Error::getLastCaller($backtrace);
422 423 424 425 426

    return array(
      '%type' => $exception->getClass(),
      // The standard PHP exception handler considers that the exception message
      // is plain-text. We mimick this behavior here.
427
      '!message' => String::checkPlain($message),
428 429 430 431 432 433 434
      '%function' => $caller['function'],
      '%file' => $caller['file'],
      '%line' => $caller['line'],
      'severity_level' => WATCHDOG_ERROR,
    );
  }

435
}