ImageStyleDownloadController.php 7.63 KB
Newer Older
1 2 3 4 5
<?php

namespace Drupal\image\Controller;

use Drupal\Component\Utility\Crypt;
6
use Drupal\Core\Image\ImageFactory;
7
use Drupal\Core\Lock\LockBackendInterface;
8
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
9 10 11 12 13 14
use Drupal\image\ImageStyleInterface;
use Drupal\system\FileDownloadController;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
15
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
16 17 18 19 20 21
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;

/**
 * Defines a controller to serve image styles.
 */
22
class ImageStyleDownloadController extends FileDownloadController {
23 24 25 26 27 28 29 30

  /**
   * The lock backend.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;

31 32 33 34 35 36 37
  /**
   * The image factory.
   *
   * @var \Drupal\Core\Image\ImageFactory
   */
  protected $imageFactory;

38 39 40 41 42 43 44
  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

45 46 47 48 49
  /**
   * Constructs a ImageStyleDownloadController object.
   *
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock backend.
50 51
   * @param \Drupal\Core\Image\ImageFactory $image_factory
   *   The image factory.
52 53
   * @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
   *   The stream wrapper manager.
54
   */
55 56
  public function __construct(LockBackendInterface $lock, ImageFactory $image_factory, StreamWrapperManagerInterface $stream_wrapper_manager = NULL) {
    parent::__construct($stream_wrapper_manager);
57
    $this->lock = $lock;
58
    $this->imageFactory = $image_factory;
59
    $this->logger = $this->getLogger('image');
60 61 62 63 64 65 66 67
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('lock'),
68 69
      $container->get('image.factory'),
      $container->get('stream_wrapper_manager')
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    );
  }

  /**
   * Generates a derivative, given a style and image path.
   *
   * After generating an image, transfer it to the requesting agent.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   * @param string $scheme
   *   The file scheme, defaults to 'private'.
   * @param \Drupal\image\ImageStyleInterface $image_style
   *   The image style to deliver.
   *
85 86 87
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response
   *   The transferred file as response or some error response.
   *
88 89
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Thrown when the file request is invalid.
90 91
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   *   Thrown when the user does not have access to the file.
92 93
   * @throws \Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException
   *   Thrown when the file is still being generated.
94 95 96 97 98 99 100 101 102 103
   */
  public function deliver(Request $request, $scheme, ImageStyleInterface $image_style) {
    $target = $request->query->get('file');
    $image_uri = $scheme . '://' . $target;

    // Check that the style is defined, the scheme is valid, and the image
    // derivative token is valid. Sites which require image derivatives to be
    // generated without a token can set the
    // 'image.settings:allow_insecure_derivatives' configuration to TRUE to
    // bypass the latter check, but this will increase the site's vulnerability
104 105 106 107 108 109
    // to denial-of-service attacks. To prevent this variable from leaving the
    // site vulnerable to the most serious attacks, a token is always required
    // when a derivative of a style is requested.
    // The $target variable for a derivative of a style has
    // styles/<style_name>/... as structure, so we check if the $target variable
    // starts with styles/.
110
    $valid = !empty($image_style) && $this->streamWrapperManager->isValidScheme($scheme);
111
    if (!$this->config('image.settings')->get('allow_insecure_derivatives') || strpos(ltrim($target, '\/'), 'styles/') === 0) {
112
      $valid &= hash_equals($image_style->getPathToken($image_uri), $request->query->get(IMAGE_DERIVATIVE_TOKEN, ''));
113 114
    }
    if (!$valid) {
115 116 117 118 119
      // Return a 404 (Page Not Found) rather than a 403 (Access Denied) as the
      // image token is for DDoS protection rather than access checking. 404s
      // are more likely to be cached (e.g. at a proxy) which enhances
      // protection from DDoS.
      throw new NotFoundHttpException();
120 121 122
    }

    $derivative_uri = $image_style->buildUri($image_uri);
123
    $headers = [];
124 125 126 127

    // If using the private scheme, let other modules provide headers and
    // control access to the file.
    if ($scheme == 'private') {
128
      $headers = $this->moduleHandler()->invokeAll('file_download', [$image_uri]);
129 130
      if (in_array(-1, $headers) || empty($headers)) {
        throw new AccessDeniedHttpException();
131 132 133 134 135
      }
    }

    // Don't try to generate file if source is missing.
    if (!file_exists($image_uri)) {
136 137 138 139 140 141 142
      // If the image style converted the extension, it has been added to the
      // original file, resulting in filenames like image.png.jpeg. So to find
      // the actual source image, we remove the extension and check if that
      // image exists.
      $path_info = pathinfo($image_uri);
      $converted_image_uri = $path_info['dirname'] . DIRECTORY_SEPARATOR . $path_info['filename'];
      if (!file_exists($converted_image_uri)) {
143
        $this->logger->notice('Source image at %source_image_path not found while trying to generate derivative image at %derivative_path.', ['%source_image_path' => $image_uri, '%derivative_path' => $derivative_uri]);
144 145 146 147 148 149
        return new Response($this->t('Error generating image, missing source file.'), 404);
      }
      else {
        // The converted file does exist, use it as the source.
        $image_uri = $converted_image_uri;
      }
150 151 152 153 154
    }

    // Don't start generating the image if the derivative already exists or if
    // generation is in progress in another thread.
    if (!file_exists($derivative_uri)) {
155
      $lock_name = 'image_style_deliver:' . $image_style->id() . ':' . Crypt::hashBase64($image_uri);
156 157 158 159
      $lock_acquired = $this->lock->acquire($lock_name);
      if (!$lock_acquired) {
        // Tell client to retry again in 3 seconds. Currently no browsers are
        // known to support Retry-After.
160
        throw new ServiceUnavailableHttpException(3, 'Image generation in progress. Try again shortly.');
161 162 163 164 165 166 167 168 169 170 171 172
      }
    }

    // Try to generate the image, unless another thread just did it while we
    // were acquiring the lock.
    $success = file_exists($derivative_uri) || $image_style->createDerivative($image_uri, $derivative_uri);

    if (!empty($lock_acquired)) {
      $this->lock->release($lock_name);
    }

    if ($success) {
173 174
      $image = $this->imageFactory->get($derivative_uri);
      $uri = $image->getSource();
175
      $headers += [
176 177
        'Content-Type' => $image->getMimeType(),
        'Content-Length' => $image->getFileSize(),
178
      ];
179 180 181 182 183
      // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
      // sets response as not cacheable if the Cache-Control header is not
      // already modified. We pass in FALSE for non-private schemes for the
      // $public parameter to make sure we don't change the headers.
      return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
184 185
    }
    else {
186
      $this->logger->notice('Unable to generate the derived image located at %path.', ['%path' => $derivative_uri]);
187
      return new Response($this->t('Error generating image.'), 500);
188 189 190 191
    }
  }

}