You are here

class ImageStyleDownloadController in WebP 8

Defines a controller to serve image styles.

Hierarchy

Expanded class hierarchy of ImageStyleDownloadController

File

src/Controller/ImageStyleDownloadController.php, line 23

Namespace

Drupal\webp\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;

  /**
   * WebP driver.
   *
   * @var \Drupal\webp\Webp
   */
  protected $webp;

  /**
   * Constructs a ImageStyleDownloadController object.
   *
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock backend.
   * @param \Drupal\Core\Image\ImageFactory $image_factory
   *   The image factory.
   * @param \Drupal\webp\Webp $webp
   *   WebP driver.
   * @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface|null $stream_wrapper_manager
   *   The stream wrapper manager.
   */
  public function __construct(LockBackendInterface $lock, ImageFactory $image_factory, Webp $webp, StreamWrapperManagerInterface $stream_wrapper_manager = NULL) {
    parent::__construct($stream_wrapper_manager);
    $this->lock = $lock;
    $this->imageFactory = $image_factory;
    $this->logger = $this
      ->getLogger('image');
    $this->webp = $webp;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('lock'), $container
      ->get('image.factory'), $container
      ->get('webp.webp'), $container
      ->get('stream_wrapper_manager'));
  }

  /**
   * 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.
   *
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response
   *   The transferred file as response or some error response.
   *
   * @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) {
    $target = $request->query
      ->get('file');
    $image_uri = $scheme . '://' . $target;
    if ($webp_wanted = preg_match('/\\.webp$/', $image_uri)) {
      $path_info = pathinfo($image_uri);
      $possible_image_uris = [
        // 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['dirname'] . DIRECTORY_SEPARATOR . $path_info['filename'],
      ];

      // Try out the different possible sources for a webp image.
      $extensions = [
        '.jpg',
        '.jpeg',
        '.png',
      ];
      foreach ($extensions as $extension) {
        $possible_image_uris[] = str_replace('.webp', mb_strtoupper($extension), $image_uri);
        $possible_image_uris[] = str_replace('.webp', $extension, $image_uri);
      }
      foreach ($possible_image_uris as $possible_image_uri) {
        if (file_exists($possible_image_uri)) {
          $image_uri = $possible_image_uri;
          break;
        }
      }
    }

    // Don't try to generate file if source is missing.
    if (!file_exists($image_uri)) {
      $this->logger
        ->notice('Source image at %source_image_path not found while trying to generate derivative image.', [
        '%source_image_path' => $image_uri,
      ]);
      return new Response($this
        ->t('Error generating image, missing source file.'), 404);
    }

    // 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
    // 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/.
    $valid = !empty($image_style) && $this->streamWrapperManager
      ->isValidScheme($scheme);
    if (!$this
      ->config('image.settings')
      ->get('allow_insecure_derivatives') || strpos(ltrim($target, '\\/'), 'styles/') === 0) {
      $valid &= $request->query
        ->get(IMAGE_DERIVATIVE_TOKEN) === $image_style
        ->getPathToken($image_uri);

      // ImageAPI Optimize case: generator searches for a WEBP, but image style
      // returns a non-WEBP (!= tokens). Sanity checks that image_style returns a token.
      if (!$valid && $image_style
        ->getDerivativeExtension(pathinfo($image_uri)['extension']) != "webp") {
        $valid = $image_style
          ->getPathToken($image_uri) ? true : false;
      }
    }
    if (!$valid) {
      throw new AccessDeniedHttpException();
    }
    $derivative_uri = $image_style
      ->buildUri($image_uri);
    $headers = [];

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

    // 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, $this
          ->t('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);
      if ($webp_wanted && ($webp = $this->webp
        ->createWebpCopy($image
        ->getSource())) && in_array('image/webp', $request
        ->getAcceptableContentTypes())) {
        return $this
          ->webpResponse($webp, $headers, $scheme);
      }
      else {
        return $this
          ->response($image, $headers, $scheme);
      }
    }
    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);
    }
  }

  /**
   * Returns a WebP image as response.
   *
   * @param string $file
   *   Path to image file.
   * @param array $headers
   *   Response headers.
   * @param string $scheme
   *   The file scheme, defaults to 'private'.
   *
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
   *   The transferred file as response.
   */
  protected function webpResponse($file, array $headers, $scheme) {
    $headers += [
      'Content-Type' => 'image/webp',
      'Content-Length' => filesize($file),
    ];

    // \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($file, 200, $headers, $scheme !== 'private');
  }

  /**
   * Returns an image style derivative as response.
   *
   * @param \Drupal\Core\Image\Image $image
   *   The image style derivation.
   * @param array $headers
   *   Response headers.
   * @param string $scheme
   *   The file scheme, defaults to 'private'.
   *
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
   *   The transferred file as response.
   */
  protected function response(Image $image, array $headers, $scheme) {
    $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. We pass in FALSE for non-private schemes for the
    // $public parameter to make sure we don't change the headers.
    return new BinaryFileResponse($image
      ->getSource(), 200, $headers, $scheme !== 'private');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
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. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
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. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
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::$imageFactory protected property The image factory.
ImageStyleDownloadController::$lock protected property The lock backend.
ImageStyleDownloadController::$logger protected property A logger instance.
ImageStyleDownloadController::$webp protected property WebP driver.
ImageStyleDownloadController::create public static function Instantiates a new instance of this class. Overrides FileDownloadController::create
ImageStyleDownloadController::deliver public function Generates a derivative, given a style and image path.
ImageStyleDownloadController::response protected function Returns an image style derivative as response.
ImageStyleDownloadController::webpResponse protected function Returns a WebP image as response.
ImageStyleDownloadController::__construct public function Constructs a ImageStyleDownloadController object. Overrides FileDownloadController::__construct
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' 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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.