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