87b842dbdc22fe1bef2674656878752d5652caa2
[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 $isAllowed = GeneralUtility::verifyFilenameAgainstDenyPattern($fileName);
699 if ($isAllowed) {
700 $fileInfo = GeneralUtility::split_fileref($fileName);
701 // Set up the permissions for the file extension
702 $fileExtensionPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace'];
703 $fileExtensionPermissions['allow'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['allow']));
704 $fileExtensionPermissions['deny'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['deny']));
705 $fileExtension = strtolower($fileInfo['fileext']);
706 if ($fileExtension !== '') {
707 // If the extension is found amongst the allowed types, we return TRUE immediately
708 if ($fileExtensionPermissions['allow'] === '*' || GeneralUtility::inList($fileExtensionPermissions['allow'], $fileExtension)) {
709 return TRUE;
710 }
711 // If the extension is found amongst the denied types, we return FALSE immediately
712 if ($fileExtensionPermissions['deny'] === '*' || GeneralUtility::inList($fileExtensionPermissions['deny'], $fileExtension)) {
713 return FALSE;
714 }
715 // If no match we return TRUE
716 return TRUE;
717 } else {
718 if ($fileExtensionPermissions['allow'] === '*') {
719 return TRUE;
720 }
721 if ($fileExtensionPermissions['deny'] === '*') {
722 return FALSE;
723 }
724 return TRUE;
725 }
726 }
727 return FALSE;
728 }
729
730 /**
731 * @param Folder $folder If a folder is given, mountpoits are checked. If not only user folder read permissions are checked.
732 *
733 * @throws Exception\InsufficientFolderAccessPermissionsException
734 */
735 protected function assureFolderReadPermission(Folder $folder = NULL) {
736 if (!$this->checkFolderActionPermission('read', $folder)) {
737 throw new Exception\InsufficientFolderAccessPermissionsException('You are not allowed to access the given folder', 1375955684);
738 }
739 }
740
741 /**
742 * @param Folder $folder If a folder is given, mountpoits are checked. If not only user folder delete permissions are checked.
743 * @param boolean $checkDeleteRecursively
744 *
745 * @throws Exception\InsufficientFolderAccessPermissionsException
746 * @throws Exception\InsufficientFolderWritePermissionsException
747 * @throws Exception\InsufficientUserPermissionsException
748 */
749 protected function assureFolderDeletePermission(Folder $folder, $checkDeleteRecursively) {
750 // Check user permissions for recursive deletion if it is requested
751 if ($checkDeleteRecursively && !$this->checkUserActionPermission('recursivedelete', 'Folder')) {
752 throw new Exception\InsufficientUserPermissionsException('You are not allowed to delete folders recursively', 1377779423);
753 }
754 // Check user action permission
755 if (!$this->checkFolderActionPermission('delete', $folder)) {
756 throw new Exception\InsufficientFolderAccessPermissionsException('You are not allowed to delete the given folder', 1377779039);
757 }
758 // Check if the user has write permissions to folders
759 // Would be good if we could check for actual write permissions in the containig folder
760 // but we cannot since we have no access to the containing folder of this file.
761 if (!$this->checkUserActionPermission('write', 'Folder')) {
762 throw new Exception\InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377779111);
763 }
764 }
765
766 /**
767 * @param FileInterface $file
768 *
769 * @throws Exception\InsufficientFileAccessPermissionsException
770 * @throws Exception\IllegalFileExtensionException
771 */
772 protected function assureFileReadPermission(FileInterface $file) {
773 if (!$this->checkFileActionPermission('read', $file)) {
774 throw new Exception\InsufficientFileAccessPermissionsException('You are not allowed to access that file.', 1375955429);
775 }
776 if (!$this->checkFileExtensionPermission($file->getName())) {
777 throw new Exception\IllegalFileExtensionException('You are not allowed to use that file extension', 1375955430);
778 }
779 }
780
781 /**
782 * @param FileInterface $file
783 *
784 * @throws Exception\IllegalFileExtensionException
785 * @throws Exception\InsufficientFileWritePermissionsException
786 * @throws Exception\InsufficientUserPermissionsException
787 */
788 protected function assureFileWritePermissions(FileInterface $file) {
789 // Check if user is allowed to write the file and $file is writable
790 if (!$this->checkFileActionPermission('write', $file)) {
791 throw new Exception\InsufficientFileWritePermissionsException('Writing to file "' . $file->getIdentifier() . '" is not allowed.', 1330121088);
792 }
793 if (!$this->checkFileExtensionPermission($file->getName())) {
794 throw new Exception\IllegalFileExtensionException('You are not allowed to edit a file with extension "' . $file->getExtension() . '"', 1366711933);
795 }
796 }
797
798 /**
799 * @param FileInterface $file
800 *
801 * @throws Exception\IllegalFileExtensionException
802 * @throws Exception\InsufficientFileWritePermissionsException
803 * @throws Exception\InsufficientFolderWritePermissionsException
804 */
805 protected function assureFileDeletePermissions(FileInterface $file) {
806 // Check for disallowed file extensions
807 if (!$this->checkFileExtensionPermission($file->getName())) {
808 throw new Exception\IllegalFileExtensionException('You are not allowed to delete a file with extension "' . $file->getExtension() . '"', 1377778916);
809 }
810 // Check further permissions if file is not a processed file
811 if (!$file instanceof ProcessedFile) {
812 // Check if user is allowed to delete the file and $file is writable
813 if (!$this->checkFileActionPermission('delete', $file)) {
814 throw new Exception\InsufficientFileWritePermissionsException('You are not allowed to delete the file "' . $file->getIdentifier() . '\'', 1319550425);
815 }
816 // Check if the user has write permissions to folders
817 // Would be good if we could check for actual write permissions in the containig folder
818 // but we cannot since we have no access to the containing folder of this file.
819 if (!$this->checkUserActionPermission('write', 'Folder')) {
820 throw new Exception\InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377778702);
821 }
822 }
823 }
824
825 /**
826 * Check if a file has the permission to be uploaded to a Folder/Storage,
827 * if not throw an exception
828 *
829 * @param string $localFilePath the temporary file name from $_FILES['file1']['tmp_name']
830 * @param Folder $targetFolder
831 * @param string $targetFileName the destination file name $_FILES['file1']['name']
832 *
833 * @throws Exception\InsufficientFolderWritePermissionsException
834 * @throws Exception\UploadException
835 * @throws Exception\IllegalFileExtensionException
836 * @throws Exception\UploadSizeException
837 * @throws Exception\InsufficientUserPermissionsException
838 * @return void
839 */
840 protected function assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName) {
841 // Check for a valid file extension
842 if (!$this->checkFileExtensionPermission($targetFileName) || ($localFilePath && !$this->checkFileExtensionPermission($localFilePath))) {
843 throw new Exception\IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1322120271);
844 }
845 // Makes sure the user is allowed to upload
846 if (!$this->checkUserActionPermission('add', 'File')) {
847 throw new Exception\InsufficientUserPermissionsException('You are not allowed to add files to this storage "' . $this->getUid() . '"', 1376992145);
848 }
849 // Check if targetFolder is writable
850 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
851 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1322120356);
852 }
853 }
854
855 /**
856 * Check if a file has the permission to be uploaded to a Folder/Storage,
857 * if not throw an exception
858 *
859 * @param string $localFilePath the temporary file name from $_FILES['file1']['tmp_name']
860 * @param Folder $targetFolder
861 * @param string $targetFileName the destination file name $_FILES['file1']['name']
862 * @param integer $uploadedFileSize
863 *
864 * @throws Exception\InsufficientFolderWritePermissionsException
865 * @throws Exception\UploadException
866 * @throws Exception\IllegalFileExtensionException
867 * @throws Exception\UploadSizeException
868 * @throws Exception\InsufficientUserPermissionsException
869 * @return void
870 */
871 protected function assureFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileSize) {
872 // Makes sure this is an uploaded file
873 if (!is_uploaded_file($localFilePath)) {
874 throw new Exception\UploadException('The upload has failed, no uploaded file found!', 1322110455);
875 }
876 // Max upload size (kb) for files.
877 $maxUploadFileSize = GeneralUtility::getMaxUploadFileSize() * 1024;
878 if ($uploadedFileSize >= $maxUploadFileSize) {
879 unlink($localFilePath);
880 throw new Exception\UploadSizeException('The uploaded file exceeds the size-limit of ' . $maxUploadFileSize . ' bytes', 1322110041);
881 }
882 $this->assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName);
883 }
884
885 /**
886 * Checks for permissions to move a file.
887 *
888 * @throws \RuntimeException
889 * @throws Exception\InsufficientFileReadPermissionsException
890 * @throws Exception\InsufficientFileWritePermissionsException
891 * @throws Exception\InsufficientFolderAccessPermissionsException
892 * @throws Exception\InsufficientUserPermissionsException
893 * @param FileInterface $file
894 * @param Folder $targetFolder
895 * @param string $targetFileName
896 * @return void
897 */
898 protected function assureFileMovePermissions(FileInterface $file, Folder $targetFolder, $targetFileName) {
899 // Check if targetFolder is within this storage
900 if ($this->getUid() !== $targetFolder->getStorage()->getUid()) {
901 throw new \RuntimeException();
902 }
903 // Check for a valid file extension
904 if (!$this->checkFileExtensionPermission($targetFileName)) {
905 throw new Exception\IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1378243279);
906 }
907 // Check if user is allowed to move and $file is readable and writable
908 if (!$this->checkFileActionPermission('move', $file)) {
909 throw new Exception\InsufficientUserPermissionsException('You are not allowed to move files to storage "' . $this->getUid() . '"', 1319219349);
910 }
911 // Check if target folder is writable
912 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
913 throw new Exception\InsufficientFolderAccessPermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319219349);
914 }
915 }
916
917 /**
918 * Checks for permissions to rename a file.
919 *
920 * @param FileInterface $file
921 * @param string $targetFileName
922 * @throws Exception\InsufficientFileWritePermissionsException
923 * @throws Exception\IllegalFileExtensionException
924 * @throws Exception\InsufficientFileReadPermissionsException
925 * @throws Exception\InsufficientUserPermissionsException
926 * @return void
927 */
928 protected function assureFileRenamePermissions(FileInterface $file, $targetFileName) {
929 // Check if file extension is allowed
930 if (!$this->checkFileExtensionPermission($targetFileName) || !$this->checkFileExtensionPermission($file->getName())) {
931 throw new Exception\IllegalFileExtensionException('You are not allowed to rename a file with to this extension', 1371466663);
932 }
933 // Check if user is allowed to rename
934 if (!$this->checkFileActionPermission('rename', $file)) {
935 throw new Exception\InsufficientUserPermissionsException('You are not allowed to rename files."', 1319219349);
936 }
937 // Check if the user is allowed to write to folders
938 // Although it would be good to check, we cannot check here if the folder actually is writable
939 // because we do not know in which folder the file resides.
940 // So we rely on the driver to throw an exception in case the renaming failed.
941 if (!$this->checkFolderActionPermission('write')) {
942 throw new Exception\InsufficientFileWritePermissionsException('You are not allowed to write to folders', 1319219349);
943 }
944 }
945
946 /**
947 * Check if a file has the permission to be copied on a File/Folder/Storage,
948 * if not throw an exception
949 *
950 * @param FileInterface $file
951 * @param Folder $targetFolder
952 * @param string $targetFileName
953 *
954 * @throws Exception
955 * @throws Exception\InsufficientFolderWritePermissionsException
956 * @throws Exception\IllegalFileExtensionException
957 * @throws Exception\InsufficientFileReadPermissionsException
958 * @throws Exception\InsufficientUserPermissionsException
959 * @return void
960 */
961 protected function assureFileCopyPermissions(FileInterface $file, Folder $targetFolder, $targetFileName) {
962 // Check if targetFolder is within this storage, this should never happen
963 if ($this->getUid() != $targetFolder->getStorage()->getUid()) {
964 throw new Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1319550405);
965 }
966 // Check if user is allowed to copy
967 if (!$this->checkFileActionPermission('copy', $file)) {
968 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the file "' . $file->getIdentifier() . '\'', 1319550425);
969 }
970 // Check if targetFolder is writable
971 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
972 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319550435);
973 }
974 // Check for a valid file extension
975 if (!$this->checkFileExtensionPermission($targetFileName) || !$this->checkFileExtensionPermission($file->getName())) {
976 throw new Exception\IllegalFileExtensionException('You are not allowed to copy a file of that type.', 1319553317);
977 }
978 }
979
980 /**
981 * Check if a file has the permission to be copied on a File/Folder/Storage,
982 * if not throw an exception
983 *
984 * @param FolderInterface $folderToCopy
985 * @param FolderInterface $targetParentFolder
986 *
987 * @throws Exception
988 * @throws Exception\InsufficientFolderWritePermissionsException
989 * @throws Exception\IllegalFileExtensionException
990 * @throws Exception\InsufficientFileReadPermissionsException
991 * @throws Exception\InsufficientUserPermissionsException
992 * @return void
993 */
994 protected function assureFolderCopyPermissions(FolderInterface $folderToCopy, FolderInterface $targetParentFolder) {
995 // Check if targetFolder is within this storage, this should never happen
996 if ($this->getUid() !== $targetParentFolder->getStorage()->getUid()) {
997 throw new Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1377777624);
998 }
999 // Check if user is allowed to copy and the folder is readable
1000 if (!$this->checkFolderActionPermission('copy', $folderToCopy)) {
1001 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the folder "' . $folderToCopy->getIdentifier() . '\'', 1377777629);
1002 }
1003 // Check if targetFolder is writable
1004 if (!$this->checkFolderActionPermission('write', $targetParentFolder)) {
1005 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetParentFolder->getIdentifier() . '"', 1377777635);
1006 }
1007 }
1008
1009 /**
1010 * Check if a file has the permission to be copied on a File/Folder/Storage,
1011 * if not throw an exception
1012 *
1013 * @param FolderInterface $folderToMove
1014 * @param FolderInterface $targetParentFolder
1015 *
1016 * @throws \InvalidArgumentException
1017 * @throws Exception\InsufficientFolderWritePermissionsException
1018 * @throws Exception\IllegalFileExtensionException
1019 * @throws Exception\InsufficientFileReadPermissionsException
1020 * @throws Exception\InsufficientUserPermissionsException
1021 * @return void
1022 */
1023 protected function assureFolderMovePermissions(FolderInterface $folderToMove, FolderInterface $targetParentFolder) {
1024 // Check if targetFolder is within this storage, this should never happen
1025 if ($this->getUid() !== $targetParentFolder->getStorage()->getUid()) {
1026 throw new \InvalidArgumentException('Cannot move a folder into a folder that does not belong to this storage.', 1325777289);
1027 }
1028 // Check if user is allowed to move and the folder is writable
1029 // In fact we would need to check if the parent folder of the folder to move is writable also
1030 // But as of now we cannot extract the parent folder from this folder
1031 if (!$this->checkFolderActionPermission('move', $folderToMove)) {
1032 throw new Exception\InsufficientFileReadPermissionsException('You are not allowed to copy the folder "' . $folderToMove->getIdentifier() . '\'', 1377778045);
1033 }
1034 // Check if targetFolder is writable
1035 if (!$this->checkFolderActionPermission('write', $targetParentFolder)) {
1036 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetParentFolder->getIdentifier() . '"', 1377778049);
1037 }
1038 }
1039
1040 /********************
1041 * FILE ACTIONS
1042 ********************/
1043 /**
1044 * Moves a file from the local filesystem to this storage.
1045 *
1046 * @param string $localFilePath The file on the server's hard disk to add.
1047 * @param Folder $targetFolder The target path, without the fileName
1048 * @param string $targetFileName The fileName. If not set, the local file name is used.
1049 * @param string $conflictMode possible value are 'cancel', 'replace', 'changeName'
1050 *
1051 * @throws \InvalidArgumentException
1052 * @throws Exception\ExistingTargetFileNameException
1053 * @return FileInterface
1054 */
1055 public function addFile($localFilePath, Folder $targetFolder, $targetFileName = '', $conflictMode = 'changeName') {
1056 $localFilePath = PathUtility::getCanonicalPath($localFilePath);
1057 if (!file_exists($localFilePath)) {
1058 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1319552745);
1059 }
1060 $this->assureFileAddPermissions($localFilePath, $targetFolder, $targetFileName);
1061 $targetFolder = $targetFolder ? $targetFolder : $this->getDefaultFolder();
1062 $targetFileName = $targetFileName ? $targetFileName : PathUtility::basename($localFilePath);
1063 if ($conflictMode === 'cancel' && $this->driver->fileExistsInFolder($targetFileName, $targetFolder)) {
1064 throw new Exception\ExistingTargetFileNameException('File "' . $targetFileName . '" already exists in folder ' . $targetFolder->getIdentifier(), 1322121068);
1065 } elseif ($conflictMode === 'changeName') {
1066 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1067 }
1068 // We do not care whether the file exists if $conflictMode is "replace",
1069 // so just use the name as is in that case
1070 return $this->driver->addFile($localFilePath, $targetFolder, $targetFileName);
1071 }
1072
1073 /**
1074 * Updates a processed file with a new file from the local filesystem.
1075 *
1076 * @param $localFilePath
1077 * @param ProcessedFile $processedFile
1078 * @return FileInterface
1079 * @throws \InvalidArgumentException
1080 * @internal use only
1081 */
1082 public function updateProcessedFile($localFilePath, ProcessedFile $processedFile) {
1083 if (!file_exists($localFilePath)) {
1084 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1319552745);
1085 }
1086 $file = $this->driver->addFile($localFilePath, $this->getProcessingFolder(), $processedFile->getName());
1087 $file->setIndexable(FALSE);
1088 return $file;
1089 }
1090
1091 /**
1092 * Creates a (cryptographic) hash for a file.
1093 *
1094 * @param FileInterface $fileObject
1095 * @param $hash
1096 * @return string
1097 */
1098 public function hashFile(FileInterface $fileObject, $hash) {
1099 return $this->driver->hash($fileObject, $hash);
1100 }
1101
1102 /**
1103 * Returns a publicly accessible URL for a file.
1104 *
1105 * WARNING: Access to the file may be restricted by further means, e.g.
1106 * some web-based authentication. You have to take care of this yourself.
1107 *
1108 * @param ResourceInterface $resourceObject The file or folder object
1109 * @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)
1110 * @return string
1111 */
1112 public function getPublicUrl(ResourceInterface $resourceObject, $relativeToCurrentScript = FALSE) {
1113 $publicUrl = NULL;
1114 if ($this->isOnline()) {
1115 // Pre-process the public URL by an accordant slot
1116 $this->emitPreGeneratePublicUrl($resourceObject, $relativeToCurrentScript, array('publicUrl' => &$publicUrl));
1117 // If slot did not handle the signal, use the default way to determine public URL
1118 if ($publicUrl === NULL) {
1119 $publicUrl = $this->driver->getPublicUrl($resourceObject, $relativeToCurrentScript);
1120 }
1121 }
1122 return $publicUrl;
1123 }
1124
1125 /**
1126 * Passes a file to the File Processing Services and returns the resulting ProcessedFile object.
1127 *
1128 * @param FileInterface $fileObject The file object
1129 * @param string $context
1130 * @param array $configuration
1131 *
1132 * @return ProcessedFile
1133 * @throws \InvalidArgumentException
1134 */
1135 public function processFile(FileInterface $fileObject, $context, array $configuration) {
1136 if ($fileObject->getStorage() !== $this) {
1137 throw new \InvalidArgumentException('Cannot process files of foreign storage', 1353401835);
1138 }
1139 $processedFile = $this->getFileProcessingService()->processFile($fileObject, $this, $context, $configuration);
1140
1141 return $processedFile;
1142 }
1143
1144 /**
1145 * Copies a file from the storage for local processing.
1146 *
1147 * @param FileInterface $fileObject
1148 * @param bool $writable
1149 * @return string Path to local file (either original or copied to some temporary local location)
1150 */
1151 public function getFileForLocalProcessing(FileInterface $fileObject, $writable = TRUE) {
1152 $filePath = $this->driver->getFileForLocalProcessing($fileObject, $writable);
1153 // @todo: shouldn't this go in the driver? this function is called from the indexing service
1154 // @todo: and recursively calls itself over and over again, this is left out for now with getModificationTime()
1155 // touch($filePath, $fileObject->getModificationTime());
1156 return $filePath;
1157 }
1158
1159 /**
1160 * Get file by identifier
1161 *
1162 * @param string $identifier
1163 * @return FileInterface
1164 */
1165 public function getFile($identifier) {
1166 return $this->driver->getFile($identifier);
1167 }
1168
1169 /**
1170 * Get information about a file
1171 *
1172 * @param FileInterface $fileObject
1173 * @return array
1174 */
1175 public function getFileInfo(FileInterface $fileObject) {
1176 return $this->driver->getFileInfo($fileObject);
1177 }
1178
1179 /**
1180 * Get information about a file by its identifier
1181 *
1182 * @param string $identifier
1183 *
1184 * @throws \BadMethodCallException
1185 * @return array
1186 */
1187 public function getFileInfoByIdentifier($identifier) {
1188 throw new \BadMethodCallException('The method ResourceStorage::getFileInfoByIdentifier() has been deprecated. Please fix your method call and use getFileInfo with the file object instead.', 1346577887);
1189 }
1190
1191 /**
1192 * Unsets the file and folder name filters, thus making this storage return unfiltered file lists.
1193 *
1194 * @return void
1195 */
1196 public function unsetFileAndFolderNameFilters() {
1197 $this->fileAndFolderNameFilters = array();
1198 }
1199
1200 /**
1201 * Resets the file and folder name filters to the default values defined in the TYPO3 configuration.
1202 *
1203 * @return void
1204 */
1205 public function resetFileAndFolderNameFiltersToDefault() {
1206 $this->fileAndFolderNameFilters = $GLOBALS['TYPO3_CONF_VARS']['SYS']['fal']['defaultFilterCallbacks'];
1207 }
1208
1209 /**
1210 * Returns the file and folder name filters used by this storage.
1211 *
1212 * @return array
1213 */
1214 public function getFileAndFolderNameFilters() {
1215 return $this->fileAndFolderNameFilters;
1216 }
1217
1218 public function setFileAndFolderNameFilters(array $filters) {
1219 $this->fileAndFolderNameFilters = $filters;
1220 return $this;
1221 }
1222
1223 public function addFileAndFolderNameFilter($filter) {
1224 $this->fileAndFolderNameFilters[] = $filter;
1225 }
1226
1227 /**
1228 * Returns a list of files in a given path, filtered by some custom filter methods.
1229 *
1230 * @see getUnfilteredFileList(), getFileListWithDefaultFilters()
1231 * @param string $path The path to list
1232 * @param integer $start The position to start the listing; if not set or 0, start from the beginning
1233 * @param integer $numberOfItems The number of items to list; if not set, return all items
1234 * @param bool $useFilters If FALSE, the list is returned without any filtering; otherwise, the filters defined for this storage are used.
1235 * @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.
1236 * @param boolean $recursive
1237 * @return array Information about the files found.
1238 */
1239 // TODO check if we should use a folder object instead of $path
1240 // TODO add unit test for $loadIndexRecords
1241 public function getFileList($path, $start = 0, $numberOfItems = 0, $useFilters = TRUE, $loadIndexRecords = TRUE, $recursive = FALSE) {
1242 // This also checks for read permissions on folder
1243 $folder = $this->getFolder($path);
1244 $rows = array();
1245 if ($loadIndexRecords) {
1246 $rows = $this->getFileRepository()->getFileIndexRecordsForFolder($folder);
1247 }
1248 $filters = $useFilters == TRUE ? $this->fileAndFolderNameFilters : array();
1249 $items = $this->driver->getFileList($path, $start, $numberOfItems, $filters, $rows, $recursive);
1250
1251 // We should not sort when fetching a recursive list, as these are indexed numerically
1252 if ($recursive === FALSE) {
1253 uksort($items, 'strnatcasecmp');
1254 }
1255
1256 return $items;
1257 }
1258
1259 /**
1260 * Returns TRUE if the specified file exists.
1261 *
1262 * @param string $identifier
1263 * @return boolean
1264 */
1265 public function hasFile($identifier) {
1266 $this->assureFolderReadPermission();
1267 return $this->driver->fileExists($identifier);
1268 }
1269
1270 /**
1271 * Checks if the queried file in the given folder exists.
1272 *
1273 * @param string $fileName
1274 * @param Folder $folder
1275 * @return boolean
1276 */
1277 public function hasFileInFolder($fileName, Folder $folder) {
1278 $this->assureFolderReadPermission($folder);
1279 return $this->driver->fileExistsInFolder($fileName, $folder);
1280 }
1281
1282 /**
1283 * Get contents of a file object
1284 *
1285 * @param FileInterface $file
1286 *
1287 * @throws Exception\InsufficientFileReadPermissionsException
1288 * @return string
1289 */
1290 public function getFileContents($file) {
1291 $this->assureFileReadPermission($file);
1292 return $this->driver->getFileContents($file);
1293 }
1294
1295 /**
1296 * Set contents of a file object.
1297 *
1298 * @param AbstractFile $file
1299 * @param string $contents
1300 *
1301 * @throws \Exception|\RuntimeException
1302 * @throws Exception\InsufficientFileWritePermissionsException
1303 * @throws Exception\InsufficientUserPermissionsException
1304 * @return integer The number of bytes written to the file
1305 */
1306 public function setFileContents(AbstractFile $file, $contents) {
1307 // Check if user is allowed to edit
1308 $this->assureFileWritePermissions($file);
1309 // Call driver method to update the file and update file properties afterwards
1310 $result = $this->driver->setFileContents($file, $contents);
1311 $fileInfo = $this->driver->getFileInfo($file);
1312 $fileInfo['sha1'] = $this->driver->hash($file, 'sha1');
1313 $file->updateProperties($fileInfo);
1314 $this->getFileRepository()->update($file);
1315 return $result;
1316 }
1317
1318 /**
1319 * Creates a new file
1320 *
1321 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_newfile()
1322 *
1323 * @param string $fileName
1324 * @param Folder $targetFolderObject
1325 *
1326 * @throws Exception\IllegalFileExtensionException
1327 * @throws Exception\InsufficientFolderWritePermissionsException
1328 * @return FileInterface The file object
1329 */
1330 public function createFile($fileName, Folder $targetFolderObject) {
1331 $this->assureFileAddPermissions('', $targetFolderObject, $fileName);
1332 return $this->driver->createFile($fileName, $targetFolderObject);
1333 }
1334
1335 /**
1336 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::deleteFile()
1337 *
1338 * @param $fileObject FileInterface
1339 * @throws Exception\InsufficientFileAccessPermissionsException
1340 * @throws Exception\FileOperationErrorException
1341 * @return boolean TRUE if deletion succeeded
1342 */
1343 public function deleteFile($fileObject) {
1344 $this->assureFileDeletePermissions($fileObject);
1345
1346 $this->emitPreFileDeleteSignal($fileObject);
1347
1348 $result = $this->driver->deleteFile($fileObject);
1349 if ($result === FALSE) {
1350 throw new Exception\FileOperationErrorException('Deleting the file "' . $fileObject->getIdentifier() . '\' failed.', 1329831691);
1351 }
1352 // Mark the file object as deleted
1353 $fileObject->setDeleted();
1354
1355 $this->emitPostFileDeleteSignal($fileObject);
1356
1357 return TRUE;
1358 }
1359
1360 /**
1361 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_copy()
1362 * copies a source file (from any location) in to the target
1363 * folder, the latter has to be part of this storage
1364 *
1365 * @param FileInterface $file
1366 * @param Folder $targetFolder
1367 * @param string $targetFileName an optional destination fileName
1368 * @param string $conflictMode "overrideExistingFile", "renameNewFile", "cancel
1369 *
1370 * @throws \Exception|Exception\AbstractFileOperationException
1371 * @throws Exception\ExistingTargetFileNameException
1372 * @return FileInterface
1373 */
1374 public function copyFile(FileInterface $file, Folder $targetFolder, $targetFileName = NULL, $conflictMode = 'renameNewFile') {
1375 if ($targetFileName === NULL) {
1376 $targetFileName = $file->getName();
1377 }
1378 $this->assureFileCopyPermissions($file, $targetFolder, $targetFileName);
1379 $this->emitPreFileCopySignal($file, $targetFolder);
1380 // File exists and we should abort, let's abort
1381 if ($conflictMode === 'cancel' && $targetFolder->hasFile($targetFileName)) {
1382 throw new Exception\ExistingTargetFileNameException('The target file already exists.', 1320291063);
1383 }
1384 // File exists and we should find another name, let's find another one
1385 if ($conflictMode === 'renameNewFile' && $targetFolder->hasFile($targetFileName)) {
1386 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1387 }
1388 $sourceStorage = $file->getStorage();
1389 // Call driver method to create a new file from an existing file object,
1390 // and return the new file object
1391 if ($sourceStorage === $this) {
1392 $newFileObject = $this->driver->copyFileWithinStorage($file, $targetFolder, $targetFileName);
1393 } else {
1394 $tempPath = $file->getForLocalProcessing();
1395 $newFileObject = $this->driver->addFile($tempPath, $targetFolder, $targetFileName);
1396 }
1397 $this->emitPostFileCopySignal($file, $targetFolder);
1398 return $newFileObject;
1399 }
1400
1401 /**
1402 * Moves a $file into a $targetFolder
1403 * the target folder has to be part of this storage
1404 *
1405 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_move()
1406 *
1407 * @param FileInterface $file
1408 * @param Folder $targetFolder
1409 * @param string $targetFileName an optional destination fileName
1410 * @param string $conflictMode "overrideExistingFile", "renameNewFile", "cancel
1411 *
1412 * @throws Exception\ExistingTargetFileNameException
1413 * @return FileInterface
1414 */
1415 public function moveFile($file, $targetFolder, $targetFileName = NULL, $conflictMode = 'renameNewFile') {
1416 if ($targetFileName === NULL) {
1417 $targetFileName = $file->getName();
1418 }
1419 $this->assureFileMovePermissions($file, $targetFolder, $targetFileName);
1420 if ($targetFolder->hasFile($targetFileName)) {
1421 // File exists and we should abort, let's abort
1422 if ($conflictMode === 'renameNewFile') {
1423 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1424 } elseif ($conflictMode === 'cancel') {
1425 throw new Exception\ExistingTargetFileNameException('The target file already exists', 1329850997);
1426 }
1427 }
1428 $this->emitPreFileMoveSignal($file, $targetFolder);
1429 $sourceStorage = $file->getStorage();
1430 // Call driver method to move the file that also updates the file
1431 // object properties
1432 try {
1433 if ($sourceStorage === $this) {
1434 $newIdentifier = $this->driver->moveFileWithinStorage($file, $targetFolder, $targetFileName);
1435 $this->updateFile($file, $newIdentifier);
1436 } else {
1437 $tempPath = $file->getForLocalProcessing();
1438 $newIdentifier = $this->driver->addFileRaw($tempPath, $targetFolder, $targetFileName);
1439 $sourceStorage->driver->deleteFileRaw($file->getIdentifier());
1440 $this->updateFile($file, $newIdentifier, $this);
1441 }
1442 } catch (\TYPO3\CMS\Core\Exception $e) {
1443 echo $e->getMessage();
1444 }
1445 $this->emitPostFileMoveSignal($file, $targetFolder);
1446 return $file;
1447 }
1448
1449 /**
1450 * Updates the properties of a file object with some that are freshly
1451 * fetched from the driver.
1452 *
1453 * @param AbstractFile $file
1454 * @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)
1455 * @param ResourceStorage $storage
1456 * @return void
1457 */
1458 protected function updateFile(AbstractFile $file, $identifier = '', $storage = NULL) {
1459 if ($identifier === '') {
1460 $identifier = $file->getIdentifier();
1461 }
1462 $fileInfo = $this->driver->getFileInfoByIdentifier($identifier);
1463 // TODO extend mapping
1464 $newProperties = array(
1465 'storage' => $fileInfo['storage'],
1466 'identifier' => $fileInfo['identifier'],
1467 'tstamp' => $fileInfo['mtime'],
1468 'crdate' => $fileInfo['ctime'],
1469 'mime_type' => $fileInfo['mimetype'],
1470 'size' => $fileInfo['size'],
1471 'name' => $fileInfo['name']
1472 );
1473 if ($storage !== NULL) {
1474 $newProperties['storage'] = $storage->getUid();
1475 }
1476 $file->updateProperties($newProperties);
1477 $this->getFileRepository()->update($file);
1478 }
1479
1480 /**
1481 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_rename()
1482 *
1483 * @param FileInterface $file
1484 * @param string $targetFileName
1485 *
1486 * @throws Exception\InsufficientFileWritePermissionsException
1487 * @throws Exception\InsufficientFileReadPermissionsException
1488 * @throws Exception\InsufficientUserPermissionsException
1489 * @return FileInterface
1490 */
1491 // TODO add $conflictMode setting
1492 public function renameFile($file, $targetFileName) {
1493 // The name should be different from the current.
1494 if ($file->getName() === $targetFileName) {
1495 return $file;
1496 }
1497 $this->assureFileRenamePermissions($file, $targetFileName);
1498 $this->emitPreFileRenameSignal($file, $targetFileName);
1499
1500 // Call driver method to rename the file that also updates the file
1501 // object properties
1502 try {
1503 $newIdentifier = $this->driver->renameFile($file, $targetFileName);
1504 $this->updateFile($file, $newIdentifier);
1505 $this->getFileRepository()->update($file);
1506 } catch (\RuntimeException $e) {
1507
1508 }
1509
1510 $this->emitPostFileRenameSignal($file, $targetFileName);
1511
1512 return $file;
1513 }
1514
1515 /**
1516 * Replaces a file with a local file (e.g. a freshly uploaded file)
1517 *
1518 * @param FileInterface $file
1519 * @param string $localFilePath
1520 *
1521 * @throws \InvalidArgumentException
1522 * @return FileInterface
1523 */
1524 public function replaceFile(FileInterface $file, $localFilePath) {
1525 $this->assureFileWritePermissions($file);
1526 if (!$this->checkFileExtensionPermission($localFilePath)) {
1527 throw new Exception\IllegalFileExtensionException('Sorce file extension not allowed', 1378132239);
1528 }
1529 if (!file_exists($localFilePath)) {
1530 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1325842622);
1531 }
1532 // TODO check permissions
1533 $this->emitPreFileReplaceSignal($file, $localFilePath);
1534 $result = $this->driver->replaceFile($file, $localFilePath);
1535 $this->emitPostFileReplaceSignal($file, $localFilePath);
1536 return $result;
1537 }
1538
1539 /**
1540 * Adds an uploaded file into the Storage. Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::file_upload()
1541 *
1542 * @param array $uploadedFileData contains information about the uploaded file given by $_FILES['file1']
1543 * @param Folder $targetFolder the target folder
1544 * @param string $targetFileName the file name to be written
1545 * @param string $conflictMode possible value are 'cancel', 'replace'
1546 * @return FileInterface The file object
1547 */
1548 public function addUploadedFile(array $uploadedFileData, Folder $targetFolder = NULL, $targetFileName = NULL, $conflictMode = 'cancel') {
1549 $localFilePath = $uploadedFileData['tmp_name'];
1550 if ($targetFolder === NULL) {
1551 $targetFolder = $this->getDefaultFolder();
1552 }
1553 if ($targetFileName === NULL) {
1554 $targetFileName = $uploadedFileData['name'];
1555 }
1556 // Handling $conflictMode is delegated to addFile()
1557 $this->assureFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileData['size']);
1558 $resultObject = $this->addFile($localFilePath, $targetFolder, $targetFileName, $conflictMode);
1559 return $resultObject;
1560 }
1561
1562 /********************
1563 * FOLDER ACTIONS
1564 ********************/
1565 /**
1566 * Returns an array with all file objects in a folder and its subfolders, with the file identifiers as keys.
1567 *
1568 * @param Folder $folder
1569 * @return File[]
1570 */
1571 protected function getAllFileObjectsInFolder(Folder $folder) {
1572 $files = array();
1573 $folderQueue = array($folder);
1574 while (!empty($folderQueue)) {
1575 $folder = array_shift($folderQueue);
1576 foreach ($folder->getSubfolders() as $subfolder) {
1577 $folderQueue[] = $subfolder;
1578 }
1579 foreach ($folder->getFiles() as $file) {
1580 $files[$file->getIdentifier()] = $file;
1581 }
1582 }
1583 return $files;
1584 }
1585
1586 /**
1587 * Moves a folder. If you want to move a folder from this storage to another
1588 * one, call this method on the target storage, otherwise you will get an exception.
1589 *
1590 * @param Folder $folderToMove The folder to move.
1591 * @param Folder $targetParentFolder The target parent folder
1592 * @param string $newFolderName
1593 * @param string $conflictMode How to handle conflicts; one of "overrideExistingFile", "renameNewFolder", "cancel
1594 *
1595 * @throws \Exception|\TYPO3\CMS\Core\Exception
1596 * @throws \InvalidArgumentException
1597 * @return Folder
1598 */
1599 // TODO add tests
1600 public function moveFolder(Folder $folderToMove, Folder $targetParentFolder, $newFolderName = NULL, $conflictMode = 'renameNewFolder') {
1601 $this->assureFolderMovePermissions($folderToMove, $targetParentFolder);
1602 $sourceStorage = $folderToMove->getStorage();
1603 $returnObject = NULL;
1604 $newFolderName = $newFolderName ? $newFolderName : $folderToMove->getName();
1605 // TODO check if folder already exists in $targetParentFolder, handle this conflict then
1606 $this->emitPreFolderMoveSignal($folderToMove, $targetParentFolder, $newFolderName);
1607 // Get all file objects now so we are able to update them after moving the folder
1608 $fileObjects = $this->getAllFileObjectsInFolder($folderToMove);
1609 if ($sourceStorage === $this) {
1610 $fileMappings = $this->driver->moveFolderWithinStorage($folderToMove, $targetParentFolder, $newFolderName);
1611 } else {
1612 $fileMappings = $this->moveFolderBetweenStorages($folderToMove, $targetParentFolder, $newFolderName);
1613 }
1614 // Update the identifier and storage of all file objects
1615 foreach ($fileObjects as $oldIdentifier => $fileObject) {
1616 $newIdentifier = $fileMappings[$oldIdentifier];
1617 $fileObject->updateProperties(array('storage' => $this, 'identifier' => $newIdentifier));
1618 $this->getFileRepository()->update($fileObject);
1619 }
1620 $returnObject = $this->getFolder($fileMappings[$folderToMove->getIdentifier()]);
1621 $this->emitPostFolderMoveSignal($folderToMove, $targetParentFolder, $newFolderName);
1622 return $returnObject;
1623 }
1624
1625 /**
1626 * Moves the given folder from a different storage to the target folder in this storage.
1627 *
1628 * @param Folder $folderToMove
1629 * @param Folder $targetParentFolder
1630 * @param string $newFolderName
1631 *
1632 * @return boolean
1633 */
1634 protected function moveFolderBetweenStorages(Folder $folderToMove, Folder $targetParentFolder, $newFolderName) {
1635 return $this->getDriver()->moveFolderBetweenStorages($folderToMove, $targetParentFolder, $newFolderName);
1636 }
1637
1638 /**
1639 * Copy folder
1640 *
1641 * @param FolderInterface $folderToCopy The folder to copy
1642 * @param FolderInterface $targetParentFolder The target folder
1643 * @param string $newFolderName
1644 * @param string $conflictMode "overrideExistingFolder", "renameNewFolder", "cancel
1645 * @return Folder The new (copied) folder object
1646 */
1647 public function copyFolder(FolderInterface $folderToCopy, FolderInterface $targetParentFolder, $newFolderName = NULL, $conflictMode = 'renameNewFolder') {
1648 // TODO implement the $conflictMode handling
1649 $this->assureFolderCopyPermissions($folderToCopy, $targetParentFolder);
1650 $returnObject = NULL;
1651 $newFolderName = $newFolderName ? $newFolderName : $folderToCopy->getName();
1652 $this->emitPreFolderCopySignal($folderToCopy, $targetParentFolder, $newFolderName);
1653 $sourceStorage = $folderToCopy->getStorage();
1654 // call driver method to move the file
1655 // that also updates the file object properties
1656 try {
1657 if ($sourceStorage === $this) {
1658 $this->driver->copyFolderWithinStorage($folderToCopy, $targetParentFolder, $newFolderName);
1659 $returnObject = $this->getFolder($targetParentFolder->getSubfolder($newFolderName)->getIdentifier());
1660 } else {
1661 $this->copyFolderBetweenStorages($folderToCopy, $targetParentFolder, $newFolderName);
1662 }
1663 } catch (\TYPO3\CMS\Core\Exception $e) {
1664 echo $e->getMessage();
1665 }
1666 $this->emitPostFolderCopySignal($folderToCopy, $targetParentFolder, $newFolderName);
1667 return $returnObject;
1668 }
1669
1670 /**
1671 * Copy folders between storages
1672 *
1673 * @param Folder $folderToCopy
1674 * @param Folder $targetParentFolder
1675 * @param string $newFolderName
1676 *
1677 * @return boolean
1678 */
1679 protected function copyFolderBetweenStorages(Folder $folderToCopy, Folder $targetParentFolder, $newFolderName) {
1680 return $this->getDriver()->copyFolderBetweenStorages($folderToCopy, $targetParentFolder, $newFolderName);
1681 }
1682
1683 /**
1684 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::folder_move()
1685 *
1686 * @param Folder $folderObject
1687 * @param string $newName
1688 * @throws \Exception
1689 * @throws \InvalidArgumentException
1690 * @return Folder
1691 */
1692 public function renameFolder($folderObject, $newName) {
1693 // TODO unit tests
1694
1695 // Renaming the folder should check if the parent folder is writable
1696 // We cannot do this however because we cannot extract the parent folder from a folder currently
1697 if (!$this->checkFolderActionPermission('rename', $folderObject)) {
1698 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException('You are not allowed to rename the folder "' . $folderObject->getIdentifier() . '\'', 1357811441);
1699 }
1700
1701 $returnObject = NULL;
1702 if ($this->driver->folderExistsInFolder($newName, $folderObject)) {
1703 throw new \InvalidArgumentException('The folder ' . $newName . ' already exists in folder ' . $folderObject->getIdentifier(), 1325418870);
1704 }
1705
1706 $this->emitPreFolderRenameSignal($folderObject, $newName);
1707
1708 $fileObjects = $this->getAllFileObjectsInFolder($folderObject);
1709 $fileMappings = $this->driver->renameFolder($folderObject, $newName);
1710 // Update the identifier of all file objects
1711 foreach ($fileObjects as $oldIdentifier => $fileObject) {
1712 $newIdentifier = $fileMappings[$oldIdentifier];
1713 $fileObject->updateProperties(array('identifier' => $newIdentifier));
1714 $this->getFileRepository()->update($fileObject);
1715 }
1716 $returnObject = $this->getFolder($fileMappings[$folderObject->getIdentifier()]);
1717
1718 $this->emitPostFolderRenameSignal($folderObject, $newName);
1719
1720 return $returnObject;
1721 }
1722
1723 /**
1724 * Previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::folder_delete()
1725 *
1726 * @param Folder $folderObject
1727 * @param boolean $deleteRecursively
1728 * @throws \RuntimeException
1729 * @return boolean
1730 */
1731 public function deleteFolder($folderObject, $deleteRecursively = FALSE) {
1732 $isEmpty = $this->driver->isFolderEmpty($folderObject);
1733 $this->assureFolderDeletePermission($folderObject, ($deleteRecursively && !$isEmpty));
1734 if (!$isEmpty && !$deleteRecursively) {
1735 throw new \RuntimeException('Could not delete folder "' . $folderObject->getIdentifier() . '" because it is not empty.', 1325952534);
1736 }
1737
1738 $this->emitPreFolderDeleteSignal($folderObject);
1739
1740 $result = $this->driver->deleteFolder($folderObject, $deleteRecursively);
1741
1742 $this->emitPostFolderDeleteSignal($folderObject);
1743
1744 return $result;
1745 }
1746
1747 /**
1748 * Returns a list of folders in a given path.
1749 *
1750 * @param string $path The path to list
1751 * @param integer $start The position to start the listing; if not set or 0, start from the beginning
1752 * @param integer $numberOfItems The number of items to list; if not set, return all items
1753 * @param boolean $useFilters If FALSE, the list is returned without any filtering; otherwise, the filters defined for this storage are used.
1754 * @return array Information about the folders found.
1755 */
1756 public function getFolderList($path, $start = 0, $numberOfItems = 0, $useFilters = TRUE) {
1757 // Permissions are checked in $this->fetchFolderListFromDriver()
1758 $filters = $useFilters === TRUE ? $this->fileAndFolderNameFilters : array();
1759 return $this->fetchFolderListFromDriver($path, $start, $numberOfItems, $filters);
1760 }
1761
1762 /**
1763 * @param $path
1764 * @param integer $start
1765 * @param integer $numberOfItems
1766 * @param array $folderFilterCallbacks
1767 * @param boolean $recursive
1768 * @return array
1769 */
1770 public function fetchFolderListFromDriver($path, $start = 0, $numberOfItems = 0, array $folderFilterCallbacks = array(), $recursive = FALSE) {
1771 // This also checks for access to that path and throws exceptions accordingly
1772 if ($this->getFolder($path) === NULL) {
1773 return array();
1774 }
1775 $items = $this->driver->getFolderList($path, $start, $numberOfItems, $folderFilterCallbacks, $recursive);
1776 if (!empty($items)) {
1777 // Exclude the _processed_ folder, so it won't get indexed etc
1778 // The processed folder might be any sub folder in storage
1779 $processingFolder = $this->getProcessingFolder();
1780 if ($processingFolder) {
1781 $processedFolderIdentifier = $this->processingFolder->getIdentifier();
1782 $processedFolderIdentifier = trim($processedFolderIdentifier, '/');
1783 $processedFolderIdentifierParts = explode('/', $processedFolderIdentifier);
1784 $processedFolderName = array_pop($processedFolderIdentifierParts);
1785 $processedFolderParent = implode('/', $processedFolderIdentifierParts);
1786 if ($processedFolderParent === trim($path, '/') && isset($items[$processedFolderName])) {
1787 unset($items[$processedFolderName]);
1788 }
1789 }
1790 uksort($items, 'strnatcasecmp');
1791 }
1792 return $items;
1793 }
1794
1795 /**
1796 * Returns TRUE if the specified folder exists.
1797 *
1798 * @param string $identifier
1799 * @return boolean
1800 */
1801 public function hasFolder($identifier) {
1802 $this->assureFolderReadPermission();
1803 return $this->driver->folderExists($identifier);
1804 }
1805
1806 /**
1807 * Checks if the given file exists in the given folder
1808 *
1809 * @param string $folderName
1810 * @param Folder $folder
1811 * @return boolean
1812 */
1813 public function hasFolderInFolder($folderName, Folder $folder) {
1814 $this->assureFolderReadPermission($folder);
1815 return $this->driver->folderExistsInFolder($folderName, $folder);
1816 }
1817
1818 /**
1819 * Creates a new folder.
1820 *
1821 * previously in \TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::func_newfolder()
1822 *
1823 * @param string $folderName The new folder name
1824 * @param Folder $parentFolder (optional) the parent folder to create the new folder inside of. If not given, the root folder is used
1825 *
1826 * @throws Exception\InsufficientFolderWritePermissionsException
1827 * @throws \InvalidArgumentException
1828 * @return Folder The new folder object
1829 */
1830 public function createFolder($folderName, Folder $parentFolder = NULL) {
1831 if ($parentFolder === NULL) {
1832 $parentFolder = $this->getRootLevelFolder();
1833 }
1834 if (!$this->driver->folderExists($parentFolder->getIdentifier())) {
1835 throw new \InvalidArgumentException('Parent folder "' . $parentFolder->getIdentifier() . '" does not exist.', 1325689164);
1836 }
1837 if (!$this->checkFolderActionPermission('add', $parentFolder)) {
1838 throw new Exception\InsufficientFolderWritePermissionsException('You are not allowed to create directories in the folder "' . $parentFolder->getIdentifier() . '"', 1323059807);
1839 }
1840 // TODO this only works with hirachical file systems
1841 $folderParts = GeneralUtility::trimExplode('/', $folderName, TRUE);
1842 foreach ($folderParts as $folder) {
1843 // TODO check if folder creation succeeded
1844 if ($this->hasFolderInFolder($folder, $parentFolder)) {
1845 $parentFolder = $this->driver->getFolderInFolder($folder, $parentFolder);
1846 } else {
1847 $parentFolder = $this->driver->createFolder($folder, $parentFolder);
1848 }
1849 }
1850 return $parentFolder;
1851 }
1852
1853 /**
1854 * Returns the default folder where new files are stored if no other folder is given.
1855 *
1856 * @return Folder
1857 */
1858 public function getDefaultFolder() {
1859 return $this->driver->getDefaultFolder();
1860 }
1861
1862 /**
1863 * @param string $identifier
1864 *
1865 * @throws Exception\NotInMountPointException
1866 * @throws Exception\FolderDoesNotExistException
1867 * @return Folder
1868 */
1869 public function getFolder($identifier) {
1870 if (!$this->driver->folderExists($identifier)) {
1871 throw new Exception\FolderDoesNotExistException('Folder ' . $identifier . ' does not exist.', 1320575630);
1872 }
1873 $folder = $this->driver->getFolder($identifier);
1874 $this->assureFolderReadPermission($folder);
1875
1876 return $folder;
1877 }
1878
1879 /**
1880 * Returns the folders on the root level of the storage
1881 * or the first mount point of this storage for this user
1882 *
1883 * @return Folder
1884 */
1885 public function getRootLevelFolder() {
1886 if (count($this->fileMounts)) {
1887 $mount = reset($this->fileMounts);
1888 return $mount['folder'];
1889 } else {
1890 return $this->driver->getRootLevelFolder();
1891 }
1892 }
1893
1894 /**
1895 * Emits the configuration pre-processing signal
1896 *
1897 * @return void
1898 */
1899 protected function emitPreProcessConfigurationSignal() {
1900 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreProcessConfiguration, array($this));
1901 }
1902
1903 /**
1904 * Emits the configuration post-processing signal
1905 *
1906 * @return void
1907 */
1908 protected function emitPostProcessConfigurationSignal() {
1909 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostProcessConfiguration, array($this));
1910 }
1911
1912 /**
1913 * Emits file pre-copy signal
1914 *
1915 * @param FileInterface $file
1916 * @param Folder $targetFolder
1917 * @return void
1918 */
1919 protected function emitPreFileCopySignal(FileInterface $file, Folder $targetFolder) {
1920 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileCopy, array($file, $targetFolder));
1921 }
1922
1923 /**
1924 * Emits the file post-copy signal
1925 *
1926 * @param FileInterface $file
1927 * @param Folder $targetFolder
1928 * @return void
1929 */
1930 protected function emitPostFileCopySignal(FileInterface $file, Folder $targetFolder) {
1931 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileCopy, array($file, $targetFolder));
1932 }
1933
1934 /**
1935 * Emits the file pre-move signal
1936 *
1937 * @param FileInterface $file
1938 * @param Folder $targetFolder
1939 * @return void
1940 */
1941 protected function emitPreFileMoveSignal(FileInterface $file, Folder $targetFolder) {
1942 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileMove, array($file, $targetFolder));
1943 }
1944
1945 /**
1946 * Emits the file post-move signal
1947 *
1948 * @param FileInterface $file
1949 * @param Folder $targetFolder
1950 * @return void
1951 */
1952 protected function emitPostFileMoveSignal(FileInterface $file, Folder $targetFolder) {
1953 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileMove, array($file, $targetFolder));
1954 }
1955
1956 /**
1957 * Emits the file pre-rename signal
1958 *
1959 * @param FileInterface $file
1960 * @param $targetFolder
1961 * @return void
1962 */
1963 protected function emitPreFileRenameSignal(FileInterface $file, $targetFolder) {
1964 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileRename, array($file, $targetFolder));
1965 }
1966
1967 /**
1968 * Emits the file post-rename signal
1969 *
1970 * @param FileInterface $file
1971 * @param $targetFolder
1972 * @return void
1973 */
1974 protected function emitPostFileRenameSignal(FileInterface $file, $targetFolder) {
1975 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileRename, array($file, $targetFolder));
1976 }
1977
1978 /**
1979 * Emits the file pre-replace signal
1980 *
1981 * @param FileInterface $file
1982 * @param $localFilePath
1983 * @return void
1984 */
1985 protected function emitPreFileReplaceSignal(FileInterface $file, $localFilePath) {
1986 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileReplace, array($file, $localFilePath));
1987 }
1988
1989 /**
1990 * Emits the file post-replace signal
1991 *
1992 * @param FileInterface $file
1993 * @param $localFilePath
1994 * @return void
1995 */
1996 protected function emitPostFileReplaceSignal(FileInterface $file, $localFilePath) {
1997 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileReplace, array($file, $localFilePath));
1998 }
1999
2000 /**
2001 * Emits the file pre-deletion signal
2002 *
2003 * @param FileInterface $file
2004 * @return void
2005 */
2006 protected function emitPreFileDeleteSignal(FileInterface $file) {
2007 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileDelete, array($file));
2008 }
2009
2010 /**
2011 * Emits the file post-deletion signal
2012 *
2013 * @param FileInterface $file
2014 * @return void
2015 */
2016 protected function emitPostFileDeleteSignal(FileInterface $file) {
2017 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileDelete, array($file));
2018 }
2019
2020 /**
2021 * Emits the folder pre-copy signal
2022 *
2023 * @param Folder $folder
2024 * @param Folder $targetFolder
2025 * @param $newName
2026 * @return void
2027 */
2028 protected function emitPreFolderCopySignal(Folder $folder, Folder $targetFolder, $newName) {
2029 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PreFolderCopy, array($folder, $targetFolder));
2030 }
2031
2032 /**
2033 * Emits the folder post-copy signal
2034 *
2035 * @param Folder $folder
2036 * @param Folder $targetFolder
2037 * @param $newName
2038 * @return void
2039 */
2040 protected function emitPostFolderCopySignal(Folder $folder, Folder $targetFolder, $newName) {
2041 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PostFolderCopy, array($folder, $targetFolder));
2042 }
2043
2044 /**
2045 * Emits the folder pre-move signal
2046 *
2047 * @param Folder $folder
2048 * @param Folder $targetFolder
2049 * @param $newName
2050 * @return void
2051 */
2052 protected function emitPreFolderMoveSignal(Folder $folder, Folder $targetFolder, $newName) {
2053 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PreFolderMove, array($folder, $targetFolder));
2054 }
2055
2056 /**
2057 * Emits the folder post-move signal
2058 *
2059 * @param Folder $folder
2060 * @param Folder $targetFolder
2061 * @param $newName
2062 * @return void
2063 */
2064 protected function emitPostFolderMoveSignal(Folder $folder, Folder $targetFolder, $newName) {
2065 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PostFolderMove, array($folder, $targetFolder));
2066 }
2067
2068 /**
2069 * Emits the folder pre-rename signal
2070 *
2071 * @param Folder $folder
2072 * @param $newName
2073 * @return void
2074 */
2075 protected function emitPreFolderRenameSignal(Folder $folder, $newName) {
2076 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PreFolderRename, array($folder, $newName));
2077 }
2078
2079 /**
2080 * Emits the folder post-rename signal
2081 *
2082 * @param Folder $folder
2083 * @param $newName
2084 * @return void
2085 */
2086 protected function emitPostFolderRenameSignal(Folder $folder, $newName) {
2087 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PostFolderRename, array($folder, $newName));
2088 }
2089
2090 /**
2091 * Emits the folder pre-deletion signal
2092 *
2093 * @param Folder $folder
2094 * @return void
2095 */
2096 protected function emitPreFolderDeleteSignal(Folder $folder) {
2097 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PreFolderDelete, array($folder));
2098 }
2099
2100 /**
2101 * Emits folder postdeletion signal.
2102 *
2103 * @param Folder $folder
2104 * @return void
2105 */
2106 protected function emitPostFolderDeleteSignal(Folder $folder) {
2107 $this->getSignalSlotDispatcher()->dispatch('ResourceStorage', self::SIGNAL_PostFolderDelete, array($folder));
2108 }
2109
2110 /**
2111 * Emits file pre-processing signal when generating a public url for a file or folder.
2112 *
2113 * @param ResourceInterface $resourceObject
2114 * @param boolean $relativeToCurrentScript
2115 * @param array $urlData
2116 */
2117 protected function emitPreGeneratePublicUrl(ResourceInterface $resourceObject, $relativeToCurrentScript, array $urlData) {
2118 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreGeneratePublicUrl, array($this, $this->driver, $resourceObject, $relativeToCurrentScript, $urlData));
2119 }
2120
2121 /**
2122 * Returns the destination path/fileName of a unique fileName/foldername in that path.
2123 * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended.
2124 * This function is used by fx. TCEmain when files are attached to records and needs to be uniquely named in the uploads/* folders
2125 *
2126 * @param Folder $folder
2127 * @param string $theFile The input fileName to check
2128 * @param boolean $dontCheckForUnique If set the fileName is returned with the path prepended without checking whether it already existed!
2129 *
2130 * @throws \RuntimeException
2131 * @return string A unique fileName inside $folder, based on $theFile.
2132 * @see \TYPO3\CMS\Core\Utility\File\BasicFileUtility::getUniqueName()
2133 */
2134 // TODO check if this should be moved back to Folder
2135 protected function getUniqueName(Folder $folder, $theFile, $dontCheckForUnique = FALSE) {
2136 static $maxNumber = 99, $uniqueNamePrefix = '';
2137 // Fetches info about path, name, extention of $theFile
2138 $origFileInfo = GeneralUtility::split_fileref($theFile);
2139 // Adds prefix
2140 if ($uniqueNamePrefix) {
2141 $origFileInfo['file'] = $uniqueNamePrefix . $origFileInfo['file'];
2142 $origFileInfo['filebody'] = $uniqueNamePrefix . $origFileInfo['filebody'];
2143 }
2144 // Check if the file exists and if not - return the fileName...
2145 $fileInfo = $origFileInfo;
2146 // The destinations file
2147 $theDestFile = $fileInfo['file'];
2148 // If the file does NOT exist we return this fileName
2149 if (!$this->driver->fileExistsInFolder($theDestFile, $folder) || $dontCheckForUnique) {
2150 return $theDestFile;
2151 }
2152 // Well the fileName in its pure form existed. Now we try to append
2153 // numbers / unique-strings and see if we can find an available fileName
2154 // This removes _xx if appended to the file
2155 $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']);
2156 $theOrigExt = $origFileInfo['realFileext'] ? '.' . $origFileInfo['realFileext'] : '';
2157 for ($a = 1; $a <= $maxNumber + 1; $a++) {
2158 // First we try to append numbers
2159 if ($a <= $maxNumber) {
2160 $insert = '_' . sprintf('%02d', $a);
2161 } else {
2162 // TODO remove constant 6
2163 $insert = '_' . substr(md5(uniqId('')), 0, 6);
2164 }
2165 $theTestFile = $theTempFileBody . $insert . $theOrigExt;
2166 // The destinations file
2167 $theDestFile = $theTestFile;
2168 // If the file does NOT exist we return this fileName
2169 if (!$this->driver->fileExistsInFolder($theDestFile, $folder)) {
2170 return $theDestFile;
2171 }
2172 }
2173 throw new \RuntimeException('Last possible name "' . $theDestFile . '" is already taken.', 1325194291);
2174 }
2175
2176 /**
2177 * Get the SignalSlot dispatcher
2178 *
2179 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
2180 */
2181 protected function getSignalSlotDispatcher() {
2182 if (!isset($this->signalSlotDispatcher)) {
2183 $this->signalSlotDispatcher = $this->getObjectManager()->get('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
2184 }
2185 return $this->signalSlotDispatcher;
2186 }
2187
2188 /**
2189 * Get the ObjectManager
2190 *
2191 * @return \TYPO3\CMS\Extbase\Object\ObjectManager
2192 */
2193 protected function getObjectManager() {
2194 return GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
2195 }
2196
2197 /**
2198 * @return ResourceFactory
2199 */
2200 protected function getFileFactory() {
2201 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\ResourceFactory');
2202 }
2203
2204 /**
2205 * @return \TYPO3\CMS\Core\Resource\FileRepository
2206 */
2207 protected function getFileRepository() {
2208 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\FileRepository');
2209 }
2210
2211 /**
2212 * @return Service\FileProcessingService
2213 */
2214 protected function getFileProcessingService() {
2215 if (!$this->fileProcessingService) {
2216 $this->fileProcessingService = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Service\\FileProcessingService', $this, $this->driver);
2217 }
2218 return $this->fileProcessingService;
2219 }
2220
2221 /**
2222 * Gets the role of a folder
2223 *
2224 * @param FolderInterface $folder Folder object to get the role from
2225 * @return string The role the folder has
2226 */
2227 public function getRole(FolderInterface $folder) {
2228 $folderRole = FolderInterface::ROLE_DEFAULT;
2229
2230 if (method_exists($this->driver, 'getRole')) {
2231 $folderRole = $this->driver->getRole($folder);
2232 }
2233
2234 if ($folder->getIdentifier() === $this->getProcessingFolder()->getIdentifier()) {
2235 $folderRole = FolderInterface::ROLE_PROCESSING;
2236 }
2237
2238 return $folderRole;
2239 }
2240
2241 /**
2242 * Getter function to return the folder where the files can
2243 * be processed. does not check for access rights here
2244 *
2245 * @todo check if we need to implement "is writable" capability
2246 * @return Folder the processing folder, can be empty as well, if the storage doesn't have a processing folder
2247 */
2248 public function getProcessingFolder() {
2249 if (!isset($this->processingFolder)) {
2250 $processingFolder = self::DEFAULT_ProcessingFolder;
2251 if (!empty($this->storageRecord['processingfolder'])) {
2252 $processingFolder = $this->storageRecord['processingfolder'];
2253 }
2254 $processingFolder = '/' . trim($processingFolder, '/') . '/';
2255 // this way, we also worry about deeplinked folders like typo3temp/_processed_
2256 if ($this->driver->folderExists($processingFolder) === FALSE) {
2257 $processingFolderParts = explode('/', $processingFolder);
2258 $parentFolder = $this->driver->getRootLevelFolder();
2259 foreach ($processingFolderParts as $folderPart) {
2260 if ($folderPart === '') {
2261 continue;
2262 }
2263 if (!$this->driver->folderExistsInFolder($folderPart, $parentFolder)) {
2264 $parentFolder = $this->driver->createFolder($folderPart, $parentFolder);
2265 } else {
2266 $parentFolder = $parentFolder->getSubfolder($folderPart);
2267 }
2268 }
2269 }
2270 $this->processingFolder = $this->driver->getFolder($processingFolder);
2271 }
2272 return $this->processingFolder;
2273 }
2274 }
2275
2276 ?>