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