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