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