‪TYPO3CMS  ‪main
ImageManipulationElement.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\EventDispatcher\EventDispatcherInterface;
28 use TYPO3\CMS\Core\Imaging\ImageManipulation\Ratio;
36 
42 {
43  private string ‪$wizardRouteName = 'ajax_wizard_image_manipulation';
44 
50  protected static ‪$defaultConfig = [
51  'file_field' => 'uid_local',
52  'allowedExtensions' => null, // default: $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
53  'cropVariants' => [
54  'default' => [
55  'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.crop_variant.default',
56  'allowedAspectRatios' => [
57  '16:9' => [
58  'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.16_9',
59  'value' => 16 / 9,
60  ],
61  '3:2' => [
62  'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.3_2',
63  'value' => 3 / 2,
64  ],
65  '4:3' => [
66  'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.4_3',
67  'value' => 4 / 3,
68  ],
69  '1:1' => [
70  'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.1_1',
71  'value' => 1.0,
72  ],
73  'NaN' => [
74  'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.free',
75  'value' => 0.0,
76  ],
77  ],
78  'selectedRatio' => 'NaN',
79  'cropArea' => [
80  'x' => 0.0,
81  'y' => 0.0,
82  'width' => 1.0,
83  'height' => 1.0,
84  ],
85  ],
86  ],
87  ];
88 
94  protected ‪$defaultFieldInformation = [
95  'tcaDescription' => [
96  'renderType' => 'tcaDescription',
97  ],
98  ];
99 
105  protected ‪$defaultFieldWizard = [
106  'localizationStateSelector' => [
107  'renderType' => 'localizationStateSelector',
108  ],
109  'otherLanguageThumbnails' => [
110  'renderType' => 'otherLanguageThumbnails',
111  'after' => [
112  'localizationStateSelector',
113  ],
114  ],
115  'defaultLanguageDifferences' => [
116  'renderType' => 'defaultLanguageDifferences',
117  'after' => [
118  'otherLanguageThumbnails',
119  ],
120  ],
121  ];
122 
123  public function ‪__construct(
124  private readonly ‪BackendViewFactory $backendViewFactory,
125  private readonly ‪UriBuilder $uriBuilder,
126  private readonly EventDispatcherInterface $eventDispatcher,
127  private readonly ‪ResourceFactory $resourceFactory,
128  private readonly ‪HashService $hashService,
129  ) {}
130 
137  public function ‪render(): array
138  {
139  $resultArray = $this->‪initializeResultArray();
140  $parameterArray = $this->data['parameterArray'];
141  $config = $this->‪populateConfiguration($parameterArray['fieldConf']['config']);
142 
143  $file = $this->‪getFile($this->data['databaseRow'], $config['file_field']);
144  if (!$file) {
145  // Early return in case we do not find a file
146  return $resultArray;
147  }
148 
149  $config = $this->‪processConfiguration($config, $parameterArray['itemFormElValue'], $file);
150 
151  $fieldInformationResult = $this->‪renderFieldInformation();
152  $fieldInformationHtml = $fieldInformationResult['html'];
153  $resultArray = $this->‪mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
154 
155  $fieldControlResult = $this->‪renderFieldControl();
156  $fieldControlHtml = $fieldControlResult['html'];
157  $resultArray = $this->‪mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
158 
159  $fieldWizardResult = $this->‪renderFieldWizard();
160  $fieldWizardHtml = $fieldWizardResult['html'];
161  $resultArray = $this->‪mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
162 
163  $arguments = [
164  'fieldInformation' => $fieldInformationHtml,
165  'fieldControl' => $fieldControlHtml,
166  'fieldWizard' => $fieldWizardHtml,
167  'isAllowedFileExtension' => in_array(strtolower($file->getExtension()), ‪GeneralUtility::trimExplode(',', strtolower($config['allowedExtensions'])), true),
168  'image' => $file,
169  'formEngine' => [
170  'field' => [
171  'value' => $parameterArray['itemFormElValue'],
172  'name' => $parameterArray['itemFormElName'],
173  ],
174  'validation' => '[]',
175  ],
176  'config' => $config,
177  'wizardUri' => $this->‪getWizardUri(),
178  'wizardPayload' => json_encode($this->‪getWizardPayload($config['cropVariants'], $file)),
179  'previewUrl' => $this->eventDispatcher->dispatch(
180  new ModifyImageManipulationPreviewUrlEvent($this->data['databaseRow'], $config, $file)
181  )->getPreviewUrl(),
182  ];
183 
184  if ($arguments['isAllowedFileExtension']) {
185  $resultArray['javaScriptModules'][] = ‪JavaScriptModuleInstruction::create(
186  '@typo3/backend/image-manipulation.js'
187  )->invoke('initializeTrigger');
188  $arguments['formEngine']['field']['id'] = ‪StringUtility::getUniqueId('formengine-image-manipulation-');
189  if ($config['required'] ?? false) {
190  $arguments['formEngine']['validation'] = $this->‪getValidationDataAsJsonString(['required' => true]);
191  }
192  }
193  $view = $this->backendViewFactory->create($this->data['request']);
194  $view->assignMultiple($arguments);
195  $resultArray['html'] = $this->‪wrapWithFieldsetAndLegend($view->render('Form/ImageManipulationElement'));
196 
197  return $resultArray;
198  }
199 
206  protected function ‪getFile(array $row, $fieldName)
207  {
208  $file = null;
209  $fileUid = !empty($row[$fieldName]) ? $row[$fieldName] : null;
210  if (is_array($fileUid) && isset($fileUid[0]['uid'])) {
211  $fileUid = $fileUid[0]['uid'];
212  }
214  try {
215  $file = $this->resourceFactory->getFileObject($fileUid);
216  } catch (FileDoesNotExistException|\InvalidArgumentException) {
217  }
218  }
219  return $file;
220  }
221 
226  protected function ‪populateConfiguration(array $baseConfiguration)
227  {
229 
230  // If ratios are set do not add default options
231  if (isset($baseConfiguration['cropVariants'])) {
232  unset(‪$defaultConfig['cropVariants']);
233  }
234 
235  $config = array_replace_recursive(‪$defaultConfig, $baseConfiguration);
236 
237  if (!is_array($config['cropVariants'])) {
238  throw new InvalidConfigurationException('Crop variants configuration must be an array', 1485377267);
239  }
240 
241  $cropVariants = [];
242  foreach ($config['cropVariants'] as $id => $cropVariant) {
243  // Filter allowed aspect ratios
244  $cropVariant['allowedAspectRatios'] = array_filter($cropVariant['allowedAspectRatios'] ?? [], static function (array $aspectRatio): bool {
245  return !(bool)($aspectRatio['disabled'] ?? false);
246  });
247 
248  // Aspect ratios may not contain a "." character, see Ratio::__construct()
249  // To match them again properly, same replacement is required here.
250  $preparedAllowedAspectRatios = [];
251  foreach ($cropVariant['allowedAspectRatios'] as $aspectRatio => $aspectRatioDefinition) {
252  $preparedAllowedAspectRatios[Ratio::prepareAspectRatioId($aspectRatio)] = $aspectRatioDefinition;
253  }
254  $cropVariant['allowedAspectRatios'] = $preparedAllowedAspectRatios;
255 
256  // Ignore disabled crop variants
257  if (!empty($cropVariant['disabled'])) {
258  continue;
259  }
260 
261  if (empty($cropVariant['allowedAspectRatios'])) {
262  throw new InvalidConfigurationException('Crop variants configuration ' . $id . ' contains no allowed aspect ratios', 1620147893);
263  }
264 
265  // Enforce a crop area (default is full image)
266  if (empty($cropVariant['cropArea'])) {
267  $cropVariant['cropArea'] = ‪Area::createEmpty()->‪asArray();
268  }
269 
270  $cropVariants[$id] = $cropVariant;
271  }
272 
273  $config['cropVariants'] = $cropVariants;
274 
275  // By default we allow all image extensions that can be handled by the GFX functionality
276  $config['allowedExtensions'] ??= ‪$GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'];
277  return $config;
278  }
279 
284  protected function ‪processConfiguration(array $config, string &$elementValue, File $file)
285  {
286  $cropVariantCollection = ‪CropVariantCollection::create($elementValue, $config['cropVariants']);
287  if (empty($config['readOnly']) && !empty($file->getProperty('width'))) {
288  $cropVariantCollection = $cropVariantCollection->applyRatioRestrictionToSelectedCropArea($file);
289  $elementValue = (string)$cropVariantCollection;
290  }
291  $config['cropVariants'] = $cropVariantCollection->asArray();
292  $config['allowedExtensions'] = implode(', ', ‪GeneralUtility::trimExplode(',', $config['allowedExtensions'], true));
293  return $config;
294  }
295 
296  protected function ‪getWizardUri(): string
297  {
298  return (string)$this->uriBuilder->buildUriFromRoute($this->wizardRouteName);
299  }
300 
301  protected function ‪getWizardPayload(array $cropVariants, ‪File $image): array
302  {
303  $uriArguments = [];
304  $arguments = [
305  'cropVariants' => $cropVariants,
306  'image' => $image->‪getUid(),
307  ];
308  $uriArguments['arguments'] = json_encode($arguments);
309  $uriArguments['signature'] = $this->hashService->hmac((string)($uriArguments['arguments'] ?? ''), $this->wizardRouteName);
310 
311  return $uriArguments;
312  }
313 }
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\getWizardPayload
‪getWizardPayload(array $cropVariants, File $image)
Definition: ImageManipulationElement.php:298
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$wizardRouteName
‪string $wizardRouteName
Definition: ImageManipulationElement.php:43
‪TYPO3\CMS\Backend\Form\Event\ModifyImageManipulationPreviewUrlEvent
Definition: ModifyImageManipulationPreviewUrlEvent.php:26
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement\renderFieldInformation
‪array renderFieldInformation()
Definition: AbstractFormElement.php:73
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$defaultFieldInformation
‪array $defaultFieldInformation
Definition: ImageManipulationElement.php:92
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\render
‪array render()
Definition: ImageManipulationElement.php:134
‪TYPO3\CMS\Backend\Form\AbstractNode\mergeChildReturnIntoExistingResult
‪array mergeChildReturnIntoExistingResult(array $existing, array $childReturn, bool $mergeHtml=true)
Definition: AbstractNode.php:104
‪TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection\create
‪static create(string $jsonString, array $tcaConfig=[])
Definition: CropVariantCollection.php:37
‪TYPO3\CMS\Backend\View\BackendViewFactory
Definition: BackendViewFactory.php:35
‪TYPO3\CMS\Core\Imaging\ImageManipulation\Area
Definition: Area.php:23
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\getFile
‪File null getFile(array $row, $fieldName)
Definition: ImageManipulationElement.php:203
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement
Definition: AbstractFormElement.php:37
‪TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException
Definition: FileDoesNotExistException.php:21
‪TYPO3\CMS\Core\Page\JavaScriptModuleInstruction
Definition: JavaScriptModuleInstruction.php:23
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\getWizardUri
‪getWizardUri()
Definition: ImageManipulationElement.php:293
‪TYPO3\CMS\Backend\Form\Element
Definition: AbstractFormElement.php:16
‪TYPO3\CMS\Core\Imaging\ImageManipulation\Area\asArray
‪asArray()
Definition: Area.php:109
‪TYPO3\CMS\Core\Resource\File\getProperty
‪getProperty(string $key)
Definition: File.php:62
‪TYPO3\CMS\Core\Utility\MathUtility\canBeInterpretedAsInteger
‪static bool canBeInterpretedAsInteger(mixed $var)
Definition: MathUtility.php:74
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\populateConfiguration
‪array populateConfiguration(array $baseConfiguration)
Definition: ImageManipulationElement.php:223
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement\wrapWithFieldsetAndLegend
‪wrapWithFieldsetAndLegend(string $innerHTML)
Definition: AbstractFormElement.php:133
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement\renderFieldControl
‪array renderFieldControl()
Definition: AbstractFormElement.php:89
‪TYPO3\CMS\Backend\Routing\UriBuilder
Definition: UriBuilder.php:44
‪TYPO3\CMS\Core\Resource\ResourceFactory
Definition: ResourceFactory.php:42
‪TYPO3\CMS\Core\Resource\File
Definition: File.php:26
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\__construct
‪__construct(private readonly BackendViewFactory $backendViewFactory, private readonly UriBuilder $uriBuilder, private readonly EventDispatcherInterface $eventDispatcher, private readonly ResourceFactory $resourceFactory, private readonly HashService $hashService,)
Definition: ImageManipulationElement.php:120
‪TYPO3\CMS\Core\Imaging\ImageManipulation\InvalidConfigurationException
Definition: InvalidConfigurationException.php:23
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$defaultFieldWizard
‪array $defaultFieldWizard
Definition: ImageManipulationElement.php:102
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\processConfiguration
‪array processConfiguration(array $config, string &$elementValue, File $file)
Definition: ImageManipulationElement.php:281
‪TYPO3\CMS\Core\Resource\AbstractFile\getUid
‪return MathUtility::canBeInterpretedAsInteger($size) ?(int) $size int getUid()
Definition: AbstractFile.php:195
‪$GLOBALS
‪$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['adminpanel']['modules']
Definition: ext_localconf.php:25
‪TYPO3\CMS\Backend\Form\AbstractNode\getValidationDataAsJsonString
‪getValidationDataAsJsonString(array $config)
Definition: AbstractNode.php:133
‪TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection
Definition: CropVariantCollection.php:23
‪TYPO3\CMS\Core\Utility\MathUtility
Definition: MathUtility.php:24
‪TYPO3\CMS\Core\Page\JavaScriptModuleInstruction\create
‪static create(string $name, ?string $exportName=null)
Definition: JavaScriptModuleInstruction.php:47
‪TYPO3\CMS\Core\Utility\GeneralUtility
Definition: GeneralUtility.php:52
‪TYPO3\CMS\Core\Utility\StringUtility
Definition: StringUtility.php:24
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement\renderFieldWizard
‪array renderFieldWizard()
Definition: AbstractFormElement.php:105
‪TYPO3\CMS\Core\Crypto\HashService
Definition: HashService.php:27
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement
Definition: ImageManipulationElement.php:42
‪TYPO3\CMS\Core\Utility\GeneralUtility\trimExplode
‪static list< string > trimExplode(string $delim, string $string, bool $removeEmptyValues=false, int $limit=0)
Definition: GeneralUtility.php:822
‪TYPO3\CMS\Core\Utility\StringUtility\getUniqueId
‪static getUniqueId(string $prefix='')
Definition: StringUtility.php:57
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$defaultConfig
‪static array $defaultConfig
Definition: ImageManipulationElement.php:49
‪TYPO3\CMS\Backend\Form\AbstractNode\initializeResultArray
‪initializeResultArray()
Definition: AbstractNode.php:77
‪TYPO3\CMS\Core\Imaging\ImageManipulation\Area\createEmpty
‪static Area createEmpty()
Definition: Area.php:81