c0e8ce6e70aa871063500545f39e41b0fb759b86
[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 * @return array Information about the files found.
854 */
855 // TODO check if we should use a folder object instead of $path
856 // TODO add unit test for $loadIndexRecords
857 public function getFileList($path, $start = 0, $numberOfItems = 0, $useFilters = TRUE, $loadIndexRecords = TRUE) {
858 $rows = array();
859 if ($loadIndexRecords) {
860 /** @var $repository \TYPO3\CMS\Core\Resource\FileRepository */
861 $repository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\FileRepository');
862 $rows = $repository->getFileIndexRecordsForFolder($this->getFolder($path));
863 }
864 $filters = $useFilters == TRUE ? $this->fileAndFolderNameFilters : array();
865 $items = $this->driver->getFileList($path, $start, $numberOfItems, $filters, $rows);
866 uksort($items, 'strnatcasecmp');
867 return $items;
868 }
869
870 /**
871 * Returns TRUE if the specified file exists.
872 *
873 * @param string $identifier
874 * @return boolean
875 */
876 public function hasFile($identifier) {
877 // @todo: access check?
878 return $this->driver->fileExists($identifier);
879 }
880
881 /**
882 * Checks if the queried file in the given folder exists.
883 *
884 * @param string $fileName
885 * @param \TYPO3\CMS\Core\Resource\Folder $folder
886 * @return boolean
887 */
888 public function hasFileInFolder($fileName, \TYPO3\CMS\Core\Resource\Folder $folder) {
889 return $this->driver->fileExistsInFolder($fileName, $folder);
890 }
891
892 /**
893 * Get contents of a file object
894 *
895 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
896 * @return string
897 */
898 public function getFileContents($file) {
899 // Check if $file is readable
900 if (!$this->checkFileActionPermission('read', $file)) {
901 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileReadPermissionsException('Reading file "' . $file->getIdentifier() . '" is not allowed.', 1330121089);
902 }
903 return $this->driver->getFileContents($file);
904 }
905
906 /**
907 * Set contents of a file object.
908 *
909 * @param \TYPO3\CMS\Core\Resource\AbstractFile $file
910 * @param string $contents
911 * @return integer The number of bytes written to the file
912 * @throws \RuntimeException
913 * @throws Exception\InsufficientFileWritePermissionsException
914 * @throws Exception\InsufficientUserPermissionsException
915 */
916 public function setFileContents(\TYPO3\CMS\Core\Resource\AbstractFile $file, $contents) {
917 // Check if user is allowed to edit
918 if (!$this->checkUserActionPermission('edit', 'File')) {
919 throw new Exception\InsufficientUserPermissionsException(('Updating file "' . $file->getIdentifier()) . '" not allowed for user.', 1330121117);
920 }
921 // Check if $file is writable
922 if (!$this->checkFileActionPermission('write', $file)) {
923 throw new Exception\InsufficientFileWritePermissionsException('Writing to file "' . $file->getIdentifier() . '" is not allowed.', 1330121088);
924 }
925 // Call driver method to update the file and update file properties afterwards
926 try {
927 $result = $this->driver->setFileContents($file, $contents);
928 $fileInfo = $this->driver->getFileInfo($file);
929 $fileInfo['sha1'] = $this->driver->hash($file, 'sha1');
930 $file->updateProperties($fileInfo);
931 } catch (\RuntimeException $e) {
932 throw $e;
933 }
934 return $result;
935 }
936
937 /**
938 * Creates a new file
939 *
940 * previously in t3lib_extFileFunc::func_newfile()
941 *
942 * @param string $fileName
943 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolderObject
944 * @return \TYPO3\CMS\Core\Resource\FileInterface The file object
945 */
946 public function createFile($fileName, \TYPO3\CMS\Core\Resource\Folder $targetFolderObject) {
947 if (!$this->checkFolderActionPermission('add', $targetFolderObject)) {
948 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException('You are not allowed to create directories on this storage "' . $targetFolderObject->getIdentifier() . '"', 1323059807);
949 }
950 return $this->driver->createFile($fileName, $targetFolderObject);
951 }
952
953 /**
954 * Previously in t3lib_extFileFunc::deleteFile()
955 *
956 * @param $fileObject \TYPO3\CMS\Core\Resource\FileInterface
957 * @return bool TRUE if deletion succeeded
958 */
959 public function deleteFile($fileObject) {
960 if (!$this->checkFileActionPermission('remove', $fileObject)) {
961 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException('You are not allowed to delete the file "' . $fileObject->getIdentifier() . '\'', 1319550425);
962 }
963 $result = $this->driver->deleteFile($fileObject);
964 if ($result === FALSE) {
965 throw new \TYPO3\CMS\Core\Resource\Exception\FileOperationErrorException('Deleting the file "' . $fileObject->getIdentifier() . '\' failed.', 1329831691);
966 }
967 // Mark the file object as deleted
968 $fileObject->setDeleted();
969 return TRUE;
970 }
971
972 /**
973 * Previously in t3lib_extFileFunc::func_copy()
974 * copies a source file (from any location) in to the target
975 * folder, the latter has to be part of this storage
976 *
977 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
978 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
979 * @param string $conflictMode "overrideExistingFile", "renameNewFile", "cancel
980 * @param string $targetFileName an optional destination fileName
981 * @return \TYPO3\CMS\Core\Resource\FileInterface
982 */
983 public function copyFile(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $targetFileName = NULL, $conflictMode = 'renameNewFile') {
984 $this->emitPreFileCopySignal($file, $targetFolder);
985 $this->checkFileCopyPermissions($file, $targetFolder, $targetFileName);
986 if ($targetFileName === NULL) {
987 $targetFileName = $file->getName();
988 }
989 // File exists and we should abort, let's abort
990 if ($conflictMode === 'cancel' && $targetFolder->hasFile($targetFileName)) {
991 throw new \TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException('The target file already exists.', 1320291063);
992 }
993 // File exists and we should find another name, let's find another one
994 if ($conflictMode === 'renameNewFile' && $targetFolder->hasFile($targetFileName)) {
995 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
996 }
997 $sourceStorage = $file->getStorage();
998 // Call driver method to create a new file from an existing file object,
999 // and return the new file object
1000 try {
1001 if ($sourceStorage == $this) {
1002 $newFileObject = $this->driver->copyFileWithinStorage($file, $targetFolder, $targetFileName);
1003 } else {
1004 $tempPath = $file->getForLocalProcessing();
1005 $newFileObject = $this->driver->addFile($tempPath, $targetFolder, $targetFileName);
1006 }
1007 } catch (\TYPO3\CMS\Core\Resource\Exception\AbstractFileOperationException $e) {
1008 throw $e;
1009 }
1010 $this->emitPostFileCopySignal($file, $targetFolder);
1011 return $newFileObject;
1012 }
1013
1014 /**
1015 * Check if a file has the permission to be uploaded to a Folder/Storage,
1016 * if not throw an exception
1017 *
1018 * @param string $localFilePath the temporary file name from $_FILES['file1']['tmp_name']
1019 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1020 * @param string $targetFileName the destination file name $_FILES['file1']['name']
1021 * @param int $uploadedFileSize
1022 * @return void
1023 */
1024 protected function checkFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileSize) {
1025 // Makes sure the user is allowed to upload
1026 if (!$this->checkUserActionPermission('upload', 'File')) {
1027 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException('You are not allowed to upload files to this storage "' . $this->getUid() . '"', 1322112430);
1028 }
1029 // Makes sure this is an uploaded file
1030 if (!is_uploaded_file($localFilePath)) {
1031 throw new \TYPO3\CMS\Core\Resource\Exception\UploadException('The upload has failed, no uploaded file found!', 1322110455);
1032 }
1033 // Max upload size (kb) for files.
1034 $maxUploadFileSize = \TYPO3\CMS\Core\Utility\GeneralUtility::getMaxUploadFileSize() * 1024;
1035 if ($uploadedFileSize >= $maxUploadFileSize) {
1036 throw new \TYPO3\CMS\Core\Resource\Exception\UploadSizeException('The uploaded file exceeds the size-limit of ' . $maxUploadFileSize . ' bytes', 1322110041);
1037 }
1038 // Check if targetFolder is writable
1039 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
1040 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1322120356);
1041 }
1042 // Check for a valid file extension
1043 if (!$this->checkFileExtensionPermission($targetFileName)) {
1044 throw new \TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1322120271);
1045 }
1046 }
1047
1048 /**
1049 * Check if a file has the permission to be copied on a File/Folder/Storage,
1050 * if not throw an exception
1051 *
1052 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1053 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1054 * @param string $targetFileName
1055 * @return void
1056 */
1057 protected function checkFileCopyPermissions(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $targetFileName) {
1058 // Check if targetFolder is within this storage, this should never happen
1059 if ($this->getUid() != $targetFolder->getStorage()->getUid()) {
1060 throw new \TYPO3\CMS\Core\Resource\Exception('The operation of the folder cannot be called by this storage "' . $this->getUid() . '"', 1319550405);
1061 }
1062 // Check if user is allowed to copy
1063 if (!$this->checkUserActionPermission('copy', 'File')) {
1064 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException('You are not allowed to copy files to this storage "' . $this->getUid() . '"', 1319550415);
1065 }
1066 // Check if $file is readable
1067 if (!$this->checkFileActionPermission('read', $file)) {
1068 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileReadPermissionsException('You are not allowed to read the file "' . $file->getIdentifier() . '\'', 1319550425);
1069 }
1070 // Check if targetFolder is writable
1071 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
1072 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319550435);
1073 }
1074 // Check for a valid file extension
1075 if (!$this->checkFileExtensionPermission($targetFileName)) {
1076 throw new \TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException('You are not allowed to copy a file of that type.', 1319553317);
1077 }
1078 }
1079
1080 /**
1081 * Moves a $file into a $targetFolder
1082 * the target folder has to be part of this storage
1083 *
1084 * previously in t3lib_extFileFunc::func_move()
1085 *
1086 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1087 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1088 * @param string $conflictMode "overrideExistingFile", "renameNewFile", "cancel
1089 * @param string $targetFileName an optional destination fileName
1090 * @return \TYPO3\CMS\Core\Resource\FileInterface
1091 */
1092 public function moveFile($file, $targetFolder, $targetFileName = NULL, $conflictMode = 'renameNewFile') {
1093 $this->checkFileMovePermissions($file, $targetFolder);
1094 if ($targetFileName === NULL) {
1095 $targetFileName = $file->getName();
1096 }
1097 if ($targetFolder->hasFile($targetFileName)) {
1098 // File exists and we should abort, let's abort
1099 if ($conflictMode === 'renameNewFile') {
1100 $targetFileName = $this->getUniqueName($targetFolder, $targetFileName);
1101 } elseif ($conflictMode === 'cancel') {
1102 throw new \TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException('The target file already exists', 1329850997);
1103 }
1104 }
1105 $this->emitPreFileMoveSignal($file, $targetFolder);
1106 $sourceStorage = $file->getStorage();
1107 // Call driver method to move the file that also updates the file
1108 // object properties
1109 try {
1110 if ($sourceStorage == $this) {
1111 $newIdentifier = $this->driver->moveFileWithinStorage($file, $targetFolder, $targetFileName);
1112 $this->updateFile($file, $newIdentifier);
1113 } else {
1114 $tempPath = $file->getForLocalProcessing();
1115 $newIdentifier = $this->driver->addFileRaw($tempPath, $targetFolder, $targetFileName);
1116 $sourceStorage->driver->deleteFileRaw($file->getIdentifier());
1117 $this->updateFile($file, $newIdentifier, $this);
1118 }
1119 } catch (\TYPO3\CMS\Core\Exception $e) {
1120 echo $e->getMessage();
1121 }
1122 $this->emitPostFileMoveSignal($file, $targetFolder);
1123 return $file;
1124 }
1125
1126 /**
1127 * Updates the properties of a file object with some that are freshly
1128 * fetched from the driver.
1129 *
1130 * @param \TYPO3\CMS\Core\Resource\AbstractFile $file
1131 * @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)
1132 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
1133 * @return void
1134 */
1135 protected function updateFile(\TYPO3\CMS\Core\Resource\AbstractFile $file, $identifier = '', $storage = NULL) {
1136 if ($identifier === '') {
1137 $identifier = $file->getIdentifier();
1138 }
1139 $fileInfo = $this->driver->getFileInfoByIdentifier($identifier);
1140 // TODO extend mapping
1141 $newProperties = array(
1142 'storage' => $fileInfo['storage'],
1143 'identifier' => $fileInfo['identifier'],
1144 'tstamp' => $fileInfo['mtime'],
1145 'crdate' => $fileInfo['ctime'],
1146 'mime_type' => $fileInfo['mimetype'],
1147 'size' => $fileInfo['size'],
1148 'name' => $fileInfo['name']
1149 );
1150 if ($storage !== NULL) {
1151 $newProperties['storage'] = $storage->getUid();
1152 }
1153 $file->updateProperties($newProperties);
1154 /** @var $fileRepository \TYPO3\CMS\Core\Resource\FileRepository */
1155 $fileRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\FileRepository');
1156 $fileRepository->update($file);
1157 }
1158
1159 /**
1160 * Checks for permissions to move a file.
1161 *
1162 * @throws \RuntimeException
1163 * @throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFileReadPermissionsException
1164 * @throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFileWritePermissionsException
1165 * @throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException
1166 * @throws \TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException
1167 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1168 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1169 * @return void
1170 */
1171 protected function checkFileMovePermissions(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder) {
1172 // Check if targetFolder is within this storage
1173 if ($this->getUid() != $targetFolder->getStorage()->getUid()) {
1174 throw new \RuntimeException();
1175 }
1176 // Check if user is allowed to move
1177 if (!$this->checkUserActionPermission('move', 'File')) {
1178 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException('You are not allowed to move files to storage "' . $this->getUid() . '"', 1319219349);
1179 }
1180 // Check if $file is readable
1181 if (!$this->checkFileActionPermission('read', $file)) {
1182 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileReadPermissionsException('You are not allowed to read the file "' . $file->getIdentifier() . '\'', 1319219349);
1183 }
1184 // Check if $file is writable
1185 if (!$this->checkFileActionPermission('write', $file)) {
1186 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileWritePermissionsException('You are not allowed to move the file "' . $file->getIdentifier() . '\'', 1319219349);
1187 }
1188 // Check if targetFolder is writable
1189 if (!$this->checkFolderActionPermission('write', $targetFolder)) {
1190 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException('You are not allowed to write to the target folder "' . $targetFolder->getIdentifier() . '"', 1319219349);
1191 }
1192 }
1193
1194 /**
1195 * Previously in t3lib_extFileFunc::func_rename()
1196 *
1197 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1198 * @param string $targetFileName
1199 * @return \TYPO3\CMS\Core\Resource\FileInterface
1200 */
1201 // TODO add $conflictMode setting
1202 public function renameFile($file, $targetFileName) {
1203 // The name should be different from the current.
1204 if ($file->getIdentifier() == $targetFileName) {
1205 return $file;
1206 }
1207 // Check if user is allowed to rename
1208 if (!$this->checkUserActionPermission('rename', 'File')) {
1209 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException('You are not allowed to rename files."', 1319219349);
1210 }
1211 // Check if $file is readable
1212 if (!$this->checkFileActionPermission('read', $file)) {
1213 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileReadPermissionsException('You are not allowed to read the file "' . $file->getIdentifier() . '\'', 1319219349);
1214 }
1215 // Check if $file is writable
1216 if (!$this->checkFileActionPermission('write', $file)) {
1217 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileWritePermissionsException('You are not allowed to rename the file "' . $file->getIdentifier() . '\'', 1319219349);
1218 }
1219 // Call driver method to rename the file that also updates the file
1220 // object properties
1221 try {
1222 $newIdentifier = $this->driver->renameFile($file, $targetFileName);
1223 $this->updateFile($file, $newIdentifier);
1224 /** @var $fileRepository \TYPO3\CMS\Core\Resource\FileRepository */
1225 $fileRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\FileRepository');
1226 $fileRepository->update($file);
1227 } catch (\RuntimeException $e) {
1228
1229 }
1230 return $file;
1231 }
1232
1233 /**
1234 * Replaces a file with a local file (e.g. a freshly uploaded file)
1235 *
1236 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1237 * @param string $localFilePath
1238 * @return \TYPO3\CMS\Core\Resource\FileInterface
1239 */
1240 public function replaceFile(\TYPO3\CMS\Core\Resource\FileInterface $file, $localFilePath) {
1241 if (!file_exists($localFilePath)) {
1242 throw new \InvalidArgumentException('File "' . $localFilePath . '" does not exist.', 1325842622);
1243 }
1244 // TODO check permissions
1245 $this->emitPreFileReplaceSignal($file, $localFilePath);
1246 $result = $this->driver->replaceFile($file, $localFilePath);
1247 $this->emitPostFileReplaceSignal($file, $localFilePath);
1248 return $result;
1249 }
1250
1251 /**
1252 * Adds an uploaded file into the Storage. Previously in t3lib_extFileFunc::file_upload()
1253 *
1254 * @param array $uploadedFileData contains information about the uploaded file given by $_FILES['file1']
1255 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder the target folder
1256 * @param string $targetFileName the file name to be written
1257 * @param string $conflictMode possible value are 'cancel', 'replace'
1258 * @return \TYPO3\CMS\Core\Resource\FileInterface The file object
1259 */
1260 public function addUploadedFile(array $uploadedFileData, \TYPO3\CMS\Core\Resource\Folder $targetFolder = NULL, $targetFileName = NULL, $conflictMode = 'cancel') {
1261 $localFilePath = $uploadedFileData['tmp_name'];
1262 if ($targetFolder === NULL) {
1263 $targetFolder = $this->getDefaultFolder();
1264 }
1265 if ($targetFileName === NULL) {
1266 $targetFileName = $uploadedFileData['name'];
1267 }
1268 // Handling $conflictMode is delegated to addFile()
1269 $this->checkFileUploadPermissions($localFilePath, $targetFolder, $targetFileName, $uploadedFileData['size']);
1270 $resultObject = $this->addFile($localFilePath, $targetFolder, $targetFileName, $conflictMode);
1271 return $resultObject;
1272 }
1273
1274 /********************
1275 * FOLDER ACTIONS
1276 ********************/
1277 /**
1278 * Returns an array with all file objects in a folder and its subfolders, with the file identifiers as keys.
1279 *
1280 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1281 * @return \TYPO3\CMS\Core\Resource\File[]
1282 */
1283 protected function getAllFileObjectsInFolder(\TYPO3\CMS\Core\Resource\Folder $folder) {
1284 $files = array();
1285 $folderQueue = array($folder);
1286 while (!empty($folderQueue)) {
1287 $folder = array_shift($folderQueue);
1288 foreach ($folder->getSubfolders() as $subfolder) {
1289 $folderQueue[] = $subfolder;
1290 }
1291 foreach ($folder->getFiles() as $file) {
1292 $files[$file->getIdentifier()] = $file;
1293 }
1294 }
1295 return $files;
1296 }
1297
1298 /**
1299 * Moves a folder. If you want to move a folder from this storage to another
1300 * one, call this method on the target storage, otherwise you will get an exception.
1301 *
1302 * @param \TYPO3\CMS\Core\Resource\Folder $folderToMove The folder to move.
1303 * @param \TYPO3\CMS\Core\Resource\Folder $targetParentFolder The target parent folder
1304 * @param string $newFolderName
1305 * @param string $conflictMode How to handle conflicts; one of "overrideExistingFile", "renameNewFolder", "cancel
1306 * @throws \TYPO3\CMS\Core\Exception
1307 * @throws \InvalidArgumentException
1308 * @return \TYPO3\CMS\Core\Resource\Folder
1309 */
1310 // TODO add tests
1311 public function moveFolder(\TYPO3\CMS\Core\Resource\Folder $folderToMove, \TYPO3\CMS\Core\Resource\Folder $targetParentFolder, $newFolderName = NULL, $conflictMode = 'renameNewFolder') {
1312 $sourceStorage = $folderToMove->getStorage();
1313 $returnObject = NULL;
1314 if (!$targetParentFolder->getStorage() == $this) {
1315 throw new \InvalidArgumentException('Cannot move a folder into a folder that does not belong to this storage.', 1325777289);
1316 }
1317 $newFolderName = $newFolderName ? $newFolderName : $folderToMove->getName();
1318 // TODO check if folder already exists in $targetParentFolder, handle this conflict then
1319 $this->emitPreFolderMoveSignal($folderToMove, $targetParentFolder, $newFolderName);
1320 // Get all file objects now so we are able to update them after moving the folder
1321 $fileObjects = $this->getAllFileObjectsInFolder($folderToMove);
1322 try {
1323 if ($sourceStorage == $this) {
1324 $fileMappings = $this->driver->moveFolderWithinStorage($folderToMove, $targetParentFolder, $newFolderName);
1325 } else {
1326 $fileMappings = $this->moveFolderBetweenStorages($folderToMove, $targetParentFolder, $newFolderName);
1327 }
1328 // Update the identifier and storage of all file objects
1329 foreach ($fileObjects as $oldIdentifier => $fileObject) {
1330 $newIdentifier = $fileMappings[$oldIdentifier];
1331 $fileObject->updateProperties(array('storage' => $this, 'identifier' => $newIdentifier));
1332 }
1333 $returnObject = $this->getFolder($fileMappings[$folderToMove->getIdentifier()]);
1334 } catch (\TYPO3\CMS\Core\Exception $e) {
1335 throw $e;
1336 }
1337 $this->emitPostFolderMoveSignal($folderToMove, $targetParentFolder, $newFolderName);
1338 return $returnObject;
1339 }
1340
1341 /**
1342 * Moves the given folder from a different storage to the target folder in this storage.
1343 *
1344 * @param \TYPO3\CMS\Core\Resource\Folder $folderToMove
1345 * @param \TYPO3\CMS\Core\Resource\Folder $targetParentFolder
1346 * @param string $newFolderName
1347 * @return array Mapping of old file identifiers to new ones
1348 */
1349 protected function moveFolderBetweenStorages(\TYPO3\CMS\Core\Resource\Folder $folderToMove, \TYPO3\CMS\Core\Resource\Folder $targetParentFolder, $newFolderName = NULL) {
1350 // This is not implemented for now as moving files between storages might cause quite some headaches when
1351 // something goes wrong. It is also not that common of a use case, so it does not hurt that much to leave it out
1352 // for now.
1353 throw new \BadMethodCallException('Moving folders between storages is not implemented.');
1354 }
1355
1356 /**
1357 * Copy folder
1358 *
1359 * @param \TYPO3\CMS\Core\Resource\Folder $folderToCopy The folder to copy
1360 * @param \TYPO3\CMS\Core\Resource\Folder $targetParentFolder The target folder
1361 * @param string $newFolderName
1362 * @param string $conflictMode "overrideExistingFolder", "renameNewFolder", "cancel
1363 * @return \TYPO3\CMS\Core\Resource\Folder The new (copied) folder object
1364 */
1365 public function copyFolder(\TYPO3\CMS\Core\Resource\Folder $folderToCopy, \TYPO3\CMS\Core\Resource\Folder $targetParentFolder, $newFolderName = NULL, $conflictMode = 'renameNewFolder') {
1366 // TODO implement the $conflictMode handling
1367 // TODO permission checks
1368 $returnObject = NULL;
1369 $newFolderName = $newFolderName ? $newFolderName : $folderToCopy->getName();
1370 $this->emitPreFolderCopySignal($folderToCopy, $targetParentFolder, $newFolderName);
1371 $sourceStorage = $folderToCopy->getStorage();
1372 // call driver method to move the file
1373 // that also updates the file object properties
1374 try {
1375 if ($sourceStorage == $this) {
1376 $this->driver->copyFolderWithinStorage($folderToCopy, $targetParentFolder, $newFolderName);
1377 $returnObject = $this->getFolder($targetParentFolder->getSubfolder($newFolderName)->getIdentifier());
1378 } else {
1379 $this->copyFolderBetweenStorages($folderToCopy, $targetParentFolder, $newFolderName);
1380 }
1381 } catch (\TYPO3\CMS\Core\Exception $e) {
1382 echo $e->getMessage();
1383 }
1384 $this->emitPostFolderCopySignal($folderToCopy, $targetParentFolder, $newFolderName);
1385 return $returnObject;
1386 }
1387
1388 /**
1389 * Moves files between storages
1390 *
1391 * @param \TYPO3\CMS\Core\Resource\Folder $folderToMove
1392 * @param \TYPO3\CMS\Core\Resource\Folder $targetParentFolder
1393 * @param null $newFolderName
1394 * @return void
1395 */
1396 protected function copyFolderBetweenStorages(\TYPO3\CMS\Core\Resource\Folder $folderToMove, \TYPO3\CMS\Core\Resource\Folder $targetParentFolder, $newFolderName = NULL) {
1397 throw new \RuntimeException('Not yet implemented!', 1330262731);
1398 }
1399
1400 /**
1401 * Previously in t3lib_extFileFunc::folder_move()
1402 *
1403 * @param \TYPO3\CMS\Core\Resource\Folder $folderObject
1404 * @param string $newName
1405 * @throws \Exception
1406 * @throws \InvalidArgumentException
1407 * @return \TYPO3\CMS\Core\Resource\Folder
1408 */
1409 public function renameFolder($folderObject, $newName) {
1410 // TODO unit tests
1411 // TODO access checks
1412 $returnObject = NULL;
1413 if ($this->driver->folderExistsInFolder($newName, $folderObject)) {
1414 throw new \InvalidArgumentException('The folder ' . $newName . ' already exists in folder ' . $folderObject->getIdentifier(), 1325418870);
1415 }
1416 $this->emitPreFolderRenameSignal($folderObject, $newName);
1417 $fileObjects = $this->getAllFileObjectsInFolder($folderObject);
1418 try {
1419 $fileMappings = $this->driver->renameFolder($folderObject, $newName);
1420 // Update the identifier of all file objects
1421 foreach ($fileObjects as $oldIdentifier => $fileObject) {
1422 $newIdentifier = $fileMappings[$oldIdentifier];
1423 $fileObject->updateProperties(array('identifier' => $newIdentifier));
1424 }
1425 $returnObject = $this->getFolder($fileMappings[$folderObject->getIdentifier()]);
1426 } catch (\Exception $e) {
1427 throw $e;
1428 }
1429 $this->emitPostFolderRenameSignal($folderObject, $newName);
1430 return $returnObject;
1431 }
1432
1433 /**
1434 * Previously in t3lib_extFileFunc::folder_delete()
1435 *
1436 * @param \TYPO3\CMS\Core\Resource\Folder $folderObject
1437 * @param bool $deleteRecursively
1438 * @throws \RuntimeException
1439 * @throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException
1440 * @return boolean
1441 */
1442 public function deleteFolder($folderObject, $deleteRecursively = FALSE) {
1443 if (!$this->checkFolderActionPermission('remove', $folderObject)) {
1444 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException('You are not allowed to access the folder "' . $folderObject->getIdentifier() . '\'', 1323423953);
1445 }
1446 if ($this->driver->isFolderEmpty($folderObject) && !$deleteRecursively) {
1447 throw new \RuntimeException('Could not delete folder "' . $folderObject->getIdentifier() . '" because it is not empty.', 1325952534);
1448 }
1449 $this->emitPreFolderDeleteSignal($folderObject);
1450 $result = $this->driver->deleteFolder($folderObject, $deleteRecursively);
1451 $this->emitPostFolderDeleteSignal($folderObject);
1452 return $result;
1453 }
1454
1455 /**
1456 * Returns a list of folders in a given path.
1457 *
1458 * @param string $path The path to list
1459 * @param integer $start The position to start the listing; if not set or 0, start from the beginning
1460 * @param integer $numberOfItems The number of items to list; if not set, return all items
1461 * @param boolean $useFilters If FALSE, the list is returned without any filtering; otherwise, the filters defined for this storage are used.
1462 * @return array Information about the folders found.
1463 */
1464 public function getFolderList($path, $start = 0, $numberOfItems = 0, $useFilters = TRUE) {
1465 $filters = $useFilters === TRUE ? $this->fileAndFolderNameFilters : array();
1466 return $this->fetchFolderListFromDriver($path, $start, $numberOfItems, $filters);
1467 }
1468
1469 /**
1470 * @param $path
1471 * @param int $start
1472 * @param int $numberOfItems
1473 * @param array $folderFilterCallbacks
1474 * @return array
1475 */
1476 public function fetchFolderListFromDriver($path, $start = 0, $numberOfItems = 0, array $folderFilterCallbacks = array()) {
1477 $items = $this->driver->getFolderList($path, $start, $numberOfItems, $folderFilterCallbacks);
1478 // Exclude the _processed_ folder, so it won't get indexed etc
1479 $processingFolder = $this->getProcessingFolder();
1480 if ($processingFolder && $path == '/') {
1481 $processedFolderIdentifier = $this->processingFolder->getIdentifier();
1482 $processedFolderIdentifier = trim($processedFolderIdentifier, '/');
1483 if (isset($items[$processedFolderIdentifier])) {
1484 unset($items[$processedFolderIdentifier]);
1485 }
1486 }
1487 uksort($items, 'strnatcasecmp');
1488 return $items;
1489 }
1490
1491 /**
1492 * Returns TRUE if the specified folder exists.
1493 *
1494 * @param string $identifier
1495 * @return boolean
1496 */
1497 public function hasFolder($identifier) {
1498 return $this->driver->folderExists($identifier);
1499 }
1500
1501 /**
1502 * Checks if the given file exists in the given folder
1503 *
1504 * @param string $folderName
1505 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1506 * @return boolean
1507 */
1508 public function hasFolderInFolder($folderName, \TYPO3\CMS\Core\Resource\Folder $folder) {
1509 return $this->driver->folderExistsInFolder($folderName, $folder);
1510 }
1511
1512 /**
1513 * Creates a new folder.
1514 *
1515 * previously in t3lib_extFileFunc::func_newfolder()
1516 *
1517 * @param string $folderName The new folder name
1518 * @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
1519 * @return \TYPO3\CMS\Core\Resource\Folder The new folder object
1520 */
1521 public function createFolder($folderName, \TYPO3\CMS\Core\Resource\Folder $parentFolder = NULL) {
1522 if ($parentFolder === NULL) {
1523 $parentFolder = $this->getRootLevelFolder();
1524 }
1525 if (!$this->driver->folderExists($parentFolder->getIdentifier())) {
1526 throw new \InvalidArgumentException('Parent folder "' . $parentFolder->getIdentifier() . '" does not exist.', 1325689164);
1527 }
1528 if (!$this->checkFolderActionPermission('add', $parentFolder)) {
1529 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException('You are not allowed to create directories in the folder "' . $parentFolder->getIdentifier() . '"', 1323059807);
1530 }
1531 $folderParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('/', $folderName, TRUE);
1532 foreach ($folderParts as $folder) {
1533 // TODO check if folder creation succeeded
1534 if ($this->hasFolderInFolder($folder, $parentFolder)) {
1535 $parentFolder = $this->driver->getFolderInFolder($folder, $parentFolder);
1536 } else {
1537 $parentFolder = $this->driver->createFolder($folder, $parentFolder);
1538 }
1539 }
1540 return $parentFolder;
1541 }
1542
1543 /**
1544 * Returns the default folder where new files are stored if no other folder is given.
1545 *
1546 * @return \TYPO3\CMS\Core\Resource\Folder
1547 */
1548 public function getDefaultFolder() {
1549 return $this->driver->getDefaultFolder();
1550 }
1551
1552 /**
1553 * @param string $identifier
1554 * @return \TYPO3\CMS\Core\Resource\Folder
1555 */
1556 public function getFolder($identifier) {
1557 if (!$this->driver->folderExists($identifier)) {
1558 throw new \TYPO3\CMS\Core\Resource\Exception\FolderDoesNotExistException('Folder ' . $identifier . ' does not exist.', 1320575630);
1559 }
1560 $folderObject = $this->driver->getFolder($identifier);
1561 if ($this->fileMounts && !$this->isWithinFileMountBoundaries($folderObject)) {
1562 throw new \TYPO3\CMS\Core\Resource\Exception\NotInMountPointException('Folder "' . $identifier . '" is not within your mount points.', 1330120649);
1563 } else {
1564 return $folderObject;
1565 }
1566 }
1567
1568 /**
1569 * Returns the folders on the root level of the storage
1570 * or the first mount point of this storage for this user
1571 *
1572 * @return \TYPO3\CMS\Core\Resource\Folder
1573 */
1574 public function getRootLevelFolder() {
1575 if (count($this->fileMounts)) {
1576 $mount = reset($this->fileMounts);
1577 return $mount['folder'];
1578 } else {
1579 return $this->driver->getRootLevelFolder();
1580 }
1581 }
1582
1583 /**
1584 * Emits the configuration pre-processing signal
1585 *
1586 * @return void
1587 */
1588 protected function emitPreProcessConfigurationSignal() {
1589 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreProcessConfiguration, array($this));
1590 }
1591
1592 /**
1593 * Emits the configuration post-processing signal
1594 *
1595 * @return void
1596 */
1597 protected function emitPostProcessConfigurationSignal() {
1598 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostProcessConfiguration, array($this));
1599 }
1600
1601 /**
1602 * Emits file pre-copy signal
1603 *
1604 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1605 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1606 * @return void
1607 */
1608 protected function emitPreFileCopySignal(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder) {
1609 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileCopy, array($file, $targetFolder));
1610 }
1611
1612 /**
1613 * Emits the file post-copy signal
1614 *
1615 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1616 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1617 * @return void
1618 */
1619 protected function emitPostFileCopySignal(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder) {
1620 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileCopy, array($file, $targetFolder));
1621 }
1622
1623 /**
1624 * Emits the file pre-move signal
1625 *
1626 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1627 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1628 * @return void
1629 */
1630 protected function emitPreFileMoveSignal(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder) {
1631 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileMove, array($file, $targetFolder));
1632 }
1633
1634 /**
1635 * Emits the file post-move signal
1636 *
1637 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1638 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1639 * @return void
1640 */
1641 protected function emitPostFileMoveSignal(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder) {
1642 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileMove, array($file, $targetFolder));
1643 }
1644
1645 /**
1646 * Emits the file pre-rename signal
1647 *
1648 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1649 * @param $targetFolder
1650 * @return void
1651 */
1652 protected function emitPreFileRenameSignal(\TYPO3\CMS\Core\Resource\FileInterface $file, $targetFolder) {
1653 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileRename, array($file, $targetFolder));
1654 }
1655
1656 /**
1657 * Emits the file post-rename signal
1658 *
1659 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1660 * @param $targetFolder
1661 * @return void
1662 */
1663 protected function emitPostFileRenameSignal(\TYPO3\CMS\Core\Resource\FileInterface $file, $targetFolder) {
1664 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileRename, array($file, $targetFolder));
1665 }
1666
1667 /**
1668 * Emits the file pre-replace signal
1669 *
1670 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1671 * @param $localFilePath
1672 * @return void
1673 */
1674 protected function emitPreFileReplaceSignal(\TYPO3\CMS\Core\Resource\FileInterface $file, $localFilePath) {
1675 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileReplace, array($file, $localFilePath));
1676 }
1677
1678 /**
1679 * Emits the file post-replace signal
1680 *
1681 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1682 * @param $localFilePath
1683 * @return void
1684 */
1685 protected function emitPostFileReplaceSignal(\TYPO3\CMS\Core\Resource\FileInterface $file, $localFilePath) {
1686 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileReplace, array($file, $localFilePath));
1687 }
1688
1689 /**
1690 * Emits the file pre-deletion signal
1691 *
1692 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1693 * @return void
1694 */
1695 protected function emitPreFileDeleteSignal(\TYPO3\CMS\Core\Resource\FileInterface $file) {
1696 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreFileDelete, array($file));
1697 }
1698
1699 /**
1700 * Emits the file post-deletion signal
1701 *
1702 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1703 * @return void
1704 */
1705 protected function emitPostFileDeleteSignal(\TYPO3\CMS\Core\Resource\FileInterface $file) {
1706 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PostFileDelete, array($file));
1707 }
1708
1709 /**
1710 * Emits the folder pre-copy signal
1711 *
1712 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1713 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1714 * @param $newName
1715 * @return void
1716 */
1717 protected function emitPreFolderCopySignal(\TYPO3\CMS\Core\Resource\Folder $folder, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $newName) {
1718 $this->getSignalSlotDispatcher()->dispatch('\TYPO3\CMS\Core\Resource\ResourceStorage', self::SIGNAL_PreFolderCopy, array($folder, $targetFolder));
1719 }
1720
1721 /**
1722 * Emits the folder post-copy signal
1723 *
1724 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1725 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1726 * @param $newName
1727 * @return void
1728 */
1729 protected function emitPostFolderCopySignal(\TYPO3\CMS\Core\Resource\Folder $folder, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $newName) {
1730 $this->getSignalSlotDispatcher()->dispatch('\TYPO3\CMS\Core\Resource\ResourceStorage', self::SIGNAL_PostFolderCopy, array($folder, $targetFolder));
1731 }
1732
1733 /**
1734 * Emits the folder pre-move signal
1735 *
1736 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1737 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1738 * @param $newName
1739 * @return void
1740 */
1741 protected function emitPreFolderMoveSignal(\TYPO3\CMS\Core\Resource\Folder $folder, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $newName) {
1742 $this->getSignalSlotDispatcher()->dispatch('\TYPO3\CMS\Core\Resource\ResourceStorage', self::SIGNAL_PreFolderMove, array($folder, $targetFolder));
1743 }
1744
1745 /**
1746 * Emits the folder post-move signal
1747 *
1748 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1749 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
1750 * @param $newName
1751 * @return void
1752 */
1753 protected function emitPostFolderMoveSignal(\TYPO3\CMS\Core\Resource\Folder $folder, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $newName) {
1754 $this->getSignalSlotDispatcher()->dispatch('\TYPO3\CMS\Core\Resource\ResourceStorage', self::SIGNAL_PostFolderMove, array($folder, $targetFolder));
1755 }
1756
1757 /**
1758 * Emits the folder pre-rename signal
1759 *
1760 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1761 * @param $newName
1762 * @return void
1763 */
1764 protected function emitPreFolderRenameSignal(\TYPO3\CMS\Core\Resource\Folder $folder, $newName) {
1765 $this->getSignalSlotDispatcher()->dispatch('\TYPO3\CMS\Core\Resource\ResourceStorage', self::SIGNAL_PreFolderRename, array($folder, $newName));
1766 }
1767
1768 /**
1769 * Emits the folder post-rename signal
1770 *
1771 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1772 * @param $newName
1773 * @return void
1774 */
1775 protected function emitPostFolderRenameSignal(\TYPO3\CMS\Core\Resource\Folder $folder, $newName) {
1776 $this->getSignalSlotDispatcher()->dispatch('\TYPO3\CMS\Core\Resource\ResourceStorage', self::SIGNAL_PostFolderRename, array($folder, $newName));
1777 }
1778
1779 /**
1780 * Emits the folder pre-deletion signal
1781 *
1782 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1783 * @return void
1784 */
1785 protected function emitPreFolderDeleteSignal(\TYPO3\CMS\Core\Resource\Folder $folder) {
1786 $this->getSignalSlotDispatcher()->dispatch('\TYPO3\CMS\Core\Resource\ResourceStorage', self::SIGNAL_PreFolderDelete, array($folder));
1787 }
1788
1789 /**
1790 * Emits folder postdeletion signal.
1791 *
1792 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1793 * @return void
1794 */
1795 protected function emitPostFolderDeleteSignal(\TYPO3\CMS\Core\Resource\Folder $folder) {
1796 $this->getSignalSlotDispatcher()->dispatch('\TYPO3\CMS\Core\Resource\ResourceStorage', self::SIGNAL_PostFolderDelete, array($folder));
1797 }
1798
1799 /**
1800 * Emits file pre-processing signal when generating a public url for a file or folder.
1801 *
1802 * @param \TYPO3\CMS\Core\Resource\ResourceInterface $resourceObject
1803 * @param boolean $relativeToCurrentScript
1804 * @param array $urlData
1805 */
1806 protected function emitPreGeneratePublicUrl(\TYPO3\CMS\Core\Resource\ResourceInterface $resourceObject, $relativeToCurrentScript, array $urlData) {
1807 $this->getSignalSlotDispatcher()->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceStorage', self::SIGNAL_PreGeneratePublicUrl, array($this, $this->driver, $resourceObject, $relativeToCurrentScript, $urlData));
1808 }
1809
1810 /**
1811 * Returns the destination path/fileName of a unique fileName/foldername in that path.
1812 * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended.
1813 * This function is used by fx. TCEmain when files are attached to records and needs to be uniquely named in the uploads/* folders
1814 *
1815 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1816 * @param string $theFile The input fileName to check
1817 * @param boolean $dontCheckForUnique If set the fileName is returned with the path prepended without checking whether it already existed!
1818 * @return string A unique fileName inside $folder, based on $theFile.
1819 * @see t3lib_basicFileFunc::getUniqueName()
1820 */
1821 // TODO check if this should be moved back to \TYPO3\CMS\Core\Resource\Folder
1822 protected function getUniqueName(\TYPO3\CMS\Core\Resource\Folder $folder, $theFile, $dontCheckForUnique = FALSE) {
1823 static $maxNumber = 99, $uniqueNamePrefix = '';
1824 // Fetches info about path, name, extention of $theFile
1825 $origFileInfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($theFile);
1826 // Adds prefix
1827 if ($uniqueNamePrefix) {
1828 $origFileInfo['file'] = $uniqueNamePrefix . $origFileInfo['file'];
1829 $origFileInfo['filebody'] = $uniqueNamePrefix . $origFileInfo['filebody'];
1830 }
1831 // Check if the file exists and if not - return the fileName...
1832 $fileInfo = $origFileInfo;
1833 // The destinations file
1834 $theDestFile = $fileInfo['file'];
1835 // If the file does NOT exist we return this fileName
1836 if (!$this->driver->fileExistsInFolder($theDestFile, $folder) || $dontCheckForUnique) {
1837 return $theDestFile;
1838 }
1839 // Well the fileName in its pure form existed. Now we try to append
1840 // numbers / unique-strings and see if we can find an available fileName
1841 // This removes _xx if appended to the file
1842 $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']);
1843 $theOrigExt = $origFileInfo['realFileext'] ? '.' . $origFileInfo['realFileext'] : '';
1844 for ($a = 1; $a <= $maxNumber + 1; $a++) {
1845 // First we try to append numbers
1846 if ($a <= $maxNumber) {
1847 $insert = '_' . sprintf('%02d', $a);
1848 } else {
1849 // TODO remove constant 6
1850 $insert = '_' . substr(md5(uniqId('')), 0, 6);
1851 }
1852 $theTestFile = $theTempFileBody . $insert . $theOrigExt;
1853 // The destinations file
1854 $theDestFile = $theTestFile;
1855 // If the file does NOT exist we return this fileName
1856 if (!$this->driver->fileExistsInFolder($theDestFile, $folder)) {
1857 return $theDestFile;
1858 }
1859 }
1860 throw new \RuntimeException('Last possible name "' . $theDestFile . '" is already taken.', 1325194291);
1861 }
1862
1863 /**
1864 * Get the SignalSlot dispatcher
1865 *
1866 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
1867 */
1868 protected function getSignalSlotDispatcher() {
1869 if (!isset($this->signalSlotDispatcher)) {
1870 $this->signalSlotDispatcher = $this->getObjectManager()->get('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
1871 }
1872 return $this->signalSlotDispatcher;
1873 }
1874
1875 /**
1876 * Get the ObjectManager
1877 *
1878 * @return \TYPO3\CMS\Extbase\Object\ObjectManager
1879 */
1880 protected function getObjectManager() {
1881 return \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
1882 }
1883
1884 /**
1885 * @return \TYPO3\CMS\Core\Resource\ResourceFactory
1886 */
1887 protected function getFileFactory() {
1888 return \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\ResourceFactory');
1889 }
1890
1891 /**
1892 * @return \TYPO3\CMS\Core\Resource\Service\FileProcessingService
1893 */
1894 protected function getFileProcessingService() {
1895 if (!$this->fileProcessingService) {
1896 $this->fileProcessingService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Service\\FileProcessingService', $this, $this->driver);
1897 }
1898 return $this->fileProcessingService;
1899 }
1900
1901 /**
1902 * Getter function to return the folder where the files can
1903 * be processed. does not check for access rights here
1904 *
1905 * @todo check if we need to implement "is writable" capability
1906 * @return \TYPO3\CMS\Core\Resource\Folder the processing folder, can be empty as well, if the storage doesn't have a processing folder
1907 */
1908 public function getProcessingFolder() {
1909 if (!isset($this->processingFolder)) {
1910 $processingFolder = self::DEFAULT_ProcessingFolder;
1911 if (!empty($this->storageRecord['processingfolder'])) {
1912 $processingFolder = $this->storageRecord['processingfolder'];
1913 }
1914 $processingFolder = '/' . trim($processingFolder, '/') . '/';
1915 // this way, we also worry about deeplinked folders like typo3temp/_processed_
1916 if ($this->driver->folderExists($processingFolder) === FALSE) {
1917 $processingFolderParts = explode('/', $processingFolder);
1918 $parentFolder = $this->driver->getRootLevelFolder();
1919 foreach ($processingFolderParts as $folderPart) {
1920 if (!$this->driver->folderExistsInFolder($folderPart, $parentFolder)) {
1921 $parentFolder = $this->driver->createFolder($folderPart, $parentFolder);
1922 } else {
1923 $parentFolder = $parentFolder->getSubfolder($folderPart);
1924 }
1925 }
1926 }
1927 $this->processingFolder = $this->driver->getFolder($processingFolder);
1928 }
1929 return $this->processingFolder;
1930 }
1931 }
1932
1933 ?>