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