2 namespace TYPO3\CMS\Core\
Resource;
4 /***************************************************************
7 * (c) 2011-2013 Andreas Wolf <andreas.wolf@typo3.org>
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
30 use TYPO3\CMS\Core\
Resource\Index\FileIndexRepository
;
31 use TYPO3\CMS\Core\Utility\GeneralUtility
;
32 use TYPO3\CMS\Core\Utility\PathUtility
;
35 * A "mount point" inside the TYPO3 file handling.
37 * A "storage" object handles
38 * - abstraction to the driver
39 * - permissions (from the driver, and from the user, + capabilities)
40 * - an entry point for files, folders, and for most other operations
42 * == Driver entry point
43 * The driver itself, that does the actual work on the file system,
44 * is inside the storage but completely shadowed by
45 * the storage, as the storage also handles the abstraction to the
48 * The storage can be on the local system, but can also be on a remote
49 * system. The combination of driver + configurable capabilities (storage
50 * is read-only e.g.) allows for flexible uses.
53 * == Permission system
54 * As all requests have to run through the storage, the storage knows about the
55 * permissions of a BE/FE user, the file permissions / limitations of the driver
56 * and has some configurable capabilities.
57 * Additionally, a BE user can use "filemounts" (known from previous installations)
58 * to limit his/her work-zone to only a subset (identifier and its subfolders/subfolders)
61 * Check 1: "User Permissions" [is the user allowed to write a file) [is the user allowed to write a file]
62 * Check 2: "File Mounts" of the User (act as subsets / filters to the identifiers) [is the user allowed to do something in this folder?]
63 * Check 3: "Capabilities" of Storage (then: of Driver) [is the storage/driver writable?]
64 * Check 4: "File permissions" of the Driver [is the folder writable?]
66 * @author Andreas Wolf <andreas.wolf@typo3.org>
67 * @author Ingmar Schlecht <ingmar@typo3.org>
69 class ResourceStorage
implements ResourceStorageInterface
{
72 * The storage driver instance belonging to this storage.
74 * @var Driver\DriverInterface
79 * The database record for this storage
83 protected $storageRecord;
86 * The configuration belonging to this storage (decoded from the configuration field).
90 protected $configuration;
93 * @var Service\FileProcessingService
95 protected $fileProcessingService;
98 * Whether to check if file or folder is in user mounts
99 * and the action is allowed for a user
100 * Default is FALSE so that resources are accessible for
101 * front end rendering or admins.
105 protected $evaluatePermissions = FALSE;
108 * User filemounts, added as an array, and used as filters
112 protected $fileMounts = array();
115 * The file permissions of the user (and their group) merged together and
116 * available as an array
120 protected $userPermissions = array();
123 * The capabilities of this storage as defined in the storage record.
124 * Also see the CAPABILITY_* constants below
128 protected $capabilities;
131 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
133 protected $signalSlotDispatcher;
138 protected $processingFolder;
141 * whether this storage is online or offline in this request
145 protected $isOnline = NULL;
150 protected $isDefault = FALSE;
153 * The filters used for the files and folder names.
157 protected $fileAndFolderNameFilters = array();
160 * Constructor for a storage object.
162 * @param Driver\DriverInterface $driver
163 * @param array $storageRecord The storage record row from the database
165 public function __construct(Driver\DriverInterface
$driver, array $storageRecord) {
166 $this->storageRecord
= $storageRecord;
167 $this->configuration
= ResourceFactory
::getInstance()->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
168 $this->capabilities
=
169 ($this->storageRecord
['is_browsable'] ? self
::CAPABILITY_BROWSABLE
: 0) |
170 ($this->storageRecord
['is_public'] ? self
::CAPABILITY_PUBLIC
: 0) |
171 ($this->storageRecord
['is_writable'] ? self
::CAPABILITY_WRITABLE
: 0);
173 $this->driver
= $driver;
174 $this->driver
->setStorageUid($storageRecord['uid']);
175 $this->driver
->mergeConfigurationCapabilities($this->capabilities
);
177 $this->driver
->processConfiguration();
178 } catch (Exception\InvalidConfigurationException
$e) {
179 // configuration error
180 // mark this storage as permanently unusable
181 $this->markAsPermanentlyOffline();
183 $this->driver
->initialize();
184 $this->capabilities
= $this->driver
->getCapabilities();
186 $this->isDefault
= (isset($storageRecord['is_default']) && $storageRecord['is_default'] == 1);
187 $this->resetFileAndFolderNameFiltersToDefault();
191 * Gets the configuration.
195 public function getConfiguration() {
196 return $this->configuration
;
200 * Sets the configuration.
202 * @param array $configuration
204 public function setConfiguration(array $configuration) {
205 $this->configuration
= $configuration;
209 * Gets the storage record.
213 public function getStorageRecord() {
214 return $this->storageRecord
;
218 * Sets the storage that belongs to this storage.
220 * @param Driver\DriverInterface $driver
221 * @return ResourceStorage
223 public function setDriver(Driver\DriverInterface
$driver) {
224 $this->driver
= $driver;
229 * Returns the driver object belonging to this storage.
231 * @return Driver\DriverInterface
233 protected function getDriver() {
234 return $this->driver
;
238 * Deprecated function, don't use it. Will be removed in some later revision.
240 * @param string $identifier
242 * @throws \BadMethodCallException
244 public function getFolderByIdentifier($identifier) {
245 throw new \
BadMethodCallException(
246 'Function TYPO3\\CMS\\Core\\Resource\\ResourceStorage::getFolderByIdentifier() has been renamed to just getFolder(). Please fix the method call.',
252 * Deprecated function, don't use it. Will be removed in some later revision.
254 * @param string $identifier
256 * @throws \BadMethodCallException
258 public function getFileByIdentifier($identifier) {
259 throw new \
BadMethodCallException(
260 'Function TYPO3\\CMS\\Core\\Resource\\ResourceStorage::getFileByIdentifier() has been renamed to just getFileInfoByIdentifier(). ' . 'Please fix the method call.',
266 * Returns the name of this storage.
270 public function getName() {
271 return $this->storageRecord
['name'];
275 * Returns the UID of this storage.
279 public function getUid() {
280 return (int)$this->storageRecord
['uid'];
284 * Tells whether there are children in this storage.
288 public function hasChildren() {
292 /*********************************
294 ********************************/
296 * Returns the capabilities of this storage.
299 * @see CAPABILITY_* constants
301 public function getCapabilities() {
302 return (int)$this->capabilities
;
306 * Returns TRUE if this storage has the given capability.
308 * @param int $capability A capability, as defined in a CAPABILITY_* constant
311 protected function hasCapability($capability) {
312 return ($this->capabilities
& $capability) == $capability;
316 * Returns TRUE if this storage is publicly available. This is just a
317 * configuration option and does not mean that it really *is* public. OTOH
318 * a storage that is marked as not publicly available will trigger the file
319 * publishing mechanisms of TYPO3.
323 public function isPublic() {
324 return $this->hasCapability(self
::CAPABILITY_PUBLIC
);
328 * Returns TRUE if this storage is writable. This is determined by the
329 * driver and the storage configuration; user permissions are not taken into account.
333 public function isWritable() {
334 return $this->hasCapability(self
::CAPABILITY_WRITABLE
);
338 * Returns TRUE if this storage is browsable by a (backend) user of TYPO3.
342 public function isBrowsable() {
343 return $this->isOnline() && $this->hasCapability(self
::CAPABILITY_BROWSABLE
);
347 * Returns TRUE if the identifiers used by this storage are case-sensitive.
351 public function usesCaseSensitiveIdentifiers() {
352 return $this->driver
->isCaseSensitiveFileSystem();
356 * Returns TRUE if this storage is browsable by a (backend) user of TYPO3.
360 public function isOnline() {
361 if ($this->isOnline
=== NULL) {
362 if ($this->getUid() === 0) {
363 $this->isOnline
= TRUE;
365 // the storage is not marked as online for a longer time
366 if ($this->storageRecord
['is_online'] == 0) {
367 $this->isOnline
= FALSE;
369 if ($this->isOnline
!== FALSE) {
370 // all files are ALWAYS available in the frontend
371 if (TYPO3_MODE
=== 'FE') {
372 $this->isOnline
= TRUE;
374 // check if the storage is disabled temporary for now
375 $registryObject = GeneralUtility
::makeInstance('TYPO3\\CMS\\Core\\Registry');
376 $offlineUntil = $registryObject->get('core', 'sys_file_storage-' . $this->getUid() . '-offline-until');
377 if ($offlineUntil && $offlineUntil > time()) {
378 $this->isOnline
= FALSE;
380 $this->isOnline
= TRUE;
385 return $this->isOnline
;
389 * Blows the "fuse" and marks the storage as offline.
391 * Can only be modified by an admin.
393 * Typically, this is only done if the configuration is wrong.
397 public function markAsPermanentlyOffline() {
398 if ($this->getUid() > 0) {
399 // @todo: move this to the storage repository
400 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('sys_file_storage', 'uid=' . (int)$this->getUid(), array('is_online' => 0));
402 $this->storageRecord
['is_online'] = 0;
403 $this->isOnline
= FALSE;
407 * Marks this storage as offline for the next 5 minutes.
409 * Non-permanent: This typically happens for remote storages
410 * that are "flaky" and not available all the time.
414 public function markAsTemporaryOffline() {
415 $registryObject = GeneralUtility
::makeInstance('TYPO3\\CMS\\Core\\Registry');
416 $registryObject->set('core', 'sys_file_storage-' . $this->getUid() . '-offline-until', time() +
60 * 5);
417 $this->storageRecord
['is_online'] = 0;
418 $this->isOnline
= FALSE;
421 /*********************************
422 * User Permissions / File Mounts
423 ********************************/
425 * Adds a filemount as a "filter" for users to only work on a subset of a
428 * @param string $folderIdentifier
429 * @param array $additionalData
431 * @throws Exception\FolderDoesNotExistException
434 public function addFileMount($folderIdentifier, $additionalData = array()) {
435 // check for the folder before we add it as a filemount
436 if ($this->driver
->folderExists($folderIdentifier) === FALSE) {
437 // if there is an error, this is important and should be handled
438 // as otherwise the user would see the whole storage without any restrictions for the filemounts
439 throw new Exception\
FolderDoesNotExistException('Folder for file mount ' . $folderIdentifier . ' does not exist.', 1334427099);
441 $data = $this->driver
->getFolderInfoByIdentifier($folderIdentifier);
442 $folderObject = ResourceFactory
::getInstance()->createFolderObject($this, $data['identifier'], $data['name']);
443 if (empty($additionalData)) {
444 $additionalData = array(
445 'path' => $folderIdentifier,
446 'title' => $folderIdentifier,
447 'folder' => $folderObject
450 $additionalData['folder'] = $folderObject;
451 if (!isset($additionalData['title'])) {
452 $additionalData['title'] = $folderIdentifier;
455 $this->fileMounts
[$folderIdentifier] = $additionalData;
459 * Returns all file mounts that are registered with this storage.
463 public function getFileMounts() {
464 return $this->fileMounts
;
468 * Checks if the given subject is within one of the registered user
469 * filemounts. If not, working with the file is not permitted for the user.
471 * @param Folder $subject
474 public function isWithinFileMountBoundaries($subject) {
475 if (!$this->evaluatePermissions
) {
478 $isWithinFilemount = FALSE;
480 $subject = $this->getRootLevelFolder();
482 $identifier = $subject->getIdentifier();
484 // Allow access to processing folder
485 if ($this->driver
->isWithin($this->getProcessingFolder()->getIdentifier(), $identifier)) {
486 $isWithinFilemount = TRUE;
488 // Check if the identifier of the subject is within at
489 // least one of the file mounts
490 foreach ($this->fileMounts
as $fileMount) {
491 if ($this->driver
->isWithin($fileMount['folder']->getIdentifier(), $identifier)) {
492 $isWithinFilemount = TRUE;
497 return $isWithinFilemount;
501 * Sets whether the permissions to access or write
502 * into this storage should be checked or not.
504 * @param boolean $evaluatePermissions
506 public function setEvaluatePermissions($evaluatePermissions) {
507 $this->evaluatePermissions
= (bool)$evaluatePermissions;
511 * Gets whether the permissions to access or write
512 * into this storage should be checked or not.
514 * @return bool $evaluatePermissions
516 public function getEvaluatePermissions() {
517 return $this->evaluatePermissions
;
521 * Sets the user permissions of the storage.
523 * @param array $userPermissions
526 public function setUserPermissions(array $userPermissions) {
527 $this->userPermissions
= $userPermissions;
531 * Checks if the ACL settings allow for a certain action
532 * (is a user allowed to read a file or copy a folder).
534 * @param string $action
535 * @param string $type either File or Folder
538 public function checkUserActionPermission($action, $type) {
539 if (!$this->evaluatePermissions
) {
544 if (!empty($this->userPermissions
[strtolower($action) . ucfirst(strtolower($type))])) {
552 * Checks if a file operation (= action) is allowed on a
553 * File/Folder/Storage (= subject).
555 * This method, by design, does not throw exceptions or do logging.
556 * Besides the usage from other methods in this class, it is also used by
557 * the File List UI to check whether an action is allowed and whether action
558 * related UI elements should thus be shown (move icon, edit icon, etc.)
560 * @param string $action action, can be read, write, delete
561 * @param FileInterface $file
564 public function checkFileActionPermission($action, FileInterface
$file) {
565 $isProcessedFile = $file instanceof ProcessedFile
;
566 // Check 1: Does the user have permission to perform the action? e.g. "readFile"
567 if (!$isProcessedFile && $this->checkUserActionPermission($action, 'File') === FALSE) {
570 // Check 2: No action allowed on files for denied file extensions
571 if (!$this->checkFileExtensionPermission($file->getName())) {
574 // Check 3: Does the user have the right to perform the action?
575 // (= is he within the file mount borders)
576 if (!$isProcessedFile && !$this->isWithinFileMountBoundaries($file)) {
579 $isReadCheck = FALSE;
580 if (in_array($action, array('read', 'copy', 'move'), TRUE)) {
583 $isWriteCheck = FALSE;
584 if (in_array($action, array('add', 'write', 'move', 'rename', 'unzip', 'delete'), TRUE)) {
585 $isWriteCheck = TRUE;
589 if (!$isProcessedFile && $file instanceof File
) {
590 $isMissing = $file->isMissing();
593 // Check 4: Check the capabilities of the storage (and the driver)
594 if ($isWriteCheck && ($isMissing ||
!$this->isWritable())) {
597 // Check 5: "File permissions" of the driver (only when file isn't marked as missing)
599 $filePermissions = $this->driver
->getPermissions($file->getIdentifier());
600 if ($isReadCheck && !$filePermissions['r']) {
603 if ($isWriteCheck && !$filePermissions['w']) {
611 * Checks if a folder operation (= action) is allowed on a Folder.
613 * This method, by design, does not throw exceptions or do logging.
614 * See the checkFileActionPermission() method above for the reasons.
616 * @param string $action
617 * @param Folder $folder
620 public function checkFolderActionPermission($action, Folder
$folder = NULL) {
621 // Check 1: Does the user have permission to perform the action? e.g. "writeFolder"
622 if ($this->checkUserActionPermission($action, 'Folder') === FALSE) {
626 // If we do not have a folder here, we cannot do further checks
627 if ($folder === NULL) {
631 // Check 2: Does the user has the right to perform the action?
632 // (= is he within the file mount borders)
633 if (!$this->isWithinFileMountBoundaries($folder)) {
636 $isReadCheck = FALSE;
637 if (in_array($action, array('read', 'copy'), TRUE)) {
640 $isWriteCheck = FALSE;
641 if (in_array($action, array('add', 'move', 'write', 'delete', 'rename'), TRUE)) {
642 $isWriteCheck = TRUE;
644 // Check 3: Check the capabilities of the storage (and the driver)
645 if ($isReadCheck && !$this->isBrowsable()) {
648 if ($isWriteCheck && !$this->isWritable()) {
651 // Check 4: "Folder permissions" of the driver
652 $folderPermissions = $this->driver
->getPermissions($folder->getIdentifier());
653 if ($isReadCheck && !$folderPermissions['r']) {
656 if ($isWriteCheck && !$folderPermissions['w']) {
663 * If the fileName is given, checks it against the
664 * TYPO3_CONF_VARS[BE][fileDenyPattern] + and if the file extension is allowed.
666 * @param string $fileName full filename
667 * @return bool TRUE if extension/filename is allowed
669 protected function checkFileExtensionPermission($fileName) {
670 if (!$this->evaluatePermissions
) {
673 $fileName = $this->driver
->sanitizeFileName($fileName);
674 $isAllowed = GeneralUtility
::verifyFilenameAgainstDenyPattern($fileName);
676 $fileInfo = GeneralUtility
::split_fileref($fileName);
677 // Set up the permissions for the file extension
678 $fileExtensionPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace'];
679 $fileExtensionPermissions['allow'] = GeneralUtility
::uniqueList(strtolower($fileExtensionPermissions['allow']));
680 $fileExtensionPermissions['deny'] = GeneralUtility
::uniqueList(strtolower($fileExtensionPermissions['deny']));
681 $fileExtension = strtolower($fileInfo['fileext']);
682 if ($fileExtension !== '') {
683 // If the extension is found amongst the allowed types, we return TRUE immediately
684 if ($fileExtensionPermissions['allow'] === '*' || GeneralUtility
::inList($fileExtensionPermissions['allow'], $fileExtension)) {
687 // If the extension is found amongst the denied types, we return FALSE immediately
688 if ($fileExtensionPermissions['deny'] === '*' || GeneralUtility
::inList($fileExtensionPermissions['deny'], $fileExtension)) {
691 // If no match we return TRUE
694 if ($fileExtensionPermissions['allow'] === '*') {
697 if ($fileExtensionPermissions['deny'] === '*') {
707 * Assures read permission for given folder.
709 * @param Folder $folder If a folder is given, mountpoints are checked. If not only user folder read permissions are checked.
711 * @throws Exception\InsufficientFolderAccessPermissionsException
713 protected function assureFolderReadPermission(Folder
$folder = NULL) {
714 if (!$this->checkFolderActionPermission('read', $folder)) {
715 throw new Exception\
InsufficientFolderAccessPermissionsException('You are not allowed to access the given folder', 1375955684);
720 * Assures delete permission for given folder.
722 * @param Folder $folder If a folder is given, mountpoints are checked. If not only user folder delete permissions are checked.
723 * @param boolean $checkDeleteRecursively
725 * @throws Exception\InsufficientFolderAccessPermissionsException
726 * @throws Exception\InsufficientFolderWritePermissionsException
727 * @throws Exception\InsufficientUserPermissionsException
729 protected function assureFolderDeletePermission(Folder
$folder, $checkDeleteRecursively) {
730 // Check user permissions for recursive deletion if it is requested
731 if ($checkDeleteRecursively && !$this->checkUserActionPermission('recursivedelete', 'Folder')) {
732 throw new Exception\
InsufficientUserPermissionsException('You are not allowed to delete folders recursively', 1377779423);
734 // Check user action permission
735 if (!$this->checkFolderActionPermission('delete', $folder)) {
736 throw new Exception\
InsufficientFolderAccessPermissionsException('You are not allowed to delete the given folder', 1377779039);
738 // Check if the user has write permissions to folders
739 // Would be good if we could check for actual write permissions in the containig folder
740 // but we cannot since we have no access to the containing folder of this file.
741 if (!$this->checkUserActionPermission('write', 'Folder')) {
742 throw new Exception\
InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377779111);
747 * Assures read permission for given file.
749 * @param FileInterface $file
751 * @throws Exception\InsufficientFileAccessPermissionsException
752 * @throws Exception\IllegalFileExtensionException
754 protected function assureFileReadPermission(FileInterface
$file) {
755 if (!$this->checkFileActionPermission('read', $file)) {
756 throw new Exception\
InsufficientFileAccessPermissionsException('You are not allowed to access that file.', 1375955429);
758 if (!$this->checkFileExtensionPermission($file->getName())) {
759 throw new Exception\
IllegalFileExtensionException('You are not allowed to use that file extension', 1375955430);
764 * Assures write permission for given file.
766 * @param FileInterface $file
768 * @throws Exception\IllegalFileExtensionException
769 * @throws Exception\InsufficientFileWritePermissionsException
770 * @throws Exception\InsufficientUserPermissionsException
772 protected function assureFileWritePermissions(FileInterface
$file) {
773 // Check if user is allowed to write the file and $file is writable
774 if (!$this->checkFileActionPermission('write', $file)) {
775 throw new Exception\
InsufficientFileWritePermissionsException('Writing to file "' . $file->getIdentifier() . '" is not allowed.', 1330121088);
777 if (!$this->checkFileExtensionPermission($file->getName())) {
778 throw new Exception\
IllegalFileExtensionException('You are not allowed to edit a file with extension "' . $file->getExtension() . '"', 1366711933);
783 * Assures delete permission for given file.
785 * @param FileInterface $file
787 * @throws Exception\IllegalFileExtensionException
788 * @throws Exception\InsufficientFileWritePermissionsException
789 * @throws Exception\InsufficientFolderWritePermissionsException
791 protected function assureFileDeletePermissions(FileInterface
$file) {
792 // Check for disallowed file extensions
793 if (!$this->checkFileExtensionPermission($file->getName())) {
794 throw new Exception\
IllegalFileExtensionException('You are not allowed to delete a file with extension "' . $file->getExtension() . '"', 1377778916);
796 // Check further permissions if file is not a processed file
797 if (!$file instanceof ProcessedFile
) {
798 // Check if user is allowed to delete the file and $file is writable
799 if (!$this->checkFileActionPermission('delete', $file)) {
800 throw new Exception\
InsufficientFileWritePermissionsException('You are not allowed to delete the file "' . $file->getIdentifier() . '"', 1319550425);
802 // Check if the user has write permissions to folders
803 // Would be good if we could check for actual write permissions in the containig folder
804 // but we cannot since we have no access to the containing folder of this file.
805 if (!$this->checkUserActionPermission('write', 'Folder')) {
806 throw new Exception\
InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377778702);
812 * Checks if a file has the permission to be uploaded to a Folder/Storage.
813 * If not, throws an exception.
815 * @param string $localFilePath the temporary file name from $_FILES['file1']['tmp_name']
816 * @param Folder $targetFolder
817 * @param string $targetFileName the destination file name $_FILES['file1']['name']
820 * @throws Exception\InsufficientFolderWritePermissionsException
821 * @throws Exception\UploadException
822 * @throws Exception\IllegalFileExtensionException
823 * @throws Exception\UploadSizeException
824 * @throws Exception\InsufficientUserPermissionsException
826 protected function assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName) {
827 // Check for a valid file extension
828 if (!$this->checkFileExtensionPermission($targetFileName) ||
($localFilePath && !$this->checkFileExtensionPermission($localFilePath))) {
829 throw new Exception\
IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1322120271);
831 // Makes sure the user is allowed to upload
832 if (!$this->checkUserActionPermission('add', 'File')) {
833 throw new Exception\
InsufficientUserPermissionsException('You are not allowed to add files to this storage "' . $this->getUid() . '"', 1376992145);
835 // Check if targetFolder is writable
836 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
837 throw new Exception\
InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1322120356);
842 * Checks if a file has the permission to be uploaded to a Folder/Storage.
843 * If not, throws an exception.
845 * @param string $localFilePath the temporary file name from $_FILES['file1']['tmp_name']
846 * @param Folder $targetFolder
847 * @param string $targetFileName the destination file name $_FILES['file1']['name']
848 * @param int $uploadedFileSize
851 * @throws Exception\InsufficientFolderWritePermissionsException
852 * @throws Exception\UploadException
853 * @throws Exception\IllegalFileExtensionException
854 * @throws Exception\UploadSizeException
855 * @throws Exception\InsufficientUserPermissionsException
857 protected function assureFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileSize) {
858 // Makes sure this is an uploaded file
859 if (!is_uploaded_file($localFilePath)) {
860 throw new Exception\
UploadException('The upload has failed, no uploaded file found!', 1322110455);
862 // Max upload size (kb) for files.
863 $maxUploadFileSize = GeneralUtility
::getMaxUploadFileSize() * 1024;
864 if ($uploadedFileSize >= $maxUploadFileSize) {
865 unlink($localFilePath);
866 throw new Exception\
UploadSizeException('The uploaded file exceeds the size-limit of ' . $maxUploadFileSize . ' bytes', 1322110041);
868 $this->assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName);
872 * Checks for permissions to move a file.
874 * @throws \RuntimeException
875 * @throws Exception\InsufficientFolderAccessPermissionsException
876 * @throws Exception\InsufficientUserPermissionsException
877 * @throws Exception\IllegalFileExtensionException
878 * @param FileInterface $file
879 * @param Folder $targetFolder
880 * @param string $targetFileName
883 protected function assureFileMovePermissions(FileInterface
$file, Folder
$targetFolder, $targetFileName) {
884 // Check if targetFolder is within this storage
885 if ($this->getUid() !== $targetFolder->getStorage()->getUid()) {
886 throw new \
RuntimeException();
888 // Check for a valid file extension
889 if (!$this->checkFileExtensionPermission($targetFileName)) {
890 throw new Exception\
IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1378243279);
892 // Check if user is allowed to move and $file is readable and writable
893 if (!$file->getStorage()->checkFileActionPermission('move', $file)) {
894 throw new Exception\
InsufficientUserPermissionsException('You are not allowed to move files to storage "' . $this->getUid() . '"', 1319219349);
896 // Check if target folder is writable
897 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
898 throw new Exception\
InsufficientFolderAccessPermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319219350);
903 * Checks for permissions to rename a file.
905 * @param FileInterface $file
906 * @param string $targetFileName
907 * @throws Exception\InsufficientFileWritePermissionsException
908 * @throws Exception\IllegalFileExtensionException
909 * @throws Exception\InsufficientFileReadPermissionsException
910 * @throws Exception\InsufficientUserPermissionsException
913 protected function assureFileRenamePermissions(FileInterface
$file, $targetFileName) {
914 // Check if file extension is allowed
915 if (!$this->checkFileExtensionPermission($targetFileName) ||
!$this->checkFileExtensionPermission($file->getName())) {
916 throw new Exception\
IllegalFileExtensionException('You are not allowed to rename a file with to this extension', 1371466663);
918 // Check if user is allowed to rename
919 if (!$this->checkFileActionPermission('rename', $file)) {
920 throw new Exception\
InsufficientUserPermissionsException('You are not allowed to rename files."', 1319219351);
922 // Check if the user is allowed to write to folders
923 // Although it would be good to check, we cannot check here if the folder actually is writable
924 // because we do not know in which folder the file resides.
925 // So we rely on the driver to throw an exception in case the renaming failed.
926 if (!$this->checkFolderActionPermission('write')) {
927 throw new Exception\
InsufficientFileWritePermissionsException('You are not allowed to write to folders', 1319219352);
932 * Check if a file has the permission to be copied on a File/Folder/Storage,
933 * if not throw an exception
935 * @param FileInterface $file
936 * @param Folder $targetFolder
937 * @param string $targetFileName
940 * @throws Exception\InsufficientFolderWritePermissionsException
941 * @throws Exception\IllegalFileExtensionException
942 * @throws Exception\InsufficientFileReadPermissionsException
943 * @throws Exception\InsufficientUserPermissionsException
946 protected function assureFileCopyPermissions(FileInterface
$file, Folder
$targetFolder, $targetFileName) {
947 // Check if targetFolder is within this storage, this should never happen
948 if ($this->getUid() != $targetFolder->getStorage()->getUid()) {
949 throw new Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1319550405);
951 // Check if user is allowed to copy
952 if (!$file->getStorage()->checkFileActionPermission('copy', $file)) {
953 throw new Exception\
InsufficientFileReadPermissionsException('You are not allowed to copy the file "' . $file->getIdentifier() . '"', 1319550426);
955 // Check if targetFolder is writable
956 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
957 throw new Exception\
InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319550435);
959 // Check for a valid file extension
960 if (!$this->checkFileExtensionPermission($targetFileName) ||
!$this->checkFileExtensionPermission($file->getName())) {
961 throw new Exception\
IllegalFileExtensionException('You are not allowed to copy a file of that type.', 1319553317);
966 * Check if a file has the permission to be copied on a File/Folder/Storage,
967 * if not throw an exception
969 * @param FolderInterface $folderToCopy
970 * @param FolderInterface $targetParentFolder
974 * @throws Exception\InsufficientFolderWritePermissionsException
975 * @throws Exception\IllegalFileExtensionException
976 * @throws Exception\InsufficientFileReadPermissionsException
977 * @throws Exception\InsufficientUserPermissionsException
978 * @throws \RuntimeException
980 protected function assureFolderCopyPermissions(FolderInterface
$folderToCopy, FolderInterface
$targetParentFolder) {
981 // Check if targetFolder is within this storage, this should never happen
982 if ($this->getUid() !== $targetParentFolder->getStorage()->getUid()) {
983 throw new Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1377777624);
985 if (!$folderToCopy instanceof Folder
) {
986 throw new \
RuntimeException('The folder "' . $folderToCopy->getIdentifier() . '" to copy is not of type Folder.', 1384209020);
988 // Check if user is allowed to copy and the folder is readable
989 if (!$folderToCopy->getStorage()->checkFolderActionPermission('copy', $folderToCopy)) {
990 throw new Exception\
InsufficientFileReadPermissionsException('You are not allowed to copy the folder "' . $folderToCopy->getIdentifier() . '"', 1377777629);
992 if (!$targetParentFolder instanceof Folder
) {
993 throw new \
RuntimeException('The target folder "' . $targetParentFolder->getIdentifier() . '" is not of type Folder.', 1384209021);
995 // Check if targetFolder is writable
996 if (!$this->checkFolderActionPermission('write', $targetParentFolder)) {
997 throw new Exception\
InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetParentFolder->getIdentifier() . '"', 1377777635);
1002 * Check if a file has the permission to be copied on a File/Folder/Storage,
1003 * if not throw an exception
1005 * @param FolderInterface $folderToMove
1006 * @param FolderInterface $targetParentFolder
1008 * @throws \InvalidArgumentException
1009 * @throws Exception\InsufficientFolderWritePermissionsException
1010 * @throws Exception\IllegalFileExtensionException
1011 * @throws Exception\InsufficientFileReadPermissionsException
1012 * @throws Exception\InsufficientUserPermissionsException
1013 * @throws \RuntimeException
1016 protected function assureFolderMovePermissions(FolderInterface
$folderToMove, FolderInterface
$targetParentFolder) {
1017 // Check if targetFolder is within this storage, this should never happen
1018 if ($this->getUid() !== $targetParentFolder->getStorage()->getUid()) {
1019 throw new \
InvalidArgumentException('Cannot move a folder into a folder that does not belong to this storage.', 1325777289);
1021 if (!$folderToMove instanceof Folder
) {
1022 throw new \
RuntimeException('The folder "' . $folderToMove->getIdentifier() . '" to move is not of type Folder.', 1384209022);
1024 // Check if user is allowed to move and the folder is writable
1025 // In fact we would need to check if the parent folder of the folder to move is writable also
1026 // But as of now we cannot extract the parent folder from this folder
1027 if (!$folderToMove->getStorage()->checkFolderActionPermission('move', $folderToMove)) {
1028 throw new Exception\
InsufficientFileReadPermissionsException('You are not allowed to copy the folder "' . $folderToMove->getIdentifier() . '"', 1377778045);
1030 if (!$targetParentFolder instanceof Folder
) {
1031 throw new \
RuntimeException('The target folder "' . $targetParentFolder->getIdentifier() . '" is not of type Folder.', 1384209023);
1033 // Check if targetFolder is writable
1034 if (!$this->checkFolderActionPermission('write', $targetParentFolder)) {
1035 throw new Exception\
InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetParentFolder->getIdentifier() . '"', 1377778049);
1039 /********************
1041 ********************/
1043 * Moves a file from the local filesystem to this storage.
1045 * @param string $localFilePath The file on the server's hard disk to add.
1046 * @param Folder $targetFolder The target path, without the fileName
1047 * @param string $targetFileName The fileName. If not set, the local file name is used.
1048 * @param string $conflictMode possible value are 'cancel', 'replace', 'changeName'
1050 * @throws \InvalidArgumentException
1051 * @throws Exception\ExistingTargetFileNameException
1052 * @return FileInterface
1054 public function addFile($localFilePath, Folder
$targetFolder, $targetFileName = '', $conflictMode = 'changeName') {
1055 $localFilePath = PathUtility
::getCanonicalPath($localFilePath);
1056 if (!file_exists($localFilePath)) {
1057 throw new \
InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1319552745);
1059 $this->assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName);
1060 $targetFolder = $targetFolder ?
: $this->getDefaultFolder();
1061 $targetFileName = $this->driver
->sanitizeFileName($targetFileName ?
: PathUtility
::basename($localFilePath));
1063 // We do not care whether the file exists yet because $targetFileName may be changed by an
1064 // external slot and only then we should check how to proceed according to $conflictMode
1065 $this->emitPreFileAddSignal($targetFileName, $targetFolder, $localFilePath);
1067 if ($conflictMode === 'cancel' && $this->driver
->fileExistsInFolder($targetFileName, $targetFolder->getIdentifier())) {
1068 throw new Exception\
ExistingTargetFileNameException('File "' . $targetFileName . '" already exists in folder ' . $targetFolder->getIdentifier(), 1322121068);
1069 } elseif ($conflictMode === 'changeName') {
1070 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1073 $fileIdentifier = $this->driver
->addFile($localFilePath, $targetFolder->getIdentifier(), $targetFileName);
1074 $file = ResourceFactory
::getInstance()->getFileObjectByStorageAndIdentifier($this->getUid(), $fileIdentifier);
1076 $this->emitPostFileAddSignal($file, $targetFolder);
1082 * Updates a processed file with a new file from the local filesystem.
1084 * @param $localFilePath
1085 * @param ProcessedFile $processedFile
1086 * @return FileInterface
1087 * @throws \InvalidArgumentException
1088 * @internal use only
1090 public function updateProcessedFile($localFilePath, ProcessedFile
$processedFile) {
1091 if (!file_exists($localFilePath)) {
1092 throw new \
InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1319552746);
1094 $fileIdentifier = $this->driver
->addFile($localFilePath, $this->getProcessingFolder()->getIdentifier(), $processedFile->getName());
1095 // @todo check if we have to update the processed file other then the identifier
1096 $processedFile->setIdentifier($fileIdentifier);
1097 return $processedFile;
1101 * Creates a (cryptographic) hash for a file.
1103 * @param FileInterface $fileObject
1104 * @param string $hash
1107 public function hashFile(FileInterface
$fileObject, $hash) {
1108 return $this->hashFileByIdentifier($fileObject->getIdentifier(), $hash);
1112 * Creates a (cryptographic) hash for a fileIdentifier.
1114 * @param string $fileIdentifier
1115 * @param string $hash
1119 public function hashFileByIdentifier($fileIdentifier, $hash) {
1120 return $this->driver
->hash($fileIdentifier, $hash);
1124 * Hashes a file identifier, taking the case sensitivity of the file system
1125 * into account. This helps mitigating problems with case-insensitive
1128 * @param string|FileInterface $file
1131 public function hashFileIdentifier($file) {
1132 if (is_object($file) && $file instanceof FileInterface
) {
1133 /** @var FileInterface $file */
1134 $file = $file->getIdentifier();
1136 return $this->driver
->hashIdentifier($file);
1140 * Returns a publicly accessible URL for a file.
1142 * WARNING: Access to the file may be restricted by further means, e.g.
1143 * some web-based authentication. You have to take care of this yourself.
1145 * @param ResourceInterface $resourceObject The file or folder object
1146 * @param boolean $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all (only for the LocalDriver)
1149 public function getPublicUrl(ResourceInterface
$resourceObject, $relativeToCurrentScript = FALSE) {
1151 if ($this->isOnline()) {
1152 // Pre-process the public URL by an accordant slot
1153 $this->emitPreGeneratePublicUrl($resourceObject, $relativeToCurrentScript, array('publicUrl' => &$publicUrl));
1154 // If slot did not handle the signal, use the default way to determine public URL
1155 if ($publicUrl === NULL) {
1157 if ($this->hasCapability(self
::CAPABILITY_PUBLIC
)) {
1158 $publicUrl = $this->driver
->getPublicUrl($resourceObject->getIdentifier());
1161 if ($publicUrl === NULL && $resourceObject instanceof FileInterface
) {
1162 $queryParameterArray = array('eID' => 'dumpFile', 't' => '');
1163 if ($resourceObject instanceof File
) {
1164 $queryParameterArray['f'] = $resourceObject->getUid();
1165 $queryParameterArray['t'] = 'f';
1166 } elseif ($resourceObject instanceof ProcessedFile
) {
1167 $queryParameterArray['p'] = $resourceObject->getUid();
1168 $queryParameterArray['t'] = 'p';
1171 $queryParameterArray['token'] = GeneralUtility
::hmac(implode('|', $queryParameterArray), 'resourceStorageDumpFile');
1172 $publicUrl = 'index.php?' . str_replace('+', '%20', http_build_query($queryParameterArray));
1175 // If requested, make the path relative to the current script in order to make it possible
1176 // to use the relative file
1177 if ($publicUrl !== NULL && $relativeToCurrentScript && !GeneralUtility
::isValidUrl($publicUrl)) {
1178 $absolutePathToContainingFolder = PathUtility
::dirname(PATH_site
. $publicUrl);
1179 $pathPart = PathUtility
::getRelativePathTo($absolutePathToContainingFolder);
1180 $filePart = substr(PATH_site
. $publicUrl, strlen($absolutePathToContainingFolder) +
1);
1181 $publicUrl = $pathPart . $filePart;
1189 * Passes a file to the File Processing Services and returns the resulting ProcessedFile object.
1191 * @param FileInterface $fileObject The file object
1192 * @param string $context
1193 * @param array $configuration
1195 * @return ProcessedFile
1196 * @throws \InvalidArgumentException
1198 public function processFile(FileInterface
$fileObject, $context, array $configuration) {
1199 if ($fileObject->getStorage() !== $this) {
1200 throw new \
InvalidArgumentException('Cannot process files of foreign storage', 1353401835);
1202 $processedFile = $this->getFileProcessingService()->processFile($fileObject, $this, $context, $configuration);
1204 return $processedFile;
1208 * Copies a file from the storage for local processing.
1210 * @param FileInterface $fileObject
1211 * @param boolean $writable
1212 * @return string Path to local file (either original or copied to some temporary local location)
1214 public function getFileForLocalProcessing(FileInterface
$fileObject, $writable = TRUE) {
1215 $filePath = $this->driver
->getFileForLocalProcessing($fileObject->getIdentifier(), $writable);
1220 * Gets a file by identifier.
1222 * @param string $identifier
1223 * @return FileInterface
1225 public function getFile($identifier) {
1226 $file = $this->getFileFactory()->getFileObjectByStorageAndIdentifier($this->getUid(), $identifier);
1227 if (!$this->driver
->fileExists($identifier)) {
1228 $file->setMissing(TRUE);
1234 * Gets information about a file.
1236 * @param FileInterface $fileObject
1240 public function getFileInfo(FileInterface
$fileObject) {
1241 return $this->getFileInfoByIdentifier($fileObject->getIdentifier());
1245 * Gets information about a file by its identifier.
1247 * @param string $identifier
1248 * @param array $propertiesToExtract
1252 public function getFileInfoByIdentifier($identifier, array $propertiesToExtract = array()) {
1253 return $this->driver
->getFileInfoByIdentifier($identifier, $propertiesToExtract);
1257 * Unsets the file and folder name filters, thus making this storage return unfiltered file lists.
1261 public function unsetFileAndFolderNameFilters() {
1262 $this->fileAndFolderNameFilters
= array();
1266 * Resets the file and folder name filters to the default values defined in the TYPO3 configuration.
1270 public function resetFileAndFolderNameFiltersToDefault() {
1271 $this->fileAndFolderNameFilters
= $GLOBALS['TYPO3_CONF_VARS']['SYS']['fal']['defaultFilterCallbacks'];
1275 * Returns the file and folder name filters used by this storage.
1279 public function getFileAndFolderNameFilters() {
1280 return $this->fileAndFolderNameFilters
;
1284 * @param array $filters
1287 public function setFileAndFolderNameFilters(array $filters) {
1288 $this->fileAndFolderNameFilters
= $filters;
1293 * @param array $filter
1295 public function addFileAndFolderNameFilter($filter) {
1296 $this->fileAndFolderNameFilters
[] = $filter;
1300 * @param string $fileIdentifier
1304 public function getFolderIdentifierFromFileIdentifier($fileIdentifier) {
1305 return $this->driver
->getParentFolderIdentifierOfIdentifier($fileIdentifier);
1309 * Returns a list of files in a given path, filtered by some custom filter methods.
1311 * @see getUnfilteredFileList(), getFileListWithDefaultFilters()
1312 * @param string $path The path to list
1313 * @param int $start The position to start the listing; if not set or 0, start from the beginning
1314 * @param int $numberOfItems The number of items to list; if not set, return all items
1315 * @param bool $useFilters If FALSE, the list is returned without any filtering; otherwise, the filters defined for this storage are used.
1316 * @param bool $loadIndexRecords If set to TRUE, the index records for all files are loaded from the database. This can greatly improve performance of this method, especially with a lot of files.
1317 * @param bool $recursive
1318 * @return array Information about the files found.
1319 * @deprecated since 6.2, will be removed two versions later
1321 public function getFileList($path, $start = 0, $numberOfItems = 0, $useFilters = TRUE, $loadIndexRecords = TRUE, $recursive = FALSE) {
1322 GeneralUtility
::logDeprecatedFunction();
1323 return $this->getFilesInFolder($this->getFolder($path), $start, $numberOfItems, $useFilters, $recursive);
1327 * @param Folder $folder
1329 * @param int $maxNumberOfItems
1330 * @param bool $useFilters
1331 * @param bool $recursive
1334 public function getFilesInFolder(Folder
$folder, $start = 0, $maxNumberOfItems = 0, $useFilters = TRUE, $recursive = FALSE) {
1335 $this->assureFolderReadPermission($folder);
1337 $rows = $this->getFileIndexRepository()->findByFolder($folder);
1339 $filters = $useFilters == TRUE ?
$this->fileAndFolderNameFilters
: array();
1340 $fileIdentifiers = array_values($this->driver
->getFilesInFolder($folder->getIdentifier(), $start, $maxNumberOfItems, $recursive, $filters));
1341 $fileIdentifiersCount = count($fileIdentifiers);
1343 if ($maxNumberOfItems === 0) {
1344 $maxNumberOfItems = $fileIdentifiersCount;
1346 $end = min($fileIdentifiersCount, $start +
$maxNumberOfItems);
1347 for ($i = $start; $i < $end; $i++
) {
1348 $identifier = $fileIdentifiers[$i];
1349 if (isset($rows[$identifier])) {
1350 $fileObject = $this->getFileFactory()->getFileObject($rows[$identifier]['uid'], $rows[$identifier]);
1352 $fileObject = $this->getFileFactory()->getFileObjectByStorageAndIdentifier($this->getUid(), $identifier);
1354 $key = $fileObject->getName();
1355 while (isset($items[$key])) {
1358 $items[$key] = $fileObject;
1360 uksort($items, 'strnatcasecmp');
1366 * @param string $folderIdentifier
1367 * @param bool $useFilters
1368 * @param bool $recursive
1372 public function getFileIdentifiersInFolder($folderIdentifier, $useFilters = TRUE, $recursive = FALSE) {
1373 $filters = $useFilters == TRUE ?
$this->fileAndFolderNameFilters
: array();
1374 return $this->driver
->getFilesInFolder($folderIdentifier, 0, 0, $recursive, $filters);
1378 * @param string $folderIdentifier
1379 * @param bool $useFilters
1380 * @param bool $recursive
1384 public function getFolderIdentifiersInFolder($folderIdentifier, $useFilters = TRUE, $recursive = FALSE) {
1385 $filters = $useFilters == TRUE ?
$this->fileAndFolderNameFilters
: array();
1386 return $this->driver
->getFoldersInFolder($folderIdentifier, 0, 0, $recursive, $filters);
1391 * Returns TRUE if the specified file exists.
1393 * @param string $identifier
1396 public function hasFile($identifier) {
1397 // Allow if identifier is in processing folder
1398 if (!$this->driver
->isWithin($this->getProcessingFolder()->getIdentifier(), $identifier)) {
1399 $this->assureFolderReadPermission();
1401 return $this->driver
->fileExists($identifier);
1405 * Checks if the queried file in the given folder exists.
1407 * @param string $fileName
1408 * @param Folder $folder
1411 public function hasFileInFolder($fileName, Folder
$folder) {
1412 $this->assureFolderReadPermission($folder);
1413 return $this->driver
->fileExistsInFolder($fileName, $folder->getIdentifier());
1417 * Get contents of a file object
1419 * @param FileInterface $file
1421 * @throws Exception\InsufficientFileReadPermissionsException
1424 public function getFileContents($file) {
1425 $this->assureFileReadPermission($file);
1426 return $this->driver
->getFileContents($file->getIdentifier());
1430 * Outputs file Contents,
1431 * clears output buffer first and sends headers accordingly.
1433 * @param FileInterface $file
1434 * @param bool $asDownload If set Content-Disposition attachment is sent, inline otherwise
1435 * @param string $alternativeFilename the filename for the download (if $asDownload is set)
1438 public function dumpFileContents(FileInterface
$file, $asDownload = FALSE, $alternativeFilename = NULL) {
1439 $downloadName = $alternativeFilename ?
: $file->getName();
1440 $contentDisposition = $asDownload ?
'attachment' : 'inline';
1441 header('Content-Disposition: ' . $contentDisposition . '; filename="' . $downloadName . '"');
1442 header('Content-Type: ' . $file->getMimeType());
1443 header('Content-Length: ' . $file->getSize());
1445 // Cache-Control header is needed here to solve an issue with browser IE8 and lower
1446 // See for more information: http://support.microsoft.com/kb/323308
1447 header("Cache-Control: ''");
1448 header('Last-Modified: ' .
1449 gmdate('D, d M Y H:i:s', array_pop($this->driver
->getFileInfoByIdentifier($file->getIdentifier(), array('mtime')))) . ' GMT',
1455 $this->driver
->dumpFileContents($file->getIdentifier());
1459 * Set contents of a file object.
1461 * @param AbstractFile $file
1462 * @param string $contents
1464 * @throws \Exception|\RuntimeException
1465 * @throws Exception\InsufficientFileWritePermissionsException
1466 * @throws Exception\InsufficientUserPermissionsException
1467 * @return int The number of bytes written to the file
1469 public function setFileContents(AbstractFile
$file, $contents) {
1470 // Check if user is allowed to edit
1471 $this->assureFileWritePermissions($file);
1472 // Call driver method to update the file and update file index entry afterwards
1473 $result = $this->driver
->setFileContents($file->getIdentifier(), $contents);
1474 $this->getIndexer()->updateIndexEntry($file);
1475 $this->emitPostFileSetContentsSignal($file, $contents);
1480 * Creates a new file
1482 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_newfile()
1484 * @param string $fileName
1485 * @param Folder $targetFolderObject
1487 * @throws Exception\IllegalFileExtensionException
1488 * @throws Exception\InsufficientFolderWritePermissionsException
1489 * @return FileInterface The file object
1491 public function createFile($fileName, Folder
$targetFolderObject) {
1492 $this->assureFileAddPermissions('', $targetFolderObject, $fileName);
1493 $newFileIdentifier = $this->driver
->createFile($fileName, $targetFolderObject->getIdentifier());
1494 $this->emitPostFileCreateSignal($newFileIdentifier, $targetFolderObject);
1495 return ResourceFactory
::getInstance()->getFileObjectByStorageAndIdentifier($this->getUid(), $newFileIdentifier);
1499 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::deleteFile()
1501 * @param $fileObject FileInterface
1502 * @throws Exception\InsufficientFileAccessPermissionsException
1503 * @throws Exception\FileOperationErrorException
1504 * @return bool TRUE if deletion succeeded
1506 public function deleteFile($fileObject) {
1507 $this->assureFileDeletePermissions($fileObject);
1509 $this->emitPreFileDeleteSignal($fileObject);
1511 $result = $this->driver
->deleteFile($fileObject->getIdentifier());
1512 if ($result === FALSE) {
1513 throw new Exception\
FileOperationErrorException('Deleting the file "' . $fileObject->getIdentifier() . '\' failed.', 1329831691);
1515 // Mark the file object as deleted
1516 if ($fileObject instanceof File
) {
1517 $fileObject->setDeleted();
1520 $this->emitPostFileDeleteSignal($fileObject);
1526 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_copy()
1527 * copies a source file (from any location) in to the target
1528 * folder, the latter has to be part of this storage
1530 * @param FileInterface $file
1531 * @param Folder $targetFolder
1532 * @param string $targetFileName an optional destination fileName
1533 * @param string $conflictMode "overrideExistingFile", "renameNewFile", "cancel
1535 * @throws \Exception|Exception\AbstractFileOperationException
1536 * @throws Exception\ExistingTargetFileNameException
1537 * @return FileInterface
1539 public function copyFile(FileInterface
$file, Folder
$targetFolder, $targetFileName = NULL, $conflictMode = 'renameNewFile') {
1540 if ($targetFileName === NULL) {
1541 $targetFileName = $file->getName();
1543 $sanitizedTargetFileName = $this->driver
->sanitizeFileName($targetFileName);
1544 $this->assureFileCopyPermissions($file, $targetFolder, $sanitizedTargetFileName);
1545 $this->emitPreFileCopySignal($file, $targetFolder);
1546 // File exists and we should abort, let's abort
1547 if ($conflictMode === 'cancel' && $targetFolder->hasFile($sanitizedTargetFileName)) {
1548 throw new Exception\
ExistingTargetFileNameException('The target file already exists.', 1320291064);
1550 // File exists and we should find another name, let's find another one
1551 if ($conflictMode === 'renameNewFile' && $targetFolder->hasFile($sanitizedTargetFileName)) {
1552 $sanitizedTargetFileName = $this->getUniqueName($targetFolder, $sanitizedTargetFileName);
1554 $sourceStorage = $file->getStorage();
1555 // Call driver method to create a new file from an existing file object,
1556 // and return the new file object
1557 if ($sourceStorage === $this) {
1558 $newFileObjectIdentifier = $this->driver
->copyFileWithinStorage($file->getIdentifier(), $targetFolder->getIdentifier(), $sanitizedTargetFileName);
1560 $tempPath = $file->getForLocalProcessing();
1561 $newFileObjectIdentifier = $this->driver
->addFile($tempPath, $targetFolder->getIdentifier(), $sanitizedTargetFileName);
1563 $newFileObject = ResourceFactory
::getInstance()->getFileObjectByStorageAndIdentifier($this->getUid(), $newFileObjectIdentifier);
1564 $this->emitPostFileCopySignal($file, $targetFolder);
1565 return $newFileObject;
1569 * Moves a $file into a $targetFolder
1570 * the target folder has to be part of this storage
1572 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_move()
1574 * @param FileInterface $file
1575 * @param Folder $targetFolder
1576 * @param string $targetFileName an optional destination fileName
1577 * @param string $conflictMode "overrideExistingFile", "renameNewFile", "cancel
1579 * @throws Exception\ExistingTargetFileNameException
1580 * @throws \RuntimeException
1581 * @return FileInterface
1583 public function moveFile($file, $targetFolder, $targetFileName = NULL, $conflictMode = 'renameNewFile') {
1584 if ($targetFileName === NULL) {
1585 $targetFileName = $file->getName();
1587 $originalFolder = $file->getParentFolder();
1588 $sanitizedTargetFileName = $this->driver
->sanitizeFileName($targetFileName);
1589 $this->assureFileMovePermissions($file, $targetFolder, $sanitizedTargetFileName);
1590 if ($targetFolder->hasFile($sanitizedTargetFileName)) {
1591 // File exists and we should abort, let's abort
1592 if ($conflictMode === 'renameNewFile') {
1593 $sanitizedTargetFileName = $this->getUniqueName($targetFolder, $sanitizedTargetFileName);
1594 } elseif ($conflictMode === 'cancel') {
1595 throw new Exception\
ExistingTargetFileNameException('The target file already exists', 1329850997);
1598 $this->emitPreFileMoveSignal($file, $targetFolder);
1599 $sourceStorage = $file->getStorage();
1600 // Call driver method to move the file and update the index entry
1602 if ($sourceStorage === $this) {
1603 $newIdentifier = $this->driver
->moveFileWithinStorage($file->getIdentifier(), $targetFolder->getIdentifier(), $sanitizedTargetFileName);
1604 if (!$file instanceof AbstractFile
) {
1605 throw new \
RuntimeException('The given file is not of type AbstractFile.', 1384209025);
1607 $file->updateProperties(array('identifier' => $newIdentifier));
1609 $tempPath = $file->getForLocalProcessing();
1610 $newIdentifier = $this->driver
->addFile($tempPath, $targetFolder->getIdentifier(), $sanitizedTargetFileName);
1611 $sourceStorage->driver
->deleteFile($file->getIdentifier());
1612 if ($file instanceof File
) {
1613 $file->updateProperties(array('storage' => $this->getUid(), 'identifier' => $newIdentifier));
1616 $this->getIndexer()->updateIndexEntry($file);
1617 } catch (\TYPO3\CMS\Core\Exception
$e) {
1618 echo $e->getMessage();
1620 $this->emitPostFileMoveSignal($file, $targetFolder, $originalFolder);
1625 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_rename()
1627 * @param FileInterface $file
1628 * @param string $targetFileName
1630 * @throws Exception\InsufficientFileWritePermissionsException
1631 * @throws Exception\InsufficientFileReadPermissionsException
1632 * @throws Exception\InsufficientUserPermissionsException
1633 * @return FileInterface
1635 public function renameFile($file, $targetFileName) {
1636 // TODO add $conflictMode setting
1638 // The name should be different from the current.
1639 if ($file->getName() === $targetFileName) {
1642 $sanitizedTargetFileName = $this->driver
->sanitizeFileName($targetFileName);
1643 $this->assureFileRenamePermissions($file, $sanitizedTargetFileName);
1644 $this->emitPreFileRenameSignal($file, $sanitizedTargetFileName);
1646 // Call driver method to rename the file and update the index entry
1648 $newIdentifier = $this->driver
->renameFile($file->getIdentifier(), $sanitizedTargetFileName);
1649 if ($file instanceof File
) {
1650 $file->updateProperties(array('identifier' => $newIdentifier));
1652 $this->getIndexer()->updateIndexEntry($file);
1653 } catch (\RuntimeException
$e) {
1657 $this->emitPostFileRenameSignal($file, $sanitizedTargetFileName);
1663 * Replaces a file with a local file (e.g. a freshly uploaded file)
1665 * @param FileInterface $file
1666 * @param string $localFilePath
1668 * @return FileInterface
1670 * @throws Exception\IllegalFileExtensionException
1671 * @throws \InvalidArgumentException
1673 public function replaceFile(FileInterface
$file, $localFilePath) {
1674 $this->assureFileWritePermissions($file);
1675 if (!$this->checkFileExtensionPermission($localFilePath)) {
1676 throw new Exception\
IllegalFileExtensionException('Source file extension not allowed.', 1378132239);
1678 if (!file_exists($localFilePath)) {
1679 throw new \
InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1325842622);
1681 $this->emitPreFileReplaceSignal($file, $localFilePath);
1682 $result = $this->driver
->replaceFile($file->getIdentifier(), $localFilePath);
1683 if ($file instanceof File
) {
1684 $this->getIndexer()->updateIndexEntry($file);
1686 $this->emitPostFileReplaceSignal($file, $localFilePath);
1691 * Adds an uploaded file into the Storage. Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::file_upload()
1693 * @param array $uploadedFileData contains information about the uploaded file given by $_FILES['file1']
1694 * @param Folder $targetFolder the target folder
1695 * @param string $targetFileName the file name to be written
1696 * @param string $conflictMode possible value are 'cancel', 'replace'
1697 * @return FileInterface The file object
1699 public function addUploadedFile(array $uploadedFileData, Folder
$targetFolder = NULL, $targetFileName = NULL, $conflictMode = 'cancel') {
1700 $localFilePath = $uploadedFileData['tmp_name'];
1701 if ($targetFolder === NULL) {
1702 $targetFolder = $this->getDefaultFolder();
1704 if ($targetFileName === NULL) {
1705 $targetFileName = $uploadedFileData['name'];
1707 // Handling $conflictMode is delegated to addFile()
1708 $this->assureFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileData['size']);
1709 $resultObject = $this->addFile($localFilePath, $targetFolder, $targetFileName, $conflictMode);
1710 return $resultObject;
1713 /********************
1715 ********************/
1717 * Returns an array with all file objects in a folder and its subfolders, with the file identifiers as keys.
1718 * @todo check if this is a duplicate
1719 * @param Folder $folder
1722 protected function getAllFileObjectsInFolder(Folder
$folder) {
1724 $folderQueue = array($folder);
1725 while (!empty($folderQueue)) {
1726 $folder = array_shift($folderQueue);
1727 foreach ($folder->getSubfolders() as $subfolder) {
1728 $folderQueue[] = $subfolder;
1730 foreach ($folder->getFiles() as $file) { /** @var FileInterface $file */
1731 $files[$file->getIdentifier()] = $file;
1738 * Moves a folder. If you want to move a folder from this storage to another
1739 * one, call this method on the target storage, otherwise you will get an exception.
1741 * @param Folder $folderToMove The folder to move.
1742 * @param Folder $targetParentFolder The target parent folder
1743 * @param string $newFolderName
1744 * @param string $conflictMode How to handle conflicts; one of "overrideExistingFile", "renameNewFolder", "cancel
1746 * @throws \Exception|\TYPO3\CMS\Core\Exception
1747 * @throws \InvalidArgumentException
1750 public function moveFolder(Folder
$folderToMove, Folder
$targetParentFolder, $newFolderName = NULL, $conflictMode = 'renameNewFolder') {
1752 $originalFolder = $folderToMove->getParentFolder();
1753 $this->assureFolderMovePermissions($folderToMove, $targetParentFolder);
1754 $sourceStorage = $folderToMove->getStorage();
1755 $returnObject = NULL;
1756 $sanitizedNewFolderName = $this->driver
->sanitizeFileName($newFolderName ?
: $folderToMove->getName());
1757 // TODO check if folder already exists in $targetParentFolder, handle this conflict then
1758 $this->emitPreFolderMoveSignal($folderToMove, $targetParentFolder, $sanitizedNewFolderName);
1759 // Get all file objects now so we are able to update them after moving the folder
1760 $fileObjects = $this->getAllFileObjectsInFolder($folderToMove);
1761 if ($sourceStorage === $this) {
1762 $fileMappings = $this->driver
->moveFolderWithinStorage($folderToMove->getIdentifier(), $targetParentFolder->getIdentifier(), $sanitizedNewFolderName);
1764 $fileMappings = $this->moveFolderBetweenStorages($folderToMove, $targetParentFolder, $sanitizedNewFolderName);
1766 // Update the identifier and storage of all file objects
1767 foreach ($fileObjects as $oldIdentifier => $fileObject) {
1768 $newIdentifier = $fileMappings[$oldIdentifier];
1769 $fileObject->updateProperties(array('storage' => $this->getUid(), 'identifier' => $newIdentifier));
1770 $this->getIndexer()->updateIndexEntry($fileObject);
1772 $returnObject = $this->getFolder($fileMappings[$folderToMove->getIdentifier()]);
1773 $this->emitPostFolderMoveSignal($folderToMove, $targetParentFolder, $returnObject->getName(), $originalFolder);
1774 return $returnObject;
1778 * Moves the given folder from a different storage to the target folder in this storage.
1780 * @param Folder $folderToMove
1781 * @param Folder $targetParentFolder
1782 * @param string $newFolderName
1785 * @throws \RuntimeException
1787 protected function moveFolderBetweenStorages(Folder
$folderToMove, Folder
$targetParentFolder, $newFolderName) {
1788 throw new \
RuntimeException('Not yet implemented');
1794 * @param FolderInterface $folderToCopy The folder to copy
1795 * @param FolderInterface $targetParentFolder The target folder
1796 * @param string $newFolderName
1797 * @param string $conflictMode "overrideExistingFolder", "renameNewFolder", "cancel
1798 * @return Folder The new (copied) folder object
1800 public function copyFolder(FolderInterface
$folderToCopy, FolderInterface
$targetParentFolder, $newFolderName = NULL, $conflictMode = 'renameNewFolder') {
1801 // TODO implement the $conflictMode handling
1802 $this->assureFolderCopyPermissions($folderToCopy, $targetParentFolder);
1803 $returnObject = NULL;
1804 $sanitizedNewFolderName = $this->driver
->sanitizeFileName($newFolderName ?
: $folderToCopy->getName());
1805 if ($folderToCopy instanceof Folder
&& $targetParentFolder instanceof Folder
) {
1806 $this->emitPreFolderCopySignal($folderToCopy, $targetParentFolder, $sanitizedNewFolderName);
1808 $sourceStorage = $folderToCopy->getStorage();
1809 // call driver method to move the file
1810 // that also updates the file object properties
1812 if ($sourceStorage === $this) {
1813 $this->driver
->copyFolderWithinStorage($folderToCopy->getIdentifier(), $targetParentFolder->getIdentifier(), $sanitizedNewFolderName);
1814 $returnObject = $this->getFolder($targetParentFolder->getSubfolder($sanitizedNewFolderName)->getIdentifier());
1816 $this->copyFolderBetweenStorages($folderToCopy, $targetParentFolder, $sanitizedNewFolderName);
1818 } catch (\TYPO3\CMS\Core\Exception
$e) {
1819 echo $e->getMessage();
1821 $this->emitPostFolderCopySignal($folderToCopy, $targetParentFolder, $returnObject->getName());
1822 return $returnObject;
1826 * Copies a folder between storages.
1828 * @param Folder $folderToCopy
1829 * @param Folder $targetParentFolder
1830 * @param string $newFolderName
1833 * @throws \RuntimeException
1835 protected function copyFolderBetweenStorages(Folder
$folderToCopy, Folder
$targetParentFolder, $newFolderName) {
1836 throw new \
RuntimeException('Not yet implemented.');
1840 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::folder_move()
1842 * @param Folder $folderObject
1843 * @param string $newName
1844 * @throws \Exception
1845 * @throws \InvalidArgumentException
1848 public function renameFolder($folderObject, $newName) {
1850 // Renaming the folder should check if the parent folder is writable
1851 // We cannot do this however because we cannot extract the parent folder from a folder currently
1852 if (!$this->checkFolderActionPermission('rename', $folderObject)) {
1853 throw new Exception\
InsufficientUserPermissionsException('You are not allowed to rename the folder "' . $folderObject->getIdentifier() . '\'', 1357811441);
1856 $sanitizedNewName = $this->driver
->sanitizeFileName($newName);
1857 $returnObject = NULL;
1858 if ($this->driver
->folderExistsInFolder($sanitizedNewName, $folderObject->getIdentifier())) {
1859 throw new \
InvalidArgumentException('The folder ' . $sanitizedNewName . ' already exists in folder ' . $folderObject->getIdentifier(), 1325418870);
1862 $this->emitPreFolderRenameSignal($folderObject, $sanitizedNewName);
1864 $fileObjects = $this->getAllFileObjectsInFolder($folderObject);
1865 $fileMappings = $this->driver
->renameFolder($folderObject->getIdentifier(), $sanitizedNewName);
1866 // Update the identifier of all file objects
1867 foreach ($fileObjects as $oldIdentifier => $fileObject) {
1868 $newIdentifier = $fileMappings[$oldIdentifier];
1869 $fileObject->updateProperties(array('identifier' => $newIdentifier));
1870 $this->getIndexer()->updateIndexEntry($fileObject);
1872 $returnObject = $this->getFolder($fileMappings[$folderObject->getIdentifier()]);
1874 $this->emitPostFolderRenameSignal($folderObject, $returnObject->getName());
1876 return $returnObject;
1880 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::folder_delete()
1882 * @param Folder $folderObject
1883 * @param bool $deleteRecursively
1884 * @throws \RuntimeException
1887 public function deleteFolder($folderObject, $deleteRecursively = FALSE) {
1888 $isEmpty = $this->driver
->isFolderEmpty($folderObject->getIdentifier());
1889 $this->assureFolderDeletePermission($folderObject, ($deleteRecursively && !$isEmpty));
1890 if (!$isEmpty && !$deleteRecursively) {
1891 throw new \
RuntimeException('Could not delete folder "' . $folderObject->getIdentifier() . '" because it is not empty.', 1325952534);
1894 $this->emitPreFolderDeleteSignal($folderObject);
1896 $result = $this->driver
->deleteFolder($folderObject->getIdentifier(), $deleteRecursively);
1898 $this->emitPostFolderDeleteSignal($folderObject);
1904 * Returns a list of folders in a given path.
1906 * @param string $path The path to list
1907 * @param int $start The position to start the listing; if not set or 0, start from the beginning
1908 * @param int $numberOfItems The number of items to list; if not set, return all items
1909 * @param bool $useFilters If FALSE, the list is returned without any filtering; otherwise, the filters defined for this storage are used.
1910 * @return array Information about the folders found.
1911 * @deprecated since TYPO3 6.2, will be removed to versions later
1913 public function getFolderList($path, $start = 0, $numberOfItems = 0, $useFilters = TRUE) {
1914 GeneralUtility
::logDeprecatedFunction();
1915 // Permissions are checked in $this->fetchFolderListFromDriver()
1916 $filters = $useFilters === TRUE ?
$this->fileAndFolderNameFilters
: array();
1917 return $this->fetchFolderListFromDriver($path, $start, $numberOfItems, $filters);
1921 * @param Folder $folder
1923 * @param int $maxNumberOfItems
1924 * @param bool $useFilters
1925 * @param bool $recursive
1929 public function getFoldersInFolder(Folder
$folder, $start = 0, $maxNumberOfItems = 0, $useFilters = TRUE, $recursive = FALSE) {
1930 $filters = $useFilters == TRUE ?
$this->fileAndFolderNameFilters
: array();
1931 $folderIdentifiers = $this->driver
->getFoldersInFolder($folder->getIdentifier(), $start, $maxNumberOfItems, $recursive, $filters);
1933 $processingIdentifier = $this->getProcessingFolder()->getIdentifier();
1934 if (isset($folderIdentifiers[$processingIdentifier])) {
1935 unset($folderIdentifiers[$processingIdentifier]);
1938 foreach ($folderIdentifiers as $folderIdentifier) {
1939 $folders[$folderIdentifier] = $this->getFolder($folderIdentifier, TRUE);
1947 * @param int $numberOfItems
1948 * @param array $folderFilterCallbacks
1949 * @param bool $recursive
1951 * @deprecated since 6.2, will be removed 2 versions later
1953 public function fetchFolderListFromDriver($path, $start = 0, $numberOfItems = 0, array $folderFilterCallbacks = array(), $recursive = FALSE) {
1954 GeneralUtility
::logDeprecatedFunction();
1955 // This also checks for access to that path and throws exceptions accordingly
1956 $parentFolder = $this->getFolder($path);
1957 if ($parentFolder === NULL) {
1960 $folders = $this->getFoldersInFolder($parentFolder, $start, $numberOfItems, count($folderFilterCallbacks) > 0, $recursive);
1961 $folderInfo = array();
1962 foreach ($folders as $folder) {
1963 $folderInfo[$folder->getIdentifier()] = array(
1964 'name' => $folder->getName(),
1965 'identifier' => $folder->getIdentifier()
1972 * Returns TRUE if the specified folder exists.
1974 * @param string $identifier
1977 public function hasFolder($identifier) {
1978 $this->assureFolderReadPermission();
1979 return $this->driver
->folderExists($identifier);
1983 * Checks if the given file exists in the given folder
1985 * @param string $folderName
1986 * @param Folder $folder
1989 public function hasFolderInFolder($folderName, Folder
$folder) {
1990 $this->assureFolderReadPermission($folder);
1991 return $this->driver
->folderExistsInFolder($folderName, $folder->getIdentifier());
1995 * Creates a new folder.
1997 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_newfolder()
1999 * @param string $folderName The new folder name
2000 * @param Folder $parentFolder (optional) the parent folder to create the new folder inside of. If not given, the root folder is used
2002 * @throws Exception\InsufficientFolderWritePermissionsException
2003 * @throws \InvalidArgumentException
2004 * @return Folder The new folder object
2006 public function createFolder($folderName, Folder
$parentFolder = NULL) {
2007 if ($parentFolder === NULL) {
2008 $parentFolder = $this->getRootLevelFolder();
2009 } elseif (!$this->driver
->folderExists($parentFolder->getIdentifier())) {
2010 throw new \
InvalidArgumentException('Parent folder "' . $parentFolder->getIdentifier() . '" does not exist.', 1325689164);
2012 if (!$this->checkFolderActionPermission('add', $parentFolder)) {
2013 throw new Exception\
InsufficientFolderWritePermissionsException('You are not allowed to create directories in the folder "' . $parentFolder->getIdentifier() . '"', 1323059807);
2016 $this->emitPreFolderAddSignal($parentFolder, $folderName);
2018 $newFolder = $this->getDriver()->createFolder($folderName, $parentFolder->getIdentifier(), TRUE);
2019 $newFolder = $this->getFolder($newFolder);
2021 $this->emitPostFolderAddSignal($newFolder);
2027 * Returns the default folder where new files are stored if no other folder is given.
2031 public function getDefaultFolder() {
2032 return $this->getFolder($this->driver
->getDefaultFolder());
2036 * @param string $identifier
2037 * @param bool $returnInaccessibleFolderObject
2040 * @throws \Exception
2041 * @throws Exception\InsufficientFolderAccessPermissionsException
2043 public function getFolder($identifier, $returnInaccessibleFolderObject = FALSE) {
2044 $data = $this->driver
->getFolderInfoByIdentifier($identifier);
2045 $folder = ResourceFactory
::getInstance()->createFolderObject($this, $data['identifier'], $data['name']);
2048 $this->assureFolderReadPermission($folder);
2049 } catch (Exception\InsufficientFolderAccessPermissionsException
$e) {
2051 if ($returnInaccessibleFolderObject) {
2052 // if parent folder is readable return inaccessible folder object
2053 $parentPermissions = $this->driver
->getPermissions($this->driver
->getParentFolderIdentifierOfIdentifier($identifier));
2054 if ($parentPermissions['r']) {
2055 $folder = GeneralUtility
::makeInstance(
2056 'TYPO3\\CMS\\Core\\Resource\\InaccessibleFolder', $this, $data['identifier'], $data['name']
2061 if ($folder === NULL) {
2069 * @param string $identifier
2072 public function isWithinProcessingFolder($identifier) {
2073 return $this->driver
->isWithin($this->getProcessingFolder()->getIdentifier(), $identifier);
2077 * Returns the folders on the root level of the storage
2078 * or the first mount point of this storage for this user.
2082 public function getRootLevelFolder() {
2083 if (count($this->fileMounts
)) {
2084 $mount = reset($this->fileMounts
);
2085 return $mount['folder'];
2087 return ResourceFactory
::getInstance()->createFolderObject($this, $this->driver
->getRootLevelFolder(), '');
2092 * Emits file pre-add signal.
2094 * @param string $targetFileName
2095 * @param Folder $targetFolder
2096 * @param string $sourceFilePath
2099 protected function emitPreFileAddSignal(&$targetFileName, Folder
$targetFolder, $sourceFilePath) {
2100 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFileAdd
, array(&$targetFileName, $targetFolder, $sourceFilePath, $this, $this->driver
));
2104 * Emits the file post-add signal.
2106 * @param FileInterface $file
2107 * @param Folder $targetFolder
2110 protected function emitPostFileAddSignal(FileInterface
$file, Folder
$targetFolder) {
2111 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFileAdd
, array($file, $targetFolder));
2115 * Emits file pre-copy signal.
2117 * @param FileInterface $file
2118 * @param Folder $targetFolder
2121 protected function emitPreFileCopySignal(FileInterface
$file, Folder
$targetFolder) {
2122 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFileCopy
, array($file, $targetFolder));
2126 * Emits the file post-copy signal.
2128 * @param FileInterface $file
2129 * @param Folder $targetFolder
2132 protected function emitPostFileCopySignal(FileInterface
$file, Folder
$targetFolder) {
2133 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFileCopy
, array($file, $targetFolder));
2137 * Emits the file pre-move signal.
2139 * @param FileInterface $file
2140 * @param Folder $targetFolder
2143 protected function emitPreFileMoveSignal(FileInterface
$file, Folder
$targetFolder) {
2144 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFileMove
, array($file, $targetFolder));
2148 * Emits the file post-move signal.
2150 * @param FileInterface $file
2151 * @param Folder $targetFolder
2152 * @param Folder $originalFolder
2155 protected function emitPostFileMoveSignal(FileInterface
$file, Folder
$targetFolder, Folder
$originalFolder) {
2156 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFileMove
, array($file, $targetFolder, $originalFolder));
2160 * Emits the file pre-rename signal
2162 * @param FileInterface $file
2163 * @param $targetFolder
2166 protected function emitPreFileRenameSignal(FileInterface
$file, $targetFolder) {
2167 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFileRename
, array($file, $targetFolder));
2171 * Emits the file post-rename signal.
2173 * @param FileInterface $file
2174 * @param $targetFolder
2177 protected function emitPostFileRenameSignal(FileInterface
$file, $targetFolder) {
2178 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFileRename
, array($file, $targetFolder));
2182 * Emits the file pre-replace signal.
2184 * @param FileInterface $file
2185 * @param $localFilePath
2188 protected function emitPreFileReplaceSignal(FileInterface
$file, $localFilePath) {
2189 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFileReplace
, array($file, $localFilePath));
2193 * Emits the file post-replace signal
2195 * @param FileInterface $file
2196 * @param $localFilePath
2199 protected function emitPostFileReplaceSignal(FileInterface
$file, $localFilePath) {
2200 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFileReplace
, array($file, $localFilePath));
2204 * Emits the file post-create signal
2206 * @param string $newFileIdentifier
2207 * @param Folder $targetFolder
2209 protected function emitPostFileCreateSignal($newFileIdentifier, Folder
$targetFolder) {
2210 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFileCreate
, array($newFileIdentifier, $targetFolder));
2214 * Emits the file pre-deletion signal.
2216 * @param FileInterface $file
2219 protected function emitPreFileDeleteSignal(FileInterface
$file) {
2220 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFileDelete
, array($file));
2224 * Emits the file post-deletion signal
2226 * @param FileInterface $file
2229 protected function emitPostFileDeleteSignal(FileInterface
$file) {
2230 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFileDelete
, array($file));
2234 * Emits the file post-set-contents signal
2236 * @param FileInterface $file
2237 * @param mixed $content
2240 protected function emitPostFileSetContentsSignal(FileInterface
$file, $content) {
2241 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFileSetContents
, array($file, $content));
2245 * Emits the folder pre-add signal.
2247 * @param Folder $targetFolder
2248 * @param string $name
2251 protected function emitPreFolderAddSignal(Folder
$targetFolder, $name) {
2252 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFolderAdd
, array($targetFolder, $name));
2256 * Emits the folder post-add signal.
2258 * @param Folder $folder
2261 protected function emitPostFolderAddSignal(Folder
$folder) {
2262 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFolderAdd
, array($folder));
2266 * Emits the folder pre-copy signal.
2268 * @param Folder $folder
2269 * @param Folder $targetFolder
2273 protected function emitPreFolderCopySignal(Folder
$folder, Folder
$targetFolder, $newName) {
2274 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFolderCopy
, array($folder, $targetFolder, $newName));
2278 * Emits the folder post-copy signal.
2280 * @param Folder $folder
2281 * @param Folder $targetFolder
2285 protected function emitPostFolderCopySignal(Folder
$folder, Folder
$targetFolder, $newName) {
2286 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFolderCopy
, array($folder, $targetFolder, $newName));
2290 * Emits the folder pre-move signal.
2292 * @param Folder $folder
2293 * @param Folder $targetFolder
2297 protected function emitPreFolderMoveSignal(Folder
$folder, Folder
$targetFolder, $newName) {
2298 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFolderMove
, array($folder, $targetFolder, $newName));
2302 * Emits the folder post-move signal.
2304 * @param Folder $folder
2305 * @param Folder $targetFolder
2307 * @param Folder $originalFolder
2310 protected function emitPostFolderMoveSignal(Folder
$folder, Folder
$targetFolder, $newName, Folder
$originalFolder) {
2311 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFolderMove
, array($folder, $targetFolder, $newName, $originalFolder));
2315 * Emits the folder pre-rename signal.
2317 * @param Folder $folder
2321 protected function emitPreFolderRenameSignal(Folder
$folder, $newName) {
2322 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFolderRename
, array($folder, $newName));
2326 * Emits the folder post-rename signal.
2328 * @param Folder $folder
2332 protected function emitPostFolderRenameSignal(Folder
$folder, $newName) {
2333 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFolderRename
, array($folder, $newName));
2337 * Emits the folder pre-deletion signal.
2339 * @param Folder $folder
2342 protected function emitPreFolderDeleteSignal(Folder
$folder) {
2343 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreFolderDelete
, array($folder));
2347 * Emits folder post-deletion signal..
2349 * @param Folder $folder
2352 protected function emitPostFolderDeleteSignal(Folder
$folder) {
2353 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PostFolderDelete
, array($folder));
2357 * Emits file pre-processing signal when generating a public url for a file or folder.
2359 * @param ResourceInterface $resourceObject
2360 * @param bool $relativeToCurrentScript
2361 * @param array $urlData
2363 protected function emitPreGeneratePublicUrl(ResourceInterface
$resourceObject, $relativeToCurrentScript, array $urlData) {
2364 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self
::SIGNAL_PreGeneratePublicUrl
, array($this, $this->driver
, $resourceObject, $relativeToCurrentScript, $urlData));
2368 * Returns the destination path/fileName of a unique fileName/foldername in that path.
2369 * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended.
2370 * This function is used by fx. TCEmain when files are attached to records and needs to be uniquely named in the uploads/* folders
2372 * @param Folder $folder
2373 * @param string $theFile The input fileName to check
2374 * @param bool $dontCheckForUnique If set the fileName is returned with the path prepended without checking whether it already existed!
2376 * @throws \RuntimeException
2377 * @return string A unique fileName inside $folder, based on $theFile.
2378 * @see \TYPO3\CMS\Core\Utility\File\BasicFileUtility::getUniqueName()
2380 protected function getUniqueName(Folder
$folder, $theFile, $dontCheckForUnique = FALSE) {
2381 static $maxNumber = 99, $uniqueNamePrefix = '';
2382 // Fetches info about path, name, extention of $theFile
2383 $origFileInfo = GeneralUtility
::split_fileref($theFile);
2385 if ($uniqueNamePrefix) {
2386 $origFileInfo['file'] = $uniqueNamePrefix . $origFileInfo['file'];
2387 $origFileInfo['filebody'] = $uniqueNamePrefix . $origFileInfo['filebody'];
2389 // Check if the file exists and if not - return the fileName...
2390 $fileInfo = $origFileInfo;
2391 // The destinations file
2392 $theDestFile = $fileInfo['file'];
2393 // If the file does NOT exist we return this fileName
2394 if (!$this->driver
->fileExistsInFolder($theDestFile, $folder->getIdentifier()) ||
$dontCheckForUnique) {
2395 return $theDestFile;
2397 // Well the fileName in its pure form existed. Now we try to append
2398 // numbers / unique-strings and see if we can find an available fileName
2399 // This removes _xx if appended to the file
2400 $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']);
2401 $theOrigExt = $origFileInfo['realFileext'] ?
'.' . $origFileInfo['realFileext'] : '';
2402 for ($a = 1; $a <= $maxNumber +
1; $a++
) {
2403 // First we try to append numbers
2404 if ($a <= $maxNumber) {
2405 $insert = '_' . sprintf('%02d', $a);
2407 $insert = '_' . substr(md5(uniqId('')), 0, 6);
2409 $theTestFile = $theTempFileBody . $insert . $theOrigExt;
2410 // The destinations file
2411 $theDestFile = $theTestFile;
2412 // If the file does NOT exist we return this fileName
2413 if (!$this->driver
->fileExistsInFolder($theDestFile, $folder->getIdentifier())) {
2414 return $theDestFile;
2417 throw new \
RuntimeException('Last possible name "' . $theDestFile . '" is already taken.', 1325194291);
2421 * Get the SignalSlot dispatcher.
2423 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
2425 protected function getSignalSlotDispatcher() {
2426 if (!isset($this->signalSlotDispatcher
)) {
2427 $this->signalSlotDispatcher
= $this->getObjectManager()->get('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
2429 return $this->signalSlotDispatcher
;
2433 * Gets the ObjectManager.
2435 * @return \TYPO3\CMS\Extbase\Object\ObjectManager
2437 protected function getObjectManager() {
2438 return GeneralUtility
::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
2442 * @return ResourceFactory
2444 protected function getFileFactory() {
2445 return GeneralUtility
::makeInstance('TYPO3\\CMS\\Core\\Resource\\ResourceFactory');
2449 * @return \TYPO3\CMS\Core\Resource\Index\FileIndexRepository
2451 protected function getFileIndexRepository() {
2452 return FileIndexRepository
::getInstance();
2456 * @return Service\FileProcessingService
2458 protected function getFileProcessingService() {
2459 if (!$this->fileProcessingService
) {
2460 $this->fileProcessingService
= GeneralUtility
::makeInstance('TYPO3\\CMS\\Core\\Resource\\Service\\FileProcessingService', $this, $this->driver
);
2462 return $this->fileProcessingService
;
2466 * Gets the role of a folder.
2468 * @param FolderInterface $folder Folder object to get the role from
2469 * @return string The role the folder has
2471 public function getRole(FolderInterface
$folder) {
2472 $folderRole = FolderInterface
::ROLE_DEFAULT
;
2474 if (method_exists($this->driver
, 'getRole')) {
2475 $folderRole = $this->driver
->getRole($folder->getIdentifier());
2478 if ($folder->getIdentifier() === $this->getProcessingFolder()->getIdentifier()) {
2479 $folderRole = FolderInterface
::ROLE_PROCESSING
;
2486 * Getter function to return the folder where the files can
2487 * be processed. Does not check for access rights here.
2491 public function getProcessingFolder() {
2492 if (!isset($this->processingFolder
)) {
2493 $processingFolder = self
::DEFAULT_ProcessingFolder
;
2494 if (!empty($this->storageRecord
['processingfolder'])) {
2495 $processingFolder = $this->storageRecord
['processingfolder'];
2497 if ($this->driver
->folderExists($processingFolder) === FALSE) {
2498 $this->processingFolder
= $this->createFolder($processingFolder);
2500 $data = $this->driver
->getFolderInfoByIdentifier($processingFolder);
2501 $this->processingFolder
= ResourceFactory
::getInstance()->createFolderObject($this, $data['identifier'], $data['name']);
2504 return $this->processingFolder
;
2508 * Gets the driver Type configured for this storage.
2512 public function getDriverType() {
2513 return $this->storageRecord
['driver'];
2519 * @return \TYPO3\CMS\Core\Resource\Index\Indexer
2521 protected function getIndexer() {
2522 return GeneralUtility
::makeInstance('TYPO3\\CMS\\Core\\Resource\\Index\\Indexer', $this);
2526 * @param bool $isDefault
2529 public function setDefault($isDefault) {
2530 $this->isDefault
= (bool)$isDefault;
2536 public function isDefault() {
2537 return $this->isDefault
;