[CLEANUP] The correct case must be used for standard PHP types in phpdoc
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Resource / ProcessedFile.php
1 <?php
2 namespace TYPO3\CMS\Core\Resource;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\GeneralUtility;
18 use TYPO3\CMS\Core\Utility\MathUtility;
19
20 /**
21 * Representation of a specific processed version of a file. These are created by the FileProcessingService,
22 * which in turn uses helper classes for doing the actual file processing. See there for a detailed description.
23 *
24 * Objects of this class may be freshly created during runtime or being fetched from the database. The latter
25 * indicates that the file has been processed earlier and was then cached.
26 *
27 * Each processed file—besides belonging to one file—has been created for a certain task (context) and
28 * configuration. All these won't change during the lifetime of a processed file; the only thing
29 * that can change is the original file, or rather it's contents. In that case, the processed file has to
30 * be processed again. Detecting this is done via comparing the current SHA1 hash of the original file against
31 * the one it had at the time the file was processed.
32 * The configuration of a processed file indicates what should be done to the original file to create the
33 * processed version. This may include things like cropping, scaling, rotating, flipping or using some special
34 * magic.
35 * A file may also meet the expectations set in the configuration without any processing. In that case, the
36 * ProcessedFile object still exists, but there is no physical file directly linked to it. Instead, it then
37 * redirects most method calls to the original file object. The data of these objects are also stored in the
38 * database, to indicate that no processing is required. With such files, the identifier and name fields in the
39 * database are empty to show this.
40 */
41 class ProcessedFile extends AbstractFile
42 {
43 /*********************************************
44 * FILE PROCESSING CONTEXTS
45 *********************************************/
46 /**
47 * Basic processing context to get a processed image with smaller
48 * width/height to render a preview
49 */
50 const CONTEXT_IMAGEPREVIEW = 'Image.Preview';
51 /**
52 * Standard processing context for the frontend, that was previously
53 * in \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getImgResource which only takes cropping, masking and scaling
54 * into account
55 */
56 const CONTEXT_IMAGECROPSCALEMASK = 'Image.CropScaleMask';
57
58 /**
59 * Processing context, i.e. the type of processing done
60 *
61 * @var string
62 */
63 protected $taskType;
64
65 /**
66 * @var Processing\TaskInterface
67 */
68 protected $task;
69
70 /**
71 * @var Processing\TaskTypeRegistry
72 */
73 protected $taskTypeRegistry;
74
75 /**
76 * Processing configuration
77 *
78 * @var array
79 */
80 protected $processingConfiguration;
81
82 /**
83 * Reference to the original file this processed file has been created from.
84 *
85 * @var File
86 */
87 protected $originalFile;
88
89 /**
90 * The SHA1 hash of the original file this processed version has been created for.
91 * Is used for detecting changes if the original file has been changed and thus
92 * we have to recreate this processed file.
93 *
94 * @var string
95 */
96 protected $originalFileSha1;
97
98 /**
99 * A flag that shows if this object has been updated during its lifetime, i.e. the file has been
100 * replaced with a new one.
101 *
102 * @var bool
103 */
104 protected $updated = false;
105
106 /**
107 * Constructor for a processed file object. Should normally not be used
108 * directly, use the corresponding factory methods instead.
109 *
110 * @param File $originalFile
111 * @param string $taskType
112 * @param array $processingConfiguration
113 * @param array $databaseRow
114 */
115 public function __construct(File $originalFile, $taskType, array $processingConfiguration, array $databaseRow = null)
116 {
117 $this->originalFile = $originalFile;
118 $this->originalFileSha1 = $this->originalFile->getSha1();
119 $this->storage = $originalFile->getStorage()->getProcessingFolder()->getStorage();
120 $this->taskType = $taskType;
121 if ($taskType === self::CONTEXT_IMAGEPREVIEW) {
122 $processingConfiguration = array_merge(['width' => 64, 'height' => 64], $processingConfiguration);
123 $processingConfiguration['width'] = MathUtility::forceIntegerInRange($processingConfiguration['width'], 1, 1000);
124 $processingConfiguration['height'] = MathUtility::forceIntegerInRange($processingConfiguration['height'], 1, 1000);
125 }
126 $this->processingConfiguration = $processingConfiguration;
127 if (is_array($databaseRow)) {
128 $this->reconstituteFromDatabaseRecord($databaseRow);
129 }
130 $this->taskTypeRegistry = GeneralUtility::makeInstance(Processing\TaskTypeRegistry::class);
131 }
132
133 /**
134 * Creates a ProcessedFile object from a database record.
135 *
136 * @param array $databaseRow
137 * @return ProcessedFile
138 */
139 protected function reconstituteFromDatabaseRecord(array $databaseRow)
140 {
141 $this->taskType = $this->taskType ?: $databaseRow['task_type'];
142 $this->processingConfiguration = $this->processingConfiguration ?: unserialize($databaseRow['configuration']);
143
144 $this->originalFileSha1 = $databaseRow['originalfilesha1'];
145 $this->identifier = $databaseRow['identifier'];
146 $this->name = $databaseRow['name'];
147 $this->properties = $databaseRow;
148 }
149
150 /********************************
151 * VARIOUS FILE PROPERTY GETTERS
152 ********************************/
153
154 /**
155 * Returns a unique checksum for this file's processing configuration and original file.
156 *
157 * @return string
158 */
159 // @todo replace these usages with direct calls to the task object
160 public function calculateChecksum()
161 {
162 return $this->getTask()->getConfigurationChecksum();
163 }
164
165 /*******************
166 * CONTENTS RELATED
167 *******************/
168 /**
169 * Replace the current file contents with the given string
170 *
171 * @param string $contents The contents to write to the file.
172 * @return File The file object (allows chaining).
173 * @throws \BadMethodCallException
174 */
175 public function setContents($contents)
176 {
177 throw new \BadMethodCallException('Setting contents not possible for processed file.', 1305438528);
178 }
179
180 /**
181 * Injects a local file, which is a processing result into the object.
182 *
183 * @param string $filePath
184 * @throws \RuntimeException
185 */
186 public function updateWithLocalFile($filePath)
187 {
188 if ($this->identifier === null) {
189 throw new \RuntimeException('Cannot update original file!', 1350582054);
190 }
191 $processingFolder = $this->originalFile->getStorage()->getProcessingFolder($this->originalFile);
192 $addedFile = $this->storage->updateProcessedFile($filePath, $this, $processingFolder);
193
194 // Update some related properties
195 $this->identifier = $addedFile->getIdentifier();
196 $this->originalFileSha1 = $this->originalFile->getSha1();
197 if ($addedFile instanceof AbstractFile) {
198 $this->updateProperties($addedFile->getProperties());
199 }
200 $this->deleted = false;
201 $this->updated = true;
202 }
203
204 /*****************************************
205 * STORAGE AND MANAGEMENT RELATED METHDOS
206 *****************************************/
207 /**
208 * Returns TRUE if this file is indexed
209 *
210 * @return bool
211 */
212 public function isIndexed()
213 {
214 // Processed files are never indexed; instead you might be looking for isPersisted()
215 return false;
216 }
217
218 /**
219 * Checks whether the ProcessedFile already has an entry in sys_file_processedfile table
220 *
221 * @return bool
222 */
223 public function isPersisted()
224 {
225 return is_array($this->properties) && array_key_exists('uid', $this->properties) && $this->properties['uid'] > 0;
226 }
227
228 /**
229 * Checks whether the ProcessedFile Object is newly created
230 *
231 * @return bool
232 */
233 public function isNew()
234 {
235 return !$this->isPersisted();
236 }
237
238 /**
239 * Checks whether the object since last reconstitution, and therefore
240 * needs persistence again
241 *
242 * @return bool
243 */
244 public function isUpdated()
245 {
246 return $this->updated;
247 }
248
249 /**
250 * Sets a new file name
251 *
252 * @param string $name
253 */
254 public function setName($name)
255 {
256 // Remove the existing file
257 if ($this->name !== $name && $this->name !== '' && $this->exists()) {
258 $this->delete();
259 }
260
261 $this->name = $name;
262 // @todo this is a *weird* hack that will fail if the storage is non-hierarchical!
263 $this->identifier = $this->storage->getProcessingFolder($this->originalFile)->getIdentifier() . $this->name;
264
265 $this->updated = true;
266 }
267
268 /******************
269 * SPECIAL METHODS
270 ******************/
271
272 /**
273 * Returns TRUE if this file is already processed.
274 *
275 * @return bool
276 */
277 public function isProcessed()
278 {
279 return $this->updated || ($this->isPersisted() && !$this->needsReprocessing());
280 }
281
282 /**
283 * Getter for the Original, unprocessed File
284 *
285 * @return File
286 */
287 public function getOriginalFile()
288 {
289 return $this->originalFile;
290 }
291
292 /**
293 * Get the identifier of the file
294 *
295 * If there is no processed file in the file system (as the original file did not have to be modified e.g.
296 * when the original image is in the boundaries of the maxW/maxH stuff), then just return the identifier of
297 * the original file
298 *
299 * @return string
300 */
301 public function getIdentifier()
302 {
303 return (!$this->usesOriginalFile()) ? $this->identifier : $this->getOriginalFile()->getIdentifier();
304 }
305
306 /**
307 * Get the name of the file
308 *
309 * If there is no processed file in the file system (as the original file did not have to be modified e.g.
310 * when the original image is in the boundaries of the maxW/maxH stuff)
311 * then just return the name of the original file
312 *
313 * @return string
314 */
315 public function getName()
316 {
317 if ($this->usesOriginalFile()) {
318 return $this->originalFile->getName();
319 }
320 return $this->name;
321 }
322
323 /**
324 * Updates properties of this object. Do not use this to reconstitute an object from the database; use
325 * reconstituteFromDatabaseRecord() instead!
326 *
327 * @param array $properties
328 */
329 public function updateProperties(array $properties)
330 {
331 if (!is_array($this->properties)) {
332 $this->properties = [];
333 }
334
335 if (array_key_exists('uid', $properties) && MathUtility::canBeInterpretedAsInteger($properties['uid'])) {
336 $this->properties['uid'] = $properties['uid'];
337 }
338
339 // @todo we should have a blacklist of properties that might not be updated
340 $this->properties = array_merge($this->properties, $properties);
341
342 // @todo when should this update be done?
343 if (!$this->isUnchanged() && $this->exists()) {
344 $this->properties = array_merge($this->properties, $this->storage->getFileInfo($this));
345 }
346 }
347
348 /**
349 * Basic array function for the DB update
350 *
351 * @return array
352 */
353 public function toArray()
354 {
355 if ($this->usesOriginalFile()) {
356 $properties = $this->originalFile->getProperties();
357 unset($properties['uid']);
358 unset($properties['pid']);
359 unset($properties['identifier']);
360 unset($properties['name']);
361
362 // Use width + height set in processed file
363 $properties['width'] = $this->properties['width'];
364 $properties['height'] = $this->properties['height'];
365 } else {
366 $properties = $this->properties;
367 $properties['identifier'] = $this->getIdentifier();
368 $properties['name'] = $this->getName();
369 }
370
371 $properties['configuration'] = serialize($this->processingConfiguration);
372
373 return array_merge($properties, [
374 'storage' => $this->getStorage()->getUid(),
375 'checksum' => $this->calculateChecksum(),
376 'task_type' => $this->taskType,
377 'configurationsha1' => sha1($properties['configuration']),
378 'original' => $this->originalFile->getUid(),
379 'originalfilesha1' => $this->originalFileSha1
380 ]);
381 }
382
383 /**
384 * Returns TRUE if this file has not been changed during processing (i.e., we just deliver the original file)
385 *
386 * @return bool
387 */
388 protected function isUnchanged()
389 {
390 return !$this->properties['width'] && $this->usesOriginalFile();
391 }
392
393 /**
394 * Defines that the original file should be used.
395 */
396 public function setUsesOriginalFile()
397 {
398 // @todo check if some of these properties can/should be set in a generic update method
399 $this->identifier = $this->originalFile->getIdentifier();
400 $this->updated = true;
401 $this->originalFileSha1 = $this->originalFile->getSha1();
402 }
403
404 /**
405 * @return bool
406 */
407 public function usesOriginalFile()
408 {
409 return $this->identifier == null || $this->identifier === $this->originalFile->getIdentifier();
410 }
411
412 /**
413 * Returns TRUE if the original file of this file changed and the file should be processed again.
414 *
415 * @return bool
416 */
417 public function isOutdated()
418 {
419 return $this->needsReprocessing();
420 }
421
422 /**
423 * Delete processed file
424 *
425 * @param bool $force
426 * @return bool
427 */
428 public function delete($force = false)
429 {
430 if (!$force && $this->isUnchanged()) {
431 return false;
432 }
433 // Only delete file when original isn't used
434 if (!$this->usesOriginalFile()) {
435 return parent::delete();
436 }
437 return true;
438 }
439
440 /**
441 * Getter for file-properties
442 *
443 * @param string $key
444 *
445 * @return mixed
446 */
447 public function getProperty($key)
448 {
449 // The uid always (!) has to come from this file and never the original file (see getOriginalFile() to get this)
450 if ($this->isUnchanged() && $key !== 'uid') {
451 return $this->originalFile->getProperty($key);
452 }
453 return $this->properties[$key];
454 }
455
456 /**
457 * Returns the uid of this file
458 *
459 * @return int
460 */
461 public function getUid()
462 {
463 return $this->properties['uid'];
464 }
465
466 /**
467 * Checks if the ProcessedFile needs reprocessing
468 *
469 * @return bool
470 */
471 public function needsReprocessing()
472 {
473 $fileMustBeRecreated = false;
474
475 // if original is missing we can not reprocess the file
476 if ($this->originalFile->isMissing()) {
477 return false;
478 }
479
480 // processedFile does not exist
481 if (!$this->usesOriginalFile() && !$this->exists()) {
482 $fileMustBeRecreated = true;
483 }
484
485 // hash does not match
486 if (array_key_exists('checksum', $this->properties) && $this->calculateChecksum() !== $this->properties['checksum']) {
487 $fileMustBeRecreated = true;
488 }
489
490 // original file changed
491 if ($this->originalFile->getSha1() !== $this->originalFileSha1) {
492 $fileMustBeRecreated = true;
493 }
494
495 if (!array_key_exists('uid', $this->properties)) {
496 $fileMustBeRecreated = true;
497 }
498
499 // remove outdated file
500 if ($fileMustBeRecreated && $this->exists()) {
501 $this->delete();
502 }
503 return $fileMustBeRecreated;
504 }
505
506 /**
507 * Returns the processing information
508 *
509 * @return array
510 */
511 public function getProcessingConfiguration()
512 {
513 return $this->processingConfiguration;
514 }
515
516 /**
517 * Getter for the task identifier.
518 *
519 * @return string
520 */
521 public function getTaskIdentifier()
522 {
523 return $this->taskType;
524 }
525
526 /**
527 * Returns the task object associated with this processed file.
528 *
529 * @return Processing\TaskInterface
530 * @throws \RuntimeException
531 */
532 public function getTask()
533 {
534 if ($this->task == null) {
535 $this->task = $this->taskTypeRegistry->getTaskForType($this->taskType, $this, $this->processingConfiguration);
536 }
537
538 return $this->task;
539 }
540
541 /**
542 * Generate the name of of the new File
543 *
544 * @return string
545 */
546 public function generateProcessedFileNameWithoutExtension()
547 {
548 $name = $this->originalFile->getNameWithoutExtension();
549 $name .= '_' . $this->originalFile->getUid();
550 $name .= '_' . $this->calculateChecksum();
551
552 return $name;
553 }
554
555 /**
556 * Returns a publicly accessible URL for this file
557 *
558 * @param bool $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all
559 * @return null|string NULL if file is deleted, the generated URL otherwise
560 */
561 public function getPublicUrl($relativeToCurrentScript = false)
562 {
563 if ($this->deleted) {
564 return null;
565 }
566 if ($this->usesOriginalFile()) {
567 return $this->getOriginalFile()->getPublicUrl($relativeToCurrentScript);
568 }
569 return $this->getStorage()->getPublicUrl($this, $relativeToCurrentScript);
570 }
571 }