[TASK] Replace further usages with Environment API
[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 * @throws \BadMethodCallException
171 */
172 public function setContents($contents)
173 {
174 throw new \BadMethodCallException('Setting contents not possible for processed file.', 1305438528);
175 }
176
177 /**
178 * Injects a local file, which is a processing result into the object.
179 *
180 * @param string $filePath
181 * @throws \RuntimeException
182 */
183 public function updateWithLocalFile($filePath)
184 {
185 if ($this->identifier === null) {
186 throw new \RuntimeException('Cannot update original file!', 1350582054);
187 }
188 $processingFolder = $this->originalFile->getStorage()->getProcessingFolder($this->originalFile);
189 $addedFile = $this->storage->updateProcessedFile($filePath, $this, $processingFolder);
190
191 // Update some related properties
192 $this->identifier = $addedFile->getIdentifier();
193 $this->originalFileSha1 = $this->originalFile->getSha1();
194 if ($addedFile instanceof AbstractFile) {
195 $this->updateProperties($addedFile->getProperties());
196 }
197 $this->deleted = false;
198 $this->updated = true;
199 }
200
201 /*****************************************
202 * STORAGE AND MANAGEMENT RELATED METHDOS
203 *****************************************/
204 /**
205 * Returns TRUE if this file is indexed
206 *
207 * @return bool
208 */
209 public function isIndexed()
210 {
211 // Processed files are never indexed; instead you might be looking for isPersisted()
212 return false;
213 }
214
215 /**
216 * Checks whether the ProcessedFile already has an entry in sys_file_processedfile table
217 *
218 * @return bool
219 */
220 public function isPersisted()
221 {
222 return is_array($this->properties) && array_key_exists('uid', $this->properties) && $this->properties['uid'] > 0;
223 }
224
225 /**
226 * Checks whether the ProcessedFile Object is newly created
227 *
228 * @return bool
229 */
230 public function isNew()
231 {
232 return !$this->isPersisted();
233 }
234
235 /**
236 * Checks whether the object since last reconstitution, and therefore
237 * needs persistence again
238 *
239 * @return bool
240 */
241 public function isUpdated()
242 {
243 return $this->updated;
244 }
245
246 /**
247 * Sets a new file name
248 *
249 * @param string $name
250 */
251 public function setName($name)
252 {
253 // Remove the existing file
254 if ($this->name !== $name && $this->name !== '' && $this->exists()) {
255 $this->delete();
256 }
257
258 $this->name = $name;
259 // @todo this is a *weird* hack that will fail if the storage is non-hierarchical!
260 $this->identifier = $this->storage->getProcessingFolder($this->originalFile)->getIdentifier() . $this->name;
261
262 $this->updated = true;
263 }
264
265 /******************
266 * SPECIAL METHODS
267 ******************/
268
269 /**
270 * Returns TRUE if this file is already processed.
271 *
272 * @return bool
273 */
274 public function isProcessed()
275 {
276 return $this->updated || ($this->isPersisted() && !$this->needsReprocessing());
277 }
278
279 /**
280 * Getter for the Original, unprocessed File
281 *
282 * @return File
283 */
284 public function getOriginalFile()
285 {
286 return $this->originalFile;
287 }
288
289 /**
290 * Get the identifier of the file
291 *
292 * If there is no processed file in the file system (as the original file did not have to be modified e.g.
293 * when the original image is in the boundaries of the maxW/maxH stuff), then just return the identifier of
294 * the original file
295 *
296 * @return string
297 */
298 public function getIdentifier()
299 {
300 return (!$this->usesOriginalFile()) ? $this->identifier : $this->getOriginalFile()->getIdentifier();
301 }
302
303 /**
304 * Get the name of the file
305 *
306 * If there is no processed file in the file system (as the original file did not have to be modified e.g.
307 * when the original image is in the boundaries of the maxW/maxH stuff)
308 * then just return the name of the original file
309 *
310 * @return string
311 */
312 public function getName()
313 {
314 if ($this->usesOriginalFile()) {
315 return $this->originalFile->getName();
316 }
317 return $this->name;
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 = [];
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, [
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 * Defines that the original file should be used.
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 }
434 return true;
435 }
436
437 /**
438 * Getter for file-properties
439 *
440 * @param string $key
441 *
442 * @return mixed
443 */
444 public function getProperty($key)
445 {
446 // The uid always (!) has to come from this file and never the original file (see getOriginalFile() to get this)
447 if ($this->isUnchanged() && $key !== 'uid') {
448 return $this->originalFile->getProperty($key);
449 }
450 return $this->properties[$key];
451 }
452
453 /**
454 * Returns the uid of this file
455 *
456 * @return int
457 */
458 public function getUid()
459 {
460 return $this->properties['uid'];
461 }
462
463 /**
464 * Checks if the ProcessedFile needs reprocessing
465 *
466 * @return bool
467 */
468 public function needsReprocessing()
469 {
470 $fileMustBeRecreated = false;
471
472 // if original is missing we can not reprocess the file
473 if ($this->originalFile->isMissing()) {
474 return false;
475 }
476
477 // processedFile does not exist
478 if (!$this->usesOriginalFile() && !$this->exists()) {
479 $fileMustBeRecreated = true;
480 }
481
482 // hash does not match
483 if (array_key_exists('checksum', $this->properties) && $this->calculateChecksum() !== $this->properties['checksum']) {
484 $fileMustBeRecreated = true;
485 }
486
487 // original file changed
488 if ($this->originalFile->getSha1() !== $this->originalFileSha1) {
489 $fileMustBeRecreated = true;
490 }
491
492 if (!array_key_exists('uid', $this->properties)) {
493 $fileMustBeRecreated = true;
494 }
495
496 // remove outdated file
497 if ($fileMustBeRecreated && $this->exists()) {
498 $this->delete();
499 }
500 return $fileMustBeRecreated;
501 }
502
503 /**
504 * Returns the processing information
505 *
506 * @return array
507 */
508 public function getProcessingConfiguration()
509 {
510 return $this->processingConfiguration;
511 }
512
513 /**
514 * Getter for the task identifier.
515 *
516 * @return string
517 */
518 public function getTaskIdentifier()
519 {
520 return $this->taskType;
521 }
522
523 /**
524 * Returns the task object associated with this processed file.
525 *
526 * @return Processing\TaskInterface
527 * @throws \RuntimeException
528 */
529 public function getTask()
530 {
531 if ($this->task == null) {
532 $this->task = $this->taskTypeRegistry->getTaskForType($this->taskType, $this, $this->processingConfiguration);
533 }
534
535 return $this->task;
536 }
537
538 /**
539 * Generate the name of of the new File
540 *
541 * @return string
542 */
543 public function generateProcessedFileNameWithoutExtension()
544 {
545 $name = $this->originalFile->getNameWithoutExtension();
546 $name .= '_' . $this->originalFile->getUid();
547 $name .= '_' . $this->calculateChecksum();
548
549 return $name;
550 }
551
552 /**
553 * Returns a publicly accessible URL for this file
554 *
555 * @param bool $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all
556 * @return string|null NULL if file is deleted, the generated URL otherwise
557 */
558 public function getPublicUrl($relativeToCurrentScript = false)
559 {
560 if ($this->deleted) {
561 return null;
562 }
563 if ($this->usesOriginalFile()) {
564 return $this->getOriginalFile()->getPublicUrl($relativeToCurrentScript);
565 }
566 return $this->getStorage()->getPublicUrl($this, $relativeToCurrentScript);
567 }
568 }