903affac09ad09691ecbf621e249d896d61fc3c8
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Element / ImageManipulationElement.php
1 <?php
2 declare(strict_types=1);
3 namespace TYPO3\CMS\Backend\Form\Element;
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
18 use TYPO3\CMS\Backend\Form\NodeFactory;
19 use TYPO3\CMS\Backend\Routing\UriBuilder;
20 use TYPO3\CMS\Core\Imaging\ImageManipulation\Area;
21 use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
22 use TYPO3\CMS\Core\Imaging\ImageManipulation\InvalidConfigurationException;
23 use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
24 use TYPO3\CMS\Core\Resource\File;
25 use TYPO3\CMS\Core\Resource\ResourceFactory;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\MathUtility;
28 use TYPO3\CMS\Core\Utility\StringUtility;
29 use TYPO3\CMS\Fluid\View\StandaloneView;
30
31 /**
32 * Generation of image manipulation FormEngine element.
33 * This is typically used in FAL relations to cut images.
34 */
35 class ImageManipulationElement extends AbstractFormElement
36 {
37 /**
38 * Default element configuration
39 *
40 * @var array
41 */
42 protected static $defaultConfig = [
43 'file_field' => 'uid_local',
44 'allowedExtensions' => null, // default: $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
45 'cropVariants' => [
46 'default' => [
47 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.crop_variant.default',
48 'allowedAspectRatios' => [
49 '16:9' => [
50 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.16_9',
51 'value' => 16 / 9
52 ],
53 '3:2' => [
54 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.3_2',
55 'value' => 3 / 2
56 ],
57 '4:3' => [
58 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.4_3',
59 'value' => 4 / 3
60 ],
61 '1:1' => [
62 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.1_1',
63 'value' => 1.0
64 ],
65 'NaN' => [
66 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.free',
67 'value' => 0.0
68 ],
69 ],
70 'selectedRatio' => 'NaN',
71 'cropArea' => [
72 'x' => 0.0,
73 'y' => 0.0,
74 'width' => 1.0,
75 'height' => 1.0,
76 ],
77 ],
78 ]
79 ];
80
81 /**
82 * Default field wizards enabled for this element.
83 *
84 * @var array
85 */
86 protected $defaultFieldWizard = [
87 'localizationStateSelector' => [
88 'renderType' => 'localizationStateSelector',
89 ],
90 'otherLanguageContent' => [
91 'renderType' => 'otherLanguageContent',
92 'after' => [
93 'localizationStateSelector'
94 ],
95 ],
96 'defaultLanguageDifferences' => [
97 'renderType' => 'defaultLanguageDifferences',
98 'after' => [
99 'otherLanguageContent',
100 ],
101 ],
102 ];
103
104 /**
105 * @var StandaloneView
106 */
107 protected $templateView;
108
109 /**
110 * @var UriBuilder
111 */
112 protected $uriBuilder;
113
114 /**
115 * @param NodeFactory $nodeFactory
116 * @param array $data
117 */
118 public function __construct(NodeFactory $nodeFactory, array $data)
119 {
120 parent::__construct($nodeFactory, $data);
121 // Would be great, if we could inject the view here, but since the constructor is in the interface, we can't
122 $this->templateView = GeneralUtility::makeInstance(StandaloneView::class);
123 $this->templateView->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/ImageManipulation/ImageCropping.html'));
124 $this->uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
125 }
126
127 /**
128 * This will render an imageManipulation field
129 *
130 * @return array As defined in initializeResultArray() of AbstractNode
131 * @throws \TYPO3\CMS\Core\Imaging\ImageManipulation\InvalidConfigurationException
132 */
133 public function render()
134 {
135 $resultArray = $this->initializeResultArray();
136 $parameterArray = $this->data['parameterArray'];
137 $config = $this->populateConfiguration($parameterArray['fieldConf']['config']);
138
139 if ($config['readOnly']) {
140 $options = [];
141 $options['parameterArray'] = [
142 'fieldConf' => [
143 'config' => $parameterArray['fieldConf']['config'],
144 ],
145 'itemFormElValue' => $parameterArray['itemFormElValue'],
146 ];
147 $options['renderType'] = 'none';
148
149 // Early return in case the field is set to read only
150 return $this->nodeFactory->create($options)->render();
151 }
152
153 $file = $this->getFile($this->data['databaseRow'], $config['file_field']);
154 if (!$file) {
155 // Early return in case we do not find a file
156 return $resultArray;
157 }
158
159 $config = $this->processConfiguration($config, $parameterArray['itemFormElValue'] ?? '{}');
160
161 $arguments = [
162 'isAllowedFileExtension' => in_array(strtolower($file->getExtension()), GeneralUtility::trimExplode(',', strtolower($config['allowedExtensions'])), true),
163 'image' => $file,
164 'formEngine' => [
165 'field' => [
166 'value' => $parameterArray['itemFormElValue'],
167 'name' => $parameterArray['itemFormElName']
168 ],
169 'validation' => '[]'
170 ],
171 'config' => $config,
172 'wizardUri' => $this->getWizardUri($config['cropVariants'], $file),
173 'previewUrl' => $this->getPreviewUrl($this->data['databaseRow'], $file),
174 ];
175
176 if ($arguments['isAllowedFileExtension']) {
177 $resultArray['requireJsModules'][] = [
178 'TYPO3/CMS/Backend/ImageManipulation' => 'function (ImageManipulation) {top.require(["cropper"], function() { ImageManipulation.initializeTrigger(); }); }'
179 ];
180 $arguments['formEngine']['field']['id'] = StringUtility::getUniqueId('formengine-image-manipulation-');
181 if (GeneralUtility::inList($config['eval'], 'required')) {
182 $arguments['formEngine']['validation'] = $this->getValidationDataAsJsonString(['required' => true]);
183 }
184 }
185 $resultArray['html'] = $this->templateView->renderSection('Element', $arguments);
186
187 return $resultArray;
188 }
189
190 /**
191 * Get file object
192 *
193 * @param array $row
194 * @param string $fieldName
195 * @return null|File
196 */
197 protected function getFile(array $row, $fieldName)
198 {
199 $file = null;
200 $fileUid = !empty($row[$fieldName]) ? $row[$fieldName] : null;
201 if (is_array($fileUid) && isset($fileUid[0]['uid'])) {
202 $fileUid = $fileUid[0]['uid'];
203 }
204 if (MathUtility::canBeInterpretedAsInteger($fileUid)) {
205 try {
206 $file = ResourceFactory::getInstance()->getFileObject($fileUid);
207 } catch (FileDoesNotExistException $e) {
208 } catch (\InvalidArgumentException $e) {
209 }
210 }
211 return $file;
212 }
213
214 /**
215 * @param array $databaseRow
216 * @param File $file
217 * @return string
218 */
219 protected function getPreviewUrl(array $databaseRow, File $file): string
220 {
221 $previewUrl = '';
222 // Hook to generate a preview URL
223 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Backend/Form/Element/ImageManipulationElement']['previewUrl']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Backend/Form/Element/ImageManipulationElement']['previewUrl'])) {
224 $hookParameters = [
225 'databaseRow' => $databaseRow,
226 'file' => $file,
227 'previewUrl' => $previewUrl,
228 ];
229 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Backend/Form/Element/ImageManipulationElement']['previewUrl'] as $listener) {
230 $previewUrl = GeneralUtility::callUserFunction($listener, $hookParameters, $this);
231 }
232 }
233 return $previewUrl;
234 }
235
236 /**
237 * @param array $baseConfiguration
238 * @return array
239 * @throws InvalidConfigurationException
240 */
241 protected function populateConfiguration(array $baseConfiguration)
242 {
243 $defaultConfig = self::$defaultConfig;
244
245 // If ratios are set do not add default options
246 if (isset($baseConfiguration['cropVariants'])) {
247 unset($defaultConfig['cropVariants']);
248 }
249
250 $config = array_replace_recursive($defaultConfig, $baseConfiguration);
251
252 if (!is_array($config['cropVariants'])) {
253 throw new InvalidConfigurationException('Crop variants configuration must be an array', 1485377267);
254 }
255
256 foreach ($config['cropVariants'] as &$cropVariant) {
257 // Enforce a crop area (default is full image)
258 if (empty($cropVariant['cropArea'])) {
259 $cropVariant['cropArea'] = Area::createEmpty()->asArray();
260 }
261 }
262 unset($cropVariant);
263
264 // By default we allow all image extensions that can be handled by the GFX functionality
265 if ($config['allowedExtensions'] === null) {
266 $config['allowedExtensions'] = $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'];
267 }
268 return $config;
269 }
270
271 /**
272 * @param array $config
273 * @param string $elementValue
274 * @return array
275 * @throws \TYPO3\CMS\Core\Imaging\ImageManipulation\InvalidConfigurationException
276 */
277 protected function processConfiguration(array $config, string $elementValue)
278 {
279 $cropVariantCollection = CropVariantCollection::create($elementValue, $config['cropVariants']);
280 $config['cropVariants'] = $cropVariantCollection->asArray();
281 $config['allowedExtensions'] = implode(', ', GeneralUtility::trimExplode(',', $config['allowedExtensions'], true));
282 return $config;
283 }
284
285 /**
286 * @param array $cropVariants
287 * @param File $image
288 * @return string
289 */
290 protected function getWizardUri(array $cropVariants, File $image): string
291 {
292 $routeName = 'ajax_wizard_image_manipulation';
293 $arguments = [
294 'cropVariants' => $cropVariants,
295 'image' => $image->getUid(),
296 ];
297 $uriArguments['arguments'] = json_encode($arguments);
298 $uriArguments['signature'] = GeneralUtility::hmac($uriArguments['arguments'], $routeName);
299 return (string)$this->uriBuilder->buildUriFromRoute($routeName, $uriArguments);
300 }
301 }