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