annotate core/modules/image/src/Controller/ImageStyleDownloadController.php @ 19:fa3358dc1485 tip

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