‪TYPO3CMS  ‪main
ImageViewHelper.php
Go to the documentation of this file.
1 <?php
2 
3 declare(strict_types=1);
4 
5 /*
6  * This file is part of the TYPO3 CMS project.
7  *
8  * It is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU General Public License, either version 2
10  * of the License, or any later version.
11  *
12  * For the full copyright and license information, please read the
13  * LICENSE.txt file that was distributed with this source code.
14  *
15  * The TYPO3 project - inspiring people to share!
16  */
17 
19 
20 use Psr\Http\Message\RequestInterface;
27 use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper;
28 use TYPO3Fluid\Fluid\Core\ViewHelper\Exception;
29 
101 final class ‪ImageViewHelper extends AbstractTagBasedViewHelper
102 {
106  protected ‪$tagName = 'img';
107 
109 
110  public function ‪__construct()
111  {
112  parent::__construct();
113  $this->imageService = GeneralUtility::makeInstance(ImageService::class);
114  }
115 
116  public function ‪initializeArguments(): void
117  {
118  parent::initializeArguments();
119  $this->registerUniversalTagAttributes();
120  $this->registerTagAttribute('alt', 'string', 'Specifies an alternate text for an image', false);
121  $this->registerTagAttribute('ismap', 'string', 'Specifies an image as a server-side image-map. Rarely used. Look at usemap instead', false);
122  $this->registerTagAttribute('longdesc', 'string', 'Specifies the URL to a document that contains a long description of an image', false);
123  $this->registerTagAttribute('usemap', 'string', 'Specifies an image as a client-side image-map', false);
124  $this->registerTagAttribute('loading', 'string', 'Native lazy-loading for images property. Can be "lazy", "eager" or "auto"', false);
125  $this->registerTagAttribute('decoding', 'string', 'Provides an image decoding hint to the browser. Can be "sync", "async" or "auto"', false);
126 
127  $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, '');
128  $this->registerArgument('treatIdAsReference', 'bool', 'given src argument is a sys_file_reference record', false, false);
129  $this->registerArgument('image', 'object', 'a FAL object (\\TYPO3\\CMS\\Core\\Resource\\File or \\TYPO3\\CMS\\Core\\Resource\\FileReference)');
130  $this->registerArgument('crop', 'string|bool|array', 'overrule cropping of image (setting to FALSE disables the cropping set in FileReference)');
131  $this->registerArgument('cropVariant', 'string', 'select a cropping variant, in case multiple croppings have been specified or stored in FileReference', false, 'default');
132  $this->registerArgument('fileExtension', 'string', 'Custom file extension to use');
133 
134  $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 for possible options.');
135  $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.width for possible options.');
136  $this->registerArgument('minWidth', 'int', 'minimum width of the image');
137  $this->registerArgument('minHeight', 'int', 'minimum height of the image');
138  $this->registerArgument('maxWidth', 'int', 'maximum width of the image');
139  $this->registerArgument('maxHeight', 'int', 'maximum height of the image');
140  $this->registerArgument('absolute', 'bool', 'Force absolute URL', false, false);
141  }
142 
149  public function ‪render(): string
150  {
151  $src = (string)$this->arguments['src'];
152  if (($src === '' && $this->arguments['image'] === null) || ($src !== '' && $this->arguments['image'] !== null)) {
153  throw new Exception($this->‪getExceptionMessage('You must either specify a string src or a File object.'), 1382284106);
154  }
155 
156  if ((string)$this->arguments['fileExtension'] && !‪GeneralUtility::inList(‪$GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], (string)$this->arguments['fileExtension'])) {
157  throw new Exception(
158  $this->‪getExceptionMessage(
159  'The extension ' . $this->arguments['fileExtension'] . ' is not specified in $GLOBALS[\'TYPO3_CONF_VARS\'][\'GFX\'][\'imagefile_ext\']'
160  . ' as a valid image file extension and can not be processed.',
161  ),
162  1618989190
163  );
164  }
165 
166  try {
167  $image = $this->imageService->getImage($src, $this->arguments['image'], (bool)$this->arguments['treatIdAsReference']);
168  $cropString = $this->arguments['crop'];
169  if ($cropString === null && $image->hasProperty('crop') && $image->getProperty('crop')) {
170  $cropString = $image->getProperty('crop');
171  }
172 
173  // CropVariantCollection needs a string, but this VH could also receive an array
174  if (is_array($cropString)) {
175  $cropString = json_encode($cropString);
176  }
177 
178  $cropVariantCollection = ‪CropVariantCollection::create((string)$cropString);
179  $cropVariant = $this->arguments['cropVariant'] ?: 'default';
180  $cropArea = $cropVariantCollection->getCropArea($cropVariant);
181  $processingInstructions = [
182  'width' => $this->arguments['width'],
183  'height' => $this->arguments['height'],
184  'minWidth' => $this->arguments['minWidth'],
185  'minHeight' => $this->arguments['minHeight'],
186  'maxWidth' => $this->arguments['maxWidth'],
187  'maxHeight' => $this->arguments['maxHeight'],
188  'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($image),
189  ];
190  if (!empty($this->arguments['fileExtension'] ?? '')) {
191  $processingInstructions['fileExtension'] = $this->arguments['fileExtension'];
192  }
193  $processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
194  $imageUri = $this->imageService->getImageUri($processedImage, $this->arguments['absolute']);
195 
196  if (!$this->tag->hasAttribute('data-focus-area')) {
197  $focusArea = $cropVariantCollection->getFocusArea($cropVariant);
198  if (!$focusArea->isEmpty()) {
199  $this->tag->addAttribute('data-focus-area', $focusArea->makeAbsoluteBasedOnFile($image));
200  }
201  }
202  $this->tag->addAttribute('src', $imageUri);
203  $this->tag->addAttribute('width', $processedImage->getProperty('width'));
204  $this->tag->addAttribute('height', $processedImage->getProperty('height'));
205 
206  if (is_string($this->arguments['alt'] ?? false) && $this->arguments['alt'] === '') {
207  // In case the "alt" attribute is explicitly set to an empty string, respect
208  // this to allow excluding it from screen readers, improving accessibility.
209  $this->tag->addAttribute('alt', '');
210  } elseif (empty($this->arguments['alt'])) {
211  // The alt-attribute is mandatory to have valid html-code, therefore use "alternative" property or empty
212  $this->tag->addAttribute('alt', $image->hasProperty('alternative') ? $image->getProperty('alternative') : '');
213  }
214  // Add title-attribute from property if not already set and the property is not an empty string
215  $title = (string)($image->hasProperty('title') ? $image->getProperty('title') : '');
216  if (empty($this->arguments['title']) && $title !== '') {
217  $this->tag->addAttribute('title', $title);
218  }
219  } catch (ResourceDoesNotExistException $e) {
220  // thrown if file does not exist
221  throw new Exception($this->‪getExceptionMessage($e->getMessage()), 1509741911, $e);
222  } catch (\UnexpectedValueException $e) {
223  // thrown if a file has been replaced with a folder
224  throw new Exception($this->‪getExceptionMessage($e->getMessage()), 1509741912, $e);
225  } catch (\InvalidArgumentException $e) {
226  // thrown if file storage does not exist
227  throw new Exception($this->‪getExceptionMessage($e->getMessage()), 1509741914, $e);
228  }
229  return $this->tag->render();
230  }
231 
232  protected function ‪getExceptionMessage(string $detailedMessage): string
233  {
235  $renderingContext = $this->renderingContext;
236  $request = $renderingContext->getRequest();
237  if ($request instanceof ‪RequestInterface) {
238  $currentContentObject = $request->getAttribute('currentContentObject');
239  if ($currentContentObject instanceof ‪ContentObjectRenderer) {
240  return sprintf('Unable to render image tag in "%s": %s', $currentContentObject->currentRecord, $detailedMessage);
241  }
242  }
243  return "Unable to render image tag: $detailedMessage";
244  }
245 }
‪TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper\render
‪render()
Definition: ImageViewHelper.php:148
‪TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection\create
‪static create(string $jsonString, array $tcaConfig=[])
Definition: CropVariantCollection.php:37
‪TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper\initializeArguments
‪initializeArguments()
Definition: ImageViewHelper.php:115
‪TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper\getExceptionMessage
‪getExceptionMessage(string $detailedMessage)
Definition: ImageViewHelper.php:231
‪TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper
Definition: ImageViewHelper.php:102
‪TYPO3\CMS\Extbase\Service\ImageService
Definition: ImageService.php:38
‪TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException
Definition: ResourceDoesNotExistException.php:23
‪TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper\$tagName
‪string $tagName
Definition: ImageViewHelper.php:105
‪TYPO3\CMS\Fluid\ViewHelpers
‪TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper\__construct
‪__construct()
Definition: ImageViewHelper.php:109
‪TYPO3\CMS\Extbase\Mvc\RequestInterface
Definition: RequestInterface.php:24
‪TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper\$imageService
‪ImageService $imageService
Definition: ImageViewHelper.php:107
‪$GLOBALS
‪$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['adminpanel']['modules']
Definition: ext_localconf.php:25
‪TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection
Definition: CropVariantCollection.php:23
‪TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer
Definition: ContentObjectRenderer.php:102
‪TYPO3\CMS\Core\Utility\GeneralUtility\inList
‪static bool inList($list, $item)
Definition: GeneralUtility.php:422
‪TYPO3\CMS\Core\Utility\GeneralUtility
Definition: GeneralUtility.php:52
‪TYPO3\CMS\Fluid\Core\Rendering\RenderingContext
Definition: RenderingContext.php:35