class ImageStyleDownloadController

Same name in other branches
  1. 9 core/modules/image/src/Controller/ImageStyleDownloadController.php \Drupal\image\Controller\ImageStyleDownloadController
  2. 8.9.x core/modules/image/src/Controller/ImageStyleDownloadController.php \Drupal\image\Controller\ImageStyleDownloadController
  3. 11.x core/modules/image/src/Controller/ImageStyleDownloadController.php \Drupal\image\Controller\ImageStyleDownloadController

Defines a controller to serve image styles.

Hierarchy

Expanded class hierarchy of ImageStyleDownloadController

1 file declares its use of ImageStyleDownloadController
image.module in core/modules/image/image.module
Exposes global functionality for creating image styles.

File

core/modules/image/src/Controller/ImageStyleDownloadController.php, line 25

Namespace

Drupal\image\Controller
View source
class ImageStyleDownloadController extends FileDownloadController {
    
    /**
     * The lock backend.
     *
     * @var \Drupal\Core\Lock\LockBackendInterface
     */
    protected $lock;
    
    /**
     * The image factory.
     *
     * @var \Drupal\Core\Image\ImageFactory
     */
    protected $imageFactory;
    
    /**
     * A logger instance.
     *
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;
    
    /**
     * File system service.
     *
     * @var \Drupal\Core\File\FileSystemInterface
     */
    protected $fileSystem;
    
