[BUGFIX] Use renamed folder object in postRename signal
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Resource / ResourceStorage.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 Psr\Http\Message\ResponseInterface;
18 use TYPO3\CMS\Core\Core\Environment;
19 use TYPO3\CMS\Core\Database\ConnectionPool;
20 use TYPO3\CMS\Core\Http\FalDumpFileContentsDecoratorStream;
21 use TYPO3\CMS\Core\Http\Response;
22 use TYPO3\CMS\Core\Log\LogManager;
23 use TYPO3\CMS\Core\Registry;
24 use TYPO3\CMS\Core\Resource\Driver\StreamableDriverInterface;
25 use TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException;
26 use TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException;
27 use TYPO3\CMS\Core\Resource\Index\FileIndexRepository;
28 use TYPO3\CMS\Core\Resource\OnlineMedia\Helpers\OnlineMediaHelperRegistry;
29 use TYPO3\CMS\Core\Utility\Exception\NotImplementedMethodException;
30 use TYPO3\CMS\Core\Utility\GeneralUtility;
31 use TYPO3\CMS\Core\Utility\PathUtility;
32 use TYPO3\CMS\Extbase\Object\ObjectManager;
33 use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
34
35 /**
36 * A "mount point" inside the TYPO3 file handling.
37 *
38 * A "storage" object handles
39 * - abstraction to the driver
40 * - permissions (from the driver, and from the user, + capabilities)
41 * - an entry point for files, folders, and for most other operations
42 *
43 * == Driver entry point
44 * The driver itself, that does the actual work on the file system,
45 * is inside the storage but completely shadowed by
46 * the storage, as the storage also handles the abstraction to the
47 * driver
48 *
49 * The storage can be on the local system, but can also be on a remote
50 * system. The combination of driver + configurable capabilities (storage
51 * is read-only e.g.) allows for flexible uses.
52 *
53 *
54 * == Permission system
55 * As all requests have to run through the storage, the storage knows about the
56 * permissions of a BE/FE user, the file permissions / limitations of the driver
57 * and has some configurable capabilities.
58 * Additionally, a BE user can use "filemounts" (known from previous installations)
59 * to limit his/her work-zone to only a subset (identifier and its subfolders/subfolders)
60 * of the user itself.
61 *
62 * Check 1: "User Permissions" [is the user allowed to write a file) [is the user allowed to write a file]
63 * Check 2: "File Mounts" of the User (act as subsets / filters to the identifiers) [is the user allowed to do something in this folder?]
64 * Check 3: "Capabilities" of Storage (then: of Driver) [is the storage/driver writable?]
65 * Check 4: "File permissions" of the Driver [is the folder writable?]
66 */
67 class ResourceStorage implements ResourceStorageInterface
68 {
69 /**
70 * The storage driver instance belonging to this storage.
71 *
72 * @var Driver\DriverInterface
73 */
74 protected $driver;
75
76 /**
77 * The database record for this storage
78 *
79 * @var array
80 */
81 protected $storageRecord;
82
83 /**
84 * The configuration belonging to this storage (decoded from the configuration field).
85 *
86 * @var array
87 */
88 protected $configuration;
89
90 /**
91 * @var Service\FileProcessingService
92 */
93 protected $fileProcessingService;
94
95 /**
96 * Whether to check if file or folder is in user mounts
97 * and the action is allowed for a user
98 * Default is FALSE so that resources are accessible for
99 * front end rendering or admins.
100 *
101 * @var bool
102 */
103 protected $evaluatePermissions = false;
104
105 /**
106 * User filemounts, added as an array, and used as filters
107 *
108 * @var array
109 */
110 protected $fileMounts = [];
111
112 /**
113 * The file permissions of the user (and their group) merged together and
114 * available as an array
115 *
116 * @var array
117 */
118 protected $userPermissions = [];
119
120 /**
121 * The capabilities of this storage as defined in the storage record.
122 * Also see the CAPABILITY_* constants below
123 *
124 * @var int
125 */
126 protected $capabilities;
127
128 /**
129 * @var Dispatcher
130 */
131 protected $signalSlotDispatcher;
132
133 /**
134 * @var Folder
135 */
136 protected $processingFolder;
137
138 /**
139 * All processing folders of this storage used in any storage
140 *
141 * @var Folder[]
142 */
143 protected $processingFolders;
144
145 /**
146 * whether this storage is online or offline in this request
147 *
148 * @var bool
149 */
150 protected $isOnline;
151
152 /**
153 * @var bool
154 */
155 protected $isDefault = false;
156
157 /**
158 * The filters used for the files and folder names.
159 *
160 * @var array
161 */
162 protected $fileAndFolderNameFilters = [];
163
164 /**
165 * Levels numbers used to generate hashed subfolders in the processing folder
166 */
167 const PROCESSING_FOLDER_LEVELS = 2;
168
169 /**
170 * Constructor for a storage object.
171 *
172 * @param Driver\DriverInterface $driver
173 * @param array $storageRecord The storage record row from the database
174 */
175 public function __construct(Driver\DriverInterface $driver, array $storageRecord)
176 {
177 $this->storageRecord = $storageRecord;
178 $this->configuration = $this->getResourceFactoryInstance()->convertFlexFormDataToConfigurationArray($storageRecord['configuration'] ?? '');
179 $this->capabilities =
180 ($this->storageRecord['is_browsable'] ?? null ? self::CAPABILITY_BROWSABLE : 0) |
181 ($this->storageRecord['is_public'] ?? null ? self::CAPABILITY_PUBLIC : 0) |
182 ($this->storageRecord['is_writable'] ?? null ? self::CAPABILITY_WRITABLE : 0);
183
184 $this->driver = $driver;
185 $this->driver->setStorageUid($storageRecord['uid'] ?? null);
186 $this->driver->mergeConfigurationCapabilities($this->capabilities);
187 try {
188 $this->driver->processConfiguration();
189 } catch (Exception\InvalidConfigurationException $e) {
190 // Configuration error
191 $this->isOnline = false;
192
193 $message = sprintf(
194 'Failed initializing storage [%d] "%s", error: %s',
195 $this->getUid(),
196 $this->getName(),
197 $e->getMessage()
198 );
199
200 // create a dedicated logger instance because we need a logger in the constructor
201 GeneralUtility::makeInstance(LogManager::class)->getLogger(static::class)->error($message);
202 }
203 $this->driver->initialize();
204 $this->capabilities = $this->driver->getCapabilities();
205
206 $this->isDefault = (isset($storageRecord['is_default']) && $storageRecord['is_default'] == 1);
207 $this->resetFileAndFolderNameFiltersToDefault();
208 }
209
210 /**
211 * Gets the configuration.
212 *
213 * @return array
214 */
215 public function getConfiguration()
216 {
217 return $this->configuration;
218 }
219
220 /**
221 * Sets the configuration.
222 *
223 * @param array $configuration
224 */
225 public function setConfiguration(array $configuration)
226 {
227 $this->configuration = $configuration;
228 }
229
230 /**
231 * Gets the storage record.
232 *
233 * @return array
234 */
235 public function getStorageRecord()
236 {
237 return $this->storageRecord;
238 }
239
240 /**
241 * Sets the storage that belongs to this storage.
242 *
243 * @param Driver\DriverInterface $driver
244 * @return ResourceStorage
245 */
246 public function setDriver(Driver\DriverInterface $driver)
247 {
248 $this->driver = $driver;
249 return $this;
250 }
251
252 /**
253 * Returns the driver object belonging to this storage.
254 *
255 * @return Driver\DriverInterface
256 */
257 protected function getDriver()
258 {
259 return $this->driver;
260 }
261
262 /**
263 * Returns the name of this storage.
264 *
265 * @return string
266 */
267 public function getName()
268 {
269 return $this->storageRecord['name'];
270 }
271
272 /**
273 * Returns the UID of this storage.
274 *
275 * @return int
276 */
277 public function getUid()
278 {
279 return (int)($this->storageRecord['uid'] ?? 0);
280 }
281
282 /**
283 * Tells whether there are children in this storage.
284 *
285 * @return bool
286 */
287 public function hasChildren()
288 {
289 return true;
290 }
291
292 /*********************************
293 * Capabilities
294 ********************************/
295 /**
296 * Returns the capabilities of this storage.
297 *
298 * @return int
299 * @see CAPABILITY_* constants
300 */
301 public function getCapabilities()
302 {
303 return (int)$this->capabilities;
304 }
305
306 /**
307 * Returns TRUE if this storage has the given capability.
308 *
309 * @param int $capability A capability, as defined in a CAPABILITY_* constant
310 * @return bool
311 */
312 protected function hasCapability($capability)
313 {
314 return ($this->capabilities & $capability) == $capability;
315 }
316
317 /**
318 * Returns TRUE if this storage is publicly available. This is just a
319 * configuration option and does not mean that it really *is* public. OTOH
320 * a storage that is marked as not publicly available will trigger the file
321 * publishing mechanisms of TYPO3.
322 *
323 * @return bool
324 */
325 public function isPublic()
326 {
327 return $this->hasCapability(self::CAPABILITY_PUBLIC);
328 }
329
330 /**
331 * Returns TRUE if this storage is writable. This is determined by the
332 * driver and the storage configuration; user permissions are not taken into account.
333 *
334 * @return bool
335 */
336 public function isWritable()
337 {
338 return $this->hasCapability(self::CAPABILITY_WRITABLE);
339 }
340
341 /**
342 * Returns TRUE if this storage is browsable by a (backend) user of TYPO3.
343 *
344 * @return bool
345 */
346 public function isBrowsable()
347 {
348 return $this->isOnline() && $this->hasCapability(self::CAPABILITY_BROWSABLE);
349 }
350
351 /**
352 * Returns TRUE if the identifiers used by this storage are case-sensitive.
353 *
354 * @return bool
355 */
356 public function usesCaseSensitiveIdentifiers()
357 {
358 return $this->driver->isCaseSensitiveFileSystem();
359 }
360
361 /**
362 * Returns TRUE if this storage is browsable by a (backend) user of TYPO3.
363 *
364 * @return bool
365 */
366 public function isOnline()
367 {
368 if ($this->isOnline === null) {
369 if ($this->getUid() === 0) {
370 $this->isOnline = true;
371 }
372 // the storage is not marked as online for a longer time
373 if ($this->storageRecord['is_online'] == 0) {
374 $this->isOnline = false;
375 }
376 if ($this->isOnline !== false) {
377 // all files are ALWAYS available in the frontend
378 if (TYPO3_MODE === 'FE') {
379 $this->isOnline = true;
380 } else {
381 // check if the storage is disabled temporary for now
382 $registryObject = GeneralUtility::makeInstance(Registry::class);
383 $offlineUntil = $registryObject->get('core', 'sys_file_storage-' . $this->getUid() . '-offline-until');
384 if ($offlineUntil && $offlineUntil > time()) {
385 $this->isOnline = false;
386 } else {
387 $this->isOnline = true;
388 }
389 }
390 }
391 }
392 return $this->isOnline;
393 }
394
395 /**
396 * Returns TRUE if auto extracting of metadata is enabled
397 *
398 * @return bool
399 */
400 public function autoExtractMetadataEnabled()
401 {
402 return !empty($this->storageRecord['auto_extract_metadata']);
403 }
404
405 /**
406 * Blows the "fuse" and marks the storage as offline.
407 *
408 * Can only be modified by an admin.
409 *
410 * Typically, this is only done if the configuration is wrong.
411 */
412 public function markAsPermanentlyOffline()
413 {
414 if ($this->getUid() > 0) {
415 // @todo: move this to the storage repository
416 GeneralUtility::makeInstance(ConnectionPool::class)
417 ->getConnectionForTable('sys_file_storage')
418 ->update(
419 'sys_file_storage',
420 ['is_online' => 0],
421 ['uid' => (int)$this->getUid()]
422 );
423 }
424 $this->storageRecord['is_online'] = 0;
425 $this->isOnline = false;
426 }
427
428 /**
429 * Marks this storage as offline for the next 5 minutes.
430 *
431 * Non-permanent: This typically happens for remote storages
432 * that are "flaky" and not available all the time.
433 */
434 public function markAsTemporaryOffline()
435 {
436 $registryObject = GeneralUtility::makeInstance(Registry::class);
437 $registryObject->set('core', 'sys_file_storage-' . $this->getUid() . '-offline-until', time() + 60 * 5);
438 $this->storageRecord['is_online'] = 0;
439 $this->isOnline = false;
440 }
441
442 /*********************************
443 * User Permissions / File Mounts
444 ********************************/
445 /**
446 * Adds a filemount as a "filter" for users to only work on a subset of a
447 * storage object
448 *
449 * @param string $folderIdentifier
450 * @param array $additionalData
451 *
452 * @throws Exception\FolderDoesNotExistException
453 */
454 public function addFileMount($folderIdentifier, $additionalData = [])
455 {
456 // check for the folder before we add it as a filemount
457 if ($this->driver->folderExists($folderIdentifier) === false) {
458 // if there is an error, this is important and should be handled
459 // as otherwise the user would see the whole storage without any restrictions for the filemounts
460 throw new Exception\FolderDoesNotExistException('Folder for file mount ' . $folderIdentifier . ' does not exist.', 1334427099);
461 }
462 $data = $this->driver->getFolderInfoByIdentifier($folderIdentifier);
463 $folderObject = $this->getResourceFactoryInstance()->createFolderObject($this, $data['identifier'], $data['name']);
464 // Use the canonical identifier instead of the user provided one!
465 $folderIdentifier = $folderObject->getIdentifier();
466 if (
467 !empty($this->fileMounts[$folderIdentifier])
468 && empty($this->fileMounts[$folderIdentifier]['read_only'])
469 && !empty($additionalData['read_only'])
470 ) {
471 // Do not overwrite a regular mount with a read only mount
472 return;
473 }
474 if (empty($additionalData)) {
475 $additionalData = [
476 'path' => $folderIdentifier,
477 'title' => $folderIdentifier,
478 'folder' => $folderObject
479 ];
480 } else {
481 $additionalData['folder'] = $folderObject;
482 if (!isset($additionalData['title'])) {
483 $additionalData['title'] = $folderIdentifier;
484 }
485 }
486 $this->fileMounts[$folderIdentifier] = $additionalData;
487 }
488
489 /**
490 * Returns all file mounts that are registered with this storage.
491 *
492 * @return array
493 */
494 public function getFileMounts()
495 {
496 return $this->fileMounts;
497 }
498
499 /**
500 * Checks if the given subject is within one of the registered user
501 * file mounts. If not, working with the file is not permitted for the user.
502 *
503 * @param ResourceInterface $subject file or folder
504 * @param bool $checkWriteAccess If true, it is not only checked if the subject is within the file mount but also whether it isn't a read only file mount
505 * @return bool
506 */
507 public function isWithinFileMountBoundaries($subject, $checkWriteAccess = false)
508 {
509 if (!$this->evaluatePermissions) {
510 return true;
511 }
512 $isWithinFileMount = false;
513 if (!$subject) {
514 $subject = $this->getRootLevelFolder();
515 }
516 $identifier = $subject->getIdentifier();
517
518 // Allow access to processing folder
519 if ($this->isWithinProcessingFolder($identifier)) {
520 $isWithinFileMount = true;
521 } else {
522 // Check if the identifier of the subject is within at
523 // least one of the file mounts
524 $writableFileMountAvailable = false;
525 foreach ($this->fileMounts as $fileMount) {
526 /** @var Folder $folder */
527 $folder = $fileMount['folder'];
528 if ($this->driver->isWithin($folder->getIdentifier(), $identifier)) {
529 $isWithinFileMount = true;
530 if (!$checkWriteAccess) {
531 break;
532 }
533 if (empty($fileMount['read_only'])) {
534 $writableFileMountAvailable = true;
535 break;
536 }
537 }
538 }
539 $isWithinFileMount = $checkWriteAccess ? $writableFileMountAvailable : $isWithinFileMount;
540 }
541 return $isWithinFileMount;
542 }
543
544 /**
545 * Sets whether the permissions to access or write
546 * into this storage should be checked or not.
547 *
548 * @param bool $evaluatePermissions
549 */
550 public function setEvaluatePermissions($evaluatePermissions)
551 {
552 $this->evaluatePermissions = (bool)$evaluatePermissions;
553 }
554
555 /**
556 * Gets whether the permissions to access or write
557 * into this storage should be checked or not.
558 *
559 * @return bool $evaluatePermissions
560 */
561 public function getEvaluatePermissions()
562 {
563 return $this->evaluatePermissions;
564 }
565
566 /**
567 * Sets the user permissions of the storage.
568 *
569 * @param array $userPermissions
570 */
571 public function setUserPermissions(array $userPermissions)
572 {
573 $this->userPermissions = $userPermissions;
574 }
575
576 /**
577 * Checks if the ACL settings allow for a certain action
578 * (is a user allowed to read a file or copy a folder).
579 *
580 * @param string $action
581 * @param string $type either File or Folder
582 * @return bool
583 */
584 public function checkUserActionPermission($action, $type)
585 {
586 if (!$this->evaluatePermissions) {
587 return true;
588 }
589
590 $allow = false;
591 if (!empty($this->userPermissions[strtolower($action) . ucfirst(strtolower($type))])) {
592 $allow = true;
593 }
594
595 return $allow;
596 }
597
598 /**
599 * Checks if a file operation (= action) is allowed on a
600 * File/Folder/Storage (= subject).
601 *
602 * This method, by design, does not throw exceptions or do logging.
603 * Besides the usage from other methods in this class, it is also used by
604 * the Filelist UI to check whether an action is allowed and whether action
605 * related UI elements should thus be shown (move icon, edit icon, etc.)
606 *
607 * @param string $action action, can be read, write, delete, editMeta
608 * @param FileInterface $file
609 * @return bool
610 */
611 public function checkFileActionPermission($action, FileInterface $file)
612 {
613 $isProcessedFile = $file instanceof ProcessedFile;
614 // Check 1: Allow editing meta data of a file if it is in mount boundaries of a writable file mount
615 if ($action === 'editMeta') {
616 return !$isProcessedFile && $this->isWithinFileMountBoundaries($file, true);
617 }
618 // Check 2: Does the user have permission to perform the action? e.g. "readFile"
619 if (!$isProcessedFile && $this->checkUserActionPermission($action, 'File') === false) {
620 return false;
621 }
622 // Check 3: No action allowed on files for denied file extensions
623 if (!$this->checkFileExtensionPermission($file->getName())) {
624 return false;
625 }
626 $isReadCheck = false;
627 if (in_array($action, ['read', 'copy', 'move', 'replace'], true)) {
628 $isReadCheck = true;
629 }
630 $isWriteCheck = false;
631 if (in_array($action, ['add', 'write', 'move', 'rename', 'replace', 'delete'], true)) {
632 $isWriteCheck = true;
633 }
634 // Check 4: Does the user have the right to perform the action?
635 // (= is he within the file mount borders)
636 if (!$isProcessedFile && !$this->isWithinFileMountBoundaries($file, $isWriteCheck)) {
637 return false;
638 }
639
640 $isMissing = false;
641 if (!$isProcessedFile && $file instanceof File) {
642 $isMissing = $file->isMissing();
643 }
644
645 if ($this->driver->fileExists($file->getIdentifier()) === false) {
646 $file->setMissing(true);
647 $isMissing = true;
648 }
649
650 // Check 5: Check the capabilities of the storage (and the driver)
651 if ($isWriteCheck && ($isMissing || !$this->isWritable())) {
652 return false;
653 }
654
655 // Check 6: "File permissions" of the driver (only when file isn't marked as missing)
656 if (!$isMissing) {
657 $filePermissions = $this->driver->getPermissions($file->getIdentifier());
658 if ($isReadCheck && !$filePermissions['r']) {
659 return false;
660 }
661 if ($isWriteCheck && !$filePermissions['w']) {
662 return false;
663 }
664 }
665 return true;
666 }
667
668 /**
669 * Checks if a folder operation (= action) is allowed on a Folder.
670 *
671 * This method, by design, does not throw exceptions or do logging.
672 * See the checkFileActionPermission() method above for the reasons.
673 *
674 * @param string $action
675 * @param Folder $folder
676 * @return bool
677 */
678 public function checkFolderActionPermission($action, Folder $folder = null)
679 {
680 // Check 1: Does the user have permission to perform the action? e.g. "writeFolder"
681 if ($this->checkUserActionPermission($action, 'Folder') === false) {
682 return false;
683 }
684
685 // If we do not have a folder here, we cannot do further checks
686 if ($folder === null) {
687 return true;
688 }
689
690 $isReadCheck = false;
691 if (in_array($action, ['read', 'copy'], true)) {
692 $isReadCheck = true;
693 }
694 $isWriteCheck = false;
695 if (in_array($action, ['add', 'move', 'write', 'delete', 'rename'], true)) {
696 $isWriteCheck = true;
697 }
698 // Check 2: Does the user has the right to perform the action?
699 // (= is he within the file mount borders)
700 if (!$this->isWithinFileMountBoundaries($folder, $isWriteCheck)) {
701 return false;
702 }
703 // Check 3: Check the capabilities of the storage (and the driver)
704 if ($isReadCheck && !$this->isBrowsable()) {
705 return false;
706 }
707 if ($isWriteCheck && !$this->isWritable()) {
708 return false;
709 }
710
711 // Check 4: "Folder permissions" of the driver
712 $folderPermissions = $this->driver->getPermissions($folder->getIdentifier());
713 if ($isReadCheck && !$folderPermissions['r']) {
714 return false;
715 }
716 if ($isWriteCheck && !$folderPermissions['w']) {
717 return false;
718 }
719 return true;
720 }
721
722 /**
723 * @param ResourceInterface $fileOrFolder
724 * @return bool
725 */
726 public function checkFileAndFolderNameFilters(ResourceInterface $fileOrFolder)
727 {
728 foreach ($this->fileAndFolderNameFilters as $filter) {
729 if (is_callable($filter)) {
730 $result = call_user_func($filter, $fileOrFolder->getName(), $fileOrFolder->getIdentifier(), $fileOrFolder->getParentFolder()->getIdentifier(), [], $this->driver);
731 // We have to use -1 as the „don't include“ return value, as call_user_func() will return FALSE
732 // If calling the method succeeded and thus we can't use that as a return value.
733 if ($result === -1) {
734 return false;
735 }
736 if ($result === false) {
737 throw new \RuntimeException(
738 'Could not apply file/folder name filter ' . $filter[0] . '::' . $filter[1],
739 1525342106
740 );
741 }
742 }
743 }
744
745 return true;
746 }
747
748 /**
749 * If the fileName is given, checks it against the
750 * TYPO3_CONF_VARS[BE][fileDenyPattern] + and if the file extension is allowed.
751 *
752 * @param string $fileName full filename
753 * @return bool TRUE if extension/filename is allowed
754 */
755 protected function checkFileExtensionPermission($fileName)
756 {
757 $fileName = $this->driver->sanitizeFileName($fileName);
758 return GeneralUtility::verifyFilenameAgainstDenyPattern($fileName);
759 }
760
761 /**
762 * Assures read permission for given folder.
763 *
764 * @param Folder $folder If a folder is given, mountpoints are checked. If not only user folder read permissions are checked.
765 * @throws Exception\InsufficientFolderAccessPermissionsException
766 */
767 protected function assureFolderReadPermission(Folder $folder = null)
768 {
769 if (!$this->checkFolderActionPermission('read', $folder)) {
770 if ($folder === null) {
771 throw new Exception\InsufficientFolderAccessPermissionsException(
772 'You are not allowed to read folders',
773 1430657869
774 );
775 }
776 throw new Exception\InsufficientFolderAccessPermissionsException(
777 'You are not allowed to access the given folder: "' . $folder->getName() . '"',
778 1375955684
779 );
780 }
781 }
782
783 /**
784 * Assures delete permission for given folder.
785 *
786 * @param Folder $folder If a folder is given, mountpoints are checked. If not only user folder delete permissions are checked.
787 * @param bool $checkDeleteRecursively
788 * @throws Exception\InsufficientFolderAccessPermissionsException
789 * @throws Exception\InsufficientFolderWritePermissionsException
790 * @throws Exception\InsufficientUserPermissionsException
791 */
792 protected function assureFolderDeletePermission(Folder $folder, $checkDeleteRecursively)
793 {
794 // Check user permissions for recursive deletion if it is requested
795 if ($checkDeleteRecursively && !$this->checkUserActionPermission('recursivedelete', 'Folder')) {
796 throw new Exception\InsufficientUserPermissionsException('You are not allowed to delete folders recursively', 1377779423);
797 }
798 // Check user action permission
799 if (!$this->checkFolderActionPermission('delete', $folder)) {
800 throw new Exception\InsufficientFolderAccessPermissionsException(
801 'You are not allowed to delete the given folder: "' . $folder->getName() . '"',
802 1377779039
803 );
804 }
805 // Check if the user has write permissions to folders
806 // Would be good if we could check for actual write permissions in the containig folder
807 // but we cannot since we have no access to the containing folder of this file.
808 if (!$this->checkUserActionPermission('write', 'Folder')) {
809 throw new Exception\InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377779111);
810 }
811 }
812
813 /**
814 * Assures read permission for given file.
815 *
816 * @param FileInterface $file
817 * @throws Exception\InsufficientFileAccessPermissionsException
818 * @throws Exception\IllegalFileExtensionException
819 */
820 protected function assureFileReadPermission(FileInterface $file)
821 {
822 if (!$this->checkFileActionPermission('read', $file)) {
823 throw new Exception\InsufficientFileAccessPermissionsException(
824 'You are not allowed to access that file: "' . $file->getName() . '"',
825 1375955429
826 );
827 }
828 if (!$this->checkFileExtensionPermission($file->getName())) {
829 throw new Exception\IllegalFileExtensionException(
830 'You are not allowed to use that file extension. File: "' . $file->getName() . '"',
831 1375955430
832 );
833 }
834 }
835
836 /**
837 * Assures write permission for given file.
838 *
839 * @param FileInterface $file
840 * @throws Exception\IllegalFileExtensionException
841 * @throws Exception\InsufficientFileWritePermissionsException
842 * @throws Exception\InsufficientUserPermissionsException
843 */
844 protected function assureFileWritePermissions(FileInterface $file)
845 {
846 // Check if user is allowed to write the file and $file is writable
847 if (!$this->checkFileActionPermission('write', $file)) {
848 throw new Exception\InsufficientFileWritePermissionsException('Writing to file "' . $file->getIdentifier() . '" is not allowed.', 1330121088);
849 }
850 if (!$this->checkFileExtensionPermission($file->getName())) {
851 throw new Exception\IllegalFileExtensionException('You are not allowed to edit a file with extension "' . $file->getExtension() . '"', 1366711933);
852 }
853 }
854
855 /**
856 * Assure replace permission for given file.
857 *
858 * @param FileInterface $file
859 * @throws Exception\InsufficientFileWritePermissionsException
860 * @throws Exception\InsufficientFolderWritePermissionsException
861 */
862 protected function assureFileReplacePermissions(FileInterface $file)
863 {
864 // Check if user is allowed to replace the file and $file is writable
865 if (!$this->checkFileActionPermission('replace', $file)) {
866 throw new Exception\InsufficientFileWritePermissionsException('Replacing file "' . $file->getIdentifier() . '" is not allowed.', 1436899571);
867 }
868 // Check if parentFolder is writable for the user
869 if (!$this->checkFolderActionPermission('write', $file->getParentFolder())) {
870 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $file->getIdentifier() . '"', 1436899572);
871 }
872 }
873
874 /**
875 * Assures delete permission for given file.
876 *
877 * @param FileInterface $file
878 * @throws Exception\IllegalFileExtensionException
879 * @throws Exception\InsufficientFileWritePermissionsException
880 * @throws Exception\InsufficientFolderWritePermissionsException
881 */
882 protected function assureFileDeletePermissions(FileInterface $file)
883 {
884 // Check for disallowed file extensions
885 if (!$this->checkFileExtensionPermission($file->getName())) {
886 throw new Exception\IllegalFileExtensionException('You are not allowed to delete a file with extension "' . $file->getExtension() . '"', 1377778916);
887 }
888 // Check further permissions if file is not a processed file
889 if (!$file instanceof ProcessedFile) {
890 // Check if user is allowed to delete the file and $file is writable
891 if (!$this->checkFileActionPermission('delete', $file)) {
892 throw new Exception\InsufficientFileWritePermissionsException('You are not allowed to delete the file "' . $file->getIdentifier() . '"', 1319550425);
893 }
894 // Check if the user has write permissions to folders
895 // Would be good if we could check for actual write permissions in the containig folder
896 // but we cannot since we have no access to the containing folder of this file.
897 if (!$this->checkUserActionPermission('write', 'Folder')) {
898 throw new Exception\InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377778702);
899 }
900 }
901 }
902
903 /**
904 * Checks if a file/user has the permission to be written to a Folder/Storage.
905 * If not, throws an exception.
906 *
907 * @param Folder $targetFolder The target folder where the file should be written
908 * @param string $targetFileName The file name which should be written into the storage
909 *
910 * @throws Exception\InsufficientFolderWritePermissionsException
911 * @throws Exception\IllegalFileExtensionException
912 * @throws Exception\InsufficientUserPermissionsException
913 */
914 protected function assureFileAddPermissions($targetFolder, $targetFileName)
915 {
916 // Check for a valid file extension
917 if (!$this->checkFileExtensionPermission($targetFileName)) {
918 throw new Exception\IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1322120271);
919 }
920 // Makes sure the user is allowed to upload
921 if (!$this->checkUserActionPermission('add', 'File')) {
922 throw new Exception\InsufficientUserPermissionsException('You are not allowed to add files to this storage "' . $this->getUid() . '"', 1376992145);
923 }
924 // Check if targetFolder is writable
925 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
926 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1322120356);
927 }
928 }
929
930 /**
931 * Checks if a file has the permission to be uploaded to a Folder/Storage.
932 * If not, throws an exception.
933 *
934 * @param string $localFilePath the temporary file name from $_FILES['file1']['tmp_name']
935 * @param Folder $targetFolder The target folder where the file should be uploaded
936 * @param string $targetFileName the destination file name $_FILES['file1']['name']
937 * @param int $uploadedFileSize
938 *
939 * @throws Exception\InsufficientFolderWritePermissionsException
940 * @throws Exception\UploadException
941 * @throws Exception\IllegalFileExtensionException
942 * @throws Exception\UploadSizeException
943 * @throws Exception\InsufficientUserPermissionsException
944 */
945 protected function assureFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileSize)
946 {
947 // Makes sure this is an uploaded file
948 if (!is_uploaded_file($localFilePath)) {
949 throw new Exception\UploadException('The upload has failed, no uploaded file found!', 1322110455);
950 }
951 // Max upload size (kb) for files.
952 $maxUploadFileSize = GeneralUtility::getMaxUploadFileSize() * 1024;
953 if ($maxUploadFileSize > 0 && $uploadedFileSize >= $maxUploadFileSize) {
954 unlink($localFilePath);
955 throw new Exception\UploadSizeException('The uploaded file exceeds the size-limit of ' . $maxUploadFileSize . ' bytes', 1322110041);
956 }
957 $this->assureFileAddPermissions($targetFolder, $targetFileName);
958 }
959
960 /**
961 * Checks for permissions to move a file.
962 *
963 * @throws \RuntimeException
964 * @throws Exception\InsufficientFolderAccessPermissionsException
965 * @throws Exception\InsufficientUserPermissionsException
966 * @throws Exception\IllegalFileExtensionException
967 * @param FileInterface $file
968 * @param Folder $targetFolder
969 * @param string $targetFileName
970 */
971 protected function assureFileMovePermissions(FileInterface $file, Folder $targetFolder, $targetFileName)
972 {
973 // Check if targetFolder is within this storage
974 if ($this->getUid() !== $targetFolder->getStorage()->getUid()) {
975 throw new \RuntimeException('The target folder is not in the same storage. Target folder given: "' . $targetFolder->getIdentifier() . '"', 1422553107);
976 }
977 // Check for a valid file extension
978 if (!$this->checkFileExtensionPermission($targetFileName)) {
979 throw new Exception\IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1378243279);
980 }
981 // Check if user is allowed to move and $file is readable and writable
982 if (!$file->getStorage()->checkFileActionPermission('move', $file)) {
983 throw new Exception\InsufficientUserPermissionsException('You are not allowed to move files to storage "' . $this->getUid() . '"', 1319219349);
984 }
985 // Check if target folder is writable
986 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
987 throw new Exception\InsufficientFolderAccessPermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319219350);
988 }
989 }
990
991 /**
992 * Checks for permissions to rename a file.
993 *
994 * @param FileInterface $file
995 * @param string $targetFileName
996 * @throws Exception\InsufficientFileWritePermissionsException
997 * @throws Exception\IllegalFileExtensionException
998 * @throws Exception\InsufficientFileReadPermissionsException
999 * @throws Exception\InsufficientUserPermissionsException
1000 */
1001 protected function assureFileRenamePermissions(FileInterface $file, $targetFileName)
1002 {
1003 // Check if file extension is allowed
1004 if (!$this->checkFileExtensionPermission($targetFileName) || !$this->checkFileExtensionPermission($file->getName())) {
1005 throw new Exception\IllegalFileExtensionException('You are not allowed to rename a file with this extension. File given: "' . $file->getName() . '"', 1371466663);
1006 }
1007 // Check if user is allowed to rename
1008 if (!$this->checkFileActionPermission('rename', $file)) {
1009 throw new Exception\InsufficientUserPermissionsException('You are not allowed to rename files. File given: "' . $file->getName() . '"', 1319219351);
1010 }
1011 // Check if the user is allowed to write to folders
1012 // Although it would be good to check, we cannot check here if the folder actually is writable
1013 // because we do not know in which folder the file resides.
1014 // So we rely on the driver to throw an exception in case the renaming failed.
1015 if (!$this->checkFolderActionPermission('write')) {
1016 throw new Exception\InsufficientFileWritePermissionsException('You are not allowed to write to folders', 1319219352);
1017 }
1018 }
1019
1020 /**
1021 * Check if a file has the permission to be copied on a File/Folder/Storage,
1022 * if not throw an exception
1023 *
1024 * @param FileInterface $file
1025 * @param Folder $targetFolder
1026 * @param string $targetFileName
1027 *
1028 * @throws Exception
1029 * @throws Exception\InsufficientFolderWritePermissionsException
1030 * @throws Exception\IllegalFileExtensionException
1031 * @throws Exception\InsufficientFileReadPermissionsException
1032 * @throws Exception\InsufficientUserPermissionsException
1033 */
1034 protected function assureFileCopyPermissions(FileInterface $file, Folder $targetFolder, $targetFileName)
1035 {
1036 // Check if targetFolder is within this storage, this should never happen
1037 if ($this->getUid() != $targetFolder->getStorage()->getUid()) {
1038 throw new Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1319550405);
1039 }
1040 // Check if user is allowed to copy
1041 if (!$file->getStorage()->checkFileActionPermission('copy', $file)) {
1042 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the file "' . $file->getIdentifier() . '"', 1319550426);
1043 }
1044 // Check if targetFolder is writable
1045 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
1046 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319550435);
1047 }
1048 // Check for a valid file extension
1049 if (!$this->checkFileExtensionPermission($targetFileName) || !$this->checkFileExtensionPermission($file->getName())) {
1050 throw new Exception\IllegalFileExtensionException('You are not allowed to copy a file of that type.', 1319553317);
1051 }
1052 }
1053
1054 /**
1055 * Check if a file has the permission to be copied on a File/Folder/Storage,
1056 * if not throw an exception
1057 *
1058 * @param FolderInterface $folderToCopy
1059 * @param FolderInterface $targetParentFolder
1060 *
1061 * @throws Exception
1062 * @throws Exception\InsufficientFolderWritePermissionsException
1063 * @throws Exception\IllegalFileExtensionException
1064 * @throws Exception\InsufficientFileReadPermissionsException
1065 * @throws Exception\InsufficientUserPermissionsException
1066 * @throws \RuntimeException
1067 */
1068 protected function assureFolderCopyPermissions(FolderInterface $folderToCopy, FolderInterface $targetParentFolder)
1069 {
1070 // Check if targetFolder is within this storage, this should never happen
1071 if ($this->getUid() !== $targetParentFolder->getStorage()->getUid()) {
1072 throw new Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1377777624);
1073 }
1074 if (!$folderToCopy instanceof Folder) {
1075 throw new \RuntimeException('The folder "' . $folderToCopy->getIdentifier() . '" to copy is not of type folder.', 1384209020);
1076 }
1077 // Check if user is allowed to copy and the folder is readable
1078 if (!$folderToCopy->getStorage()->checkFolderActionPermission('copy', $folderToCopy)) {
1079 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the folder "' . $folderToCopy->getIdentifier() . '"', 1377777629);
1080 }
1081 if (!$targetParentFolder instanceof Folder) {
1082 throw new \RuntimeException('The target folder "' . $targetParentFolder->getIdentifier() . '" is not of type folder.', 1384209021);
1083 }
1084 // Check if targetFolder is writable
1085 if (!$this->checkFolderActionPermission('write', $targetParentFolder)) {
1086 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetParentFolder->getIdentifier() . '"', 1377777635);
1087 }
1088 }
1089
1090 /**
1091 * Check if a file has the permission to be copied on a File/Folder/Storage,
1092 * if not throw an exception
1093 *
1094 * @param FolderInterface $folderToMove
1095 * @param FolderInterface $targetParentFolder
1096 *
1097 * @throws \InvalidArgumentException
1098 * @throws Exception\InsufficientFolderWritePermissionsException
1099 * @throws Exception\IllegalFileExtensionException
1100 * @throws Exception\InsufficientFileReadPermissionsException
1101 * @throws Exception\InsufficientUserPermissionsException
1102 * @throws \RuntimeException
1103 */
1104 protected function assureFolderMovePermissions(FolderInterface $folderToMove, FolderInterface $targetParentFolder)
1105 {
1106 // Check if targetFolder is within this storage, this should never happen
1107 if ($this->getUid() !== $targetParentFolder->getStorage()->getUid()) {
1108 throw new \InvalidArgumentException('Cannot move a folder into a folder that does not belong to this storage.', 1325777289);
1109 }
1110 if (!$folderToMove instanceof Folder) {
1111 throw new \RuntimeException('The folder "' . $folderToMove->getIdentifier() . '" to move is not of type Folder.', 1384209022);
1112 }
1113 // Check if user is allowed to move and the folder is writable
1114 // In fact we would need to check if the parent folder of the folder to move is writable also
1115 // But as of now we cannot extract the parent folder from this folder
1116 if (!$folderToMove->getStorage()->checkFolderActionPermission('move', $folderToMove)) {
1117 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the folder "' . $folderToMove->getIdentifier() . '"', 1377778045);
1118 }
1119 if (!$targetParentFolder instanceof Folder) {
1120 throw new \RuntimeException('The target folder "' . $targetParentFolder->getIdentifier() . '" is not of type Folder.', 1384209023);
1121 }
1122 // Check if targetFolder is writable
1123 if (!$this->checkFolderActionPermission('write', $targetParentFolder)) {
1124 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetParentFolder->getIdentifier() . '"', 1377778049);
1125 }
1126 }
1127
1128 /**
1129 * Clean a fileName from not allowed characters
1130 *
1131 * @param string $fileName The name of the file to be add, If not set, the local file name is used
1132 * @param Folder $targetFolder The target folder where the file should be added
1133 *
1134 * @throws \InvalidArgumentException
1135 * @throws Exception\ExistingTargetFileNameException
1136 * @return string
1137 */
1138 public function sanitizeFileName($fileName, Folder $targetFolder = null)
1139 {
1140 $targetFolder = $targetFolder ?: $this->getDefaultFolder();
1141 $fileName = $this->driver->sanitizeFileName($fileName);
1142
1143 // The file name could be changed by an external slot
1144 $fileName = $this->emitSanitizeFileNameSignal($fileName, $targetFolder);
1145
1146 return $fileName;
1147 }
1148
1149 /********************
1150 * FILE ACTIONS
1151 ********************/
1152 /**
1153 * Moves a file from the local filesystem to this storage.
1154 *
1155 * @param string $localFilePath The file on the server's hard disk to add
1156 * @param Folder $targetFolder The target folder where the file should be added
1157 * @param string $targetFileName The name of the file to be add, If not set, the local file name is used
1158 * @param string $conflictMode a value of the DuplicationBehavior enumeration
1159 * @param bool $removeOriginal if set the original file will be removed after successful operation
1160 *
1161 * @throws \InvalidArgumentException
1162 * @throws Exception\ExistingTargetFileNameException
1163 * @return FileInterface
1164 */
1165 public function addFile($localFilePath, Folder $targetFolder, $targetFileName = '', $conflictMode = DuplicationBehavior::RENAME, $removeOriginal = true)
1166 {
1167 $localFilePath = PathUtility::getCanonicalPath($localFilePath);
1168 // File is not available locally NOR is it an uploaded file
1169 if (!is_uploaded_file($localFilePath) && !file_exists($localFilePath)) {
1170 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1319552745);
1171 }
1172 $conflictMode = DuplicationBehavior::cast($conflictMode);
1173 $targetFolder = $targetFolder ?: $this->getDefaultFolder();
1174 $targetFileName = $this->sanitizeFileName($targetFileName ?: PathUtility::basename($localFilePath), $targetFolder);
1175
1176 $targetFileName = $this->emitPreFileAddSignal($targetFileName, $targetFolder, $localFilePath);
1177
1178 $this->assureFileAddPermissions($targetFolder, $targetFileName);
1179
1180 $replaceExisting = false;
1181 if ($conflictMode->equals(DuplicationBehavior::CANCEL) && $this->driver->fileExistsInFolder($targetFileName, $targetFolder->getIdentifier())) {
1182 throw new Exception\ExistingTargetFileNameException('File "' . $targetFileName . '" already exists in folder ' . $targetFolder->getIdentifier(), 1322121068);
1183 }
1184 if ($conflictMode->equals(DuplicationBehavior::RENAME)) {
1185 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1186 } elseif ($conflictMode->equals(DuplicationBehavior::REPLACE) && $this->driver->fileExistsInFolder($targetFileName, $targetFolder->getIdentifier())) {
1187 $replaceExisting = true;
1188 }
1189
1190 $fileIdentifier = $this->driver->addFile($localFilePath, $targetFolder->getIdentifier(), $targetFileName, $removeOriginal);
1191 $file = $this->getResourceFactoryInstance()->getFileObjectByStorageAndIdentifier($this->getUid(), $fileIdentifier);
1192
1193 if ($replaceExisting && $file instanceof File) {
1194 $this->getIndexer()->updateIndexEntry($file);
1195 }
1196
1197 $this->emitPostFileAddSignal($file, $targetFolder);
1198
1199 return $file;
1200 }
1201
1202 /**
1203 * Updates a processed file with a new file from the local filesystem.
1204 *
1205 * @param string $localFilePath
1206 * @param ProcessedFile $processedFile
1207 * @param Folder $processingFolder
1208 * @return FileInterface
1209 * @throws \InvalidArgumentException
1210 * @internal use only
1211 */
1212 public function updateProcessedFile($localFilePath, ProcessedFile $processedFile, Folder $processingFolder = null)
1213 {
1214 if (!file_exists($localFilePath)) {
1215 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1319552746);
1216 }
1217 if ($processingFolder === null) {
1218 $processingFolder = $this->getProcessingFolder($processedFile->getOriginalFile());
1219 }
1220 $fileIdentifier = $this->driver->addFile($localFilePath, $processingFolder->getIdentifier(), $processedFile->getName());
1221 // @todo check if we have to update the processed file other then the identifier
1222 $processedFile->setIdentifier($fileIdentifier);
1223 return $processedFile;
1224 }
1225
1226 /**
1227 * Creates a (cryptographic) hash for a file.
1228 *
1229 * @param FileInterface $fileObject
1230 * @param string $hash
1231 * @return string
1232 */
1233 public function hashFile(FileInterface $fileObject, $hash)
1234 {
1235 return $this->hashFileByIdentifier($fileObject->getIdentifier(), $hash);
1236 }
1237
1238 /**
1239 * Creates a (cryptographic) hash for a fileIdentifier.
1240 *
1241 * @param string $fileIdentifier
1242 * @param string $hash
1243 *
1244 * @return string
1245 */
1246 public function hashFileByIdentifier($fileIdentifier, $hash)
1247 {
1248 return $this->driver->hash($fileIdentifier, $hash);
1249 }
1250
1251 /**
1252 * Hashes a file identifier, taking the case sensitivity of the file system
1253 * into account. This helps mitigating problems with case-insensitive
1254 * databases.
1255 *
1256 * @param string|FileInterface $file
1257 * @return string
1258 */
1259 public function hashFileIdentifier($file)
1260 {
1261 if (is_object($file) && $file instanceof FileInterface) {
1262 /** @var FileInterface $file */
1263 $file = $file->getIdentifier();
1264 }
1265 return $this->driver->hashIdentifier($file);
1266 }
1267
1268 /**
1269 * Returns a publicly accessible URL for a file.
1270 *
1271 * WARNING: Access to the file may be restricted by further means, e.g.
1272 * some web-based authentication. You have to take care of this yourself.
1273 *
1274 * @param ResourceInterface $resourceObject The file or folder object
1275 * @param bool $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all (only for the LocalDriver)
1276 * @return string|null NULL if file is missing or deleted, the generated url otherwise
1277 */
1278 public function getPublicUrl(ResourceInterface $resourceObject, $relativeToCurrentScript = false)
1279 {
1280 $publicUrl = null;
1281 if ($this->isOnline()) {
1282 // Pre-process the public URL by an accordant slot
1283 $this->emitPreGeneratePublicUrlSignal($resourceObject, $relativeToCurrentScript, ['publicUrl' => &$publicUrl]);
1284
1285 if (
1286 $publicUrl === null
1287 && $resourceObject instanceof File
1288 && ($helper = OnlineMediaHelperRegistry::getInstance()->getOnlineMediaHelper($resourceObject)) !== false
1289 ) {
1290 $publicUrl = $helper->getPublicUrl($resourceObject, $relativeToCurrentScript);
1291 }
1292
1293 // If slot did not handle the signal, use the default way to determine public URL
1294 if ($publicUrl === null) {
1295 if ($this->hasCapability(self::CAPABILITY_PUBLIC)) {
1296 $publicUrl = $this->driver->getPublicUrl($resourceObject->getIdentifier());
1297 }
1298
1299 if ($publicUrl === null && $resourceObject instanceof FileInterface) {
1300 $queryParameterArray = ['eID' => 'dumpFile', 't' => ''];
1301 if ($resourceObject instanceof File) {
1302 $queryParameterArray['f'] = $resourceObject->getUid();
1303 $queryParameterArray['t'] = 'f';
1304 } elseif ($resourceObject instanceof ProcessedFile) {
1305 $queryParameterArray['p'] = $resourceObject->getUid();
1306 $queryParameterArray['t'] = 'p';
1307 }
1308
1309 $queryParameterArray['token'] = GeneralUtility::hmac(implode('|', $queryParameterArray), 'resourceStorageDumpFile');
1310 $publicUrl = GeneralUtility::locationHeaderUrl(PathUtility::getAbsoluteWebPath(Environment::getPublicPath() . '/index.php'));
1311 $publicUrl .= '?' . http_build_query($queryParameterArray, '', '&', PHP_QUERY_RFC3986);
1312 }
1313
1314 // If requested, make the path relative to the current script in order to make it possible
1315 // to use the relative file
1316 if ($publicUrl !== null && $relativeToCurrentScript && !GeneralUtility::isValidUrl($publicUrl)) {
1317 $absolutePathToContainingFolder = PathUtility::dirname(Environment::getPublicPath() . '/' . $publicUrl);
1318 $pathPart = PathUtility::getRelativePathTo($absolutePathToContainingFolder);
1319 $filePart = substr(Environment::getPublicPath() . '/' . $publicUrl, strlen($absolutePathToContainingFolder) + 1);
1320 $publicUrl = $pathPart . $filePart;
1321 }
1322 }
1323 }
1324 return $publicUrl;
1325 }
1326
1327 /**
1328 * Passes a file to the File Processing Services and returns the resulting ProcessedFile object.
1329 *
1330 * @param FileInterface $fileObject The file object
1331 * @param string $context
1332 * @param array $configuration
1333 *
1334 * @return ProcessedFile
1335 * @throws \InvalidArgumentException
1336 */
1337 public function processFile(FileInterface $fileObject, $context, array $configuration)
1338 {
1339 if ($fileObject->getStorage() !== $this) {
1340 throw new \InvalidArgumentException('Cannot process files of foreign storage', 1353401835);
1341 }
1342 $processedFile = $this->getFileProcessingService()->processFile($fileObject, $this, $context, $configuration);
1343
1344 return $processedFile;
1345 }
1346
1347 /**
1348 * Copies a file from the storage for local processing.
1349 *
1350 * @param FileInterface $fileObject
1351 * @param bool $writable
1352 * @return string Path to local file (either original or copied to some temporary local location)
1353 */
1354 public function getFileForLocalProcessing(FileInterface $fileObject, $writable = true)
1355 {
1356 $filePath = $this->driver->getFileForLocalProcessing($fileObject->getIdentifier(), $writable);
1357 return $filePath;
1358 }
1359
1360 /**
1361 * Gets a file by identifier.
1362 *
1363 * @param string $identifier
1364 * @return FileInterface
1365 */
1366 public function getFile($identifier)
1367 {
1368 $file = $this->getFileFactory()->getFileObjectByStorageAndIdentifier($this->getUid(), $identifier);
1369 if (!$this->driver->fileExists($identifier)) {
1370 $file->setMissing(true);
1371 }
1372 return $file;
1373 }
1374
1375 /**
1376 * Gets information about a file.
1377 *
1378 * @param FileInterface $fileObject
1379 * @return array
1380 * @internal
1381 */
1382 public function getFileInfo(FileInterface $fileObject)
1383 {
1384 return $this->getFileInfoByIdentifier($fileObject->getIdentifier());
1385 }
1386
1387 /**
1388 * Gets information about a file by its identifier.
1389 *
1390 * @param string $identifier
1391 * @param array $propertiesToExtract
1392 * @return array
1393 * @internal
1394 */
1395 public function getFileInfoByIdentifier($identifier, array $propertiesToExtract = [])
1396 {
1397 return $this->driver->getFileInfoByIdentifier($identifier, $propertiesToExtract);
1398 }
1399
1400 /**
1401 * Unsets the file and folder name filters, thus making this storage return unfiltered filelists.
1402 */
1403 public function unsetFileAndFolderNameFilters()
1404 {
1405 $this->fileAndFolderNameFilters = [];
1406 }
1407
1408 /**
1409 * Resets the file and folder name filters to the default values defined in the TYPO3 configuration.
1410 */
1411 public function resetFileAndFolderNameFiltersToDefault()
1412 {
1413 $this->fileAndFolderNameFilters = $GLOBALS['TYPO3_CONF_VARS']['SYS']['fal']['defaultFilterCallbacks'];
1414 }
1415
1416 /**
1417 * Returns the file and folder name filters used by this storage.
1418 *
1419 * @return array
1420 */
1421 public function getFileAndFolderNameFilters()
1422 {
1423 return $this->fileAndFolderNameFilters;
1424 }
1425
1426 /**
1427 * @param array $filters
1428 * @return $this
1429 */
1430 public function setFileAndFolderNameFilters(array $filters)
1431 {
1432 $this->fileAndFolderNameFilters = $filters;
1433 return $this;
1434 }
1435
1436 /**
1437 * @param callable $filter
1438 */
1439 public function addFileAndFolderNameFilter($filter)
1440 {
1441 $this->fileAndFolderNameFilters[] = $filter;
1442 }
1443
1444 /**
1445 * @param string $fileIdentifier
1446 *
1447 * @return string
1448 */
1449 public function getFolderIdentifierFromFileIdentifier($fileIdentifier)
1450 {
1451 return $this->driver->getParentFolderIdentifierOfIdentifier($fileIdentifier);
1452 }
1453
1454 /**
1455 * Get file from folder
1456 *
1457 * @param string $fileName
1458 * @param Folder $folder
1459 * @return File|ProcessedFile|null
1460 */
1461 public function getFileInFolder($fileName, Folder $folder)
1462 {
1463 $identifier = $this->driver->getFileInFolder($fileName, $folder->getIdentifier());
1464 return $this->getFileFactory()->getFileObjectByStorageAndIdentifier($this->getUid(), $identifier);
1465 }
1466
1467 /**
1468 * @param Folder $folder
1469 * @param int $start
1470 * @param int $maxNumberOfItems
1471 * @param bool $useFilters
1472 * @param bool $recursive
1473 * @param string $sort Property name used to sort the items.
1474 * Among them may be: '' (empty, no sorting), name,
1475 * fileext, size, tstamp and rw.
1476 * If a driver does not support the given property, it
1477 * should fall back to "name".
1478 * @param bool $sortRev TRUE to indicate reverse sorting (last to first)
1479 * @return File[]
1480 * @throws Exception\InsufficientFolderAccessPermissionsException
1481 */
1482 public function getFilesInFolder(Folder $folder, $start = 0, $maxNumberOfItems = 0, $useFilters = true, $recursive = false, $sort = '', $sortRev = false)
1483 {
1484 $this->assureFolderReadPermission($folder);
1485
1486 $rows = $this->getFileIndexRepository()->findByFolder($folder);
1487
1488 $filters = $useFilters == true ? $this->fileAndFolderNameFilters : [];
1489 $fileIdentifiers = array_values($this->driver->getFilesInFolder($folder->getIdentifier(), $start, $maxNumberOfItems, $recursive, $filters, $sort, $sortRev));
1490
1491 $items = [];
1492 foreach ($fileIdentifiers as $identifier) {
1493 if (isset($rows[$identifier])) {
1494 $fileObject = $this->getFileFactory()->getFileObject($rows[$identifier]['uid'], $rows[$identifier]);
1495 } else {
1496 $fileObject = $this->getFileFactory()->getFileObjectByStorageAndIdentifier($this->getUid(), $identifier);
1497 }
1498 if ($fileObject instanceof FileInterface) {
1499 $key = $fileObject->getName();
1500 while (isset($items[$key])) {
1501 $key .= 'z';
1502 }
1503 $items[$key] = $fileObject;
1504 }
1505 }
1506
1507 return $items;
1508 }
1509
1510 /**
1511 * @param string $folderIdentifier
1512 * @param bool $useFilters
1513 * @param bool $recursive
1514 * @return array
1515 */
1516 public function getFileIdentifiersInFolder($folderIdentifier, $useFilters = true, $recursive = false)
1517 {
1518 $filters = $useFilters == true ? $this->fileAndFolderNameFilters : [];
1519 return $this->driver->getFilesInFolder($folderIdentifier, 0, 0, $recursive, $filters);
1520 }
1521
1522 /**
1523 * @param Folder $folder
1524 * @param bool $useFilters
1525 * @param bool $recursive
1526 * @return int Number of files in folder
1527 * @throws Exception\InsufficientFolderAccessPermissionsException
1528 */
1529 public function countFilesInFolder(Folder $folder, $useFilters = true, $recursive = false)
1530 {
1531 $this->assureFolderReadPermission($folder);
1532 $filters = $useFilters ? $this->fileAndFolderNameFilters : [];
1533 return $this->driver->countFilesInFolder($folder->getIdentifier(), $recursive, $filters);
1534 }
1535
1536 /**
1537 * @param string $folderIdentifier
1538 * @param bool $useFilters
1539 * @param bool $recursive
1540 * @return array
1541 */
1542 public function getFolderIdentifiersInFolder($folderIdentifier, $useFilters = true, $recursive = false)
1543 {
1544 $filters = $useFilters == true ? $this->fileAndFolderNameFilters : [];
1545 return $this->driver->getFoldersInFolder($folderIdentifier, 0, 0, $recursive, $filters);
1546 }
1547
1548 /**
1549 * Returns TRUE if the specified file exists
1550 *
1551 * @param string $identifier
1552 * @return bool
1553 */
1554 public function hasFile($identifier)
1555 {
1556 // Allow if identifier is in processing folder
1557 if (!$this->isWithinProcessingFolder($identifier)) {
1558 $this->assureFolderReadPermission();
1559 }
1560 return $this->driver->fileExists($identifier);
1561 }
1562
1563 /**
1564 * Get all processing folders that live in this storage
1565 *
1566 * @return Folder[]
1567 */
1568 public function getProcessingFolders()
1569 {
1570 if ($this->processingFolders === null) {
1571 $this->processingFolders = [];
1572 $this->processingFolders[] = $this->getProcessingFolder();
1573 /** @var StorageRepository $storageRepository */
1574 $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
1575 $allStorages = $storageRepository->findAll();
1576 foreach ($allStorages as $storage) {
1577 // To circumvent the permission check of the folder, we use the factory to create it "manually" instead of directly using $storage->getProcessingFolder()
1578 // See #66695 for details
1579 list($storageUid, $processingFolderIdentifier) = array_pad(GeneralUtility::trimExplode(':', $storage->getStorageRecord()['processingfolder']), 2, null);
1580 if (empty($processingFolderIdentifier) || (int)$storageUid !== $this->getUid()) {
1581 continue;
1582 }
1583 $potentialProcessingFolder = $this->getResourceFactoryInstance()->createFolderObject($this, $processingFolderIdentifier, $processingFolderIdentifier);
1584 if ($potentialProcessingFolder->getStorage() === $this && $potentialProcessingFolder->getIdentifier() !== $this->getProcessingFolder()->getIdentifier()) {
1585 $this->processingFolders[] = $potentialProcessingFolder;
1586 }
1587 }
1588 }
1589
1590 return $this->processingFolders;
1591 }
1592
1593 /**
1594 * Returns TRUE if folder that is in current storage is set as
1595 * processing folder for one of the existing storages
1596 *
1597 * @param Folder $folder
1598 * @return bool
1599 */
1600 public function isProcessingFolder(Folder $folder)
1601 {
1602 $isProcessingFolder = false;
1603 foreach ($this->getProcessingFolders() as $processingFolder) {
1604 if ($folder->getCombinedIdentifier() === $processingFolder->getCombinedIdentifier()) {
1605 $isProcessingFolder = true;
1606 break;
1607 }
1608 }
1609 return $isProcessingFolder;
1610 }
1611
1612 /**
1613 * Checks if the queried file in the given folder exists
1614 *
1615 * @param string $fileName
1616 * @param Folder $folder
1617 * @return bool
1618 */
1619 public function hasFileInFolder($fileName, Folder $folder)
1620 {
1621 $this->assureFolderReadPermission($folder);
1622 return $this->driver->fileExistsInFolder($fileName, $folder->getIdentifier());
1623 }
1624
1625 /**
1626 * Get contents of a file object
1627 *
1628 * @param FileInterface $file
1629 *
1630 * @throws Exception\InsufficientFileReadPermissionsException
1631 * @return string
1632 */
1633 public function getFileContents($file)
1634 {
1635 $this->assureFileReadPermission($file);
1636 return $this->driver->getFileContents($file->getIdentifier());
1637 }
1638
1639 /**
1640 * Returns a PSR-7 Response which can be used to stream the requested file
1641 *
1642 * @param FileInterface $file
1643 * @param bool $asDownload If set Content-Disposition attachment is sent, inline otherwise
1644 * @param string $alternativeFilename the filename for the download (if $asDownload is set)
1645 * @param string $overrideMimeType If set this will be used as Content-Type header instead of the automatically detected mime type.
1646 * @return ResponseInterface
1647 */
1648 public function streamFile(
1649 FileInterface $file,
1650 bool $asDownload = false,
1651 string $alternativeFilename = null,
1652 string $overrideMimeType = null
1653 ): ResponseInterface {
1654 if (!$this->driver instanceof StreamableDriverInterface) {
1655 return $this->getPseudoStream($file, $asDownload, $alternativeFilename, $overrideMimeType);
1656 }
1657
1658 $properties = [
1659 'as_download' => $asDownload,
1660 'filename_overwrite' => $alternativeFilename,
1661 'mimetype_overwrite' => $overrideMimeType,
1662 ];
1663 return $this->driver->streamFile($file->getIdentifier(), $properties);
1664 }
1665
1666 /**
1667 * Wrap DriverInterface::dumpFileContents into a SelfEmittableStreamInterface
1668 *
1669 * @param FileInterface $file
1670 * @param bool $asDownload If set Content-Disposition attachment is sent, inline otherwise
1671 * @param string $alternativeFilename the filename for the download (if $asDownload is set)
1672 * @param string $overrideMimeType If set this will be used as Content-Type header instead of the automatically detected mime type.
1673 * @return ResponseInterface
1674 */
1675 protected function getPseudoStream(
1676 FileInterface $file,
1677 bool $asDownload = false,
1678 string $alternativeFilename = null,
1679 string $overrideMimeType = null
1680 ) {
1681 $downloadName = $alternativeFilename ?: $file->getName();
1682 $contentDisposition = $asDownload ? 'attachment' : 'inline';
1683
1684 $stream = new FalDumpFileContentsDecoratorStream($file->getIdentifier(), $this->driver, $file->getSize());
1685 $headers = [
1686 'Content-Disposition' => $contentDisposition . '; filename="' . $downloadName . '"',
1687 'Content-Type' => $overrideMimeType ?: $file->getMimeType(),
1688 'Content-Length' => (string)$file->getSize(),
1689 'Last-Modified' => gmdate('D, d M Y H:i:s', array_pop($this->driver->getFileInfoByIdentifier($file->getIdentifier(), ['mtime']))) . ' GMT',
1690 // Cache-Control header is needed here to solve an issue with browser IE8 and lower
1691 // See for more information: http://support.microsoft.com/kb/323308
1692 'Cache-Control' => '',
1693 ];
1694
1695 return new Response($stream, 200, $headers);
1696 }
1697
1698 /**
1699 * Set contents of a file object.
1700 *
1701 * @param AbstractFile $file
1702 * @param string $contents
1703 *
1704 * @throws \Exception|\RuntimeException
1705 * @throws Exception\InsufficientFileWritePermissionsException
1706 * @throws Exception\InsufficientUserPermissionsException
1707 * @return int The number of bytes written to the file
1708 */
1709 public function setFileContents(AbstractFile $file, $contents)
1710 {
1711 // Check if user is allowed to edit
1712 $this->assureFileWritePermissions($file);
1713 $this->emitPreFileSetContentsSignal($file, $contents);
1714 // Call driver method to update the file and update file index entry afterwards
1715 $result = $this->driver->setFileContents($file->getIdentifier(), $contents);
1716 if ($file instanceof File) {
1717 $this->getIndexer()->updateIndexEntry($file);
1718 }
1719 $this->emitPostFileSetContentsSignal($file, $contents);
1720 return $result;
1721 }
1722
1723 /**
1724 * Creates a new file
1725 *
1726 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_newfile()
1727 *
1728 * @param string $fileName The name of the file to be created
1729 * @param Folder $targetFolderObject The target folder where the file should be created
1730 *
1731 * @throws Exception\IllegalFileExtensionException
1732 * @throws Exception\InsufficientFolderWritePermissionsException
1733 * @return FileInterface The file object
1734 */
1735 public function createFile($fileName, Folder $targetFolderObject)
1736 {
1737 $this->assureFileAddPermissions($targetFolderObject, $fileName);
1738 $this->emitPreFileCreateSignal($fileName, $targetFolderObject);
1739 $newFileIdentifier = $this->driver->createFile($fileName, $targetFolderObject->getIdentifier());
1740 $this->emitPostFileCreateSignal($newFileIdentifier, $targetFolderObject);
1741 return $this->getResourceFactoryInstance()->getFileObjectByStorageAndIdentifier($this->getUid(), $newFileIdentifier);
1742 }
1743
1744 /**
1745 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::deleteFile()
1746 *
1747 * @param FileInterface $fileObject
1748 * @throws Exception\InsufficientFileAccessPermissionsException
1749 * @throws Exception\FileOperationErrorException
1750 * @return bool TRUE if deletion succeeded
1751 */
1752 public function deleteFile($fileObject)
1753 {
1754 $this->assureFileDeletePermissions($fileObject);
1755
1756 $this->emitPreFileDeleteSignal($fileObject);
1757 $deleted = true;
1758
1759 if ($this->driver->fileExists($fileObject->getIdentifier())) {
1760 // Disable permission check to find nearest recycler and move file without errors
1761 $currentPermissions = $this->evaluatePermissions;
1762 $this->evaluatePermissions = false;
1763
1764 $recyclerFolder = $this->getNearestRecyclerFolder($fileObject);
1765 if ($recyclerFolder === null) {
1766 $result = $this->driver->deleteFile($fileObject->getIdentifier());
1767 } else {
1768 $result = $this->moveFile($fileObject, $recyclerFolder);
1769 $deleted = false;
1770 }
1771
1772 $this->evaluatePermissions = $currentPermissions;
1773
1774 if (!$result) {
1775 throw new Exception\FileOperationErrorException('Deleting the file "' . $fileObject->getIdentifier() . '\' failed.', 1329831691);
1776 }
1777 }
1778 // Mark the file object as deleted
1779 if ($deleted && $fileObject instanceof AbstractFile) {
1780 $fileObject->setDeleted();
1781 }
1782
1783 $this->emitPostFileDeleteSignal($fileObject);
1784
1785 return true;
1786 }
1787
1788 /**
1789 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_copy()
1790 * copies a source file (from any location) in to the target
1791 * folder, the latter has to be part of this storage
1792 *
1793 * @param FileInterface $file
1794 * @param Folder $targetFolder
1795 * @param string $targetFileName an optional destination fileName
1796 * @param string $conflictMode a value of the DuplicationBehavior enumeration
1797 *
1798 * @throws \Exception|Exception\AbstractFileOperationException
1799 * @throws Exception\ExistingTargetFileNameException
1800 * @return FileInterface
1801 */
1802 public function copyFile(FileInterface $file, Folder $targetFolder, $targetFileName = null, $conflictMode = DuplicationBehavior::RENAME)
1803 {
1804 $conflictMode = DuplicationBehavior::cast($conflictMode);
1805 if ($targetFileName === null) {
1806 $targetFileName = $file->getName();
1807 }
1808 $sanitizedTargetFileName = $this->driver->sanitizeFileName($targetFileName);
1809 $this->assureFileCopyPermissions($file, $targetFolder, $sanitizedTargetFileName);
1810 $this->emitPreFileCopySignal($file, $targetFolder);
1811 // File exists and we should abort, let's abort
1812 if ($conflictMode->equals(DuplicationBehavior::CANCEL) && $targetFolder->hasFile($sanitizedTargetFileName)) {
1813 throw new Exception\ExistingTargetFileNameException('The target file already exists.', 1320291064);
1814 }
1815 // File exists and we should find another name, let's find another one
1816 if ($conflictMode->equals(DuplicationBehavior::RENAME) && $targetFolder->hasFile($sanitizedTargetFileName)) {
1817 $sanitizedTargetFileName = $this->getUniqueName($targetFolder, $sanitizedTargetFileName);
1818 }
1819 $sourceStorage = $file->getStorage();
1820 // Call driver method to create a new file from an existing file object,
1821 // and return the new file object
1822 if ($sourceStorage === $this) {
1823 $newFileObjectIdentifier = $this->driver->copyFileWithinStorage($file->getIdentifier(), $targetFolder->getIdentifier(), $sanitizedTargetFileName);
1824 } else {
1825 $tempPath = $file->getForLocalProcessing();
1826 $newFileObjectIdentifier = $this->driver->addFile($tempPath, $targetFolder->getIdentifier(), $sanitizedTargetFileName);
1827 }
1828 $newFileObject = $this->getResourceFactoryInstance()->getFileObjectByStorageAndIdentifier($this->getUid(), $newFileObjectIdentifier);
1829 $this->emitPostFileCopySignal($file, $targetFolder);
1830 return $newFileObject;
1831 }
1832
1833 /**
1834 * Moves a $file into a $targetFolder
1835 * the target folder has to be part of this storage
1836 *
1837 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_move()
1838 *
1839 * @param FileInterface $file
1840 * @param Folder $targetFolder
1841 * @param string $targetFileName an optional destination fileName
1842 * @param string $conflictMode a value of the DuplicationBehavior enumeration
1843 *
1844 * @throws Exception\ExistingTargetFileNameException
1845 * @throws \RuntimeException
1846 * @return FileInterface
1847 */
1848 public function moveFile($file, $targetFolder, $targetFileName = null, $conflictMode = DuplicationBehavior::RENAME)
1849 {
1850 $conflictMode = DuplicationBehavior::cast($conflictMode);
1851 if ($targetFileName === null) {
1852 $targetFileName = $file->getName();
1853 }
1854 $originalFolder = $file->getParentFolder();
1855 $sanitizedTargetFileName = $this->driver->sanitizeFileName($targetFileName);
1856 $this->assureFileMovePermissions($file, $targetFolder, $sanitizedTargetFileName);
1857 if ($targetFolder->hasFile($sanitizedTargetFileName)) {
1858 // File exists and we should abort, let's abort
1859 if ($conflictMode->equals(DuplicationBehavior::RENAME)) {
1860 $sanitizedTargetFileName = $this->getUniqueName($targetFolder, $sanitizedTargetFileName);
1861 } elseif ($conflictMode->equals(DuplicationBehavior::CANCEL)) {
1862 throw new Exception\ExistingTargetFileNameException('The target file already exists', 1329850997);
1863 }
1864 }
1865 $this->emitPreFileMoveSignal($file, $targetFolder, $sanitizedTargetFileName);
1866 $sourceStorage = $file->getStorage();
1867 // Call driver method to move the file and update the index entry
1868 try {
1869 if ($sourceStorage === $this) {
1870 $newIdentifier = $this->driver->moveFileWithinStorage($file->getIdentifier(), $targetFolder->getIdentifier(), $sanitizedTargetFileName);
1871 if (!$file instanceof AbstractFile) {
1872 throw new \RuntimeException('The given file is not of type AbstractFile.', 1384209025);
1873 }
1874 $file->updateProperties(['identifier' => $newIdentifier]);
1875 } else {
1876 $tempPath = $file->getForLocalProcessing();
1877 $newIdentifier = $this->driver->addFile($tempPath, $targetFolder->getIdentifier(), $sanitizedTargetFileName);
1878
1879 // Disable permission check to find nearest recycler and move file without errors
1880 $currentPermissions = $sourceStorage->evaluatePermissions;
1881 $sourceStorage->evaluatePermissions = false;
1882
1883 $recyclerFolder = $sourceStorage->getNearestRecyclerFolder($file);
1884 if ($recyclerFolder === null) {
1885 $sourceStorage->driver->deleteFile($file->getIdentifier());
1886 } else {
1887 $sourceStorage->moveFile($file, $recyclerFolder);
1888 }
1889 $sourceStorage->evaluatePermissions = $currentPermissions;
1890 if ($file instanceof File) {
1891 $file->updateProperties(['storage' => $this->getUid(), 'identifier' => $newIdentifier]);
1892 }
1893 }
1894 $this->getIndexer()->updateIndexEntry($file);
1895 } catch (\TYPO3\CMS\Core\Exception $e) {
1896 echo $e->getMessage();
1897 }
1898 $this->emitPostFileMoveSignal($file, $targetFolder, $originalFolder);
1899 return $file;
1900 }
1901
1902 /**
1903 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_rename()
1904 *
1905 * @param FileInterface $file
1906 * @param string $targetFileName
1907 * @param string $conflictMode
1908 * @return FileInterface
1909 * @throws ExistingTargetFileNameException
1910 */
1911 public function renameFile($file, $targetFileName, $conflictMode = DuplicationBehavior::RENAME)
1912 {
1913 // The name should be different from the current.
1914 if ($file->getName() === $targetFileName) {
1915 return $file;
1916 }
1917 $sanitizedTargetFileName = $this->driver->sanitizeFileName($targetFileName);
1918 $this->assureFileRenamePermissions($file, $sanitizedTargetFileName);
1919 $this->emitPreFileRenameSignal($file, $sanitizedTargetFileName);
1920
1921 $conflictMode = DuplicationBehavior::cast($conflictMode);
1922
1923 // Call driver method to rename the file and update the index entry
1924 try {
1925 $newIdentifier = $this->driver->renameFile($file->getIdentifier(), $sanitizedTargetFileName);
1926 if ($file instanceof File) {
1927 $file->updateProperties(['identifier' => $newIdentifier]);
1928 }
1929 $this->getIndexer()->updateIndexEntry($file);
1930 } catch (ExistingTargetFileNameException $exception) {
1931 if ($conflictMode->equals(DuplicationBehavior::RENAME)) {
1932 $newName = $this->getUniqueName($file->getParentFolder(), $sanitizedTargetFileName);
1933 $file = $this->renameFile($file, $newName);
1934 } elseif ($conflictMode->equals(DuplicationBehavior::CANCEL)) {
1935 throw $exception;
1936 } elseif ($conflictMode->equals(DuplicationBehavior::REPLACE)) {
1937 $sourceFileIdentifier = substr($file->getCombinedIdentifier(), 0, strrpos($file->getCombinedIdentifier(), '/') + 1) . $targetFileName;
1938 $sourceFile = $this->getResourceFactoryInstance()->getFileObjectFromCombinedIdentifier($sourceFileIdentifier);
1939 $file = $this->replaceFile($sourceFile, Environment::getPublicPath() . '/' . $file->getPublicUrl());
1940 }
1941 } catch (\RuntimeException $e) {
1942 }
1943
1944 $this->emitPostFileRenameSignal($file, $sanitizedTargetFileName);
1945
1946 return $file;
1947 }
1948
1949 /**
1950 * Replaces a file with a local file (e.g. a freshly uploaded file)
1951 *
1952 * @param FileInterface $file
1953 * @param string $localFilePath
1954 *
1955 * @return FileInterface
1956 *
1957 * @throws Exception\IllegalFileExtensionException
1958 * @throws \InvalidArgumentException
1959 */
1960 public function replaceFile(FileInterface $file, $localFilePath)
1961 {
1962 $this->assureFileReplacePermissions($file);
1963 if (!file_exists($localFilePath)) {
1964 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1325842622);
1965 }
1966 $this->emitPreFileReplaceSignal($file, $localFilePath);
1967 $this->driver->replaceFile($file->getIdentifier(), $localFilePath);
1968 if ($file instanceof File) {
1969 $this->getIndexer()->updateIndexEntry($file);
1970 }
1971 $this->emitPostFileReplaceSignal($file, $localFilePath);
1972
1973 return $file;
1974 }
1975
1976 /**
1977 * Adds an uploaded file into the Storage. Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::file_upload()
1978 *
1979 * @param array $uploadedFileData contains information about the uploaded file given by $_FILES['file1']
1980 * @param Folder $targetFolder the target folder
1981 * @param string $targetFileName the file name to be written
1982 * @param string $conflictMode a value of the DuplicationBehavior enumeration
1983 * @return FileInterface The file object
1984 */
1985 public function addUploadedFile(array $uploadedFileData, Folder $targetFolder = null, $targetFileName = null, $conflictMode = DuplicationBehavior::CANCEL)
1986 {
1987 $conflictMode = DuplicationBehavior::cast($conflictMode);
1988 $localFilePath = $uploadedFileData['tmp_name'];
1989 if ($targetFolder === null) {
1990 $targetFolder = $this->getDefaultFolder();
1991 }
1992 if ($targetFileName === null) {
1993 $targetFileName = $uploadedFileData['name'];
1994 }
1995 $targetFileName = $this->driver->sanitizeFileName($targetFileName);
1996
1997 $this->assureFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileData['size']);
1998 if ($this->hasFileInFolder($targetFileName, $targetFolder) && $conflictMode->equals(DuplicationBehavior::REPLACE)) {
1999 $file = $this->getFileInFolder($targetFileName, $targetFolder);
2000 $resultObject = $this->replaceFile($file, $localFilePath);
2001 } else {
2002 $resultObject = $this->addFile($localFilePath, $targetFolder, $targetFileName, (string)$conflictMode);
2003 }
2004 return $resultObject;
2005 }
2006
2007 /********************
2008 * FOLDER ACTIONS
2009 ********************/
2010 /**
2011 * Returns an array with all file objects in a folder and its subfolders, with the file identifiers as keys.
2012 * @todo check if this is a duplicate
2013 * @param Folder $folder
2014 * @return File[]
2015 */
2016 protected function getAllFileObjectsInFolder(Folder $folder)
2017 {
2018 $files = [];
2019 $folderQueue = [$folder];
2020 while (!empty($folderQueue)) {
2021 $folder = array_shift($folderQueue);
2022 foreach ($folder->getSubfolders() as $subfolder) {
2023 $folderQueue[] = $subfolder;
2024 }
2025 foreach ($folder->getFiles() as $file) {
2026 /** @var FileInterface $file */
2027 $files[$file->getIdentifier()] = $file;
2028 }
2029 }
2030
2031 return $files;
2032 }
2033
2034 /**
2035 * Moves a folder. If you want to move a folder from this storage to another
2036 * one, call this method on the target storage, otherwise you will get an exception.
2037 *
2038 * @param Folder $folderToMove The folder to move.
2039 * @param Folder $targetParentFolder The target parent folder
2040 * @param string $newFolderName
2041 * @param string $conflictMode a value of the DuplicationBehavior enumeration
2042 *
2043 * @throws \Exception|\TYPO3\CMS\Core\Exception
2044 * @throws \InvalidArgumentException
2045 * @throws InvalidTargetFolderException
2046 * @return Folder
2047 */
2048 public function moveFolder(Folder $folderToMove, Folder $targetParentFolder, $newFolderName = null, $conflictMode = DuplicationBehavior::RENAME)
2049 {
2050 // @todo add tests
2051 $originalFolder = $folderToMove->getParentFolder();
2052 $this->assureFolderMovePermissions($folderToMove, $targetParentFolder);
2053 $sourceStorage = $folderToMove->getStorage();
2054 $returnObject = null;
2055 $sanitizedNewFolderName = $this->driver->sanitizeFileName($newFolderName ?: $folderToMove->getName());
2056 // @todo check if folder already exists in $targetParentFolder, handle this conflict then
2057 $this->emitPreFolderMoveSignal($folderToMove, $targetParentFolder, $sanitizedNewFolderName);
2058 // Get all file objects now so we are able to update them after moving the folder
2059 $fileObjects = $this->getAllFileObjectsInFolder($folderToMove);
2060 if ($sourceStorage === $this) {
2061 if ($this->isWithinFolder($folderToMove, $targetParentFolder)) {
2062 throw new InvalidTargetFolderException(
2063 sprintf(
2064 'Cannot move folder "%s" into target folder "%s", because the target folder is already within the folder to be moved!',
2065 $folderToMove->getName(),
2066 $targetParentFolder->getName()
2067 ),
2068 1422723050
2069 );
2070 }
2071 $fileMappings = $this->driver->moveFolderWithinStorage($folderToMove->getIdentifier(), $targetParentFolder->getIdentifier(), $sanitizedNewFolderName);
2072 } else {
2073 $fileMappings = $this->moveFolderBetweenStorages($folderToMove, $targetParentFolder, $sanitizedNewFolderName);
2074 }
2075 // Update the identifier and storage of all file objects
2076 foreach ($fileObjects as $oldIdentifier => $fileObject) {
2077 $newIdentifier = $fileMappings[$oldIdentifier];
2078 $fileObject->updateProperties(['storage' => $this->getUid(), 'identifier' => $newIdentifier]);
2079 $this->getIndexer()->updateIndexEntry($fileObject);
2080 }
2081 $returnObject = $this->getFolder($fileMappings[$folderToMove->getIdentifier()]);
2082 $this->emitPostFolderMoveSignal($folderToMove, $targetParentFolder, $returnObject->getName(), $originalFolder);
2083 return $returnObject;
2084 }
2085
2086 /**
2087 * Moves the given folder from a different storage to the target folder in this storage.
2088 *
2089 * @param Folder $folderToMove
2090 * @param Folder $targetParentFolder
2091 * @param string $newFolderName
2092 * @throws NotImplementedMethodException
2093 */
2094 protected function moveFolderBetweenStorages(Folder $folderToMove, Folder $targetParentFolder, $newFolderName)
2095 {
2096 throw new NotImplementedMethodException('Not yet implemented', 1476046361);
2097 }
2098
2099 /**
2100 * Copies a folder.
2101 *
2102 * @param FolderInterface $folderToCopy The folder to copy
2103 * @param FolderInterface $targetParentFolder The target folder
2104 * @param string $newFolderName
2105 * @param string $conflictMode a value of the DuplicationBehavior enumeration
2106 * @return Folder The new (copied) folder object
2107 * @throws InvalidTargetFolderException
2108 */
2109 public function copyFolder(FolderInterface $folderToCopy, FolderInterface $targetParentFolder, $newFolderName = null, $conflictMode = DuplicationBehavior::RENAME)
2110 {
2111 // @todo implement the $conflictMode handling
2112 $this->assureFolderCopyPermissions($folderToCopy, $targetParentFolder);
2113 $returnObject = null;
2114 $sanitizedNewFolderName = $this->driver->sanitizeFileName($newFolderName ?: $folderToCopy->getName());
2115 if ($folderToCopy instanceof Folder && $targetParentFolder instanceof Folder) {
2116 $this->emitPreFolderCopySignal($folderToCopy, $targetParentFolder, $sanitizedNewFolderName);
2117 }
2118 $sourceStorage = $folderToCopy->getStorage();
2119 // call driver method to move the file
2120 // that also updates the file object properties
2121 if ($sourceStorage === $this) {
2122 if ($this->isWithinFolder($folderToCopy, $targetParentFolder)) {
2123 throw new InvalidTargetFolderException(
2124 sprintf(
2125 'Cannot copy folder "%s" into target folder "%s", because the target folder is already within the folder to be copied!',
2126 $folderToCopy->getName(),
2127 $targetParentFolder->getName()
2128 ),
2129 1422723059
2130 );
2131 }
2132 $this->driver->copyFolderWithinStorage($folderToCopy->getIdentifier(), $targetParentFolder->getIdentifier(), $sanitizedNewFolderName);
2133 $returnObject = $this->getFolder($targetParentFolder->getSubfolder($sanitizedNewFolderName)->getIdentifier());
2134 } else {
2135 $this->copyFolderBetweenStorages($folderToCopy, $targetParentFolder, $sanitizedNewFolderName);
2136 }
2137 $this->emitPostFolderCopySignal($folderToCopy, $targetParentFolder, $returnObject->getName());
2138 return $returnObject;
2139 }
2140
2141 /**
2142 * Copies a folder between storages.
2143 *
2144 * @param Folder $folderToCopy
2145 * @param Folder $targetParentFolder
2146 * @param string $newFolderName
2147 * @throws NotImplementedMethodException
2148 */
2149 protected function copyFolderBetweenStorages(Folder $folderToCopy, Folder $targetParentFolder, $newFolderName)
2150 {
2151 throw new NotImplementedMethodException('Not yet implemented.', 1476046386);
2152 }
2153
2154 /**
2155 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::folder_move()
2156 *
2157 * @param Folder $folderObject
2158 * @param string $newName
2159 * @throws \Exception
2160 * @throws \InvalidArgumentException
2161 * @return Folder
2162 */
2163 public function renameFolder($folderObject, $newName)
2164 {
2165
2166 // Renaming the folder should check if the parent folder is writable
2167 // We cannot do this however because we cannot extract the parent folder from a folder currently
2168 if (!$this->checkFolderActionPermission('rename', $folderObject)) {
2169 throw new Exception\InsufficientUserPermissionsException('You are not allowed to rename the folder "' . $folderObject->getIdentifier() . '\'', 1357811441);
2170 }
2171
2172 $sanitizedNewName = $this->driver->sanitizeFileName($newName);
2173 $returnObject = null;
2174 if ($this->driver->folderExistsInFolder($sanitizedNewName, $folderObject->getIdentifier())) {
2175 throw new \InvalidArgumentException('The folder ' . $sanitizedNewName . ' already exists in folder ' . $folderObject->getIdentifier(), 1325418870);
2176 }
2177
2178 $this->emitPreFolderRenameSignal($folderObject, $sanitizedNewName);
2179
2180 $fileObjects = $this->getAllFileObjectsInFolder($folderObject);
2181 $fileMappings = $this->driver->renameFolder($folderObject->getIdentifier(), $sanitizedNewName);
2182 // Update the identifier of all file objects
2183 foreach ($fileObjects as $oldIdentifier => $fileObject) {
2184 $newIdentifier = $fileMappings[$oldIdentifier];
2185 $fileObject->updateProperties(['identifier' => $newIdentifier]);
2186 $this->getIndexer()->updateIndexEntry($fileObject);
2187 }
2188 $returnObject = $this->getFolder($fileMappings[$folderObject->getIdentifier()]);
2189
2190 $this->emitPostFolderRenameSignal($returnObject, $returnObject->getName());
2191
2192 return $returnObject;
2193 }
2194
2195 /**
2196 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::folder_delete()
2197 *
2198 * @param Folder $folderObject
2199 * @param bool $deleteRecursively
2200 * @throws \RuntimeException
2201 * @throws Exception\InsufficientFolderAccessPermissionsException
2202 * @throws Exception\InsufficientUserPermissionsException
2203 * @throws Exception\FileOperationErrorException
2204 * @throws Exception\InvalidPathException
2205 * @return bool
2206 */
2207 public function deleteFolder($folderObject, $deleteRecursively = false)
2208 {
2209 $isEmpty = $this->driver->isFolderEmpty($folderObject->getIdentifier());
2210 $this->assureFolderDeletePermission($folderObject, $deleteRecursively && !$isEmpty);
2211 if (!$isEmpty && !$deleteRecursively) {
2212 throw new \RuntimeException('Could not delete folder "' . $folderObject->getIdentifier() . '" because it is not empty.', 1325952534);
2213 }
2214
2215 $this->emitPreFolderDeleteSignal($folderObject);
2216
2217 foreach ($this->getFilesInFolder($folderObject, 0, 0, false, $deleteRecursively) as $file) {
2218 $this->deleteFile($file);
2219 }
2220
2221 $result = $this->driver->deleteFolder($folderObject->getIdentifier(), $deleteRecursively);
2222
2223 $this->emitPostFolderDeleteSignal($folderObject);
2224
2225 return $result;
2226 }
2227
2228 /**
2229 * Returns the Identifier for a folder within a given folder.
2230 *
2231 * @param string $folderName The name of the target folder
2232 * @param Folder $parentFolder
2233 * @param bool $returnInaccessibleFolderObject
2234 * @return Folder|InaccessibleFolder
2235 * @throws \Exception
2236 * @throws Exception\InsufficientFolderAccessPermissionsException
2237 */
2238 public function getFolderInFolder($folderName, Folder $parentFolder, $returnInaccessibleFolderObject = false)
2239 {
2240 $folderIdentifier = $this->driver->getFolderInFolder($folderName, $parentFolder->getIdentifier());
2241 return $this->getFolder($folderIdentifier, $returnInaccessibleFolderObject);
2242 }
2243
2244 /**
2245 * @param Folder $folder
2246 * @param int $start
2247 * @param int $maxNumberOfItems
2248 * @param bool $useFilters
2249 * @param bool $recursive
2250 * @param string $sort Property name used to sort the items.
2251 * Among them may be: '' (empty, no sorting), name,
2252 * fileext, size, tstamp and rw.
2253 * If a driver does not support the given property, it
2254 * should fall back to "name".
2255 * @param bool $sortRev TRUE to indicate reverse sorting (last to first)
2256 * @return Folder[]
2257 */
2258 public function getFoldersInFolder(Folder $folder, $start = 0, $maxNumberOfItems = 0, $useFilters = true, $recursive = false, $sort = '', $sortRev = false)
2259 {
2260 $filters = $useFilters == true ? $this->fileAndFolderNameFilters : [];
2261
2262 $folderIdentifiers = $this->driver->getFoldersInFolder($folder->getIdentifier(), $start, $maxNumberOfItems, $recursive, $filters, $sort, $sortRev);
2263
2264 // Exclude processing folders
2265 foreach ($this->getProcessingFolders() as $processingFolder) {
2266 $processingIdentifier = $processingFolder->getIdentifier();
2267 if (isset($folderIdentifiers[$processingIdentifier])) {
2268 unset($folderIdentifiers[$processingIdentifier]);
2269 }
2270 }
2271 $folders = [];
2272 foreach ($folderIdentifiers as $folderIdentifier) {
2273 $folders[$folderIdentifier] = $this->getFolder($folderIdentifier, true);
2274 }
2275 return $folders;
2276 }
2277
2278 /**
2279 * @param Folder $folder
2280 * @param bool $useFilters
2281 * @param bool $recursive
2282 * @return int Number of subfolders
2283 * @throws Exception\InsufficientFolderAccessPermissionsException
2284 */
2285 public function countFoldersInFolder(Folder $folder, $useFilters = true, $recursive = false)
2286 {
2287 $this->assureFolderReadPermission($folder);
2288 $filters = $useFilters ? $this->fileAndFolderNameFilters : [];
2289 return $this->driver->countFoldersInFolder($folder->getIdentifier(), $recursive, $filters);
2290 }
2291
2292 /**
2293 * Returns TRUE if the specified folder exists.
2294 *
2295 * @param string $identifier
2296 * @return bool
2297 */
2298 public function hasFolder($identifier)
2299 {
2300 $this->assureFolderReadPermission();
2301 return $this->driver->folderExists($identifier);
2302 }
2303
2304 /**
2305 * Checks if the given file exists in the given folder
2306 *
2307 * @param string $folderName
2308 * @param Folder $folder
2309 * @return bool
2310 */
2311 public function hasFolderInFolder($folderName, Folder $folder)
2312 {
2313 $this->assureFolderReadPermission($folder);
2314 return $this->driver->folderExistsInFolder($folderName, $folder->getIdentifier());
2315 }
2316
2317 /**
2318 * Creates a new folder.
2319 *
2320 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_newfolder()
2321 *
2322 * @param string $folderName The new folder name
2323 * @param Folder $parentFolder (optional) the parent folder to create the new folder inside of. If not given, the root folder is used
2324 * @return Folder
2325 * @throws Exception\ExistingTargetFolderException
2326 * @throws Exception\InsufficientFolderAccessPermissionsException
2327 * @throws Exception\InsufficientFolderWritePermissionsException
2328 * @throws \Exception
2329 */
2330 public function createFolder($folderName, Folder $parentFolder = null)
2331 {
2332 if ($parentFolder === null) {
2333 $parentFolder = $this->getRootLevelFolder();
2334 } elseif (!$this->driver->folderExists($parentFolder->getIdentifier())) {
2335 throw new \InvalidArgumentException('Parent folder "' . $parentFolder->getIdentifier() . '" does not exist.', 1325689164);
2336 }
2337 if (!$this->checkFolderActionPermission('add', $parentFolder)) {
2338 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to create directories in the folder "' . $parentFolder->getIdentifier() . '"', 1323059807);
2339 }
2340 if ($this->driver->folderExistsInFolder($folderName, $parentFolder->getIdentifier())) {
2341 throw new Exception\ExistingTargetFolderException('Folder "' . $folderName . '" already exists.', 1423347324);
2342 }
2343
2344 $this->emitPreFolderAddSignal($parentFolder, $folderName);
2345
2346 $newFolder = $this->getDriver()->createFolder($folderName, $parentFolder->getIdentifier(), true);
2347 $newFolder = $this->getFolder($newFolder);
2348
2349 $this->emitPostFolderAddSignal($newFolder);
2350
2351 return $newFolder;
2352 }
2353
2354 /**
2355 * Retrieves information about a folder
2356 *
2357 * @param Folder $folder
2358 * @return array
2359 */
2360 public function getFolderInfo(Folder $folder)
2361 {
2362 return $this->driver->getFolderInfoByIdentifier($folder->getIdentifier());
2363 }
2364
2365 /**
2366 * Returns the default folder where new files are stored if no other folder is given.
2367 *
2368 * @return Folder
2369 */
2370 public function getDefaultFolder()
2371 {
2372 return $this->getFolder($this->driver->getDefaultFolder());
2373 }
2374
2375 /**
2376 * @param string $identifier
2377 * @param bool $returnInaccessibleFolderObject
2378 *
2379 * @return Folder|InaccessibleFolder
2380 * @throws \Exception
2381 * @throws Exception\InsufficientFolderAccessPermissionsException
2382 */
2383 public function getFolder($identifier, $returnInaccessibleFolderObject = false)
2384 {
2385 $data = $this->driver->getFolderInfoByIdentifier($identifier);
2386 $folder = $this->getResourceFactoryInstance()->createFolderObject($this, $data['identifier'], $data['name']);
2387
2388 try {
2389 $this->assureFolderReadPermission($folder);
2390 } catch (Exception\InsufficientFolderAccessPermissionsException $e) {
2391 $folder = null;
2392 if ($returnInaccessibleFolderObject) {
2393 // if parent folder is readable return inaccessible folder object
2394 $parentPermissions = $this->driver->getPermissions($this->driver->getParentFolderIdentifierOfIdentifier($identifier));
2395 if ($parentPermissions['r']) {
2396 $folder = GeneralUtility::makeInstance(
2397 InaccessibleFolder::class,
2398 $this,
2399 $data['identifier'],
2400 $data['name']
2401 );
2402 }
2403 }
2404
2405 if ($folder === null) {
2406 throw $e;
2407 }
2408 }
2409 return $folder;
2410 }
2411
2412 /**
2413 * Returns TRUE if the specified file is in a folder that is set a processing for a storage
2414 *
2415 * @param string $identifier
2416 * @return bool
2417 */
2418 public function isWithinProcessingFolder($identifier)
2419 {
2420 $inProcessingFolder = false;
2421 foreach ($this->getProcessingFolders() as $processingFolder) {
2422 if ($this->driver->isWithin($processingFolder->getIdentifier(), $identifier)) {
2423 $inProcessingFolder = true;
2424 break;
2425 }
2426 }
2427 return $inProcessingFolder;
2428 }
2429
2430 /**
2431 * Checks if a resource (file or folder) is within the given folder
2432 *
2433 * @param Folder $folder
2434 * @param ResourceInterface $resource
2435 * @return bool
2436 * @throws \InvalidArgumentException
2437 */
2438 public function isWithinFolder(Folder $folder, ResourceInterface $resource)
2439 {
2440 if ($folder->getStorage() !== $this) {
2441 throw new \InvalidArgumentException('Given folder "' . $folder->getIdentifier() . '" is not part of this storage!', 1422709241);
2442 }
2443 if ($folder->getStorage() !== $resource->getStorage()) {
2444 return false;
2445 }
2446 return $this->driver->isWithin($folder->getIdentifier(), $resource->getIdentifier());
2447 }
2448
2449 /**
2450 * Returns the folders on the root level of the storage
2451 * or the first mount point of this storage for this user
2452 * if $respectFileMounts is set.
2453 *
2454 * @param bool $respectFileMounts
2455 * @return Folder
2456 */
2457 public function getRootLevelFolder($respectFileMounts = true)
2458 {
2459 if ($respectFileMounts && !empty($this->fileMounts)) {
2460 $mount = reset($this->fileMounts);
2461 return $mount['folder'];
2462 }
2463 return $this->getResourceFactoryInstance()->createFolderObject($this, $this->driver->getRootLevelFolder(), '');
2464 }
2465
2466 /**
2467 * Emits sanitize fileName signal.
2468 *
2469 * @param string $fileName
2470 * @param Folder $targetFolder
2471 * @return string Modified target file name
2472 */
2473 protected function emitSanitizeFileNameSignal($fileName, Folder $targetFolder)
2474 {
2475 list($fileName) = $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_SanitizeFileName, [$fileName, $targetFolder, $this, $this->driver]);
2476 return $fileName;
2477 }
2478
2479 /**
2480 * Emits file pre-add signal.
2481 *
2482 * @param string $targetFileName
2483 * @param Folder $targetFolder
2484 * @param string $sourceFilePath
2485 * @return string Modified target file name
2486 */
2487 protected function emitPreFileAddSignal($targetFileName, Folder $targetFolder, $sourceFilePath)
2488 {
2489 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFileAdd, [&$targetFileName, $targetFolder, $sourceFilePath, $this, $this->driver]);
2490 return $targetFileName;
2491 }
2492
2493 /**
2494 * Emits the file post-add signal.
2495 *
2496 * @param FileInterface $file
2497 * @param Folder $targetFolder
2498 */
2499 protected function emitPostFileAddSignal(FileInterface $file, Folder $targetFolder)
2500 {
2501 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFileAdd, [$file, $targetFolder]);
2502 }
2503
2504 /**
2505 * Emits file pre-copy signal.
2506 *
2507 * @param FileInterface $file
2508 * @param Folder $targetFolder
2509 */
2510 protected function emitPreFileCopySignal(FileInterface $file, Folder $targetFolder)
2511 {
2512 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFileCopy, [$file, $targetFolder]);
2513 }
2514
2515 /**
2516 * Emits the file post-copy signal.
2517 *
2518 * @param FileInterface $file
2519 * @param Folder $targetFolder
2520 */
2521 protected function emitPostFileCopySignal(FileInterface $file, Folder $targetFolder)
2522 {
2523 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFileCopy, [$file, $targetFolder]);
2524 }
2525
2526 /**
2527 * Emits the file pre-move signal.
2528 *
2529 * @param FileInterface $file
2530 * @param Folder $targetFolder
2531 * @param string $targetFileName
2532 */
2533 protected function emitPreFileMoveSignal(FileInterface $file, Folder $targetFolder, string $targetFileName)
2534 {
2535 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFileMove, [$file, $targetFolder, $targetFileName]);
2536 }
2537
2538 /**
2539 * Emits the file post-move signal.
2540 *
2541 * @param FileInterface $file
2542 * @param Folder $targetFolder
2543 * @param FolderInterface $originalFolder
2544 */
2545 protected function emitPostFileMoveSignal(FileInterface $file, Folder $targetFolder, FolderInterface $originalFolder)
2546 {
2547 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFileMove, [$file, $targetFolder, $originalFolder]);
2548 }
2549
2550 /**
2551 * Emits the file pre-rename signal
2552 *
2553 * @param FileInterface $file
2554 * @param $targetFolder
2555 */
2556 protected function emitPreFileRenameSignal(FileInterface $file, $targetFolder)
2557 {
2558 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFileRename, [$file, $targetFolder]);
2559 }
2560
2561 /**
2562 * Emits the file post-rename signal.
2563 *
2564 * @param FileInterface $file
2565 * @param string $sanitizedTargetFileName
2566 */
2567 protected function emitPostFileRenameSignal(FileInterface $file, $sanitizedTargetFileName)
2568 {
2569 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFileRename, [$file, $sanitizedTargetFileName]);
2570 }
2571
2572 /**
2573 * Emits the file pre-replace signal.
2574 *
2575 * @param FileInterface $file
2576 * @param $localFilePath
2577 */
2578 protected function emitPreFileReplaceSignal(FileInterface $file, $localFilePath)
2579 {
2580 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFileReplace, [$file, $localFilePath]);
2581 }
2582
2583 /**
2584 * Emits the file post-replace signal
2585 *
2586 * @param FileInterface $file
2587 * @param string $localFilePath
2588 */
2589 protected function emitPostFileReplaceSignal(FileInterface $file, $localFilePath)
2590 {
2591 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFileReplace, [$file, $localFilePath]);
2592 }
2593
2594 /**
2595 * Emits the file pre-create signal
2596 *
2597 * @param string $fileName
2598 * @param Folder $targetFolder
2599 */
2600 protected function emitPreFileCreateSignal(string $fileName, Folder $targetFolder)
2601 {
2602 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFileCreate, [$fileName, $targetFolder]);
2603 }
2604
2605 /**
2606 * Emits the file post-create signal
2607 *
2608 * @param string $newFileIdentifier
2609 * @param Folder $targetFolder
2610 */
2611 protected function emitPostFileCreateSignal($newFileIdentifier, Folder $targetFolder)
2612 {
2613 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFileCreate, [$newFileIdentifier, $targetFolder]);
2614 }
2615
2616 /**
2617 * Emits the file pre-deletion signal.
2618 *
2619 * @param FileInterface $file
2620 */
2621 protected function emitPreFileDeleteSignal(FileInterface $file)
2622 {
2623 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFileDelete, [$file]);
2624 }
2625
2626 /**
2627 * Emits the file post-deletion signal
2628 *
2629 * @param FileInterface $file
2630 */
2631 protected function emitPostFileDeleteSignal(FileInterface $file)
2632 {
2633 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFileDelete, [$file]);
2634 }
2635
2636 /**
2637 * Emits the file pre-set-contents signal
2638 *
2639 * @param FileInterface $file
2640 * @param mixed $content
2641 */
2642 protected function emitPreFileSetContentsSignal(FileInterface $file, $content)
2643 {
2644 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFileSetContents, [$file, $content]);
2645 }
2646
2647 /**
2648 * Emits the file post-set-contents signal
2649 *
2650 * @param FileInterface $file
2651 * @param mixed $content
2652 */
2653 protected function emitPostFileSetContentsSignal(FileInterface $file, $content)
2654 {
2655 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFileSetContents, [$file, $content]);
2656 }
2657
2658 /**
2659 * Emits the folder pre-add signal.
2660 *
2661 * @param Folder $targetFolder
2662 * @param string $name
2663 */
2664 protected function emitPreFolderAddSignal(Folder $targetFolder, $name)
2665 {
2666 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFolderAdd, [$targetFolder, $name]);
2667 }
2668
2669 /**
2670 * Emits the folder post-add signal.
2671 *
2672 * @param Folder $folder
2673 */
2674 protected function emitPostFolderAddSignal(Folder $folder)
2675 {
2676 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFolderAdd, [$folder]);
2677 }
2678
2679 /**
2680 * Emits the folder pre-copy signal.
2681 *
2682 * @param Folder $folder
2683 * @param Folder $targetFolder
2684 * @param $newName
2685 */
2686 protected function emitPreFolderCopySignal(Folder $folder, Folder $targetFolder, $newName)
2687 {
2688 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFolderCopy, [$folder, $targetFolder, $newName]);
2689 }
2690
2691 /**
2692 * Emits the folder post-copy signal.
2693 *
2694 * @param Folder $folder
2695 * @param Folder $targetFolder
2696 * @param $newName
2697 */
2698 protected function emitPostFolderCopySignal(Folder $folder, Folder $targetFolder, $newName)
2699 {
2700 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFolderCopy, [$folder, $targetFolder, $newName]);
2701 }
2702
2703 /**
2704 * Emits the folder pre-move signal.
2705 *
2706 * @param Folder $folder
2707 * @param Folder $targetFolder
2708 * @param $newName
2709 */
2710 protected function emitPreFolderMoveSignal(Folder $folder, Folder $targetFolder, $newName)
2711 {
2712 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFolderMove, [$folder, $targetFolder, $newName]);
2713 }
2714
2715 /**
2716 * Emits the folder post-move signal.
2717 *
2718 * @param Folder $folder
2719 * @param Folder $targetFolder
2720 * @param string $newName
2721 * @param Folder $originalFolder
2722 */
2723 protected function emitPostFolderMoveSignal(Folder $folder, Folder $targetFolder, $newName, Folder $originalFolder)
2724 {
2725 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFolderMove, [$folder, $targetFolder, $newName, $originalFolder]);
2726 }
2727
2728 /**
2729 * Emits the folder pre-rename signal.
2730 *
2731 * @param Folder $folder
2732 * @param string $newName
2733 */
2734 protected function emitPreFolderRenameSignal(Folder $folder, $newName)
2735 {
2736 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFolderRename, [$folder, $newName]);
2737 }
2738
2739 /**
2740 * Emits the folder post-rename signal.
2741 *
2742 * @param Folder $folder
2743 * @param string $newName
2744 */
2745 protected function emitPostFolderRenameSignal(Folder $folder, $newName)
2746 {
2747 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFolderRename, [$folder, $newName]);
2748 }
2749
2750 /**
2751 * Emits the folder pre-deletion signal.
2752 *
2753 * @param Folder $folder
2754 */
2755 protected function emitPreFolderDeleteSignal(Folder $folder)
2756 {
2757 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreFolderDelete, [$folder]);
2758 }
2759
2760 /**
2761 * Emits folder post-deletion signal..
2762 *
2763 * @param Folder $folder
2764 */
2765 protected function emitPostFolderDeleteSignal(Folder $folder)
2766 {
2767 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PostFolderDelete, [$folder]);
2768 }
2769
2770 /**
2771 * Emits file pre-processing signal when generating a public url for a file or folder.
2772 *
2773 * @param ResourceInterface $resourceObject
2774 * @param bool $relativeToCurrentScript
2775 * @param array $urlData
2776 */
2777 protected function emitPreGeneratePublicUrlSignal(ResourceInterface $resourceObject, $relativeToCurrentScript, array $urlData)
2778 {
2779 $this->getSignalSlotDispatcher()->dispatch(self::class, self::SIGNAL_PreGeneratePublicUrl, [$this, $this->driver, $resourceObject, $relativeToCurrentScript, $urlData]);
2780 }
2781
2782 /**
2783 * Returns the destination path/fileName of a unique fileName/foldername in that path.
2784 * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber.
2785 * Hereafter a unique string will be appended.
2786 * This function is used by fx. DataHandler when files are attached to records
2787 * and needs to be uniquely named in the uploads/* folders
2788 *
2789 * @param FolderInterface $folder
2790 * @param string $theFile The input fileName to check
2791 * @param bool $dontCheckForUnique If set the fileName is returned with the path prepended without checking whether it already existed!
2792 *
2793 * @throws \RuntimeException
2794 * @return string A unique fileName inside $folder, based on $theFile.
2795 * @see \TYPO3\CMS\Core\Utility\File\BasicFileUtility::getUniqueName()
2796 */
2797 protected function getUniqueName(FolderInterface $folder, $theFile, $dontCheckForUnique = false)
2798 {
2799 $maxNumber = 99;
2800 // Fetches info about path, name, extension of $theFile
2801 $origFileInfo = PathUtility::pathinfo($theFile);
2802 // Check if the file exists and if not - return the fileName...
2803 // The destinations file
2804 $theDestFile = $origFileInfo['basename'];
2805 // If the file does NOT exist we return this fileName
2806 if (!$this->driver->fileExistsInFolder($theDestFile, $folder->getIdentifier()) || $dontCheckForUnique) {
2807 return $theDestFile;
2808 }
2809 // Well the fileName in its pure form existed. Now we try to append
2810 // numbers / unique-strings and see if we can find an available fileName
2811 // This removes _xx if appended to the file
2812 $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filename']);
2813 $theOrigExt = $origFileInfo['extension'] ? '.' . $origFileInfo['extension'] : '';
2814 for ($a = 1; $a <= $maxNumber + 1; $a++) {
2815 // First we try to append numbers
2816 if ($a <= $maxNumber) {
2817 $insert = '_' . sprintf('%02d', $a);
2818 } else {
2819 $insert = '_' . substr(md5(uniqid('', true)), 0, 6);
2820 }
2821 $theTestFile = $theTempFileBody . $insert . $theOrigExt;
2822 // The destinations file
2823 $theDestFile = $theTestFile;
2824 // If the file does NOT exist we return this fileName
2825 if (!$this->driver->fileExistsInFolder($theDestFile, $folder->getIdentifier())) {
2826 return $theDestFile;
2827 }
2828 }
2829 throw new \RuntimeException('Last possible name "' . $theDestFile . '" is already taken.', 1325194291);
2830 }
2831
2832 /**
2833 * Get the SignalSlot dispatcher.
2834 *
2835 * @return Dispatcher
2836 */
2837 protected function getSignalSlotDispatcher()
2838 {
2839 if (!isset($this->signalSlotDispatcher)) {
2840 $this->signalSlotDispatcher = $this->getObjectManager()->get(Dispatcher::class);
2841 }
2842 return $this->signalSlotDispatcher;
2843 }
2844
2845 /**
2846 * Gets the ObjectManager.
2847 *
2848 * @return ObjectManager
2849 */
2850 protected function getObjectManager()
2851 {
2852 return GeneralUtility::makeInstance(ObjectManager::class);
2853 }
2854
2855 /**
2856 * @return ResourceFactory
2857 */
2858 protected function getFileFactory()
2859 {
2860 return GeneralUtility::makeInstance(ResourceFactory::class);
2861 }
2862
2863 /**
2864 * @return Index\FileIndexRepository
2865 */
2866 protected function getFileIndexRepository()
2867 {
2868 return FileIndexRepository::getInstance();
2869 }
2870
2871 /**
2872 * @return Service\FileProcessingService
2873 */
2874 protected function getFileProcessingService()
2875 {
2876 if (!$this->fileProcessingService) {
2877 $this->fileProcessingService = GeneralUtility::makeInstance(Service\FileProcessingService::class, $this, $this->driver);
2878 }
2879 return $this->fileProcessingService;
2880 }
2881
2882 /**
2883 * Gets the role of a folder.
2884 *
2885 * @param FolderInterface $folder Folder object to get the role from
2886 * @return string The role the folder has
2887 */
2888 public function getRole(FolderInterface $folder)
2889 {
2890 $folderRole = FolderInterface::ROLE_DEFAULT;
2891 $identifier = $folder->getIdentifier();
2892 if (method_exists($this->driver, 'getRole')) {
2893 $folderRole = $this->driver->getRole($folder->getIdentifier());
2894 }
2895 if (isset($this->fileMounts[$identifier])) {
2896 $folderRole = FolderInterface::ROLE_MOUNT;
2897
2898 if (!empty($this->fileMounts[$identifier]['read_only'])) {
2899 $folderRole = FolderInterface::ROLE_READONLY_MOUNT;
2900 }
2901 if ($this->fileMounts[$identifier]['user_mount']) {
2902 $folderRole = FolderInterface::ROLE_USER_MOUNT;
2903 }
2904 }
2905 if ($folder instanceof Folder && $this->isProcessingFolder($folder)) {
2906 $folderRole = FolderInterface::ROLE_PROCESSING;
2907 }
2908
2909 return $folderRole;
2910 }
2911
2912 /**
2913 * Getter function to return the folder where the files can
2914 * be processed. Does not check for access rights here.
2915 *
2916 * @param File $file Specific file you want to have the processing folder for
2917 * @return Folder
2918 */
2919 public function getProcessingFolder(File $file = null)
2920 {
2921 // If a file is given, make sure to return the processing folder of the correct storage
2922 if ($file !== null && $file->getStorage()->getUid() !== $this->getUid()) {
2923 return $file->getStorage()->getProcessingFolder($file);
2924 }
2925 if (!isset($this->processingFolder)) {
2926 $processingFolder = self::DEFAULT_ProcessingFolder;
2927 if (!empty($this->storageRecord['processingfolder'])) {
2928 $processingFolder = $this->storageRecord['processingfolder'];
2929 }
2930 try {
2931 if (strpos($processingFolder, ':') !== false) {
2932 list($storageUid, $processingFolderIdentifier) = explode(':', $processingFolder, 2);
2933 $storage = $this->getResourceFactoryInstance()->getStorageObject($storageUid);
2934 if ($storage->hasFolder($processingFolderIdentifier)) {
2935 $this->processingFolder = $storage->getFolder($processingFolderIdentifier);
2936 } else {
2937 $rootFolder = $storage->getRootLevelFolder(false);
2938 $currentEvaluatePermissions = $storage->getEvaluatePermissions();
2939 $storage->setEvaluatePermissions(false);
2940 $this->processingFolder = $storage->createFolder(
2941 ltrim($processingFolderIdentifier, '/'),
2942 $rootFolder
2943 );
2944 $storage->setEvaluatePermissions($currentEvaluatePermissions);
2945 }
2946 } else {
2947 if ($this->driver->folderExists($processingFolder) === false) {
2948 $rootFolder = $this->getRootLevelFolder(false);
2949 try {
2950 $currentEvaluatePermissions = $this->evaluatePermissions;
2951 $this->evaluatePermissions = false;
2952 $this->processingFolder = $this->createFolder(
2953 $processingFolder,
2954 $rootFolder
2955 );
2956 $this->evaluatePermissions = $currentEvaluatePermissions;
2957 } catch (\InvalidArgumentException $e) {
2958 $this->processingFolder = GeneralUtility::makeInstance(
2959 InaccessibleFolder::class,
2960 $this,
2961 $processingFolder,
2962 $processingFolder
2963 );
2964 }
2965 } else {
2966 $data = $this->driver->getFolderInfoByIdentifier($processingFolder);
2967 $this->processingFolder = $this->getResourceFactoryInstance()->createFolderObject($this, $data['identifier'], $data['name']);
2968 }
2969 }
2970 } catch (Exception\InsufficientFolderWritePermissionsException $e) {
2971 $this->processingFolder = GeneralUtility::makeInstance(
2972 InaccessibleFolder::class,
2973 $this,
2974 $processingFolder,
2975 $processingFolder
2976 );
2977 } catch (Exception\ResourcePermissionsUnavailableException $e) {
2978 $this->processingFolder = GeneralUtility::makeInstance(
2979 InaccessibleFolder::class,
2980 $this,
2981 $processingFolder,
2982 $processingFolder
2983 );
2984 }
2985 }
2986
2987 $processingFolder = $this->processingFolder;
2988 if (!empty($file)) {
2989 $processingFolder = $this->getNestedProcessingFolder($file, $processingFolder);
2990 }
2991 return $processingFolder;
2992 }
2993
2994 /**
2995 * Getter function to return the the file's corresponding hashed subfolder
2996 * of the processed folder
2997 *
2998 * @param File $file
2999 * @param Folder $rootProcessingFolder
3000 * @return Folder
3001 * @throws Exception\InsufficientFolderWritePermissionsException
3002 */
3003 protected function getNestedProcessingFolder(File $file, Folder $rootProcessingFolder)
3004 {
3005 $processingFolder = $rootProcessingFolder;
3006 $nestedFolderNames = $this->getNamesForNestedProcessingFolder(
3007 $file->getIdentifier(),
3008 self::PROCESSING_FOLDER_LEVELS
3009 );
3010
3011 try {
3012 foreach ($nestedFolderNames as $folderName) {
3013 if ($processingFolder->hasFolder($folderName)) {
3014 $processingFolder = $processingFolder->getSubfolder($folderName);
3015 } else {
3016 $currentEvaluatePermissions = $processingFolder->getStorage()->getEvaluatePermissions();
3017 $processingFolder->getStorage()->setEvaluatePermissions(false);
3018 $processingFolder = $processingFolder->createFolder($folderName);
3019 $processingFolder->getStorage()->setEvaluatePermissions($currentEvaluatePermissions);
3020 }
3021 }
3022 } catch (Exception\FolderDoesNotExistException $e) {
3023 }
3024
3025 return $processingFolder;
3026 }
3027
3028 /**
3029 * Generates appropriate hashed sub-folder path for a given file identifier
3030 *
3031 * @param string $fileIdentifier
3032 * @param int $levels
3033 * @return string[]
3034 */
3035 protected function getNamesForNestedProcessingFolder($fileIdentifier, $levels)
3036 {
3037 $names = [];
3038 if ($levels === 0) {
3039 return $names;
3040 }
3041 $hash = md5($fileIdentifier);
3042 for ($i = 1; $i <= $levels; $i++) {
3043 $names[] = substr($hash, $i, 1);
3044 }
3045 return $names;
3046 }
3047
3048 /**
3049 * Gets the driver Type configured for this storage.
3050 *
3051 * @return string
3052 */
3053 public function getDriverType()
3054 {
3055 return $this->storageRecord['driver'];
3056 }
3057
3058 /**
3059 * Gets the Indexer.
3060 *
3061 * @return Index\Indexer
3062 */
3063 protected function getIndexer()
3064 {
3065 return GeneralUtility::makeInstance(Index\Indexer::class, $this);
3066 }
3067
3068 /**
3069 * @param bool $isDefault
3070 */
3071 public function setDefault($isDefault)
3072 {
3073 $this->isDefault = (bool)$isDefault;
3074 }
3075
3076 /**
3077 * @return bool
3078 */
3079 public function isDefault()
3080 {
3081 return $this->isDefault;
3082 }
3083
3084 /**
3085 * @return ResourceFactory
3086 */
3087 public function getResourceFactoryInstance(): ResourceFactory
3088 {
3089 return ResourceFactory::getInstance();
3090 }
3091
3092 /**
3093 * Returns the current BE user.
3094 *
3095 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
3096 */
3097 protected function getBackendUser()
3098 {
3099 return $GLOBALS['BE_USER'];
3100 }
3101
3102 /**
3103 * Get the nearest Recycler folder for given file
3104 *
3105 * Return null if:
3106 * - There is no folder with ROLE_RECYCLER in the rootline of the given File
3107 * - File is a ProcessedFile (we don't know the concept of recycler folders for processedFiles)
3108 * - File is located in a folder with ROLE_RECYCLER
3109 *
3110 * @param FileInterface $file
3111 * @return Folder|null
3112 */
3113 protected function getNearestRecyclerFolder(FileInterface $file)
3114 {
3115 if ($file instanceof ProcessedFile) {
3116 return null;
3117 }
3118
3119 $recyclerFolder = null;
3120 $folder = $file->getParentFolder();
3121
3122 do {
3123 if ($folder->getRole() === FolderInterface::ROLE_RECYCLER) {
3124 break;
3125 }
3126
3127 foreach ($folder->getSubfolders() as $subFolder) {
3128 if ($subFolder->getRole() === FolderInterface::ROLE_RECYCLER) {
3129 $recyclerFolder = $subFolder;
3130 break;
3131 }
3132 }
3133
3134 $parentFolder = $folder->getParentFolder();
3135 $isFolderLoop = $folder->getIdentifier() === $parentFolder->getIdentifier();
3136 $folder = $parentFolder;
3137 } while ($recyclerFolder === null && !$isFolderLoop);
3138
3139 return $recyclerFolder;
3140 }
3141 }