[FOLLOWUP][TASK] Spread TypeConverter priorities
[Packages/TYPO3.CMS.git] / typo3 / sysext / form / Classes / Mvc / Property / TypeConverter / UploadedFileReferenceConverter.php
1 <?php
2 declare(strict_types=1);
3 namespace TYPO3\CMS\Form\Mvc\Property\TypeConverter;
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\Core\Resource\File as File;
19 use TYPO3\CMS\Core\Resource\FileReference as CoreFileReference;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21 use TYPO3\CMS\Extbase\Domain\Model\AbstractFileFolder;
22 use TYPO3\CMS\Extbase\Domain\Model\FileReference as ExtbaseFileReference;
23 use TYPO3\CMS\Extbase\Error\Error;
24 use TYPO3\CMS\Extbase\Property\Exception\TypeConverterException;
25 use TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface;
26 use TYPO3\CMS\Extbase\Property\TypeConverter\AbstractTypeConverter;
27 use TYPO3\CMS\Extbase\Validation\Validator\AbstractValidator;
28
29 /**
30 * Class UploadedFileReferenceConverter
31 *
32 * Scope: frontend
33 * @internal
34 */
35 class UploadedFileReferenceConverter extends AbstractTypeConverter
36 {
37
38 /**
39 * Folder where the file upload should go to (including storage).
40 */
41 const CONFIGURATION_UPLOAD_FOLDER = 1;
42
43 /**
44 * How to handle a upload when the name of the uploaded file conflicts.
45 */
46 const CONFIGURATION_UPLOAD_CONFLICT_MODE = 2;
47
48 /**
49 * Validator for file types
50 */
51 const CONFIGURATION_FILE_VALIDATORS = 4;
52
53 /**
54 * @var string
55 */
56 protected $defaultUploadFolder = '1:/user_upload/';
57
58 /**
59 * One of 'cancel', 'replace', 'rename'
60 *
61 * @var string
62 */
63 protected $defaultConflictMode = 'rename';
64
65 /**
66 * @var array
67 */
68 protected $sourceTypes = ['array'];
69
70 /**
71 * @var string
72 */
73 protected $targetType = ExtbaseFileReference::class;
74
75 /**
76 * Take precedence over the available FileReferenceConverter
77 *
78 * @var int
79 */
80 protected $priority = 12;
81
82 /**
83 * @var \TYPO3\CMS\Core\Resource\FileInterface[]
84 */
85 protected $convertedResources = [];
86
87 /**
88 * @var \TYPO3\CMS\Core\Resource\ResourceFactory
89 */
90 protected $resourceFactory;
91
92 /**
93 * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
94 */
95 protected $hashService;
96
97 /**
98 * @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
99 */
100 protected $persistenceManager;
101
102 /**
103 * @param \TYPO3\CMS\Core\Resource\ResourceFactory $resourceFactory
104 * @return void
105 * @internal
106 */
107 public function injectResourceFactory(\TYPO3\CMS\Core\Resource\ResourceFactory $resourceFactory)
108 {
109 $this->resourceFactory = $resourceFactory;
110 }
111
112 /**
113 * @param \TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService
114 * @return void
115 * @internal
116 */
117 public function injectHashService(\TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService)
118 {
119 $this->hashService = $hashService;
120 }
121
122 /**
123 * @param \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface $persistenceManager
124 * @return void
125 * @internal
126 */
127 public function injectPersistenceManager(\TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface $persistenceManager)
128 {
129 $this->persistenceManager = $persistenceManager;
130 }
131
132 /**
133 * Actually convert from $source to $targetType, taking into account the fully
134 * built $convertedChildProperties and $configuration.
135 *
136 * @param string|int $source
137 * @param string $targetType
138 * @param array $convertedChildProperties
139 * @param PropertyMappingConfigurationInterface $configuration
140 * @return AbstractFileFolder
141 * @internal
142 */
143 public function convertFrom($source, $targetType, array $convertedChildProperties = [], PropertyMappingConfigurationInterface $configuration = null)
144 {
145 if (!isset($source['error']) || $source['error'] === \UPLOAD_ERR_NO_FILE) {
146 if (isset($source['submittedFile']['resourcePointer'])) {
147 try {
148 $resourcePointer = $this->hashService->validateAndStripHmac($source['submittedFile']['resourcePointer']);
149 if (strpos($resourcePointer, 'file:') === 0) {
150 $fileUid = substr($resourcePointer, 5);
151 return $this->createFileReferenceFromFalFileObject($this->resourceFactory->getFileObject($fileUid));
152 } else {
153 return $this->createFileReferenceFromFalFileReferenceObject($this->resourceFactory->getFileReferenceObject($resourcePointer), $resourcePointer);
154 }
155 } catch (\InvalidArgumentException $e) {
156 // Nothing to do. No file is uploaded and resource pointer is invalid. Discard!
157 }
158 }
159 return null;
160 }
161
162 if ($source['error'] !== \UPLOAD_ERR_OK) {
163 return $this->objectManager->get(Error::class, $this->getUploadErrorMessage($source['error']), 1471715915);
164 }
165
166 if (isset($this->convertedResources[$source['tmp_name']])) {
167 return $this->convertedResources[$source['tmp_name']];
168 }
169
170 try {
171 $resource = $this->importUploadedResource($source, $configuration);
172 } catch (\Exception $e) {
173 return $this->objectManager->get(Error::class, $e->getMessage(), $e->getCode());
174 }
175
176 $this->convertedResources[$source['tmp_name']] = $resource;
177 return $resource;
178 }
179
180 /**
181 * Import a resource and respect configuration given for properties
182 *
183 * @param array $uploadInfo
184 * @param PropertyMappingConfigurationInterface $configuration
185 * @return ExtbaseFileReference
186 * @throws TypeConverterException
187 */
188 protected function importUploadedResource(
189 array $uploadInfo,
190 PropertyMappingConfigurationInterface $configuration
191 ): ExtbaseFileReference {
192 if (!GeneralUtility::verifyFilenameAgainstDenyPattern($uploadInfo['name'])) {
193 throw new TypeConverterException('Uploading files with PHP file extensions is not allowed!', 1471710357);
194 }
195
196 $uploadFolderId = $configuration->getConfigurationValue(self::class, self::CONFIGURATION_UPLOAD_FOLDER) ?: $this->defaultUploadFolder;
197 $conflictMode = $configuration->getConfigurationValue(self::class, self::CONFIGURATION_UPLOAD_CONFLICT_MODE) ?: $this->defaultConflictMode;
198
199 $uploadFolder = $this->resourceFactory->retrieveFileOrFolderObject($uploadFolderId);
200 $uploadedFile = $uploadFolder->addUploadedFile($uploadInfo, $conflictMode);
201
202 $validators = $configuration->getConfigurationValue(self::class, self::CONFIGURATION_FILE_VALIDATORS);
203 if (is_array($validators)) {
204 foreach ($validators as $validator) {
205 if ($validator instanceof AbstractValidator) {
206 $validationResult = $validator->validate($uploadedFile);
207 if ($validationResult->hasErrors()) {
208 $uploadedFile->getStorage()->deleteFile($uploadedFile);
209 throw new TypeConverterException($validationResult->getErrors()[0]->getMessage(), 1471708999);
210 }
211 }
212 }
213 }
214
215 $resourcePointer = isset($uploadInfo['submittedFile']['resourcePointer']) && strpos($uploadInfo['submittedFile']['resourcePointer'], 'file:') === false
216 ? $this->hashService->validateAndStripHmac($uploadInfo['submittedFile']['resourcePointer'])
217 : null;
218
219 $fileReferenceModel = $this->createFileReferenceFromFalFileObject($uploadedFile, $resourcePointer);
220
221 return $fileReferenceModel;
222 }
223
224 /**
225 * @param File $file
226 * @param int $resourcePointer
227 * @return ExtbaseFileReference
228 */
229 protected function createFileReferenceFromFalFileObject(
230 File $file,
231 int $resourcePointer = null
232 ): ExtbaseFileReference {
233 $fileReference = $this->resourceFactory->createFileReferenceObject(
234 [
235 'uid_local' => $file->getUid(),
236 'uid_foreign' => uniqid('NEW_'),
237 'uid' => uniqid('NEW_'),
238 'crop' => null,
239 ]
240 );
241 return $this->createFileReferenceFromFalFileReferenceObject($fileReference, $resourcePointer);
242 }
243
244 /**
245 * @param CoreFileReference $falFileReference
246 * @param int $resourcePointer
247 * @return ExtbaseFileReference
248 */
249 protected function createFileReferenceFromFalFileReferenceObject(
250 CoreFileReference $falFileReference,
251 int $resourcePointer = null
252 ): ExtbaseFileReference {
253 if ($resourcePointer === null) {
254 $fileReference = $this->objectManager->get(ExtbaseFileReference::class);
255 } else {
256 $fileReference = $this->persistenceManager->getObjectByIdentifier($resourcePointer, ExtbaseFileReference::class, false);
257 }
258
259 $fileReference->setOriginalResource($falFileReference);
260 return $fileReference;
261 }
262
263 /**
264 * Returns a human-readable message for the given PHP file upload error
265 * constant.
266 *
267 * @param int $errorCode
268 * @return string
269 */
270 protected function getUploadErrorMessage(int $errorCode): string
271 {
272 switch ($errorCode) {
273 case \UPLOAD_ERR_INI_SIZE:
274 return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
275 case \UPLOAD_ERR_FORM_SIZE:
276 return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
277 case \UPLOAD_ERR_PARTIAL:
278 return 'The uploaded file was only partially uploaded';
279 case \UPLOAD_ERR_NO_FILE:
280 return 'No file was uploaded';
281 case \UPLOAD_ERR_NO_TMP_DIR:
282 return 'Missing a temporary folder';
283 case \UPLOAD_ERR_CANT_WRITE:
284 return 'Failed to write file to disk';
285 case \UPLOAD_ERR_EXTENSION:
286 return 'File upload stopped by extension';
287 default:
288 return 'Unknown upload error';
289 }
290 }
291 }