711962045a89fba1d81abe804878617d346638a2
[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 $this->processingConfiguration = $processingConfiguration;
122 if (is_array($databaseRow)) {
123 $this->reconstituteFromDatabaseRecord($databaseRow);
124 }
125 $this->taskTypeRegistry = GeneralUtility::makeInstance(Processing\TaskTypeRegistry::class);
126 }
127
128 /**
129 * Creates a ProcessedFile object from a database record.
130 *
131 * @param array $databaseRow
132 */
133 protected function reconstituteFromDatabaseRecord(array $databaseRow)
134 {
135 $this->taskType = $this->taskType ?: $databaseRow['task_type'];
136 $this->processingConfiguration = $this->processingConfiguration ?: unserialize($databaseRow['configuration']);
137
138 $this->originalFileSha1 = $databaseRow['originalfilesha1'];
139 $this->identifier = $databaseRow['identifier'];
140 $this->name = $databaseRow['name'];
141 $this->properties = $databaseRow;
142
143 if (!empty($databaseRow['storage']) && (int)$this->storage->getUid() !== (int)$databaseRow['storage']) {
144 $this->storage = ResourceFactory::getInstance()->getStorageObject($databaseRow['storage']);
145 }
146 }
147
148 /********************************
149 * VARIOUS FILE PROPERTY GETTERS
150 ********************************/
151
152 /**
153 * Returns a unique checksum for this file's processing configuration and original file.
154 *
155 * @return string
156 */
157 // @todo replace these usages with direct calls to the task object
158 public function calculateChecksum()
159 {
160 return $this->getTask()->getConfigurationChecksum();
161 }
162
163 /*******************
164 * CONTENTS RELATED
165 *******************/
166 /**
167 * Replace the current file contents with the given string
168 *
169 * @param string $contents The contents to write to the file.
170 * @return File The file object (allows chaining).
171 * @throws \BadMethodCallException
172 */
173 public function setContents($contents)
174 {
175 throw new \BadMethodCallException('Setting contents not possible for processed file.', 1305438528);
176 }
177
178 /**
179 * Injects a local file, which is a processing result into the object.
180 *
181 * @param string $filePath
182 * @throws \RuntimeException
183 */
184 public function updateWithLocalFile($filePath)
185 {
186 if ($this->identifier === null) {
187 throw new \RuntimeException('Cannot update original file!', 1350582054);
188 }
189 $processingFolder = $this->originalFile->getStorage()->getProcessingFolder($this->originalFile);
190 $addedFile = $this->storage->updateProcessedFile($filePath, $this, $processingFolder);
191
192 // Update some related properties
193 $this->identifier = $addedFile->getIdentifier();
194 $this->originalFileSha1 = $this->originalFile->getSha1();
195 if ($addedFile instanceof AbstractFile) {
196 $this->updateProperties($addedFile->getProperties());
197 }
198 $this->deleted = false;
199 $this->updated = true;
200 }
201
202 /*****************************************
203 * STORAGE AND MANAGEMENT RELATED METHDOS
204 *****************************************/
205 /**
206 * Returns TRUE if this file is indexed
207 *
208 * @return bool
209 */
210 public function isIndexed()
211 {
212 // Processed files are never indexed; instead you might be looking for isPersisted()
213 return false;
214 }
215
216 /**
217 * Checks whether the ProcessedFile already has an entry in sys_file_processedfile table
218 *
219 * @return bool
220 */
221 public function isPersisted()
222 {
223 return is_array($this->properties) && array_key_exists('uid', $this->properties) && $this->properties['uid'] > 0;
224 }
225
226 /**
227 * Checks whether the ProcessedFile Object is newly created
228 *
229 * @return bool
230 */
231 public function isNew()
232 {
233 return !$this->isPersisted();
234 }
235
236 /**
237 * Checks whether the object since last reconstitution, and therefore
238 * needs persistence again
239 *
240 * @return bool
241 */
242 public function isUpdated()
243 {
244 return $this->updated;
245 }
246
247 /**
248 * Sets a new file name
249 *
250 * @param string $name
251 */
252 public function setName($name)
253 {
254 // Remove the existing file
255 if ($this->name !== $name && $this->name !== '' && $this->exists()) {
256 $this->delete();
257 }
258
259 $this->name = $name;
260 // @todo this is a *weird* hack that will fail if the storage is non-hierarchical!
261 $this->identifier = $this->storage->getProcessingFolder($this->originalFile)->getIdentifier() . $this->name;
262
263 $this->updated = true;
264 }
265
266 /******************
267 * SPECIAL METHODS
268 ******************/
269
270 /**
271 * Returns TRUE if this file is already processed.
272 *
273 * @return bool
274 */
275 public function isProcessed()
276 {
277 return $this->updated || ($this->isPersisted() && !$this->needsReprocessing());
278 }
279
280 /**
281 * Getter for the Original, unprocessed File
282 *
283 * @return File
284 */
285 public function getOriginalFile()
286 {
287 return $this->originalFile;
288 }
289
290 /**
291 * Get the identifier of the file
292 *
293 * If there is no processed file in the file system (as the original file did not have to be modified e.g.
294 * when the original image is in the boundaries of the maxW/maxH stuff), then just return the identifier of
295 * the original file
296 *
297 * @return string
298 */
299 public function getIdentifier()
300 {
301 return (!$this->usesOriginalFile()) ? $this->identifier : $this->getOriginalFile()->getIdentifier();
302 }
303
304 /**
305 * Get the name of the file
306 *
307 * If there is no processed file in the file system (as the original file did not have to be modified e.g.
308 * when the original image is in the boundaries of the maxW/maxH stuff)
309 * then just return the name of the original file
310 *
311 * @return string
312 */
313 public function getName()
314 {
315 if ($this->usesOriginalFile()) {
316 return $this->originalFile->getName();
317 }
318 return $this->name;
319 }
320
321 /**
322 * Updates properties of this object. Do not use this to reconstitute an object from the database; use
323 * reconstituteFromDatabaseRecord() instead!
324 *
325 * @param array $properties
326 */
327 public function updateProperties(array $properties)
328 {
329 if (!is_array($this->properties)) {
330 $this->properties = [];
331 }
332
333 if (array_key_exists('uid', $properties) && MathUtility::canBeInterpretedAsInteger($properties['uid'])) {
334 $this->properties['uid'] = $properties['uid'];
335 }
336
337 // @todo we should have a blacklist of properties that might not be updated
338 $this->properties = array_merge($this->properties, $properties);
339
340 // @todo when should this update be done?
341 if (!$this->isUnchanged() && $this->exists()) {
342 $this->properties = array_merge($this->properties, $this->storage->getFileInfo($this));
343 }
344 }
345
346 /**
347 * Basic array function for the DB update
348 *
349 * @return array
350 */
351 public function toArray()
352 {
353 if ($this->usesOriginalFile()) {
354 $properties = $this->originalFile->getProperties();
355 unset($properties['uid']);
356 unset($properties['pid']);
357 unset($properties['identifier']);
358 unset($properties['name']);
359
360 // Use width + height set in processed file
361 $properties['width'] = $this->properties['width'];
362 $properties['height'] = $this->properties['height'];
363 } else {
364 $properties = $this->properties;
365 $properties['identifier'] = $this->getIdentifier();
366 $properties['name'] = $this->getName();
367 }
368
369 $properties['configuration'] = serialize($this->processingConfiguration);
370
371 return array_merge($properties, [
372 'storage' => $this->getStorage()->getUid(),
373 'checksum' => $this->calculateChecksum(),
374 'task_type' => $this->taskType,
375 'configurationsha1' => sha1($properties['configuration']),
376 'original' => $this->originalFile->getUid(),
377 'originalfilesha1' => $this->originalFileSha1
378 ]);
379 }
380
381 /**
382 * Returns TRUE if this file has not been changed during processing (i.e., we just deliver the original file)
383 *
384 * @return bool
385 */
386 protected function isUnchanged()
387 {
388 return !$this->properties['width'] && $this->usesOriginalFile();
389 }
390
391 /**
392 * Defines that the original file should be used.
393 */
394 public function setUsesOriginalFile()
395 {
396 // @todo check if some of these properties can/should be set in a generic update method
397 $this->identifier = $this->originalFile->getIdentifier();
398 $this->updated = true;
399 $this->originalFileSha1 = $this->originalFile->getSha1();
400 }
401
402 /**
403 * @return bool
404 */
405 public function usesOriginalFile()
406 {
407 return $this->identifier == null || $this->identifier === $this->originalFile->getIdentifier();
408 }
409
410 /**
411 * Returns TRUE if the original file of this file changed and the file should be processed again.
412 *
413 * @return bool
414 */
415 public function isOutdated()
416 {
417 return $this->needsReprocessing();
418 }
419
420 /**
421 * Delete processed file
422 *
423 * @param bool $force
424 * @return bool
425 */
426 public function delete($force = false)
427 {
428 if (!$force && $this->isUnchanged()) {
429 return false;
430 }
431 // Only delete file when original isn't used
432 if (!$this->usesOriginalFile()) {
433 return parent::delete();
434 }
435 return true;
436 }
437
438 /**
439 * Getter for file-properties
440 *
441 * @param string $key
442 *
443 * @return mixed
444 */
445 public function getProperty($key)
446 {
447 // The uid always (!) has to come from this file and never the original file (see getOriginalFile() to get this)
448 if ($this->isUnchanged() && $key !== 'uid') {
449 return $this->originalFile->getProperty($key);
450 }
451 return $this->properties[$key];
452 }
453
454 /**
455 * Returns the uid of this file
456 *
457 * @return int
458 */
459 public function getUid()
460 {
461 return $this->properties['uid'];
462 }
463
464 /**
465 * Checks if the ProcessedFile needs reprocessing
466 *
467 * @return bool
468 */
469 public function needsReprocessing()
470 {
471 $fileMustBeRecreated = false;
472
473 // if original is missing we can not reprocess the file
474 if ($this->originalFile->isMissing()) {
475 return false;
476 }
477
478 // processedFile does not exist
479 if (!$this->usesOriginalFile() && !$this->exists()) {
480 $fileMustBeRecreated = true;
481 }
482
483 // hash does not match
484 if (array_key_exists('checksum', $this->properties) && $this->calculateChecksum() !== $this->properties['checksum']) {
485 $fileMustBeRecreated = true;
486 }
487
488 // original file changed
489 if ($this->originalFile->getSha1() !== $this->originalFileSha1) {
490 $fileMustBeRecreated = true;
491 }
492
493 if (!array_key_exists('uid', $this->properties)) {
494 $fileMustBeRecreated = true;
495 }
496
497 // remove outdated file
498 if ($fileMustBeRecreated && $this->exists()) {
499 $this->delete();
500 }
501 return $fileMustBeRecreated;
502 }
503
504 /**
505 * Returns the processing information
506 *
507 * @return array
508 */
509 public function getProcessingConfiguration()
510 {
511 return $this->processingConfiguration;
512 }
513
514 /**
515 * Getter for the task identifier.
516 *
517 * @return string
518 */
519 public function getTaskIdentifier()
520 {
521 return $this->taskType;
522 }
523
524 /**
525 * Returns the task object associated with this processed file.
526 *
527 * @return Processing\TaskInterface
528 * @throws \RuntimeException
529 */
530 public function getTask()
531 {
532 if ($this->task == null) {
533 $this->task = $this->taskTypeRegistry->getTaskForType($this->taskType, $this, $this->processingConfiguration);
534 }
535
536 return $this->task;
537 }
538
539 /**
540 * Generate the name of of the new File
541 *
542 * @return string
543 */
544 public function generateProcessedFileNameWithoutExtension()
545 {
546 $name = $this->originalFile->getNameWithoutExtension();
547 $name .= '_' . $this->originalFile->getUid();
548 $name .= '_' . $this->calculateChecksum();
549
550 return $name;
551 }
552
553 /**
554 * Returns a publicly accessible URL for this file
555 *
556 * @param bool $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all
557 * @return string|null NULL if file is deleted, the generated URL otherwise
558 */
559 public function getPublicUrl($relativeToCurrentScript = false)
560 {
561 if ($this->deleted) {
562 return null;
563 }
564 if ($this->usesOriginalFile()) {
565 return $this->getOriginalFile()->getPublicUrl($relativeToCurrentScript);
566 }
567 return $this->getStorage()->getPublicUrl($this, $relativeToCurrentScript);
568 }
569 }