class S3fsImageStyleDownloadController in S3 File System 8.3
Same name and namespace in other branches
- 4.0.x src/Controller/S3fsImageStyleDownloadController.php \Drupal\s3fs\Controller\S3fsImageStyleDownloadController
Defines a controller to serve public/s3 Amazon S3 image styles.
Hierarchy
- class \Drupal\Core\Controller\ControllerBase implements ContainerInjectionInterface uses LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\system\FileDownloadController
- class \Drupal\image\Controller\ImageStyleDownloadController
- class \Drupal\s3fs\Controller\S3fsImageStyleDownloadController
- class \Drupal\image\Controller\ImageStyleDownloadController
- class \Drupal\system\FileDownloadController
Expanded class hierarchy of S3fsImageStyleDownloadController
File
- src/
Controller/ S3fsImageStyleDownloadController.php, line 18
Namespace
Drupal\s3fs\ControllerView source
class S3fsImageStyleDownloadController extends ImageStyleDownloadController {
/**
* Generates a Amazon S3 derivative, given a style and image path.
*
* After generating an image, redirect it to the requesting agent. Only used
* for public or s3 schemes. Private scheme use the normal workflow:
* \Drupal\image\Controller\ImageStyleDownloadController::deliver().
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
* @param string $scheme
* The file scheme.
* @param \Drupal\image\ImageStyleInterface $image_style
* The image style to deliver.
*
* @return \Drupal\Core\Routing\TrustedRedirectResponse|\Symfony\Component\HttpFoundation\Response
* The redirect 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.
*
* @see \Drupal\image\Controller\ImageStyleDownloadController::deliver()
*/
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
// 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) && \Drupal::service('stream_wrapper_manager')
->isValidScheme($scheme);
if (!$this
->config('image.settings')
->get('allow_insecure_derivatives') || strpos(ltrim($target, '\\/'), 'styles/') === 0) {
$valid &= hash_equals($request->query
->get(IMAGE_DERIVATIVE_TOKEN), $image_style
->getPathToken($image_uri));
}
if (!$valid) {
throw new AccessDeniedHttpException();
}
$derivative_uri = $image_style
->buildUri($image_uri);
// Private scheme use:
// \Drupal\image\Controller\ImageStyleDownloadController::deliver()
// instead of this.
if ($scheme == 'private') {
throw new AccessDeniedHttpException();
}
// Don't try to generate file if source is missing.
if (!file_exists($image_uri)) {
// 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)) {
$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);
}
else {
// The converted file does exist, use it as the source.
$image_uri = $converted_image_uri;
}
}
// 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 = 's3fs_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);
if (!$success) {
// If we successfully generate the derivative, wait until S3 acknowledges
// its existence. Otherwise, redirecting to it may cause a 403 error.
$success = $image_style
->createDerivative($image_uri, $derivative_uri) && \Drupal::service('stream_wrapper_manager')
->getViaScheme('s3')
->waitUntilFileExists($derivative_uri);
}
if (!empty($lock_acquired)) {
$this->lock
->release($lock_name);
}
if ($success) {
$responseCacheTags = $image_style
->getCacheTags();
// Try to get a managed file and flush the cache.
$storage = $this
->entityTypeManager()
->getStorage('file');
$result = $storage
->getQuery()
->condition('uri', $image_uri, '=')
->execute();
if (!empty($result)) {
$file = $storage
->load(reset($result));
Cache::invalidateTags($file
->getCacheTags());
$responseCacheTags = Cache::mergeTags($responseCacheTags, $file
->getCacheTags());
}
// Perform a 302 Redirect to the new image derivative in S3.
// It must be TrustedRedirectResponse for external redirects.
$response = new TrustedRedirectResponse($image_style
->buildUrl($image_uri));
$cacheableMetadata = $response
->getCacheableMetadata();
$cacheableMetadata
->addCacheContexts([
'url.query_args:file',
'url.query_args:itok',
]);
$cacheableMetadata
->setCacheMaxAge((int) $this
->config('s3fs.settings')
->get('redirect_styles_ttl'));
$cacheableMetadata
->setCacheTags($responseCacheTags);
$response
->addCacheableDependency($cacheableMetadata);
return $response;
}
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);
}
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ControllerBase:: |
protected | property | The configuration factory. | |
ControllerBase:: |
protected | property | The current user service. | 1 |
ControllerBase:: |
protected | property | The entity form builder. | |
ControllerBase:: |
protected | property | The entity manager. | |
ControllerBase:: |
protected | property | The entity type manager. | |
ControllerBase:: |
protected | property | The form builder. | 2 |
ControllerBase:: |
protected | property | The key-value storage. | 1 |
ControllerBase:: |
protected | property | The language manager. | 1 |
ControllerBase:: |
protected | property | The module handler. | 2 |
ControllerBase:: |
protected | property | The state service. | |
ControllerBase:: |
protected | function | Returns the requested cache bin. | |
ControllerBase:: |
protected | function | Retrieves a configuration object. | |
ControllerBase:: |
private | function | Returns the service container. | |
ControllerBase:: |
protected | function | Returns the current user. | 1 |
ControllerBase:: |
protected | function | Retrieves the entity form builder. | |
ControllerBase:: |
protected | function | Retrieves the entity manager service. | |
ControllerBase:: |
protected | function | Retrieves the entity type manager. | |
ControllerBase:: |
protected | function | Returns the form builder service. | 2 |
ControllerBase:: |
protected | function | Returns a key/value storage collection. | 1 |
ControllerBase:: |
protected | function | Returns the language manager service. | 1 |
ControllerBase:: |
protected | function | Returns the module handler. | 2 |
ControllerBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
ControllerBase:: |
protected | function | Returns the state storage service. | |
FileDownloadController:: |
protected | property | The stream wrapper manager. | |
FileDownloadController:: |
public | function | Handles private file transfers. | |
ImageStyleDownloadController:: |
protected | property | The image factory. | |
ImageStyleDownloadController:: |
protected | property | The lock backend. | |
ImageStyleDownloadController:: |
protected | property | A logger instance. | |
ImageStyleDownloadController:: |
public static | function |
Instantiates a new instance of this class. Overrides FileDownloadController:: |
|
ImageStyleDownloadController:: |
public | function |
Constructs a ImageStyleDownloadController object. Overrides FileDownloadController:: |
|
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
S3fsImageStyleDownloadController:: |
public | function |
Generates a Amazon S3 derivative, given a style and image path. Overrides ImageStyleDownloadController:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |