annotate core/modules/image/src/Controller/ImageStyleDownloadController.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children c2387f117808
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\image\Controller;
Chris@0 4
Chris@0 5 use Drupal\Component\Utility\Crypt;
Chris@0 6 use Drupal\Core\Image\ImageFactory;
Chris@0 7 use Drupal\Core\Lock\LockBackendInterface;
Chris@0 8 use Drupal\image\ImageStyleInterface;
Chris@0 9 use Drupal\system\FileDownloadController;
Chris@0 10 use Symfony\Component\DependencyInjection\ContainerInterface;
Chris@0 11 use Symfony\Component\HttpFoundation\BinaryFileResponse;
Chris@0 12 use Symfony\Component\HttpFoundation\Request;
Chris@0 13 use Symfony\Component\HttpFoundation\Response;
Chris@0 14 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
Chris@0 15 use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
Chris@0 16
Chris@0 17 /**
Chris@0 18 * Defines a controller to serve image styles.
Chris@0 19 */
Chris@0 20 class ImageStyleDownloadController extends FileDownloadController {
Chris@0 21
Chris@0 22 /**
Chris@0 23 * The lock backend.
Chris@0 24 *
Chris@0 25 * @var \Drupal\Core\Lock\LockBackendInterface
Chris@0 26 */
Chris@0 27 protected $lock;
Chris@0 28
Chris@0 29 /**
Chris@0 30 * The image factory.
Chris@0 31 *
Chris@0 32 * @var \Drupal\Core\Image\ImageFactory
Chris@0 33 */
Chris@0 34 protected $imageFactory;
Chris@0 35
Chris@0 36 /**
Chris@0 37 * A logger instance.
Chris@0 38 *
Chris@0 39 * @var \Psr\Log\LoggerInterface
Chris@0 40 */
Chris@0 41 protected $logger;
Chris@0 42
Chris@0 43 /**
Chris@0 44 * Constructs a ImageStyleDownloadController object.
Chris@0 45 *
Chris@0 46 * @param \Drupal\Core\Lock\LockBackendInterface $lock
Chris@0 47 * The lock backend.
Chris@0 48 * @param \Drupal\Core\Image\ImageFactory $image_factory
Chris@0 49 * The image factory.
Chris@0 50 */
Chris@0 51 public function __construct(LockBackendInterface $lock, ImageFactory $image_factory) {
Chris@0 52 $this->lock = $lock;
Chris@0 53 $this->imageFactory = $image_factory;
Chris@0 54 $this->logger = $this->getLogger('image');
Chris@0 55 }
Chris@0 56
Chris@0 57 /**
Chris@0 58 * {@inheritdoc}
Chris@0 59 */
Chris@0 60 public static function create(ContainerInterface $container) {
Chris@0 61 return new static(
Chris@0 62 $container->get('lock'),
Chris@0 63 $container->get('image.factory')
Chris@0 64 );
Chris@0 65 }
Chris@0 66
Chris@0 67 /**
Chris@0 68 * Generates a derivative, given a style and image path.
Chris@0 69 *
Chris@0 70 * After generating an image, transfer it to the requesting agent.
Chris@0 71 *
Chris@0 72 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 73 * The request object.
Chris@0 74 * @param string $scheme
Chris@0 75 * The file scheme, defaults to 'private'.
Chris@0 76 * @param \Drupal\image\ImageStyleInterface $image_style
Chris@0 77 * The image style to deliver.
Chris@0 78 *
Chris@0 79 * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response
Chris@0 80 * The transferred file as response or some error response.
Chris@0 81 *
Chris@0 82 * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
Chris@0 83 * Thrown when the user does not have access to the file.
Chris@0 84 * @throws \Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException
Chris@0 85 * Thrown when the file is still being generated.
Chris@0 86 */
Chris@0 87 public function deliver(Request $request, $scheme, ImageStyleInterface $image_style) {
Chris@0 88 $target = $request->query->get('file');
Chris@0 89 $image_uri = $scheme . '://' . $target;
Chris@0 90
Chris@0 91 // Check that the style is defined, the scheme is valid, and the image
Chris@0 92 // derivative token is valid. Sites which require image derivatives to be
Chris@0 93 // generated without a token can set the
Chris@0 94 // 'image.settings:allow_insecure_derivatives' configuration to TRUE to
Chris@0 95 // bypass the latter check, but this will increase the site's vulnerability
Chris@0 96 // to denial-of-service attacks. To prevent this variable from leaving the
Chris@0 97 // site vulnerable to the most serious attacks, a token is always required
Chris@0 98 // when a derivative of a style is requested.
Chris@0 99 // The $target variable for a derivative of a style has
Chris@0 100 // styles/<style_name>/... as structure, so we check if the $target variable
Chris@0 101 // starts with styles/.
Chris@0 102 $valid = !empty($image_style) && file_stream_wrapper_valid_scheme($scheme);
Chris@0 103 if (!$this->config('image.settings')->get('allow_insecure_derivatives') || strpos(ltrim($target, '\/'), 'styles/') === 0) {
Chris@0 104 $valid &= $request->query->get(IMAGE_DERIVATIVE_TOKEN) === $image_style->getPathToken($image_uri);
Chris@0 105 }
Chris@0 106 if (!$valid) {
Chris@0 107 throw new AccessDeniedHttpException();
Chris@0 108 }
Chris@0 109
Chris@0 110 $derivative_uri = $image_style->buildUri($image_uri);
Chris@0 111 $headers = [];
Chris@0 112
Chris@0 113 // If using the private scheme, let other modules provide headers and
Chris@0 114 // control access to the file.
Chris@0 115 if ($scheme == 'private') {
Chris@0 116 $headers = $this->moduleHandler()->invokeAll('file_download', [$image_uri]);
Chris@0 117 if (in_array(-1, $headers) || empty($headers)) {
Chris@0 118 throw new AccessDeniedHttpException();
Chris@0 119 }
Chris@0 120 }
Chris@0 121
Chris@0 122 // Don't try to generate file if source is missing.
Chris@0 123 if (!file_exists($image_uri)) {
Chris@0 124 // If the image style converted the extension, it has been added to the
Chris@0 125 // original file, resulting in filenames like image.png.jpeg. So to find
Chris@0 126 // the actual source image, we remove the extension and check if that
Chris@0 127 // image exists.
Chris@0 128 $path_info = pathinfo($image_uri);
Chris@0 129 $converted_image_uri = $path_info['dirname'] . DIRECTORY_SEPARATOR . $path_info['filename'];
Chris@0 130 if (!file_exists($converted_image_uri)) {
Chris@0 131 $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]);
Chris@0 132 return new Response($this->t('Error generating image, missing source file.'), 404);
Chris@0 133 }
Chris@0 134 else {
Chris@0 135 // The converted file does exist, use it as the source.
Chris@0 136 $image_uri = $converted_image_uri;
Chris@0 137 }
Chris@0 138 }
Chris@0 139
Chris@0 140 // Don't start generating the image if the derivative already exists or if
Chris@0 141 // generation is in progress in another thread.
Chris@0 142 if (!file_exists($derivative_uri)) {
Chris@0 143 $lock_name = 'image_style_deliver:' . $image_style->id() . ':' . Crypt::hashBase64($image_uri);
Chris@0 144 $lock_acquired = $this->lock->acquire($lock_name);
Chris@0 145 if (!$lock_acquired) {
Chris@0 146 // Tell client to retry again in 3 seconds. Currently no browsers are
Chris@0 147 // known to support Retry-After.
Chris@0 148 throw new ServiceUnavailableHttpException(3, $this->t('Image generation in progress. Try again shortly.'));
Chris@0 149 }
Chris@0 150 }
Chris@0 151
Chris@0 152 // Try to generate the image, unless another thread just did it while we
Chris@0 153 // were acquiring the lock.
Chris@0 154 $success = file_exists($derivative_uri) || $image_style->createDerivative($image_uri, $derivative_uri);
Chris@0 155
Chris@0 156 if (!empty($lock_acquired)) {
Chris@0 157 $this->lock->release($lock_name);
Chris@0 158 }
Chris@0 159
Chris@0 160 if ($success) {
Chris@0 161 $image = $this->imageFactory->get($derivative_uri);
Chris@0 162 $uri = $image->getSource();
Chris@0 163 $headers += [
Chris@0 164 'Content-Type' => $image->getMimeType(),
Chris@0 165 'Content-Length' => $image->getFileSize(),
Chris@0 166 ];
Chris@0 167 // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
Chris@0 168 // sets response as not cacheable if the Cache-Control header is not
Chris@0 169 // already modified. We pass in FALSE for non-private schemes for the
Chris@0 170 // $public parameter to make sure we don't change the headers.
Chris@0 171 return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
Chris@0 172 }
Chris@0 173 else {
Chris@0 174 $this->logger->notice('Unable to generate the derived image located at %path.', ['%path' => $derivative_uri]);
Chris@0 175 return new Response($this->t('Error generating image.'), 500);
Chris@0 176 }
Chris@0 177 }
Chris@0 178
Chris@0 179 }