    /**
     * Constructs an ImageStyleDownloadController object.
     *
     * @param \Drupal\Core\Lock\LockBackendInterface $lock
     *   The lock backend.
     * @param \Drupal\Core\Image\ImageFactory $image_factory
     *   The image factory.
     * @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
     *   The stream wrapper manager.
     * @param \Drupal\Core\File\FileSystemInterface $file_system
     *   The system service.
     */
    public function __construct(LockBackendInterface $lock, ImageFactory $image_factory, StreamWrapperManagerInterface $stream_wrapper_manager, FileSystemInterface $file_system) {
        parent::__construct($stream_wrapper_manager);
        $this->lock = $lock;
        $this->imageFactory = $image_factory;
        $this->logger = $this->getLogger('image');
        $this->fileSystem = $file_system;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('lock'), $container->get('image.factory'), $container->get('stream_wrapper_manager'), $container->get('file_system'));
    }
    
    /**
     * 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.
     * @param string $required_derivative_scheme
     *   The required scheme for the derivative image.
     *
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response
     *   The transferred file as response or some error response.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     *   Thrown when the file request is invalid.
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
     *   Thrown when the user does not have access to the file.
     * @throws \Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException
     *   Thrown when the file is still being generated.
     */
    public function deliver(Request $request, $scheme, ImageStyleInterface $image_style, string $required_derivative_scheme) {
        $target = $request->query
            ->get('file');
        $image_uri = $scheme . '://' . $target;
        $image_uri = $this->streamWrapperManager
            ->normalizeUri($image_uri);
        $sample_image_uri = $scheme . '://' . $this->config('image.settings')
            ->get('preview_image');
        if ($this->streamWrapperManager
            ->isValidScheme($scheme)) {
            $normalized_target = $this->streamWrapperManager
                ->getTarget($image_uri);
            if ($normalized_target !== FALSE) {
                if (!in_array($scheme, Settings::get('file_sa_core_2023_005_schemes', []))) {
                    $parts = explode('/', $normalized_target);
                    if (array_intersect($parts, [
                        '.',
                        '..',
                    ])) {
                        throw new NotFoundHttpException();
                    }
                }
            }
        }
        // Check that the style is defined and the scheme is valid.
        $valid = !empty($image_style) && $this->streamWrapperManager
            ->isValidScheme($scheme);
        // Also validate the derivative token. Sites which require image
        // derivatives to be generated without a token can set the
        // 'image.settings:allow_insecure_derivatives' configuration to TRUE to
        // bypass this check, but this will increase the site's vulnerability
        // 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/.
        $token = $request->query
            ->get(IMAGE_DERIVATIVE_TOKEN, '');
        $token_is_valid = hash_equals($image_style->getPathToken($image_uri), $token) || hash_equals($image_style->getPathToken($scheme . '://' . $target), $token);
        if (!$this->config('image.settings')
            ->get('allow_insecure_derivatives') || str_starts_with(ltrim($target, '\\/'), 'styles/')) {
            $valid = $valid && $token_is_valid;
        }
        if (!$valid) {
            // 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();
        }
        $derivative_uri = $image_style->buildUri($image_uri);
        $derivative_scheme = $this->streamWrapperManager
            ->getScheme($derivative_uri);
        if ($required_derivative_scheme !== $derivative_scheme) {
            throw new AccessDeniedHttpException("The scheme for this image doesn't match the scheme for the original image");
        }
        if ($token_is_valid) {
            $is_public = $scheme !== 'private';
        }
        else {
            $core_schemes = [
                'public',
                'private',
                'temporary',
            ];
            $additional_public_schemes = array_diff(Settings::get('file_additional_public_schemes', []), $core_schemes);
            $public_schemes = array_merge([
                'public',
            ], $additional_public_schemes);
            $is_public = in_array($derivative_scheme, $public_schemes, TRUE);
        }
        $headers = [];
        // Don't try to generate file if source is missing.
        if ($image_uri !== $sample_image_uri && !$this->sourceImageExists($image_uri, $token_is_valid)) {
            // 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.
            $converted_image_uri = static::getUriWithoutConvertedExtension($image_uri);
            if ($converted_image_uri !== $image_uri && $this->sourceImageExists($converted_image_uri, $token_is_valid)) {
                // The converted file does exist, use it as the source.
                $image_uri = $converted_image_uri;
            }
            else {
                $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,
                ]);
                return new Response($this->t('Error generating image, missing source file.'), 404);
            }
        }
        // If not using a public scheme, let other modules provide headers and
        // control access to the file.
        if (!$is_public) {
            $headers = $this->moduleHandler()
                ->invokeAll('file_download', [
                $image_uri,
            ]);
            if (in_array(-1, $headers) || empty($headers)) {
                throw new AccessDeniedHttpException();
            }
        }
        // If it is default sample.png, ignore scheme.
        // This value swap must be done after hook_file_download is called since
        // the hooks are expecting a URI, not a file path.
        if ($image_uri === $sample_image_uri) {
            $image_uri = $target;
        }
        // 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)) {
            $lock_name = 'image_style_deliver:' . $image_style->id() . ':' . Crypt::hashBase64($image_uri);
            $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.
                throw new ServiceUnavailableHttpException(3, 'Image generation in progress. Try again shortly.');
            }
        }
        // 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) {
            $image = $this->imageFactory
                ->get($derivative_uri);
            $uri = $image->getSource();
            $headers += [
                'Content-Type' => $image->getMimeType(),
                'Content-Length' => $image->getFileSize(),
            ];
            // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
            // sets response as not cacheable if the Cache-Control header is not
            // already modified. When $is_public is TRUE, the following sets the
            // Cache-Control header to "public".
            return new BinaryFileResponse($uri, 200, $headers, $is_public);
        }
        else {
            $this->logger
                ->notice('Unable to generate the derived image located at %path.', [
                '%path' => $derivative_uri,
            ]);
            return new Response($this->t('Error generating image.'), 500);
        }
    }
    
    /**
     * Checks whether the provided source image exists.
     *
     * @param string $image_uri
     *   The URI for the source image.
     * @param bool $token_is_valid
     *   Whether a valid image token was supplied.
     *
     * @return bool
     *   Whether the source image exists.
     */
    private function sourceImageExists(string $image_uri, bool $token_is_valid) : bool {
        $exists = file_exists($image_uri);
        // If the file doesn't exist, we can stop here.
        if (!$exists) {
            return FALSE;
        }
        if ($token_is_valid) {
            return TRUE;
        }
        if (StreamWrapperManager::getScheme($image_uri) !== 'public') {
            return TRUE;
        }
        $image_path = $this->fileSystem
            ->realpath($image_uri);
        $private_path = Settings::get('file_private_path');
        if ($private_path) {
            $private_path = realpath($private_path);
            if ($private_path && str_starts_with($image_path, $private_path)) {
                return FALSE;
            }
        }
        return TRUE;
    }
    
    /**
     * Get the file URI without the extension from any conversion image style.
     *
     * If the image style converted the image, then an extension has been added
     * to the original file, resulting in filenames like image.png.jpeg.
     *
     * @param string $uri
     *   The file URI.
     *
     * @return string
     *   The file URI without the extension from any conversion image style.
     */
    public static function getUriWithoutConvertedExtension(string $uri) : string {
        $original_uri = $uri;
        $path_info = pathinfo(StreamWrapperManager::getTarget($uri));
        // Only convert the URI when the filename still has an extension.
        if (!empty($path_info['filename']) && pathinfo($path_info['filename'], PATHINFO_EXTENSION)) {
            $original_uri = StreamWrapperManager::getScheme($uri) . '://';
            if (!empty($path_info['dirname']) && $path_info['dirname'] !== '.') {
                $original_uri .= $path_info['dirname'] . DIRECTORY_SEPARATOR;
            }
            $original_uri .= $path_info['filename'];
        }
        return $original_uri;
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 2
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 1
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 1
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 2
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 1
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 1
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
FileDownloadController::$streamWrapperManager protected property The stream wrapper manager.
FileDownloadController::download public function Handles private file transfers.
ImageStyleDownloadController::$fileSystem protected property File system service.
ImageStyleDownloadController::$imageFactory protected property The image factory.
ImageStyleDownloadController::$lock protected property The lock backend.
ImageStyleDownloadController::$logger protected property A logger instance.
ImageStyleDownloadController::create public static function Instantiates a new instance of the implementing class using autowiring. Overrides AutowireTrait::create
ImageStyleDownloadController::deliver public function Generates a derivative, given a style and image path.
ImageStyleDownloadController::getUriWithoutConvertedExtension public static function Get the file URI without the extension from any conversion image style.
ImageStyleDownloadController::sourceImageExists private function Checks whether the provided source image exists.
ImageStyleDownloadController::__construct public function Constructs an ImageStyleDownloadController object. Overrides FileDownloadController::__construct
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.