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