‪TYPO3CMS  10.4
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 
32 
38 {
42  private ‪$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 
125  protected ‪$templateView;
126 
130  protected ‪$uriBuilder;
131 
136  public function ‪__construct(‪NodeFactory ‪$nodeFactory, array ‪$data)
137  {
138  parent::__construct(‪$nodeFactory, ‪$data);
139  // Would be great, if we could inject the view here, but since the constructor is in the interface, we can't
140  $this->templateView = GeneralUtility::makeInstance(StandaloneView::class);
141  $this->templateView->setLayoutRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Layouts/')]);
142  $this->templateView->setPartialRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Partials/ImageManipulation/')]);
143  $this->templateView->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/ImageManipulation/ImageManipulationElement.html'));
144  $this->uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
145  }
146 
153  public function ‪render()
154  {
155  $resultArray = $this->‪initializeResultArray();
156  $parameterArray = $this->data['parameterArray'];
157  $config = $this->‪populateConfiguration($parameterArray['fieldConf']['config']);
158 
159  $file = $this->‪getFile($this->data['databaseRow'], $config['file_field']);
160  if (!$file) {
161  // Early return in case we do not find a file
162  return $resultArray;
163  }
164 
165  $config = $this->‪processConfiguration($config, $parameterArray['itemFormElValue'], $file);
166 
167  $fieldInformationResult = $this->‪renderFieldInformation();
168  $fieldInformationHtml = $fieldInformationResult['html'];
169  $resultArray = $this->‪mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
170 
171  $fieldControlResult = $this->‪renderFieldControl();
172  $fieldControlHtml = $fieldControlResult['html'];
173  $resultArray = $this->‪mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
174 
175  $fieldWizardResult = $this->‪renderFieldWizard();
176  $fieldWizardHtml = $fieldWizardResult['html'];
177  $resultArray = $this->‪mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
178 
179  $arguments = [
180  'fieldInformation' => $fieldInformationHtml,
181  'fieldControl' => $fieldControlHtml,
182  'fieldWizard' => $fieldWizardHtml,
183  'isAllowedFileExtension' => in_array(strtolower($file->getExtension()), ‪GeneralUtility::trimExplode(',', strtolower($config['allowedExtensions'])), true),
184  'image' => $file,
185  'formEngine' => [
186  'field' => [
187  'value' => $parameterArray['itemFormElValue'],
188  'name' => $parameterArray['itemFormElName']
189  ],
190  'validation' => '[]'
191  ],
192  'config' => $config,
193  'wizardUri' => $this->‪getWizardUri(),
194  'wizardPayload' => json_encode($this->‪getWizardPayload($config['cropVariants'], $file)),
195  'previewUrl' => $this->‪getPreviewUrl($this->data['databaseRow'], $file),
196  ];
197 
198  if ($arguments['isAllowedFileExtension']) {
199  $resultArray['requireJsModules'][] = [
200  'TYPO3/CMS/Backend/ImageManipulation' => 'function (ImageManipulation) {top.require(["cropper"], function() { ImageManipulation.initializeTrigger(); }); }'
201  ];
202  $arguments['formEngine']['field']['id'] = ‪StringUtility::getUniqueId('formengine-image-manipulation-');
203  if (GeneralUtility::inList($config['eval'], 'required')) {
204  $arguments['formEngine']['validation'] = $this->‪getValidationDataAsJsonString(['required' => true]);
205  }
206  }
207  $this->templateView->assignMultiple($arguments);
208  $resultArray['html'] = $this->templateView->render();
209 
210  return $resultArray;
211  }
212 
220  protected function ‪getFile(array $row, $fieldName)
221  {
222  $file = null;
223  $fileUid = !empty($row[$fieldName]) ? $row[$fieldName] : null;
224  if (is_array($fileUid) && isset($fileUid[0]['uid'])) {
225  $fileUid = $fileUid[0]['uid'];
226  }
228  try {
229  $file = GeneralUtility::makeInstance(ResourceFactory::class)->getFileObject($fileUid);
230  } catch (FileDoesNotExistException|\InvalidArgumentException $e) {
231  }
232  }
233  return $file;
234  }
235 
241  protected function ‪getPreviewUrl(array $databaseRow, ‪File $file): string
242  {
243  $previewUrl = '';
244  // Hook to generate a preview URL
245  $hookParameters = [
246  'databaseRow' => $databaseRow,
247  'file' => $file,
248  'previewUrl' => $previewUrl,
249  ];
250  foreach (‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Backend/Form/Element/ImageManipulationElement']['previewUrl'] ?? [] as $listener) {
251  $previewUrl = GeneralUtility::callUserFunction($listener, $hookParameters, $this);
252  }
253  return $previewUrl;
254  }
255 
261  protected function ‪populateConfiguration(array $baseConfiguration)
262  {
264 
265  // If ratios are set do not add default options
266  if (isset($baseConfiguration['cropVariants'])) {
267  unset(‪$defaultConfig['cropVariants']);
268  }
269 
270  $config = array_replace_recursive(‪$defaultConfig, $baseConfiguration);
271 
272  if (!is_array($config['cropVariants'])) {
273  throw new ‪InvalidConfigurationException('Crop variants configuration must be an array', 1485377267);
274  }
275 
276  $cropVariants = [];
277  foreach ($config['cropVariants'] as $id => $cropVariant) {
278 
279  // Filter allowed aspect ratios
280  $cropVariant['allowedAspectRatios'] = array_filter($cropVariant['allowedAspectRatios'] ?? [], static function ($aspectRatio) {
281  return !(bool)($aspectRatio['disabled'] ?? false);
282  });
283 
284  // Ignore disabled crop variants
285  if (!empty($cropVariant['disabled'])) {
286  continue;
287  }
288 
289  if (empty($cropVariant['allowedAspectRatios'])) {
290  throw new ‪InvalidConfigurationException('Crop variants configuration ' . $id . ' contains no allowed aspect ratios', 1620147893);
291  }
292 
293  // Enforce a crop area (default is full image)
294  if (empty($cropVariant['cropArea'])) {
295  $cropVariant['cropArea'] = ‪Area::createEmpty()->‪asArray();
296  }
297 
298  $cropVariants[$id] = $cropVariant;
299  }
300 
301  $config['cropVariants'] = $cropVariants;
302 
303  // By default we allow all image extensions that can be handled by the GFX functionality
304  if ($config['allowedExtensions'] === null) {
305  $config['allowedExtensions'] = ‪$GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'];
306  }
307  return $config;
308  }
309 
317  protected function ‪processConfiguration(array $config, string &$elementValue, ‪File $file)
318  {
319  $cropVariantCollection = ‪CropVariantCollection::create($elementValue, $config['cropVariants']);
320  if (empty($config['readOnly']) && !empty($file->‪getProperty('width'))) {
321  $cropVariantCollection = $cropVariantCollection->applyRatioRestrictionToSelectedCropArea($file);
322  $elementValue = (string)$cropVariantCollection;
323  }
324  $config['cropVariants'] = $cropVariantCollection->asArray();
325  $config['allowedExtensions'] = implode(', ', ‪GeneralUtility::trimExplode(',', $config['allowedExtensions'], true));
326  return $config;
327  }
328 
332  protected function ‪getWizardUri(): string
333  {
334  return (string)$this->uriBuilder->buildUriFromRoute($this->wizardRouteName);
335  }
336 
342  protected function ‪getWizardPayload(array $cropVariants, ‪File $image): array
343  {
344  $uriArguments = [];
345  $arguments = [
346  'cropVariants' => $cropVariants,
347  'image' => $image->‪getUid(),
348  ];
349  $uriArguments['arguments'] = json_encode($arguments);
350  $uriArguments['signature'] = GeneralUtility::hmac((string)($uriArguments['arguments'] ?? ''), $this->wizardRouteName);
351 
352  return $uriArguments;
353  }
354 }
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$wizardRouteName
‪string $wizardRouteName
Definition: ImageManipulationElement.php:41
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$templateView
‪StandaloneView $templateView
Definition: ImageManipulationElement.php:120
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement\renderFieldInformation
‪array renderFieldInformation()
Definition: AbstractFormElement.php:72
‪TYPO3\CMS\Core\Utility\MathUtility\canBeInterpretedAsInteger
‪static bool canBeInterpretedAsInteger($var)
Definition: MathUtility.php:74
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$defaultFieldInformation
‪array $defaultFieldInformation
Definition: ImageManipulationElement.php:90
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\render
‪array render()
Definition: ImageManipulationElement.php:147
‪TYPO3\CMS\Backend\Form\AbstractNode\mergeChildReturnIntoExistingResult
‪array mergeChildReturnIntoExistingResult(array $existing, array $childReturn, bool $mergeHtml=true)
Definition: AbstractNode.php:116
‪TYPO3\CMS\Backend\Form\AbstractNode\initializeResultArray
‪array initializeResultArray()
Definition: AbstractNode.php:90
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\getWizardPayload
‪array getWizardPayload(array $cropVariants, File $image)
Definition: ImageManipulationElement.php:336
‪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:214
‪TYPO3\CMS\Backend\Form\AbstractNode\$nodeFactory
‪NodeFactory $nodeFactory
Definition: AbstractNode.php:36
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement
Definition: AbstractFormElement.php:32
‪TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException
Definition: FileDoesNotExistException.php:22
‪TYPO3\CMS\Backend\Form\Element
Definition: AbstractFormElement.php:16
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\populateConfiguration
‪array populateConfiguration(array $baseConfiguration)
Definition: ImageManipulationElement.php:255
‪TYPO3\CMS\Backend\Form\AbstractNode\getValidationDataAsJsonString
‪string getValidationDataAsJsonString(array $config)
Definition: AbstractNode.php:151
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement\renderFieldControl
‪array renderFieldControl()
Definition: AbstractFormElement.php:88
‪TYPO3\CMS\Backend\Routing\UriBuilder
Definition: UriBuilder.php:38
‪TYPO3\CMS\Backend\Form\AbstractNode\$data
‪array $data
Definition: AbstractNode.php:42
‪TYPO3\CMS\Core\Resource\ResourceFactory
Definition: ResourceFactory.php:41
‪TYPO3\CMS\Core\Resource\File
Definition: File.php:24
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\getPreviewUrl
‪string getPreviewUrl(array $databaseRow, File $file)
Definition: ImageManipulationElement.php:235
‪TYPO3\CMS\Core\Resource\AbstractFile\getUid
‪int getUid()
Definition: AbstractFile.php:202
‪TYPO3\CMS\Core\Imaging\ImageManipulation\InvalidConfigurationException
Definition: InvalidConfigurationException.php:24
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$defaultFieldWizard
‪array $defaultFieldWizard
Definition: ImageManipulationElement.php:100
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\__construct
‪__construct(NodeFactory $nodeFactory, array $data)
Definition: ImageManipulationElement.php:130
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\processConfiguration
‪array processConfiguration(array $config, string &$elementValue, File $file)
Definition: ImageManipulationElement.php:311
‪TYPO3\CMS\Core\Utility\GeneralUtility\trimExplode
‪static string[] trimExplode($delim, $string, $removeEmptyValues=false, $limit=0)
Definition: GeneralUtility.php:1059
‪TYPO3\CMS\Backend\Form\NodeFactory
Definition: NodeFactory.php:37
‪TYPO3\CMS\Core\Utility\StringUtility\getUniqueId
‪static string getUniqueId($prefix='')
Definition: StringUtility.php:92
‪TYPO3\CMS\Fluid\View\StandaloneView
Definition: StandaloneView.php:34
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$uriBuilder
‪UriBuilder $uriBuilder
Definition: ImageManipulationElement.php:124
‪$GLOBALS
‪$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['adminpanel']['modules']
Definition: ext_localconf.php:5
‪TYPO3\CMS\Core\Resource\File\getProperty
‪mixed getProperty($key)
Definition: File.php:65
‪TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection
Definition: CropVariantCollection.php:23
‪TYPO3\CMS\Core\Utility\MathUtility
Definition: MathUtility.php:22
‪TYPO3\CMS\Core\Utility\GeneralUtility
Definition: GeneralUtility.php:46
‪TYPO3\CMS\Core\Imaging\ImageManipulation\Area\asArray
‪array asArray()
Definition: Area.php:119
‪TYPO3\CMS\Core\Utility\StringUtility
Definition: StringUtility.php:22
‪TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection\create
‪static CropVariantCollection create(string $jsonString, array $tcaConfig=[])
Definition: CropVariantCollection.php:42
‪TYPO3\CMS\Backend\Form\Element\AbstractFormElement\renderFieldWizard
‪array renderFieldWizard()
Definition: AbstractFormElement.php:104
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement
Definition: ImageManipulationElement.php:38
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\$defaultConfig
‪static array $defaultConfig
Definition: ImageManipulationElement.php:47
‪TYPO3\CMS\Backend\Form\Element\ImageManipulationElement\getWizardUri
‪string getWizardUri()
Definition: ImageManipulationElement.php:326
‪TYPO3\CMS\Core\Imaging\ImageManipulation\Area\createEmpty
‪static Area createEmpty()
Definition: Area.php:90