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