Files

217 lines
12 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Fluid\ViewHelpers;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Service\ImageService;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Exception;
use TYPO3Fluid\Fluid\Core\ViewHelper\InvalidArgumentValueException;
/**
* ViewHelper to resize, crop or convert a given image (if required) and render
* the corresponding HTML `<img>` tag showing the processed image.
*
* Note that image operations (cropping, scaling, converting) on
* non-FAL files (i.e. extension resources) may be changed in future TYPO3
* versions, since those operations are coupled with FAL metadata. Each
* non-FAL image operation creates a "fake" FAL record, which may lead to problems.
*
* External URLs are not processed.
*
* ```
* <f:image src="EXT:myext/Resources/Public/typo3_logo.png" width="100c" />
* <f:image fileExtension="webp" image="{imageObject}" maxWidth="400" maxHeight="400" />
* ```
*
* @see https://docs.typo3.org/permalink/t3viewhelper:typo3-fluid-image
*/
final class ImageViewHelper extends AbstractTagBasedViewHelper
{
/**
* @var string
*/
protected $tagName = 'img';
public function __construct(
private readonly ImageService $imageService
) {
parent::__construct();
}
public function initializeArguments(): void
{
parent::initializeArguments();
$this->registerArgument('src', 'string', 'a path to a file, a combined FAL identifier or an uid (int). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead', false, '');
$this->registerArgument('treatIdAsReference', 'bool', 'given src argument is a sys_file_reference record', false, false);
$this->registerArgument('image', 'object', 'a FAL object (\\TYPO3\\CMS\\Core\\Resource\\File or \\TYPO3\\CMS\\Core\\Resource\\FileReference)');
$this->registerArgument('crop', 'string|bool|array', 'overrule cropping of image (setting to FALSE disables the cropping set in FileReference)');
$this->registerArgument('cropVariant', 'string', 'select a cropping variant, in case multiple croppings have been specified or stored in FileReference', false, 'default');
$this->registerArgument('fileExtension', 'string', 'Custom file extension to use');
$this->registerArgument('width', 'string', 'width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width in the TypoScript Reference on https://docs.typo3.org/permalink/t3tsref:confval-imgresource-width for possible options.');
$this->registerArgument('height', 'string', 'height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.height in the TypoScript Reference https://docs.typo3.org/permalink/t3tsref:confval-imgresource-height for possible options.');
$this->registerArgument('minWidth', 'int', 'minimum width of the image');
$this->registerArgument('minHeight', 'int', 'minimum height of the image');
$this->registerArgument('maxWidth', 'int', 'maximum width of the image');
$this->registerArgument('maxHeight', 'int', 'maximum height of the image');
$this->registerArgument('absolute', 'bool', 'Force absolute URL', false, false);
$this->registerArgument('base64', 'bool', 'Adds the image data base64-encoded inline to the images "src" attribute. Useful for FluidEmail templates.', false, false);
}
/**
* Resizes a given image (if required) and renders the respective img tag.
*
* @see https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Image/
*/
public function render(): string
{
$src = (string)$this->arguments['src'];
if (($src === '' && $this->arguments['image'] === null) || ($src !== '' && $this->arguments['image'] !== null)) {
throw new InvalidArgumentValueException($this->getExceptionMessage('You must either specify a string src or a File object.'), 1382284106);
}
if ((string)$this->arguments['fileExtension'] && !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], (string)$this->arguments['fileExtension'])) {
throw new InvalidArgumentValueException(
$this->getExceptionMessage(
'The extension ' . $this->arguments['fileExtension'] . ' is not specified in $GLOBALS[\'TYPO3_CONF_VARS\'][\'GFX\'][\'imagefile_ext\']'
. ' as a valid image file extension and can not be processed.',
),
1618989190
);
}
try {
$image = $this->imageService->getImage($src, $this->arguments['image'], (bool)$this->arguments['treatIdAsReference']);
if ($this->isUnavailable($image)) {
return '';
}
$cropString = $this->arguments['crop'];
if ($cropString === null && $image->hasProperty('crop') && $image->getProperty('crop')) {
$cropString = $image->getProperty('crop');
}
// CropVariantCollection needs a string, but this VH could also receive an array
if (is_array($cropString)) {
$cropString = json_encode($cropString);
}
$cropVariantCollection = CropVariantCollection::create((string)$cropString);
$cropVariant = $this->arguments['cropVariant'] ?: 'default';
$cropArea = $cropVariantCollection->getCropArea($cropVariant);
$processingInstructions = [
'width' => $this->arguments['width'],
'height' => $this->arguments['height'],
'minWidth' => $this->arguments['minWidth'],
'minHeight' => $this->arguments['minHeight'],
'maxWidth' => $this->arguments['maxWidth'],
'maxHeight' => $this->arguments['maxHeight'],
'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($image),
];
if (!empty($this->arguments['fileExtension'] ?? '')) {
$processingInstructions['fileExtension'] = $this->arguments['fileExtension'];
}
$processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
if ($this->arguments['base64']) {
$imageSrc = 'data:' . $processedImage->getMimeType() . ';base64,' . base64_encode($processedImage->getContents());
} else {
$imageSrc = $this->imageService->getImageUri($processedImage, $this->arguments['absolute']);
if ($imageSrc === '') {
// No public URL could be determined, for instance because the file resides in a
// non-public storage and no request is available to create a file dump URL from.
return '';
}
}
if (!$this->tag->hasAttribute('data-focus-area')) {
$focusArea = $cropVariantCollection->getFocusArea($cropVariant);
if (!$focusArea->isEmpty()) {
$this->tag->addAttribute('data-focus-area', (string)$focusArea->makeAbsoluteBasedOnFile($image));
}
}
$this->tag->addAttribute('src', $imageSrc);
$this->tag->addAttribute('width', $processedImage->getProperty('width'));
$this->tag->addAttribute('height', $processedImage->getProperty('height'));
if (isset($this->additionalArguments['alt']) && $this->additionalArguments['alt'] === '') {
// In case the "alt" attribute is explicitly set to an empty string, respect
// this to allow excluding it from screen readers, improving accessibility.
$this->tag->addAttribute('alt', '');
} elseif (!isset($this->additionalArguments['alt'])) {
// The alt-attribute is mandatory to have valid html-code, therefore use "alternative" property or empty
$this->tag->addAttribute('alt', $image->getProperty('alternative') ?? '');
}
// Only add title-attribute from image if not set in additional-arguments.
// In case the "title" attribute is explicitly set to an empty string,
// it will not fallback to an image-title.
// This allows excluding it explicitly from screen readers, improving accessibility.
if (!isset($this->additionalArguments['title'])) {
$title = trim((string)($image->hasProperty('title') ? $image->getProperty('title') : ''));
// The title-attribute is not mandatory, therefore use "title" property or omit fully
if ($title !== '') {
$this->tag->addAttribute('title', $title);
}
}
} catch (ResourceDoesNotExistException $e) {
// thrown if file does not exist
throw new Exception($this->getExceptionMessage($e->getMessage()), 1509741911, $e);
} catch (\UnexpectedValueException $e) {
// thrown if a file has been replaced with a folder
throw new Exception($this->getExceptionMessage($e->getMessage()), 1509741912, $e);
} catch (\InvalidArgumentException $e) {
// thrown if file storage does not exist
throw new Exception($this->getExceptionMessage($e->getMessage()), 1509741914, $e);
}
return $this->tag->render();
}
/**
* A file that has been flagged as missing by the file indexer, that has been deleted, or that
* resides in an offline storage can not be processed and has no public URL. Rendering an "img"
* tag for it would result in an empty "src" attribute, so nothing is rendered instead.
*/
private function isUnavailable(FileInterface $image): bool
{
$file = $image instanceof FileReference ? $image->getOriginalFile() : $image;
if (!$file instanceof File) {
return false;
}
return $file->isMissing() || $file->isDeleted() || !$file->getStorage()->isOnline();
}
private function getExceptionMessage(string $detailedMessage): string
{
if ($this->renderingContext->hasAttribute(ServerRequestInterface::class)) {
$request = $this->renderingContext->getAttribute(ServerRequestInterface::class);
$currentContentObject = $request->getAttribute('currentContentObject');
if ($currentContentObject instanceof ContentObjectRenderer) {
return sprintf('Unable to render image tag in "%s": %s', $currentContentObject->currentRecord, $detailedMessage);
}
}
return "Unable to render image tag: $detailedMessage";
}
}