f2fc82dd54216db12bb87897e24bba10bc8de6a4
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Resource / ResourceStorage.php
1 <?php
2 namespace TYPO3\CMS\Core\Resource;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2011-2013 Andreas Wolf <andreas.wolf@typo3.org>
8 * All rights reserved
9 *
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.
15 *
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 textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
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.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 use TYPO3\CMS\Core\Utility\GeneralUtility;
31 use TYPO3\CMS\Core\Utility\PathUtility;
32
33 /**
34 * A "mount point" inside the TYPO3 file handling.
35 *
36 * A "storage" object handles
37 * - abstraction to the driver
38 * - permissions (from the driver, and from the user, + capabilities)
39 * - an entry point for files, folders, and for most other operations
40 *
41 * == Driver entry point
42 * The driver itself, that does the actual work on the file system,
43 * is inside the storage but completely shadowed by
44 * the storage, as the storage also handles the abstraction to the
45 * driver
46 *
47 * The storage can be on the local system, but can also be on a remote
48 * system. The combination of driver + configurable capabilities (storage
49 * is read-only e.g.) allows for flexible uses.
50 *
51 *
52 * == Permission system
53 * As all requests have to run through the storage, the storage knows about the
54 * permissions of a BE/FE user, the file permissions / limitations of the driver
55 * and has some configurable capabilities.
56 * Additionally, a BE user can use "filemounts" (known from previous installations)
57 * to limit his/her work-zone to only a subset (identifier and its subfolders/subfolders)
58 * of the user itself.
59 *
60 * Check 1: "User Permissions" [is the user allowed to write a file) [is the user allowed to write a file]
61 * Check 2: "File Mounts" of the User (act as subsets / filters to the identifiers) [is the user allowed to do something in this folder?]
62 * Check 3: "Capabilities" of Storage (then: of Driver) [is the storage/driver writable?]
63 * Check 4: "File permissions" of the Driver [is the folder writable?]
64 *
65 * @author Andreas Wolf <andreas.wolf@typo3.org>
66 * @author Ingmar Schlecht <ingmar@typo3.org>
67 */
68 class ResourceStorage {
69
70 const SIGNAL_PreProcessConfiguration = 'preProcessConfiguration';
71 const SIGNAL_PostProcessConfiguration = 'postProcessConfiguration';
72 const SIGNAL_PreFileCopy = 'preFileCopy';
73 const SIGNAL_PostFileCopy = 'postFileCopy';
74 const SIGNAL_PreFileMove = 'preFileMove';
75 const SIGNAL_PostFileMove = 'postFileMove';
76 const SIGNAL_PreFileDelete = 'preFileDelete';
77 const SIGNAL_PostFileDelete = 'postFileDelete';
78 const SIGNAL_PreFileRename = 'preFileRename';
79 const SIGNAL_PostFileRename = 'postFileRename';
80 const SIGNAL_PreFileReplace = 'preFileReplace';
81 const SIGNAL_PostFileReplace = 'postFileReplace';
82 const SIGNAL_PreFolderCopy = 'preFolderCopy';
83 const SIGNAL_PostFolderCopy = 'postFolderCopy';
84 const SIGNAL_PreFolderMove = 'preFolderMove';
85 const SIGNAL_PostFolderMove = 'postFolderMove';
86 const SIGNAL_PreFolderDelete = 'preFolderDelete';
87 const SIGNAL_PostFolderDelete = 'postFolderDelete';
88 const SIGNAL_PreFolderRename = 'preFolderRename';
89 const SIGNAL_PostFolderRename = 'postFolderRename';
90 const SIGNAL_PreGeneratePublicUrl = 'preGeneratePublicUrl';
91 /**
92 * The storage driver instance belonging to this storage.
93 *
94 * @var Driver\AbstractDriver
95 */
96 protected $driver;
97
98 /**
99 * The database record for this storage
100 *
101 * @var array
102 */
103 protected $storageRecord;
104
105 /**
106 * The configuration belonging to this storage (decoded from the configuration field).
107 *
108 * @var array
109 */
110 protected $configuration;
111
112 /**
113 * The base URI to this storage.
114 *
115 * @var string
116 */
117 protected $baseUri;
118
119 /**
120 * @var Service\FileProcessingService
121 */
122 protected $fileProcessingService;
123
124 /**
125 * Whether to check if file or folder is in user mounts
126 * and the action is allowed for a user
127 * Default is FALSE so that resources are accessible for
128 * front end rendering or admins.
129 *
130 * @var boolean
131 */
132 protected $evaluatePermissions = FALSE;
133
134 /**
135 * User filemounts, added as an array, and used as filters
136 *
137 * @var array
138 */
139 protected $fileMounts = array();
140
141 /**
142 * The file permissions of the user (and their group) merged together and
143 * available as an array
144 *
145 * @var array
146 */
147 protected $userPermissions = array();
148
149 /**
150 * The capabilities of this storage as defined in the storage record.
151 * Also see the CAPABILITY_* constants below
152 *
153 * @var integer
154 */
155 protected $capabilities;
156
157 /**
158 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
159 */
160 protected $signalSlotDispatcher;
161
162 /**
163 * Capability for being browsable by (backend) users
164 */
165 const CAPABILITY_BROWSABLE = 1;
166 /**
167 * Capability for publicly accessible storages (= accessible from the web)
168 */
169 const CAPABILITY_PUBLIC = 2;
170 /**
171 * Capability for writable storages. This only signifies writability in
172 * general - this might also be further limited by configuration.
173 */
174 const CAPABILITY_WRITABLE = 4;
175 /**
176 * Name of the default processing folder
177 */
178 const DEFAULT_ProcessingFolder = '_processed_';
179 /**
180 * @var Folder
181 */
182 protected $processingFolder;
183
184 /**
185 * whether this storage is online or offline in this request
186 *
187 * @var boolean
188 */
189 protected $isOnline = NULL;
190
191 /**
192 * The filters used for the files and folder names.
193 *
194 * @var array
195 */
196 protected $fileAndFolderNameFilters = array();
197
198 /**
199 * Constructor for a storage object.
200 *
201 * @param Driver\AbstractDriver $driver
202 * @param array $storageRecord The storage record row from the database
203 */
204 public function __construct(Driver\AbstractDriver $driver, array $storageRecord) {
205 $this->storageRecord = $storageRecord;
206 $this->configuration = ResourceFactory::getInstance()->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
207 $this->driver = $driver;
208 $this->driver->setStorage($this);
209 try {
210 $this->driver->processConfiguration();
211 } catch (Exception\InvalidConfigurationException $e) {
212 // configuration error
213 // mark this storage as permanently unusable
214 $this->markAsPermanentlyOffline();
215 }
216 $this->driver->initialize();
217 $this->capabilities = ($this->storageRecord['is_browsable'] && $this->driver->hasCapability(self::CAPABILITY_BROWSABLE) ? self::CAPABILITY_BROWSABLE : 0) + ($this->storageRecord['is_public'] && $this->driver->hasCapability(self::CAPABILITY_PUBLIC) ? self::CAPABILITY_PUBLIC : 0) + ($this->storageRecord['is_writable'] && $this->driver->hasCapability(self::CAPABILITY_WRITABLE) ? self::CAPABILITY_WRITABLE : 0);
218 // TODO do not set the "public" capability if no public URIs can be generated
219 $this->processConfiguration();
220 $this->resetFileAndFolderNameFiltersToDefault();
221 }
222
223 /**
224 * Gets the configuration
225 *
226 * @return array
227 */
228 public function getConfiguration() {
229 return $this->configuration;
230 }
231
232 /**
233 * Sets the configuration.
234 *
235 * @param array $configuration
236 */
237 public function setConfiguration(array $configuration) {
238 $this->configuration = $configuration;
239 }
240
241 /**
242 * Gets the storage record.
243 *
244 * @return array
245 */
246 public function getStorageRecord() {
247 return $this->storageRecord;
248 }
249
250 /**
251 * Processes the configuration of this storage.
252 *
253 * @throws \InvalidArgumentException If a required configuration option is not set or has an invalid value.
254 * @return void
255 */
256 protected function processConfiguration() {
257 $this->emitPreProcessConfigurationSignal();
258 if (isset($this->configuration['baseUri'])) {
259 $this->baseUri = rtrim($this->configuration['baseUri'], '/') . '/';
260 }
261 $this->emitPostProcessConfigurationSignal();
262 }
263
264 /**
265 * Returns the base URI of this storage; all files are reachable via URLs
266 * beginning with this string.
267 *
268 * @return string
269 */
270 public function getBaseUri() {
271 return $this->baseUri;
272 }
273
274 /**
275 * Sets the storage that belongs to this storage.
276 *
277 * @param Driver\AbstractDriver $driver
278 * @return ResourceStorage
279 */
280 public function setDriver(Driver\AbstractDriver $driver) {
281 $this->driver = $driver;
282 return $this;
283 }
284
285 /**
286 * Returns the driver object belonging to this storage.
287 *
288 * @return Driver\AbstractDriver
289 */
290 protected function getDriver() {
291 return $this->driver;
292 }
293
294 /**
295 * Deprecated function, don't use it. Will be removed in some later revision.
296 *
297 * @param string $identifier
298 *
299 * @throws \BadMethodCallException
300 */
301 public function getFolderByIdentifier($identifier) {
302 throw new \BadMethodCallException('Function TYPO3\\CMS\\Core\\Resource\\ResourceStorage::getFolderByIdentifier() has been renamed to just getFolder(). Please fix the method call.', 1333754514);
303 }
304
305 /**
306 * Deprecated function, don't use it. Will be removed in some later revision.
307 *
308 * @param string $identifier
309 *
310 * @throws \BadMethodCallException
311 */
312 public function getFileByIdentifier($identifier) {
313 throw new \BadMethodCallException('Function TYPO3\\CMS\\Core\\Resource\\ResourceStorage::getFileByIdentifier() has been renamed to just getFileInfoByIdentifier(). ' . 'Please fix the method call.', 1333754533);
314 }
315
316 /**
317 * Returns the name of this storage.
318 *
319 * @return string
320 */
321 public function getName() {
322 return $this->storageRecord['name'];
323 }
324
325 /**
326 * Returns the uid of this storage.
327 *
328 * @return integer
329 */
330 public function getUid() {
331 return (int) $this->storageRecord['uid'];
332 }
333
334 /**
335 * Tells whether there are children in this storage
336 *
337 * @return boolean
338 */
339 public function hasChildren() {
340 return TRUE;
341 }
342
343 /*********************************
344 * Capabilities
345 ********************************/
346 /**
347 * Returns the capabilities of this storage.
348 *
349 * @return integer
350 * @see CAPABILITY_* constants
351 */
352 public function getCapabilities() {
353 return (int) $this->capabilities;
354 }
355
356 /**
357 * Returns TRUE if this storage has the given capability.
358 *
359 * @param integer $capability A capability, as defined in a CAPABILITY_* constant
360 * @return boolean
361 */
362 protected function hasCapability($capability) {
363 return ($this->capabilities & $capability) == $capability;
364 }
365
366 /**
367 * Returns TRUE if this storage is publicly available. This is just a
368 * configuration option and does not mean that it really *is* public. OTOH
369 * a storage that is marked as not publicly available will trigger the file
370 * publishing mechanisms of TYPO3.
371 *
372 * @return boolean
373 */
374 public function isPublic() {
375 return $this->hasCapability(self::CAPABILITY_PUBLIC);
376 }
377
378 /**
379 * Returns TRUE if this storage is writable. This is determined by the
380 * driver and the storage configuration; user permissions are not taken into account.
381 *
382 * @return boolean
383 */
384 public function isWritable() {
385 return $this->hasCapability(self::CAPABILITY_WRITABLE);
386 }
387
388 /**
389 * Returns TRUE if this storage is browsable by a (backend) user of TYPO3.
390 *
391 * @return boolean
392 */
393 public function isBrowsable() {
394 return $this->isOnline() && $this->hasCapability(self::CAPABILITY_BROWSABLE);
395 }
396
397 /**
398 * Returns TRUE if this storage is browsable by a (backend) user of TYPO3.
399 *
400 * @return boolean
401 */
402 public function isOnline() {
403 if ($this->isOnline === NULL) {
404 if ($this->getUid() === 0) {
405 $this->isOnline = TRUE;
406 }
407 // the storage is not marked as online for a longer time
408 if ($this->storageRecord['is_online'] == 0) {
409 $this->isOnline = FALSE;
410 }
411 if ($this->isOnline !== FALSE) {
412 // all files are ALWAYS available in the frontend
413 if (TYPO3_MODE === 'FE') {
414 $this->isOnline = TRUE;
415 } else {
416 // check if the storage is disabled temporary for now
417 $registryObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
418 $offlineUntil = $registryObject->get('core', 'sys_file_storage-' . $this->getUid() . '-offline-until');
419 if ($offlineUntil && $offlineUntil > time()) {
420 $this->isOnline = FALSE;
421 } else {
422 $this->isOnline = TRUE;
423 }
424 }
425 }
426 }
427 return $this->isOnline;
428 }
429
430 /**
431 * blow the "fuse" and mark the storage as offline
432 * can only be modified by an admin
433 * typically this is only done if the configuration is wrong
434 */
435 public function markAsPermanentlyOffline() {
436 if ($this->getUid() > 0) {
437 // @todo: move this to the storage repository
438 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('sys_file_storage', 'uid=' . intval($this->getUid()), array('is_online' => 0));
439 }
440 $this->storageRecord['is_online'] = 0;
441 $this->isOnline = FALSE;
442 }
443
444 /**
445 * mark this storage as offline
446 *
447 * non-permanent: this typically happens for remote storages
448 * that are "flaky" and not available all the time
449 * mark this storage as offline for the next 5 minutes
450 *
451 * @return void
452 */
453 public function markAsTemporaryOffline() {
454 $registryObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
455 $registryObject->set('core', 'sys_file_storage-' . $this->getUid() . '-offline-until', time() + 60 * 5);
456 $this->storageRecord['is_online'] = 0;
457 $this->isOnline = FALSE;
458 }
459
460 /*********************************
461 * User Permissions / File Mounts
462 ********************************/
463 /**
464 * Adds a filemount as a "filter" for users to only work on a subset of a
465 * storage object
466 *
467 * @param string $folderIdentifier
468 * @param array $additionalData
469 *
470 * @throws Exception\FolderDoesNotExistException
471 * @return void
472 */
473 public function addFileMount($folderIdentifier, $additionalData = array()) {
474 // check for the folder before we add it as a filemount
475 if ($this->driver->folderExists($folderIdentifier) === FALSE) {
476 // if there is an error, this is important and should be handled
477 // as otherwise the user would see the whole storage without any restrictions for the filemounts
478 throw new Exception\FolderDoesNotExistException('Folder for file mount ' . $folderIdentifier . ' does not exist.', 1334427099);
479 }
480 $folderObject = $this->driver->getFolder($folderIdentifier);
481 if (empty($additionalData)) {
482 $additionalData = array(
483 'path' => $folderIdentifier,
484 'title' => $folderIdentifier,
485 'folder' => $folderObject
486 );
487 } else {
488 $additionalData['folder'] = $folderObject;
489 if (!isset($additionalData['title'])) {
490 $additionalData['title'] = $folderIdentifier;
491 }
492 }
493 $this->fileMounts[$folderIdentifier] = $additionalData;
494 }
495
496 /**
497 * Returns all file mounts that are registered with this storage.
498 *
499 * @return array
500 */
501 public function getFileMounts() {
502 return $this->fileMounts;
503 }
504
505 /**
506 * Checks if the given subject is within one of the registered user
507 * filemounts. If not, working with the file is not permitted for the user.
508 *
509 * @param $subject
510 * @return boolean
511 */
512 public function isWithinFileMountBoundaries($subject) {
513 if (!$this->evaluatePermissions) {
514 return TRUE;
515 }
516 $isWithinFilemount = FALSE;
517 if (!$subject) {
518 $subject = $this->getRootLevelFolder();
519 }
520 $identifier = $subject->getIdentifier();
521
522 // Allow access to processing folder
523 if ($this->driver->isWithin($this->getProcessingFolder(), $identifier)) {
524 $isWithinFilemount = TRUE;
525 } else {
526 // Check if the identifier of the subject is within at
527 // least one of the file mounts
528 foreach ($this->fileMounts as $fileMount) {
529 if ($this->driver->isWithin($fileMount['folder'], $identifier)) {
530 $isWithinFilemount = TRUE;
531 break;
532 }
533 }
534 }
535 return $isWithinFilemount;
536 }
537
538 /**
539 * @param $evaluatePermissions
540 */
541 public function setEvaluatePermissions($evaluatePermissions) {
542 $this->evaluatePermissions = (boolean) $evaluatePermissions;
543 }
544
545 /**
546 * Sets the user permissions of the storage
547 *
548 * @param array $userPermissions
549 * @return void
550 */
551 public function setUserPermissions(array $userPermissions) {
552 $this->userPermissions = $userPermissions;
553 }
554
555 /**
556 * Check if the ACL settings allow for a certain action
557 * (is a user allowed to read a file or copy a folder)
558 *
559 * @param string $action
560 * @param string $type either File or Folder
561 * @return bool
562 */
563 public function checkUserActionPermission($action, $type) {
564 if (!$this->evaluatePermissions) {
565 return TRUE;
566 }
567
568 $allow = FALSE;
569 if (!empty($this->userPermissions[strtolower($action) . ucfirst(strtolower($type))])) {
570 $allow = TRUE;
571 }
572
573 return $allow;
574 }
575
576 /**
577 * Check if a file operation (= action) is allowed on a
578 * File/Folder/Storage (= subject).
579 *
580 * This method, by design, does not throw exceptions or do logging.
581 * Besides the usage from other methods in this class, it is also used by
582 * the File List UI to check whether an action is allowed and whether action
583 * related UI elements should thus be shown (move icon, edit icon, etc.)
584 *
585 * @param string $action, can be read, write, delete
586 * @param FileInterface $file
587 * @return boolean
588 */
589 public function checkFileActionPermission($action, FileInterface $file) {
590 $isProcessedFile = $file instanceof ProcessedFile;
591 // Check 1: Does the user have permission to perform the action? e.g. "readFile"
592 if (!$isProcessedFile && $this->checkUserActionPermission($action, 'File') === FALSE) {
593 return FALSE;
594 }
595 // Check 2: No action allowed on files for denied file extensions
596 if (!$this->checkFileExtensionPermission($file->getName())) {
597 return FALSE;
598 }
599 // Check 3: Does the user have the right to perform the action?
600 // (= is he within the file mount borders)
601 if (!$isProcessedFile && !$this->isWithinFileMountBoundaries($file)) {
602 return FALSE;
603 }
604 $isReadCheck = FALSE;
605 if (in_array($action, array('read', 'copy', 'move'), TRUE)) {
606 $isReadCheck = TRUE;
607 }
608 $isWriteCheck = FALSE;
609 if (in_array($action, array('add', 'write', 'move', 'rename', 'unzip', 'delete'), TRUE)) {
610 $isWriteCheck = TRUE;
611 }
612
613 $isMissing = FALSE;
614 if (!$isProcessedFile) {
615 $isMissing = $file->isMissing();
616 }
617
618 // Check 4: Check the capabilities of the storage (and the driver)
619 if ($isWriteCheck && ($isMissing || !$this->isWritable())) {
620 return FALSE;
621 }
622 // Check 5: "File permissions" of the driver (only when file isn't marked as missing)
623 if (!$isMissing) {
624 $filePermissions = $this->driver->getFilePermissions($file);
625 if ($isReadCheck && !$filePermissions['r']) {
626 return FALSE;
627 }
628 if ($isWriteCheck && !$filePermissions['w']) {
629 return FALSE;
630 }
631 }
632 return TRUE;
633 }
634
635 /**
636 * Check if a folder operation (= action) is allowed on a Folder
637 *
638 * This method, by design, does not throw exceptions or do logging.
639 * See the checkFileActionPermission() method above for the reasons.
640 *
641 * @param string $action
642 * @param Folder $folder
643 * @return boolean
644 */
645 public function checkFolderActionPermission($action, Folder $folder = NULL) {
646 // Check 1: Does the user have permission to perform the action? e.g. "writeFolder"
647 if ($this->checkUserActionPermission($action, 'Folder') === FALSE) {
648 return FALSE;
649 }
650
651 // If we do not have a folder here, we cannot do further checks
652 if ($folder === NULL) {
653 return TRUE;
654 }
655
656 // Check 2: Does the user has the right to perform the action?
657 // (= is he within the file mount borders)
658 if (!$this->isWithinFileMountBoundaries($folder)) {
659 return FALSE;
660 }
661 $isReadCheck = FALSE;
662 if (in_array($action, array('read', 'copy'), TRUE)) {
663 $isReadCheck = TRUE;
664 }
665 $isWriteCheck = FALSE;
666 if (in_array($action, array('add', 'move', 'write', 'delete', 'rename'), TRUE)) {
667 $isWriteCheck = TRUE;
668 }
669 // Check 3: Check the capabilities of the storage (and the driver)
670 if ($isReadCheck && !$this->isBrowsable()) {
671 return FALSE;
672 }
673 if ($isWriteCheck && !$this->isWritable()) {
674 return FALSE;
675 }
676 // Check 4: "Folder permissions" of the driver
677 $folderPermissions = $this->driver->getFolderPermissions($folder);
678 if ($isReadCheck && !$folderPermissions['r']) {
679 return FALSE;
680 }
681 if ($isWriteCheck && !$folderPermissions['w']) {
682 return FALSE;
683 }
684 return TRUE;
685 }
686
687 /**
688 * If the fileName is given, check it against the
689 * TYPO3_CONF_VARS[BE][fileDenyPattern] + and if the file extension is allowed
690 *
691 * @param string $fileName Full filename
692 * @return boolean TRUE if extension/filename is allowed
693 */
694 protected function checkFileExtensionPermission($fileName) {
695 if (!$this->evaluatePermissions) {
696 return TRUE;
697 }
698 $fileName = $this->driver->sanitizeFileName($fileName);
699 $isAllowed = GeneralUtility::verifyFilenameAgainstDenyPattern($fileName);
700 if ($isAllowed) {
701 $fileInfo = GeneralUtility::split_fileref($fileName);
702 // Set up the permissions for the file extension
703 $fileExtensionPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace'];
704 $fileExtensionPermissions['allow'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['allow']));
705 $fileExtensionPermissions['deny'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['deny']));
706 $fileExtension = strtolower($fileInfo['fileext']);
707 if ($fileExtension !== '') {
708 // If the extension is found amongst the allowed types, we return TRUE immediately
709 if ($fileExtensionPermissions['allow'] === '*' || GeneralUtility::inList($fileExtensionPermissions['allow'], $fileExtension)) {
710 return TRUE;
711 }
712 // If the extension is found amongst the denied types, we return FALSE immediately
713 if ($fileExtensionPermissions['deny'] === '*' || GeneralUtility::inList($fileExtensionPermissions['deny'], $fileExtension)) {
714 return FALSE;
715 }
716 // If no match we return TRUE
717 return TRUE;
718 } else {
719 if ($fileExtensionPermissions['allow'] === '*') {
720 return TRUE;
721 }
722 if ($fileExtensionPermissions['deny'] === '*') {
723 return FALSE;
724 }
725 return TRUE;
726 }
727 }
728 return FALSE;
729 }
730
731 /**
732 * @param Folder $folder If a folder is given, mountpoits are checked. If not only user folder read permissions are checked.
733 *
734 * @throws Exception\InsufficientFolderAccessPermissionsException
735 */
736 protected function assureFolderReadPermission(Folder $folder = NULL) {
737 if (!$this->checkFolderActionPermission('read', $folder)) {
738 throw new Exception\InsufficientFolderAccessPermissionsException('You are not allowed to access the given folder', 1375955684);
739 }
740 }
741
742 /**
743 * @param Folder $folder If a folder is given, mountpoits are checked. If not only user folder delete permissions are checked.
744 * @param boolean $checkDeleteRecursively
745 *
746 * @throws Exception\InsufficientFolderAccessPermissionsException
747 * @throws Exception\InsufficientFolderWritePermissionsException
748 * @throws Exception\InsufficientUserPermissionsException
749 */
750 protected function assureFolderDeletePermission(Folder $folder, $checkDeleteRecursively) {
751 // Check user permissions for recursive deletion if it is requested
752 if ($checkDeleteRecursively && !$this->checkUserActionPermission('recursivedelete', 'Folder')) {
753 throw new Exception\InsufficientUserPermissionsException('You are not allowed to delete folders recursively', 1377779423);
754 }
755 // Check user action permission
756 if (!$this->checkFolderActionPermission('delete', $folder)) {
757 throw new Exception\InsufficientFolderAccessPermissionsException('You are not allowed to delete the given folder', 1377779039);
758 }
759 // Check if the user has write permissions to folders
760 // Would be good if we could check for actual write permissions in the containig folder
761 // but we cannot since we have no access to the containing folder of this file.
762 if (!$this->checkUserActionPermission('write', 'Folder')) {
763 throw new Exception\InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377779111);
764 }
765 }
766
767 /**
768 * @param FileInterface $file
769 *
770 * @throws Exception\InsufficientFileAccessPermissionsException
771 * @throws Exception\IllegalFileExtensionException
772 */
773 protected function assureFileReadPermission(FileInterface $file) {
774 if (!$this->checkFileActionPermission('read', $file)) {
775 throw new Exception\InsufficientFileAccessPermissionsException('You are not allowed to access that file.', 1375955429);
776 }
777 if (!$this->checkFileExtensionPermission($file->getName())) {
778 throw new Exception\IllegalFileExtensionException('You are not allowed to use that file extension', 1375955430);
779 }
780 }
781
782 /**
783 * @param FileInterface $file
784 *
785 * @throws Exception\IllegalFileExtensionException
786 * @throws Exception\InsufficientFileWritePermissionsException
787 * @throws Exception\InsufficientUserPermissionsException
788 */
789 protected function assureFileWritePermissions(FileInterface $file) {
790 // Check if user is allowed to write the file and $file is writable
791 if (!$this->checkFileActionPermission('write', $file)) {
792 throw new Exception\InsufficientFileWritePermissionsException('Writing to file "' . $file->getIdentifier() . '" is not allowed.', 1330121088);
793 }
794 if (!$this->checkFileExtensionPermission($file->getName())) {
795 throw new Exception\IllegalFileExtensionException('You are not allowed to edit a file with extension "' . $file->getExtension() . '"', 1366711933);
796 }
797 }
798
799 /**
800 * @param FileInterface $file
801 *
802 * @throws Exception\IllegalFileExtensionException
803 * @throws Exception\InsufficientFileWritePermissionsException
804 * @throws Exception\InsufficientFolderWritePermissionsException
805 */
806 protected function assureFileDeletePermissions(FileInterface $file) {
807 // Check for disallowed file extensions
808 if (!$this->checkFileExtensionPermission($file->getName())) {
809 throw new Exception\IllegalFileExtensionException('You are not allowed to delete a file with extension "' . $file->getExtension() . '"', 1377778916);
810 }
811 // Check further permissions if file is not a processed file
812 if (!$file instanceof ProcessedFile) {
813 // Check if user is allowed to delete the file and $file is writable
814 if (!$this->checkFileActionPermission('delete', $file)) {
815 throw new Exception\InsufficientFileWritePermissionsException('You are not allowed to delete the file "' . $file->getIdentifier() . '\'', 1319550425);
816 }
817 // Check if the user has write permissions to folders
818 // Would be good if we could check for actual write permissions in the containig folder
819 // but we cannot since we have no access to the containing folder of this file.
820 if (!$this->checkUserActionPermission('write', 'Folder')) {
821 throw new Exception\InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377778702);
822 }
823 }
824 }
825
826 /**
827 * Check if a file has the permission to be uploaded to a Folder/Storage,
828 * if not throw an exception
829 *
830 * @param string $localFilePath the temporary file name from $_FILES['file1']['tmp_name']
831 * @param Folder $targetFolder
832 * @param string $targetFileName the destination file name $_FILES['file1']['name']
833 *
834 * @throws Exception\InsufficientFolderWritePermissionsException
835 * @throws Exception\UploadException
836 * @throws Exception\IllegalFileExtensionException
837 * @throws Exception\UploadSizeException
838 * @throws Exception\InsufficientUserPermissionsException
839 * @return void
840 */
841 protected function assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName) {
842 // Check for a valid file extension
843 if (!$this->checkFileExtensionPermission($targetFileName) || ($localFilePath && !$this->checkFileExtensionPermission($localFilePath))) {
844 throw new Exception\IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1322120271);
845 }
846 // Makes sure the user is allowed to upload
847 if (!$this->checkUserActionPermission('add', 'File')) {
848 throw new Exception\InsufficientUserPermissionsException('You are not allowed to add files to this storage "' . $this->getUid() . '"', 1376992145);
849 }
850 // Check if targetFolder is writable
851 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
852 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1322120356);
853 }
854 }
855
856 /**
857 * Check if a file has the permission to be uploaded to a Folder/Storage,
858 * if not throw an exception
859 *
860 * @param string $localFilePath the temporary file name from $_FILES['file1']['tmp_name']
861 * @param Folder $targetFolder
862 * @param string $targetFileName the destination file name $_FILES['file1']['name']
863 * @param integer $uploadedFileSize
864 *
865 * @throws Exception\InsufficientFolderWritePermissionsException
866 * @throws Exception\UploadException
867 * @throws Exception\IllegalFileExtensionException
868 * @throws Exception\UploadSizeException
869 * @throws Exception\InsufficientUserPermissionsException
870 * @return void
871 */
872 protected function assureFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileSize) {
873 // Makes sure this is an uploaded file
874 if (!is_uploaded_file($localFilePath)) {
875 throw new Exception\UploadException('The upload has failed, no uploaded file found!', 1322110455);
876 }
877 // Max upload size (kb) for files.
878 $maxUploadFileSize = GeneralUtility::getMaxUploadFileSize() * 1024;
879 if ($uploadedFileSize >= $maxUploadFileSize) {
880 unlink($localFilePath);
881 throw new Exception\UploadSizeException('The uploaded file exceeds the size-limit of ' . $maxUploadFileSize . ' bytes', 1322110041);
882 }
883 $this->assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName);
884 }
885
886 /**
887 * Checks for permissions to move a file.
888 *
889 * @throws \RuntimeException
890 * @throws Exception\InsufficientFileReadPermissionsException
891 * @throws Exception\InsufficientFileWritePermissionsException
892 * @throws Exception\InsufficientFolderAccessPermissionsException
893 * @throws Exception\InsufficientUserPermissionsException
894 * @param FileInterface $file
895 * @param Folder $targetFolder
896 * @param string $targetFileName
897 * @return void
898 */
899 protected function assureFileMovePermissions(FileInterface $file, Folder $targetFolder, $targetFileName) {
900 // Check if targetFolder is within this storage
901 if ($this->getUid() !== $targetFolder->getStorage()->getUid()) {
902 throw new \RuntimeException();
903 }
904 // Check for a valid file extension
905 if (!$this->checkFileExtensionPermission($targetFileName)) {
906 throw new Exception\IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1378243279);
907 }
908 // Check if user is allowed to move and $file is readable and writable
909 if (!$this->checkFileActionPermission('move', $file)) {
910 throw new Exception\InsufficientUserPermissionsException('You are not allowed to move files to storage "' . $this->getUid() . '"', 1319219349);
911 }
912 // Check if target folder is writable
913 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
914 throw new Exception\InsufficientFolderAccessPermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319219349);
915 }
916 }
917
918 /**
919 * Checks for permissions to rename a file.
920 *
921 * @param FileInterface $file
922 * @param string $targetFileName
923 * @throws Exception\InsufficientFileWritePermissionsException
924 * @throws Exception\IllegalFileExtensionException
925 * @throws Exception\InsufficientFileReadPermissionsException
926 * @throws Exception\InsufficientUserPermissionsException
927 * @return void
928 */
929 protected function assureFileRenamePermissions(FileInterface $file, $targetFileName) {
930 // Check if file extension is allowed
931 if (!$this->checkFileExtensionPermission($targetFileName) || !$this->checkFileExtensionPermission($file->getName())) {
932 throw new Exception\IllegalFileExtensionException('You are not allowed to rename a file with to this extension', 1371466663);
933 }
934 // Check if user is allowed to rename
935 if (!$this->checkFileActionPermission('rename', $file)) {
936 throw new Exception\InsufficientUserPermissionsException('You are not allowed to rename files."', 1319219349);
937 }
938 // Check if the user is allowed to write to folders
939 // Although it would be good to check, we cannot check here if the folder actually is writable
940 // because we do not know in which folder the file resides.
941 // So we rely on the driver to throw an exception in case the renaming failed.
942 if (!$this->checkFolderActionPermission('write')) {
943 throw new Exception\InsufficientFileWritePermissionsException('You are not allowed to write to folders', 1319219349);
944 }
945 }
946
947 /**
948 * Check if a file has the permission to be copied on a File/Folder/Storage,
949 * if not throw an exception
950 *
951 * @param FileInterface $file
952 * @param Folder $targetFolder
953 * @param string $targetFileName
954 *
955 * @throws Exception
956 * @throws Exception\InsufficientFolderWritePermissionsException
957 * @throws Exception\IllegalFileExtensionException
958 * @throws Exception\InsufficientFileReadPermissionsException
959 * @throws Exception\InsufficientUserPermissionsException
960 * @return void
961 */
962 protected function assureFileCopyPermissions(FileInterface $file, Folder $targetFolder, $targetFileName) {
963 // Check if targetFolder is within this storage, this should never happen
964 if ($this->getUid() != $targetFolder->getStorage()->getUid()) {
965 throw new Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1319550405);
966 }
967 // Check if user is allowed to copy
968 if (!$this->checkFileActionPermission('copy', $file)) {
969 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the file "' . $file->getIdentifier() . '\'', 1319550425);
970 }
971 // Check if targetFolder is writable
972 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
973 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319550435);
974 }
975 // Check for a valid file extension
976 if (!$this->checkFileExtensionPermission($targetFileName) || !$this->checkFileExtensionPermission($file->getName())) {
977 throw new Exception\IllegalFileExtensionException('You are not allowed to copy a file of that type.', 1319553317);
978 }
979 }
980
981 /**
982 * Check if a file has the permission to be copied on a File/Folder/Storage,
983 * if not throw an exception
984 *
985 * @param FolderInterface $folderToCopy
986 * @param FolderInterface $targetParentFolder
987 *
988 * @throws Exception
989 * @throws Exception\InsufficientFolderWritePermissionsException
990 * @throws Exception\IllegalFileExtensionException
991 * @throws Exception\InsufficientFileReadPermissionsException
992 * @throws Exception\InsufficientUserPermissionsException
993 * @return void
994 */
995 protected function assureFolderCopyPermissions(FolderInterface $folderToCopy, FolderInterface $targetParentFolder) {
996 // Check if targetFolder is within this storage, this should never happen
997 if ($this->getUid() !== $targetParentFolder->getStorage()->getUid()) {
998 throw new Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1377777624);
999 }
1000 // Check if user is allowed to copy and the folder is readable
1001 if (!$this->checkFolderActionPermission('copy', $folderToCopy)) {
1002 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the folder "' . $folderToCopy->getIdentifier() . '\'', 1377777629);
1003 }
1004 // Check if targetFolder is writable
1005 if (!$this->checkFolderActionPermission('write', $targetParentFolder)) {
1006 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetParentFolder->getIdentifier() . '"', 1377777635);
1007 }
1008 }
1009
1010 /**
1011 * Check if a file has the permission to be copied on a File/Folder/Storage,
1012 * if not throw an exception
1013 *
1014 * @param FolderInterface $folderToMove
1015 * @param FolderInterface $targetParentFolder
1016 *
1017 * @throws \InvalidArgumentException
1018 * @throws Exception\InsufficientFolderWritePermissionsException
1019 * @throws Exception\IllegalFileExtensionException
1020 * @throws Exception\InsufficientFileReadPermissionsException
1021 * @throws Exception\InsufficientUserPermissionsException
1022 * @return void
1023 */
1024 protected function assureFolderMovePermissions(FolderInterface $folderToMove, FolderInterface $targetParentFolder) {
1025 // Check if targetFolder is within this storage, this should never happen
1026 if ($this->getUid() !== $targetParentFolder->getStorage()->getUid()) {
1027 throw new \InvalidArgumentException('Cannot move a folder into a folder that does not belong to this storage.', 1325777289);
1028 }
1029 // Check if user is allowed to move and the folder is writable
1030 // In fact we would need to check if the parent folder of the folder to move is writable also
1031 // But as of now we cannot extract the parent folder from this folder
1032 if (!$this->checkFolderActionPermission('move', $folderToMove)) {
1033 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the folder "' . $folderToMove->getIdentifier() . '\'', 1377778045);
1034 }
1035 // Check if targetFolder is writable
1036 if (!$this->checkFolderActionPermission('write', $targetParentFolder)) {
1037 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetParentFolder->getIdentifier() . '"', 1377778049);
1038 }
1039 }
1040
1041 /********************
1042 * FILE ACTIONS
1043 ********************/
1044 /**
1045 * Moves a file from the local filesystem to this storage.
1046 *
1047 * @param string $localFilePath The file on the server's hard disk to add.
1048 * @param Folder $targetFolder The target path, without the fileName
1049 * @param string $targetFileName The fileName. If not set, the local file name is used.
1050 * @param string $conflictMode possible value are 'cancel', 'replace', 'changeName'
1051 *
1052 * @throws \InvalidArgumentException
1053 * @throws Exception\ExistingTargetFileNameException
1054 * @return FileInterface
1055 */
1056 public function addFile($localFilePath, Folder $targetFolder, $targetFileName = '', $conflictMode = 'changeName') {
1057 $localFilePath = PathUtility::getCanonicalPath($localFilePath);
1058 if (!file_exists($localFilePath)) {
1059 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1319552745);
1060 }
1061 $this->assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName);
1062 $targetFolder = $targetFolder ? $targetFolder : $this->getDefaultFolder();
1063 $targetFileName = $targetFileName ? $targetFileName : PathUtility::basename($localFilePath);
1064 if ($conflictMode === 'cancel' && $this->driver->fileExistsInFolder($targetFileName, $targetFolder)) {
1065 throw new Exception\ExistingTargetFileNameException('File "' . $targetFileName . '" already exists in folder ' . $targetFolder->getIdentifier(), 1322121068);
1066 } elseif ($conflictMode === 'changeName') {
1067 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1068 }
1069 // We do not care whether the file exists if $conflictMode is "replace",
1070 // so just use the name as is in that case
1071 return $this->driver->addFile($localFilePath, $targetFolder, $targetFileName);
1072 }
1073
1074 /**
1075 * Updates a processed file with a new file from the local filesystem.
1076 *
1077 * @param $localFilePath
1078 * @param ProcessedFile $processedFile
1079 * @return FileInterface
1080 * @throws \InvalidArgumentException
1081 * @internal use only
1082 */
1083 public function updateProcessedFile($localFilePath, ProcessedFile $processedFile) {
1084 if (!file_exists($localFilePath)) {
1085 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1319552745);
1086 }
1087 $file = $this->driver->addFile($localFilePath, $this->getProcessingFolder(), $processedFile->getName());
1088 $file->setIndexable(FALSE);
1089 return $file;
1090 }
1091
1092 /**
1093 * Creates a (cryptographic) hash for a file.
1094 *
1095 * @param FileInterface $fileObject
1096 * @param $hash
1097 * @return string
1098 */
1099 public function hashFile(FileInterface $fileObject, $hash) {
1100 return $this->driver->hash($fileObject, $hash);
1101 }
1102
1103 /**
1104 * Returns a publicly accessible URL for a file.
1105 *
1106 * WARNING: Access to the file may be restricted by further means, e.g.
1107 * some web-based authentication. You have to take care of this yourself.
1108 *
1109 * @param ResourceInterface $resourceObject The file or folder object
1110 * @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)
1111 * @return string
1112 */
1113 public function getPublicUrl(ResourceInterface $resourceObject, $relativeToCurrentScript = FALSE) {
1114 $publicUrl = NULL;
1115 if ($this->isOnline()) {
1116 // Pre-process the public URL by an accordant slot
1117 $this->emitPreGeneratePublicUrl($resourceObject, $relativeToCurrentScript, array('publicUrl' => &$publicUrl));
1118 // If slot did not handle the signal, use the default way to determine public URL
1119 if ($publicUrl === NULL) {
1120 $publicUrl = $this->driver->getPublicUrl($resourceObject, $relativeToCurrentScript);
1121 }
1122 }
1123 return $publicUrl;
1124 }
1125
1126 /**
1127 * Passes a file to the File Processing Services and returns the resulting ProcessedFile object.
1128 *
1129 * @param FileInterface $fileObject The file object
1130 * @param string $context
1131 * @param array $configuration
1132 *
1133 * @return ProcessedFile
1134 * @throws \InvalidArgumentException
1135 */
1136 public function processFile(FileInterface $fileObject, $context, array $configuration) {
1137 if ($fileObject->getStorage() !== $this) {
1138 throw new \InvalidArgumentException('Cannot process files of foreign storage', 1353401835);
1139 }
1140 $processedFile = $this->getFileProcessingService()->processFile($fileObject, $this, $context, $configuration);
1141
1142 return $processedFile;
1143 }
1144
1145 /**
1146 * Copies a file from the storage for local processing.
1147 *
1148 * @param FileInterface $fileObject
1149 * @param bool $writable
1150 * @return string Path to local file (either original or copied to some temporary local location)
1151 */
1152 public function getFileForLocalProcessing(FileInterface $fileObject, $writable = TRUE) {
1153 $filePath = $this->driver->getFileForLocalProcessing($fileObject, $writable);
1154 // @todo: shouldn't this go in the driver? this function is called from the indexing service
1155 // @todo: and recursively calls itself over and over again, this is left out for now with getModificationTime()
1156 // touch($filePath, $fileObject->getModificationTime());
1157 return $filePath;
1158 }
1159
1160 /**
1161 * Get file by identifier
1162 *
1163 * @param string $identifier
1164 * @return FileInterface
1165 */
1166 public function getFile($identifier) {
1167 return $this->driver->getFile($identifier);
1168 }
1169
1170 /**
1171 * Get information about a file
1172 *
1173 * @param FileInterface $fileObject
1174 * @return array
1175 */
1176 public function getFileInfo(FileInterface $fileObject) {
1177 return $this->driver->getFileInfo($fileObject);
1178 }
1179
1180 /**
1181 * Get information about a file by its identifier
1182 *
1183 * @param string $identifier
1184 *
1185 * @throws \BadMethodCallException
1186 * @return array
1187 */
1188 public function getFileInfoByIdentifier($identifier) {
1189 throw new \BadMethodCallException('The method ResourceStorage::getFileInfoByIdentifier() has been deprecated. Please fix your method call and use getFileInfo with the file object instead.', 1346577887);
1190 }
1191
1192 /**
1193 * Unsets the file and folder name filters, thus making this storage return unfiltered file lists.
1194 *
1195 * @return void
1196 */
1197 public function unsetFileAndFolderNameFilters() {
1198 $this->fileAndFolderNameFilters = array();
1199 }
1200
1201 /**
1202 * Resets the file and folder name filters to the default values defined in the TYPO3 configuration.
1203 *
1204 * @return void
1205 */
1206 public function resetFileAndFolderNameFiltersToDefault() {
1207 $this->fileAndFolderNameFilters = $GLOBALS['TYPO3_CONF_VARS']['SYS']['fal']['defaultFilterCallbacks'];
1208 }
1209
1210 /**
1211 * Returns the file and folder name filters used by this storage.
1212 *
1213 * @return array
1214 */
1215 public function getFileAndFolderNameFilters() {
1216 return $this->fileAndFolderNameFilters;
1217 }
1218
1219 public function setFileAndFolderNameFilters(array $filters) {
1220 $this->fileAndFolderNameFilters = $filters;
1221 return $this;
1222 }
1223
1224 public function addFileAndFolderNameFilter($filter) {
1225 $this->fileAndFolderNameFilters[] = $filter;
1226 }
1227
1228 /**
1229 * Returns a list of files in a given path, filtered by some custom filter methods.
1230 *
1231 * @see getUnfilteredFileList(), getFileListWithDefaultFilters()
1232 * @param string $path The path to list
1233 * @param integer $start The position to start the listing; if not set or 0, start from the beginning
1234 * @param integer $numberOfItems The number of items to list; if not set, return all items
1235 * @param bool $useFilters If FALSE, the list is returned without any filtering; otherwise, the filters defined for this storage are used.
1236 * @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.
1237 * @param boolean $recursive
1238 * @return array Information about the files found.
1239 */
1240 // TODO check if we should use a folder object instead of $path
1241 // TODO add unit test for $loadIndexRecords
1242 public function getFileList($path, $start = 0, $numberOfItems = 0, $useFilters = TRUE, $loadIndexRecords = TRUE, $recursive = FALSE) {
1243 // This also checks for read permissions on folder
1244 $folder = $this->getFolder($path);
1245 $rows = array();
1246 if ($loadIndexRecords) {
1247 $rows = $this->getFileRepository()->getFileIndexRecordsForFolder($folder);
1248 }
1249 $filters = $useFilters == TRUE ? $this->fileAndFolderNameFilters : array();
1250 $items = $this->driver->getFileList($path, $start, $numberOfItems, $filters, $rows, $recursive);
1251
1252 // We should not sort when fetching a recursive list, as these are indexed numerically
1253 if ($recursive === FALSE) {
1254 uksort($items, 'strnatcasecmp');
1255 }
1256
1257 return $items;
1258 }
1259
1260 /**
1261 * Returns TRUE if the specified file exists.
1262 *
1263 * @param string $identifier
1264 * @return boolean
1265 */
1266 public function hasFile($identifier) {
1267 // Allow if identifier is in processing folder
1268 if (!$this->driver->isWithin($this->getProcessingFolder(), $identifier)) {
1269 $this->assureFolderReadPermission();
1270 }
1271 return $this->driver->fileExists($identifier);
1272 }
1273
1274 /**
1275 * Checks if the queried file in the given folder exists.
1276 *
1277 * @param string $fileName
1278 * @param Folder $folder
1279 * @return boolean
1280 */
1281 public function hasFileInFolder($fileName, Folder $folder) {
1282 $this->assureFolderReadPermission($folder);
1283 return $this->driver->fileExistsInFolder($fileName, $folder);
1284 }
1285
1286 /**
1287 * Get contents of a file object
1288 *
1289 * @param FileInterface $file
1290 *
1291 * @throws Exception\InsufficientFileReadPermissionsException
1292 * @return string
1293 */
1294 public function getFileContents($file) {
1295 $this->assureFileReadPermission($file);
1296 return $this->driver->getFileContents($file);
1297 }
1298
1299 /**
1300 * Set contents of a file object.
1301 *
1302 * @param AbstractFile $file
1303 * @param string $contents
1304 *
1305 * @throws \Exception|\RuntimeException
1306 * @throws Exception\InsufficientFileWritePermissionsException
1307 * @throws Exception\InsufficientUserPermissionsException
1308 * @return integer The number of bytes written to the file
1309 */
1310 public function setFileContents(AbstractFile $file, $contents) {
1311 // Check if user is allowed to edit
1312 $this->assureFileWritePermissions($file);
1313 // Call driver method to update the file and update file properties afterwards
1314 $result = $this->driver->setFileContents($file, $contents);
1315 $fileInfo = $this->driver->getFileInfo($file);
1316 $fileInfo['sha1'] = $this->driver->hash($file, 'sha1');
1317 $file->updateProperties($fileInfo);
1318 $this->getFileRepository()->update($file);
1319 return $result;
1320 }
1321
1322 /**
1323 * Creates a new file
1324 *
1325 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_newfile()
1326 *
1327 * @param string $fileName
1328 * @param Folder $targetFolderObject
1329 *
1330 * @throws Exception\IllegalFileExtensionException
1331 * @throws Exception\InsufficientFolderWritePermissionsException
1332 * @return FileInterface The file object
1333 */
1334 public function createFile($fileName, Folder $targetFolderObject) {
1335 $this->assureFileAddPermissions('', $targetFolderObject, $fileName);
1336 return $this->driver->createFile($fileName, $targetFolderObject);
1337 }
1338
1339 /**
1340 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::deleteFile()
1341 *
1342 * @param $fileObject FileInterface
1343 * @throws Exception\InsufficientFileAccessPermissionsException
1344 * @throws Exception\FileOperationErrorException
1345 * @return boolean TRUE if deletion succeeded
1346 */
1347 public function deleteFile($fileObject) {
1348 $this->assureFileDeletePermissions($fileObject);
1349
1350 $this->emitPreFileDeleteSignal($fileObject);
1351
1352 $result = $this->driver->deleteFile($fileObject);
1353 if ($result === FALSE) {
1354 throw new Exception\FileOperationErrorException('Deleting the file "' . $fileObject->getIdentifier() . '\' failed.', 1329831691);
1355 }
1356 // Mark the file object as deleted
1357 $fileObject->setDeleted();
1358
1359 $this->emitPostFileDeleteSignal($fileObject);
1360
1361 return TRUE;
1362 }
1363
1364 /**
1365 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_copy()
1366 * copies a source file (from any location) in to the target
1367 * folder, the latter has to be part of this storage
1368 *
1369 * @param FileInterface $file
1370 * @param Folder $targetFolder
1371 * @param string $targetFileName an optional destination fileName
1372 * @param string $conflictMode "overrideExistingFile", "renameNewFile", "cancel
1373 *
1374 * @throws \Exception|Exception\AbstractFileOperationException
1375 * @throws Exception\ExistingTargetFileNameException
1376 * @return FileInterface
1377 */
1378 public function copyFile(FileInterface $file, Folder $targetFolder, $targetFileName = NULL, $conflictMode = 'renameNewFile') {
1379 if ($targetFileName === NULL) {
1380 $targetFileName = $file->getName();
1381 }
1382 $this->assureFileCopyPermissions($file, $targetFolder, $targetFileName);
1383 $this->emitPreFileCopySignal($file, $targetFolder);
1384 // File exists and we should abort, let's abort
1385 if ($conflictMode === 'cancel' && $targetFolder->hasFile($targetFileName)) {
1386 throw new Exception\ExistingTargetFileNameException('The target file already exists.', 1320291063);
1387 }
1388 // File exists and we should find another name, let's find another one
1389 if ($conflictMode === 'renameNewFile' && $targetFolder->hasFile($targetFileName)) {
1390 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1391 }
1392 $sourceStorage = $file->getStorage();
1393 // Call driver method to create a new file from an existing file object,
1394 // and return the new file object
1395 if ($sourceStorage === $this) {
1396 $newFileObject = $this->driver->copyFileWithinStorage($file, $targetFolder, $targetFileName);
1397 } else {
1398 $tempPath = $file->getForLocalProcessing();
1399 $newFileObject = $this->driver->addFile($tempPath, $targetFolder, $targetFileName);
1400 }
1401 $this->emitPostFileCopySignal($file, $targetFolder);
1402 return $newFileObject;
1403 }
1404
1405 /**
1406 * Moves a $file into a $targetFolder
1407 * the target folder has to be part of this storage
1408 *
1409 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_move()
1410 *
1411 * @param FileInterface $file
1412 * @param Folder $targetFolder
1413 * @param string $targetFileName an optional destination fileName
1414 * @param string $conflictMode "overrideExistingFile", "renameNewFile", "cancel
1415 *
1416 * @throws Exception\ExistingTargetFileNameException
1417 * @return FileInterface
1418 */
1419 public function moveFile($file, $targetFolder, $targetFileName = NULL, $conflictMode = 'renameNewFile') {
1420 if ($targetFileName === NULL) {
1421 $targetFileName = $file->getName();
1422 }
1423 $this->assureFileMovePermissions($file, $targetFolder, $targetFileName);
1424 if ($targetFolder->hasFile($targetFileName)) {
1425 // File exists and we should abort, let's abort
1426 if ($conflictMode === 'renameNewFile') {
1427 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1428 } elseif ($conflictMode === 'cancel') {
1429 throw new Exception\ExistingTargetFileNameException('The target file already exists', 1329850997);
1430 }
1431 }
1432 $this->emitPreFileMoveSignal($file, $targetFolder);
1433 $sourceStorage = $file->getStorage();
1434 // Call driver method to move the file that also updates the file
1435 // object properties
1436 try {
1437 if ($sourceStorage === $this) {
1438 $newIdentifier = $this->driver->moveFileWithinStorage($file, $targetFolder, $targetFileName);
1439 $this->updateFile($file, $newIdentifier);
1440 } else {
1441 $tempPath = $file->getForLocalProcessing();
1442 $newIdentifier = $this->driver->addFileRaw($tempPath, $targetFolder, $targetFileName);
1443 $sourceStorage->driver->deleteFileRaw($file->getIdentifier());
1444 $this->updateFile($file, $newIdentifier, $this);
1445 }
1446 } catch (\TYPO3\CMS\Core\Exception $e) {
1447 echo $e->getMessage();
1448 }
1449 $this->emitPostFileMoveSignal($file, $targetFolder);
1450 return $file;
1451 }
1452
1453 /**
1454 * Updates the properties of a file object with some that are freshly
1455 * fetched from the driver.
1456 *
1457 * @param AbstractFile $file
1458 * @param string $identifier The identifier of the file. If set, this will overwrite the file object's identifier (use e.g. after moving a file)
1459 * @param ResourceStorage $storage
1460 * @return void
1461 */
1462 protected function updateFile(AbstractFile $file, $identifier = '', $storage = NULL) {
1463 if ($identifier === '') {
1464 $identifier = $file->getIdentifier();
1465 }
1466 $fileInfo = $this->driver->getFileInfoByIdentifier($identifier);
1467 // TODO extend mapping
1468 $newProperties = array(
1469 'storage' => $fileInfo['storage'],
1470 'identifier' => $fileInfo['identifier'],
1471 'tstamp' => $fileInfo['mtime'],
1472 'crdate' => $fileInfo['ctime'],
1473 'mime_type' => $fileInfo['mimetype'],
1474 'size' => $fileInfo['size'],
1475 'name' => $fileInfo['name']
1476 );
1477 if ($storage !== NULL) {
1478 $newProperties['storage'] = $storage->getUid();
1479 }
1480 $file->updateProperties($newProperties);
1481 $this->getFileRepository()->update($file);
1482 }
1483
1484 /**
1485 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_rename()
1486 *
1487 * @param FileInterface $file
1488 * @param string $targetFileName
1489 *
1490 * @throws Exception\InsufficientFileWritePermissionsException
1491 * @throws Exception\InsufficientFileReadPermissionsException
1492 * @throws Exception\InsufficientUserPermissionsException
1493 * @return FileInterface
1494 */
1495 // TODO add $conflictMode setting
1496 public function renameFile($file, $targetFileName) {
1497 // The name should be different from the current.
1498 if ($file->getName() === $targetFileName) {
1499 return $file;
1500 }
1501 $this->assureFileRenamePermissions($file, $targetFileName);
1502 $this->emitPreFileRenameSignal($file, $targetFileName);
1503
1504 // Call driver method to rename the file that also updates the file
1505 // object properties
1506 try {
1507 $newIdentifier = $this->driver->renameFile($file, $targetFileName);
1508 $this->updateFile($file, $newIdentifier);
1509 $this->getFileRepository()->update($file);
1510 } catch (\RuntimeException $e) {
1511
1512 }
1513
1514 $this->emitPostFileRenameSignal($file, $targetFileName);
1515
1516 return $file;
1517 }
1518
1519 /**
1520 * Replaces a file with a local file (e.g. a freshly uploaded file)
1521 *
1522 * @param FileInterface $file
1523 * @param string $localFilePath
1524 *
1525 * @throws \InvalidArgumentException
1526 * @return FileInterface
1527 */
1528 public function replaceFile(FileInterface $file, $localFilePath) {
1529 $this->assureFileWritePermissions($file);
1530 if (!$this->checkFileExtensionPermission($localFilePath)) {
1531 throw new Exception\IllegalFileExtensionException('Sorce file extension not allowed', 1378132239);
1532 }
1533 if (!file_exists($localFilePath)) {
1534 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1325842622);
1535 }
1536 // TODO check permissions
1537 $this->emitPreFileReplaceSignal($file, $localFilePath);
1538 $result = $this->driver->replaceFile($file, $localFilePath);
1539 $this->emitPostFileReplaceSignal($file, $localFilePath);
1540 return $result;
1541 }
1542
1543 /**
1544 * Adds an uploaded file into the Storage. Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::file_upload()
1545 *
1546 * @param array $uploadedFileData contains information about the uploaded file given by $_FILES['file1']
1547 * @param Folder $targetFolder the target folder
1548 * @param string $targetFileName the file name to be written
1549 * @param string $conflictMode possible value are 'cancel', 'replace'
1550 * @return FileInterface The file object
1551 */
1552 public function addUploadedFile(array $uploadedFileData, Folder $targetFolder = NULL, $targetFileName = NULL, $conflictMode = 'cancel') {
1553 $localFilePath = $uploadedFileData['tmp_name'];
1554 if ($targetFolder === NULL) {
1555 $targetFolder = $this->getDefaultFolder();
1556 }
1557 if ($targetFileName === NULL) {
1558 $targetFileName = $uploadedFileData['name'];
1559 }
1560 // Handling $conflictMode is delegated to addFile()
1561 $this->assureFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileData['size']);
1562 $resultObject = $this->addFile($localFilePath, $targetFolder, $targetFileName, $conflictMode);
1563 return $resultObject;
1564 }
1565
1566 /********************
1567 * FOLDER ACTIONS
1568 ********************/
1569 /**
1570 * Returns an array with all file objects in a folder and its subfolders, with the file identifiers as keys.
1571 *
1572 * @param Folder $folder
1573 * @return File[]
1574 */
1575 protected function getAllFileObjectsInFolder(Folder $folder) {
1576 $files = array();
1577 $folderQueue = array($folder);
1578 while (!empty($folderQueue)) {
1579 $folder = array_shift($folderQueue);
1580 foreach ($folder->getSubfolders() as $subfolder) {
1581 $folderQueue[] = $subfolder;
1582 }
1583 foreach ($folder->getFiles() as $file) {
1584 $files[$file->getIdentifier()] = $file;
1585 }
1586 }
1587 return $files;
1588 }
1589
1590 /**
1591 * Moves a folder. If you want to move a folder from this storage to another
1592 * one, call this method on the target storage, otherwise you will get an exception.
1593 *
1594 * @param Folder $folderToMove The folder to move.
1595 * @param Folder $targetParentFolder The target parent folder
1596 * @param string $newFolderName
1597 * @param string $conflictMode How to handle conflicts; one of "overrideExistingFile", "renameNewFolder", "cancel
1598 *
1599 * @throws \Exception|\TYPO3\CMS\Core\Exception
1600 * @throws \InvalidArgumentException
1601 * @return Folder
1602 */
1603 // TODO add tests
1604 public function moveFolder(Folder $folderToMove, Folder $targetParentFolder, $newFolderName = NULL, $conflictMode = 'renameNewFolder') {
1605 $this->assureFolderMovePermissions($folderToMove, $targetParentFolder);
1606 $sourceStorage = $folderToMove->getStorage();
1607 $returnObject = NULL;
1608 $newFolderName = $newFolderName ? $newFolderName : $folderToMove->getName();
1609 // TODO check if folder already exists in $targetParentFolder, handle this conflict then
1610 $this->emitPreFolderMoveSignal($folderToMove, $targetParentFolder, $newFolderName);
1611 // Get all file objects now so we are able to update them after moving the folder
1612 $fileObjects = $this->getAllFileObjectsInFolder($folderToMove);
1613 if ($sourceStorage === $this) {
1614 $fileMappings = $this->driver->moveFolderWithinStorage($folderToMove, $targetParentFolder, $newFolderName);
1615 } else {
1616 $fileMappings = $this->moveFolderBetweenStorages($folderToMove, $targetParentFolder, $newFolderName);
1617 }
1618 // Update the identifier and storage of all file objects
1619 foreach ($fileObjects as $oldIdentifier => $fileObject) {
1620 $newIdentifier = $fileMappings[$oldIdentifier];
1621 $fileObject->updateProperties(array('storage' => $this, 'identifier' => $newIdentifier));
1622 $this->getFileRepository()->update($fileObject);
1623 }
1624 $returnObject = $this->getFolder($fileMappings[$folderToMove->getIdentifier()]);
1625 $this->emitPostFolderMoveSignal($folderToMove, $targetParentFolder, $newFolderName);
1626 return $returnObject;
1627 }
1628
1629 /**
1630 * Moves the given folder from a different storage to the target folder in this storage.
1631 *
1632 * @param Folder $folderToMove
1633 * @param Folder $targetParentFolder
1634 * @param string $newFolderName
1635 *
1636 * @return boolean
1637 */
1638 protected function moveFolderBetweenStorages(Folder $folderToMove, Folder $targetParentFolder, $newFolderName) {
1639 return $this->getDriver()->moveFolderBetweenStorages($folderToMove, $targetParentFolder, $newFolderName);
1640 }
1641
1642 /**
1643 * Copy folder
1644 *
1645 * @param FolderInterface $folderToCopy The folder to copy
1646 * @param FolderInterface $targetParentFolder The target folder
1647 * @param string $newFolderName
1648 * @param string $conflictMode "overrideExistingFolder", "renameNewFolder", "cancel
1649 * @return Folder The new (copied) folder object
1650 */
1651 public function copyFolder(FolderInterface $folderToCopy, FolderInterface $targetParentFolder, $newFolderName = NULL, $conflictMode = 'renameNewFolder') {
1652 // TODO implement the $conflictMode handling
1653 $this->assureFolderCopyPermissions($folderToCopy, $targetParentFolder);
1654 $returnObject = NULL;
1655 $newFolderName = $newFolderName ? $newFolderName : $folderToCopy->getName();
1656 $this->emitPreFolderCopySignal($folderToCopy, $targetParentFolder, $newFolderName);
1657 $sourceStorage = $folderToCopy->getStorage();
1658 // call driver method to move the file
1659 // that also updates the file object properties
1660 try {
1661 if ($sourceStorage === $this) {
1662 $this->driver->copyFolderWithinStorage($folderToCopy, $targetParentFolder, $newFolderName);
1663 $returnObject = $this->getFolder($targetParentFolder->getSubfolder($newFolderName)->getIdentifier());
1664 } else {
1665 $this->copyFolderBetweenStorages($folderToCopy, $targetParentFolder, $newFolderName);
1666 }
1667 } catch (\TYPO3\CMS\Core\Exception $e) {
1668 echo $e->getMessage();
1669 }
1670 $this->emitPostFolderCopySignal($folderToCopy, $targetParentFolder, $newFolderName);
1671 return $returnObject;
1672 }
1673
1674 /**
1675 * Copy folders between storages
1676 *
1677 * @param Folder $folderToCopy
1678 * @param Folder $targetParentFolder
1679 * @param string $newFolderName
1680 *
1681 * @return boolean
1682 */
1683 protected function copyFolderBetweenStorages(Folder $folderToCopy, Folder $targetParentFolder, $newFolderName) {
1684 return $this->getDriver()->copyFolderBetweenStorages($folderToCopy, $targetParentFolder, $newFolderName);
1685 }
1686
1687 /**
1688 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::folder_move()
1689 *
1690 * @param Folder $folderObject
1691 * @param string $newName
1692 * @throws \Exception
1693 * @throws \InvalidArgumentException
1694 * @return Folder
1695 */
1696 public function renameFolder($folderObject, $newName) {
1697 // TODO unit tests
1698
1699 // Renaming the folder should check if the parent folder is writable
1700 // We cannot do this however because we cannot extract the parent folder from a folder currently
1701 if (!$this->checkFolderActionPermission('rename', $folderObject)) {
1702 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException('You are not allowed to rename the folder "' . $folderObject->getIdentifier() . '\'', 1357811441);
1703 }
1704
1705 $returnObject = NULL;
1706 if ($this->driver->folderExistsInFolder($newName, $folderObject)) {
1707 throw new \InvalidArgumentException('The folder ' . $newName . ' already exists in folder ' . $folderObject->getIdentifier(), 1325418870);
1708 }
1709
1710 $this->emitPreFolderRenameSignal($folderObject, $newName);
1711
1712 $fileObjects = $this->getAllFileObjectsInFolder($folderObject);
1713 $fileMappings = $this->driver->renameFolder($folderObject, $newName);
1714 // Update the identifier of all file objects
1715 foreach ($fileObjects as $oldIdentifier => $fileObject) {
1716 $newIdentifier = $fileMappings[$oldIdentifier];
1717 $fileObject->updateProperties(array('identifier' => $newIdentifier));
1718 $this->getFileRepository()->update($fileObject);
1719 }
1720 $returnObject = $this->getFolder($fileMappings[$folderObject->getIdentifier()]);
1721
1722 $this->emitPostFolderRenameSignal($folderObject, $newName);
1723
1724 return $returnObject;
1725 }
1726
1727 /**
1728 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::folder_delete()
1729 *
1730 * @param Folder $folderObject
1731 * @param boolean $deleteRecursively
1732 * @throws \RuntimeException
1733 * @return boolean
1734 */
1735 public function deleteFolder($folderObject, $deleteRecursively = FALSE) {
1736 $isEmpty = $this->driver->isFolderEmpty($folderObject);
1737 $this->assureFolderDeletePermission($folderObject, ($deleteRecursively && !$isEmpty));
1738 if (!$isEmpty && !$deleteRecursively) {
1739 throw new \RuntimeException('Could not delete folder "' . $folderObject->getIdentifier() . '" because it is not empty.', 1325952534);
1740 }
1741
1742 $this->emitPreFolderDeleteSignal($folderObject);
1743
1744 $result = $this->driver->deleteFolder($folderObject, $deleteRecursively);
1745
1746 $this->emitPostFolderDeleteSignal($folderObject);
1747
1748 return $result;
1749 }
1750
1751 /**
1752 * Returns a list of folders in a given path.
1753 *
1754 * @param string $path The path to list
1755 * @param integer $start The position to start the listing; if not set or 0, start from the beginning
1756 * @param integer $numberOfItems The number of items to list; if not set, return all items
1757 * @param boolean $useFilters If FALSE, the list is returned without any filtering; otherwise, the filters defined for this storage are used.
1758 * @return array Information about the folders found.
1759 */
1760 public function getFolderList($path, $start = 0, $numberOfItems = 0, $useFilters = TRUE) {
1761 // Permissions are checked in $this->fetchFolderListFromDriver()
1762 $filters = $useFilters === TRUE ? $this->fileAndFolderNameFilters : array();
1763 return $this->fetchFolderListFromDriver($path, $start, $numberOfItems, $filters);
1764 }
1765
1766 /**
1767 * @param $path
1768 * @param integer $start
1769 * @param integer $numberOfItems
1770 * @param array $folderFilterCallbacks
1771 * @param boolean $recursive
1772 * @return array
1773 */
1774 public function fetchFolderListFromDriver($path, $start = 0, $numberOfItems = 0, array $folderFilterCallbacks = array(), $recursive = FALSE) {
1775 // This also checks for access to that path and throws exceptions accordingly
1776 if ($this->getFolder($path) === NULL) {
1777 return array();
1778 }
1779 $items = $this->driver->getFolderList($path, $start, $numberOfItems, $folderFilterCallbacks, $recursive);
1780 if (!empty($items)) {
1781 // Exclude the _processed_ folder, so it won't get indexed etc
1782 // The processed folder might be any sub folder in storage
1783 $processingFolder = $this->getProcessingFolder();
1784 if ($processingFolder) {
1785 $processedFolderIdentifier = $this->processingFolder->getIdentifier();
1786 $processedFolderIdentifier = trim($processedFolderIdentifier, '/');
1787 $processedFolderIdentifierParts = explode('/', $processedFolderIdentifier);
1788 $processedFolderName = array_pop($processedFolderIdentifierParts);
1789 $processedFolderParent = implode('/', $processedFolderIdentifierParts);
1790 if ($processedFolderParent === trim($path, '/') && isset($items[$processedFolderName])) {
1791 unset($items[$processedFolderName]);
1792 }
1793 }
1794 uksort($items, 'strnatcasecmp');
1795 }
1796 return $items;
1797 }
1798
1799 /**
1800 * Returns TRUE if the specified folder exists.
1801 *
1802 * @param string $identifier
1803 * @return boolean
1804 */
1805 public function hasFolder($identifier) {
1806 $this->assureFolderReadPermission();
1807 return $this->driver->folderExists($identifier);
1808 }
1809
1810 /**
1811 * Checks if the given file exists in the given folder
1812 *
1813 * @param string $folderName
1814 * @param Folder $folder
1815 * @return boolean
1816 */
1817 public function hasFolderInFolder($folderName, Folder $folder) {
1818 $this->assureFolderReadPermission($folder);
1819 return $this->driver->folderExistsInFolder($folderName, $folder);
1820 }
1821
1822 /**
1823 * Creates a new folder.
1824 *
1825 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_newfolder()
1826 *
1827 * @param string $folderName The new folder name
1828 * @param Folder $parentFolder (optional) the parent folder to create the new folder inside of. If not given, the root folder is used
1829 *
1830 * @throws Exception\InsufficientFolderWritePermissionsException
1831 * @throws \InvalidArgumentException
1832 * @return Folder The new folder object
1833 */
1834 public function createFolder($folderName, Folder $parentFolder = NULL) {
1835 if ($parentFolder === NULL) {
1836 $parentFolder = $this->getRootLevelFolder();
1837 }
1838 if (!$this->driver->folderExists($parentFolder->getIdentifier())) {
1839 throw new \InvalidArgumentException('Parent folder "' . $parentFolder->getIdentifier() . '" does not exist.', 1325689164);
1840 }
1841 if (!$this->checkFolderActionPermission('add', $parentFolder)) {
1842 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to create directories in the folder "' . $parentFolder->getIdentifier() . '"', 1323059807);
1843 }
1844 // TODO this only works with hirachical file systems
1845 $folderParts = GeneralUtility::trimExplode('/', $folderName, TRUE);
1846 foreach ($folderParts as $folder) {
1847 // TODO check if folder creation succeeded
1848 if ($this->hasFolderInFolder($folder, $parentFolder)) {
1849 $parentFolder = $this->driver->getFolderInFolder($folder, $parentFolder);
1850 } else {
1851 $parentFolder = $this->driver->createFolder($folder, $parentFolder);
1852 }
1853 }
1854 return $parentFolder;
1855 }
1856
1857 /**
1858 * Returns the default folder where new files are stored if no other folder is given.
1859 *
1860 * @return Folder
1861 */
1862 public function getDefaultFolder() {
1863 return $this->driver->getDefaultFolder();
1864 }
1865
1866 /**
1867 * @param string $identifier
1868 *
1869 * @throws Exception\NotInMountPointException
1870 * @throws Exception\FolderDoesNotExistException
1871 * @return Folder
1872 */
1873 public function getFolder($identifier) {
1874 if (!$this->driver->folderExists($identifier)) {
1875 throw new Exception\FolderDoesNotExistException('Folder ' . $identifier . ' does not exist.', 1320575630);
1876 }
1877 $folder = $this->driver->getFolder($identifier);
1878 $this->assureFolderReadPermission($folder);
1879
1880 return $folder;
1881 }
1882
1883 /**
1884 * Returns the folders on the root level of the storage
1885 * or the first mount point of this storage for this user
1886 *
1887 * @return Folder
1888 */
1889 public function getRootLevelFolder() {
1890 if (count($this->fileMounts)) {
1891 $mount = reset($this->fileMounts);
1892 return $mount['folder'];
1893 } else {
1894 return $this->driver->getRootLevelFolder();
1895 }
1896 }
1897
1898 /**
1899 * Emits the configuration pre-processing signal
1900 *
1901 * @return void
1902 */
1903 protected function emitPreProcessConfigurationSignal() {
1904 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreProcessConfiguration, array($this));
1905 }
1906
1907 /**
1908 * Emits the configuration post-processing signal
1909 *
1910 * @return void
1911 */
1912 protected function emitPostProcessConfigurationSignal() {
1913 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostProcessConfiguration, array($this));
1914 }
1915
1916 /**
1917 * Emits file pre-copy signal
1918 *
1919 * @param FileInterface $file
1920 * @param Folder $targetFolder
1921 * @return void
1922 */
1923 protected function emitPreFileCopySignal(FileInterface $file, Folder $targetFolder) {
1924 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileCopy, array($file, $targetFolder));
1925 }
1926
1927 /**
1928 * Emits the file post-copy signal
1929 *
1930 * @param FileInterface $file
1931 * @param Folder $targetFolder
1932 * @return void
1933 */
1934 protected function emitPostFileCopySignal(FileInterface $file, Folder $targetFolder) {
1935 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileCopy, array($file, $targetFolder));
1936 }
1937
1938 /**
1939 * Emits the file pre-move signal
1940 *
1941 * @param FileInterface $file
1942 * @param Folder $targetFolder
1943 * @return void
1944 */
1945 protected function emitPreFileMoveSignal(FileInterface $file, Folder $targetFolder) {
1946 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileMove, array($file, $targetFolder));
1947 }
1948
1949 /**
1950 * Emits the file post-move signal
1951 *
1952 * @param FileInterface $file
1953 * @param Folder $targetFolder
1954 * @return void
1955 */
1956 protected function emitPostFileMoveSignal(FileInterface $file, Folder $targetFolder) {
1957 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileMove, array($file, $targetFolder));
1958 }
1959
1960 /**
1961 * Emits the file pre-rename signal
1962 *
1963 * @param FileInterface $file
1964 * @param $targetFolder
1965 * @return void
1966 */
1967 protected function emitPreFileRenameSignal(FileInterface $file, $targetFolder) {
1968 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileRename, array($file, $targetFolder));
1969 }
1970
1971 /**
1972 * Emits the file post-rename signal
1973 *
1974 * @param FileInterface $file
1975 * @param $targetFolder
1976 * @return void
1977 */
1978 protected function emitPostFileRenameSignal(FileInterface $file, $targetFolder) {
1979 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileRename, array($file, $targetFolder));
1980 }
1981
1982 /**
1983 * Emits the file pre-replace signal
1984 *
1985 * @param FileInterface $file
1986 * @param $localFilePath
1987 * @return void
1988 */
1989 protected function emitPreFileReplaceSignal(FileInterface $file, $localFilePath) {
1990 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileReplace, array($file, $localFilePath));
1991 }
1992
1993 /**
1994 * Emits the file post-replace signal
1995 *
1996 * @param FileInterface $file
1997 * @param $localFilePath
1998 * @return void
1999 */
2000 protected function emitPostFileReplaceSignal(FileInterface $file, $localFilePath) {
2001 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileReplace, array($file, $localFilePath));
2002 }
2003
2004 /**
2005 * Emits the file pre-deletion signal
2006 *
2007 * @param FileInterface $file
2008 * @return void
2009 */
2010 protected function emitPreFileDeleteSignal(FileInterface $file) {
2011 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileDelete, array($file));
2012 }
2013
2014 /**
2015 * Emits the file post-deletion signal
2016 *
2017 * @param FileInterface $file
2018 * @return void
2019 */
2020 protected function emitPostFileDeleteSignal(FileInterface $file) {
2021 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileDelete, array($file));
2022 }
2023
2024 /**
2025 * Emits the folder pre-copy signal
2026 *
2027 * @param Folder $folder
2028 * @param Folder $targetFolder
2029 * @param $newName
2030 * @return void
2031 */
2032 protected function emitPreFolderCopySignal(Folder $folder, Folder $targetFolder, $newName) {
2033 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PreFolderCopy, array($folder, $targetFolder));
2034 }
2035
2036 /**
2037 * Emits the folder post-copy signal
2038 *
2039 * @param Folder $folder
2040 * @param Folder $targetFolder
2041 * @param $newName
2042 * @return void
2043 */
2044 protected function emitPostFolderCopySignal(Folder $folder, Folder $targetFolder, $newName) {
2045 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PostFolderCopy, array($folder, $targetFolder));
2046 }
2047
2048 /**
2049 * Emits the folder pre-move signal
2050 *
2051 * @param Folder $folder
2052 * @param Folder $targetFolder
2053 * @param $newName
2054 * @return void
2055 */
2056 protected function emitPreFolderMoveSignal(Folder $folder, Folder $targetFolder, $newName) {
2057 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PreFolderMove, array($folder, $targetFolder));
2058 }
2059
2060 /**
2061 * Emits the folder post-move signal
2062 *
2063 * @param Folder $folder
2064 * @param Folder $targetFolder
2065 * @param $newName
2066 * @return void
2067 */
2068 protected function emitPostFolderMoveSignal(Folder $folder, Folder $targetFolder, $newName) {
2069 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PostFolderMove, array($folder, $targetFolder));
2070 }
2071
2072 /**
2073 * Emits the folder pre-rename signal
2074 *
2075 * @param Folder $folder
2076 * @param $newName
2077 * @return void
2078 */
2079 protected function emitPreFolderRenameSignal(Folder $folder, $newName) {
2080 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PreFolderRename, array($folder, $newName));
2081 }
2082
2083 /**
2084 * Emits the folder post-rename signal
2085 *
2086 * @param Folder $folder
2087 * @param $newName
2088 * @return void
2089 */
2090 protected function emitPostFolderRenameSignal(Folder $folder, $newName) {
2091 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PostFolderRename, array($folder, $newName));
2092 }
2093
2094 /**
2095 * Emits the folder pre-deletion signal
2096 *
2097 * @param Folder $folder
2098 * @return void
2099 */
2100 protected function emitPreFolderDeleteSignal(Folder $folder) {
2101 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PreFolderDelete, array($folder));
2102 }
2103
2104 /**
2105 * Emits folder postdeletion signal.
2106 *
2107 * @param Folder $folder
2108 * @return void
2109 */
2110 protected function emitPostFolderDeleteSignal(Folder $folder) {
2111 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PostFolderDelete, array($folder));
2112 }
2113
2114 /**
2115 * Emits file pre-processing signal when generating a public url for a file or folder.
2116 *
2117 * @param ResourceInterface $resourceObject
2118 * @param boolean $relativeToCurrentScript
2119 * @param array $urlData
2120 */
2121 protected function emitPreGeneratePublicUrl(ResourceInterface $resourceObject, $relativeToCurrentScript, array $urlData) {
2122 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreGeneratePublicUrl, array($this, $this->driver, $resourceObject, $relativeToCurrentScript, $urlData));
2123 }
2124
2125 /**
2126 * Returns the destination path/fileName of a unique fileName/foldername in that path.
2127 * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended.
2128 * This function is used by fx. TCEmain when files are attached to records and needs to be uniquely named in the uploads/* folders
2129 *
2130 * @param Folder $folder
2131 * @param string $theFile The input fileName to check
2132 * @param boolean $dontCheckForUnique If set the fileName is returned with the path prepended without checking whether it already existed!
2133 *
2134 * @throws \RuntimeException
2135 * @return string A unique fileName inside $folder, based on $theFile.
2136 * @see \TYPO3\CMS\Core\Utility\File\BasicFileUtility::getUniqueName()
2137 */
2138 // TODO check if this should be moved back to Folder
2139 protected function getUniqueName(Folder $folder, $theFile, $dontCheckForUnique = FALSE) {
2140 static $maxNumber = 99, $uniqueNamePrefix = '';
2141 // Fetches info about path, name, extention of $theFile
2142 $origFileInfo = GeneralUtility::split_fileref($theFile);
2143 // Adds prefix
2144 if ($uniqueNamePrefix) {
2145 $origFileInfo['file'] = $uniqueNamePrefix . $origFileInfo['file'];
2146 $origFileInfo['filebody'] = $uniqueNamePrefix . $origFileInfo['filebody'];
2147 }
2148 // Check if the file exists and if not - return the fileName...
2149 $fileInfo = $origFileInfo;
2150 // The destinations file
2151 $theDestFile = $fileInfo['file'];
2152 // If the file does NOT exist we return this fileName
2153 if (!$this->driver->fileExistsInFolder($theDestFile, $folder) || $dontCheckForUnique) {
2154 return $theDestFile;
2155 }
2156 // Well the fileName in its pure form existed. Now we try to append
2157 // numbers / unique-strings and see if we can find an available fileName
2158 // This removes _xx if appended to the file
2159 $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']);
2160 $theOrigExt = $origFileInfo['realFileext'] ? '.' . $origFileInfo['realFileext'] : '';
2161 for ($a = 1; $a <= $maxNumber + 1; $a++) {
2162 // First we try to append numbers
2163 if ($a <= $maxNumber) {
2164 $insert = '_' . sprintf('%02d', $a);
2165 } else {
2166 // TODO remove constant 6
2167 $insert = '_' . substr(md5(uniqId('')), 0, 6);
2168 }
2169 $theTestFile = $theTempFileBody . $insert . $theOrigExt;
2170 // The destinations file
2171 $theDestFile = $theTestFile;
2172 // If the file does NOT exist we return this fileName
2173 if (!$this->driver->fileExistsInFolder($theDestFile, $folder)) {
2174 return $theDestFile;
2175 }
2176 }
2177 throw new \RuntimeException('Last possible name "' . $theDestFile . '" is already taken.', 1325194291);
2178 }
2179
2180 /**
2181 * Get the SignalSlot dispatcher
2182 *
2183 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
2184 */
2185 protected function getSignalSlotDispatcher() {
2186 if (!isset($this->signalSlotDispatcher)) {
2187 $this->signalSlotDispatcher = $this->getObjectManager()->get('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
2188 }
2189 return $this->signalSlotDispatcher;
2190 }
2191
2192 /**
2193 * Get the ObjectManager
2194 *
2195 * @return \TYPO3\CMS\Extbase\Object\ObjectManager
2196 */
2197 protected function getObjectManager() {
2198 return GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
2199 }
2200
2201 /**
2202 * @return ResourceFactory
2203 */
2204 protected function getFileFactory() {
2205 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\ResourceFactory');
2206 }
2207
2208 /**
2209 * @return \TYPO3\CMS\Core\Resource\FileRepository
2210 */
2211 protected function getFileRepository() {
2212 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\FileRepository');
2213 }
2214
2215 /**
2216 * @return Service\FileProcessingService
2217 */
2218 protected function getFileProcessingService() {
2219 if (!$this->fileProcessingService) {
2220 $this->fileProcessingService = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Service\\FileProcessingService', $this, $this->driver);
2221 }
2222 return $this->fileProcessingService;
2223 }
2224
2225 /**
2226 * Gets the role of a folder
2227 *
2228 * @param FolderInterface $folder Folder object to get the role from
2229 * @return string The role the folder has
2230 */
2231 public function getRole(FolderInterface $folder) {
2232 $folderRole = FolderInterface::ROLE_DEFAULT;
2233
2234 if (method_exists($this->driver, 'getRole')) {
2235 $folderRole = $this->driver->getRole($folder);
2236 }
2237
2238 if ($folder->getIdentifier() === $this->getProcessingFolder()->getIdentifier()) {
2239 $folderRole = FolderInterface::ROLE_PROCESSING;
2240 }
2241
2242 return $folderRole;
2243 }
2244
2245 /**
2246 * Getter function to return the folder where the files can
2247 * be processed. does not check for access rights here
2248 *
2249 * @todo check if we need to implement "is writable" capability
2250 * @return Folder the processing folder, can be empty as well, if the storage doesn't have a processing folder
2251 */
2252 public function getProcessingFolder() {
2253 if (!isset($this->processingFolder)) {
2254 $processingFolder = self::DEFAULT_ProcessingFolder;
2255 if (!empty($this->storageRecord['processingfolder'])) {
2256 $processingFolder = $this->storageRecord['processingfolder'];
2257 }
2258 $processingFolder = '/' . trim($processingFolder, '/') . '/';
2259 // this way, we also worry about deeplinked folders like typo3temp/_processed_
2260 if ($this->driver->folderExists($processingFolder) === FALSE) {
2261 // TODO: This assumes that we have a hirarchical storage.
2262 // TODO: Recursive creation of folders should go to the driver, so that we can just call $this->driver->createFolder() here.
2263 $processingFolderParts = explode('/', $processingFolder);
2264 $parentFolder = $this->driver->getRootLevelFolder();
2265 foreach ($processingFolderParts as $folderPart) {
2266 if ($folderPart === '') {
2267 continue;
2268 }
2269 if (!$this->driver->folderExistsInFolder($folderPart, $parentFolder)) {
2270 $parentFolder = $this->driver->createFolder($folderPart, $parentFolder);
2271 } else {
2272 // We do not use the Folder API here to get the subfolder
2273 // Because permission checks are triggered then, which is not wanted
2274 // Since the whole method assumes that folders are hirarchical,
2275 // we can also asume it here to build the subfolder identifier
2276 // and fetch it directly from the driver.
2277 $subFolderIdentifier = $parentFolder->getIdentifier() . $folderPart;
2278 $parentFolder = $this->driver->getFolder($subFolderIdentifier);
2279 }
2280 }
2281 }
2282 $this->processingFolder = $this->driver->getFolder($processingFolder);
2283 }
2284 return $this->processingFolder;
2285 }
2286 }
2287
2288 ?>