ResourceStorage.php 119 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
15

16
17
namespace TYPO3\CMS\Core\Resource;

18
use Psr\EventDispatcher\EventDispatcherInterface;
19
use Psr\Http\Message\ResponseInterface;
20
use Psr\Http\Message\ServerRequestInterface;
21
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
22
use TYPO3\CMS\Core\Core\Environment;
23
use TYPO3\CMS\Core\Database\ConnectionPool;
24
use TYPO3\CMS\Core\Http\ApplicationType;
25
26
use TYPO3\CMS\Core\Http\FalDumpFileContentsDecoratorStream;
use TYPO3\CMS\Core\Http\Response;
27
use TYPO3\CMS\Core\Http\UploadedFile;
28
use TYPO3\CMS\Core\Log\LogManager;
29
use TYPO3\CMS\Core\Registry;
30
use TYPO3\CMS\Core\Resource\Driver\DriverInterface;
31
use TYPO3\CMS\Core\Resource\Driver\StreamableDriverInterface;
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use TYPO3\CMS\Core\Resource\Event\AfterFileAddedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFileContentsSetEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFileCopiedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFileCreatedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFileDeletedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFileMovedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFileRenamedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFileReplacedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFolderAddedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFolderCopiedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFolderDeletedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFolderMovedEvent;
use TYPO3\CMS\Core\Resource\Event\AfterFolderRenamedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFileAddedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFileContentsSetEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFileCopiedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFileCreatedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFileDeletedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFileMovedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFileRenamedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFileReplacedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFolderAddedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFolderCopiedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFolderDeletedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFolderMovedEvent;
use TYPO3\CMS\Core\Resource\Event\BeforeFolderRenamedEvent;
use TYPO3\CMS\Core\Resource\Event\GeneratePublicUrlForResourceEvent;
use TYPO3\CMS\Core\Resource\Event\SanitizeFileNameEvent;
60
use TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException;
61
62
63
64
65
66
67
68
69
70
71
use TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException;
use TYPO3\CMS\Core\Resource\Exception\FileOperationErrorException;
use TYPO3\CMS\Core\Resource\Exception\FolderDoesNotExistException;
use TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException;
use TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException;
use TYPO3\CMS\Core\Resource\Exception\InsufficientFileReadPermissionsException;
use TYPO3\CMS\Core\Resource\Exception\InsufficientFileWritePermissionsException;
use TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException;
use TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException;
use TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException;
use TYPO3\CMS\Core\Resource\Exception\InvalidConfigurationException;
72
use TYPO3\CMS\Core\Resource\Exception\InvalidHashException;
73
use TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException;
74
75
76
use TYPO3\CMS\Core\Resource\Exception\ResourcePermissionsUnavailableException;
use TYPO3\CMS\Core\Resource\Exception\UploadException;
use TYPO3\CMS\Core\Resource\Exception\UploadSizeException;
77
use TYPO3\CMS\Core\Resource\Filter\ImportExportFilter;
78
use TYPO3\CMS\Core\Resource\Index\FileIndexRepository;
79
use TYPO3\CMS\Core\Resource\Index\Indexer;
80
use TYPO3\CMS\Core\Resource\OnlineMedia\Helpers\OnlineMediaHelperRegistry;
81
82
83
84
85
use TYPO3\CMS\Core\Resource\Search\FileSearchDemand;
use TYPO3\CMS\Core\Resource\Search\Result\DriverFilteredSearchResult;
use TYPO3\CMS\Core\Resource\Search\Result\EmptyFileSearchResult;
use TYPO3\CMS\Core\Resource\Search\Result\FileSearchResult;
use TYPO3\CMS\Core\Resource\Search\Result\FileSearchResultInterface;
86
use TYPO3\CMS\Core\Resource\Security\FileNameValidator;
87
use TYPO3\CMS\Core\Resource\Service\FileProcessingService;
88
use TYPO3\CMS\Core\Service\FlexFormService;
89
use TYPO3\CMS\Core\Utility\Exception\NotImplementedMethodException;
90
use TYPO3\CMS\Core\Utility\GeneralUtility;
91
use TYPO3\CMS\Core\Utility\PathUtility;
92
use TYPO3\CMS\Core\Utility\StringUtility;
93

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/**
 * A "mount point" inside the TYPO3 file handling.
 *
 * A "storage" object handles
 * - abstraction to the driver
 * - permissions (from the driver, and from the user, + capabilities)
 * - an entry point for files, folders, and for most other operations
 *
 * == Driver entry point
 * The driver itself, that does the actual work on the file system,
 * is inside the storage but completely shadowed by
 * the storage, as the storage also handles the abstraction to the
 * driver
 *
 * The storage can be on the local system, but can also be on a remote
 * system. The combination of driver + configurable capabilities (storage
 * is read-only e.g.) allows for flexible uses.
 *
 *
 * == Permission system
 * As all requests have to run through the storage, the storage knows about the
 * permissions of a BE/FE user, the file permissions / limitations of the driver
 * and has some configurable capabilities.
 * Additionally, a BE user can use "filemounts" (known from previous installations)
 * to limit his/her work-zone to only a subset (identifier and its subfolders/subfolders)
 * of the user itself.
 *
 * Check 1: "User Permissions" [is the user allowed to write a file) [is the user allowed to write a file]
 * Check 2: "File Mounts" of the User (act as subsets / filters to the identifiers) [is the user allowed to do something in this folder?]
 * Check 3: "Capabilities" of Storage (then: of Driver) [is the storage/driver writable?]
 * Check 4: "File permissions" of the Driver [is the folder writable?]
 */
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
class ResourceStorage implements ResourceStorageInterface
{
    /**
     * The storage driver instance belonging to this storage.
     *
     * @var Driver\DriverInterface
     */
    protected $driver;

    /**
     * The database record for this storage
     *
     * @var array
     */
    protected $storageRecord;

    /**
     * The configuration belonging to this storage (decoded from the configuration field).
     *
     * @var array
     */
    protected $configuration;

    /**
     * @var Service\FileProcessingService
     */
    protected $fileProcessingService;

    /**
     * Whether to check if file or folder is in user mounts
     * and the action is allowed for a user
     * Default is FALSE so that resources are accessible for
     * front end rendering or admins.
     *
     * @var bool
     */
    protected $evaluatePermissions = false;

    /**
     * User filemounts, added as an array, and used as filters
     *
     * @var array
     */
169
    protected $fileMounts = [];
170
171
172
173
174
175
176

    /**
     * The file permissions of the user (and their group) merged together and
     * available as an array
     *
     * @var array
     */
177
    protected $userPermissions = [];
178
179
180
181
182
183
184
185
186
187

    /**
     * The capabilities of this storage as defined in the storage record.
     * Also see the CAPABILITY_* constants below
     *
     * @var int
     */
    protected $capabilities;

    /**
188
     * @var EventDispatcherInterface
189
     */
190
    protected $eventDispatcher;
191
192

    /**
193
     * @var Folder|null
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
     */
    protected $processingFolder;

    /**
     * All processing folders of this storage used in any storage
     *
     * @var Folder[]
     */
    protected $processingFolders;

    /**
     * whether this storage is online or offline in this request
     *
     * @var bool
     */
209
    protected $isOnline;
210
211
212
213
214
215
216
217
218
219
220

    /**
     * @var bool
     */
    protected $isDefault = false;

    /**
     * The filters used for the files and folder names.
     *
     * @var array
     */
221
    protected $fileAndFolderNameFilters = [];
222

223
224
225
226
227
    /**
     * Levels numbers used to generate hashed subfolders in the processing folder
     */
    const PROCESSING_FOLDER_LEVELS = 2;

228
229
230
231
232
    /**
     * Constructor for a storage object.
     *
     * @param Driver\DriverInterface $driver
     * @param array $storageRecord The storage record row from the database
233
     * @param EventDispatcherInterface|null $eventDispatcher
234
     */
235
    public function __construct(DriverInterface $driver, array $storageRecord, EventDispatcherInterface $eventDispatcher = null)
236
237
    {
        $this->storageRecord = $storageRecord;
238
        $this->eventDispatcher = $eventDispatcher ?? GeneralUtility::makeInstance(EventDispatcherInterface::class);
239
240
241
242
243
244
245
        if (is_array($storageRecord['configuration'] ?? null)) {
            $this->configuration = $storageRecord['configuration'];
        } elseif (!empty($storageRecord['configuration'] ?? '')) {
            $this->configuration = GeneralUtility::makeInstance(FlexFormService::class)->convertFlexFormContentToArray($storageRecord['configuration']);
        } else {
            $this->configuration = [];
        }
246
        $this->capabilities =
247
248
            ($this->storageRecord['is_browsable'] ?? null ? self::CAPABILITY_BROWSABLE : 0) |
            ($this->storageRecord['is_public'] ?? null ? self::CAPABILITY_PUBLIC : 0) |
249
250
251
            ($this->storageRecord['is_writable'] ?? null ? self::CAPABILITY_WRITABLE : 0) |
            // Always let the driver decide whether to set this capability
            self::CAPABILITY_HIERARCHICAL_IDENTIFIERS;
252
253

        $this->driver = $driver;
254
        $this->driver->setStorageUid($storageRecord['uid'] ?? null);
255
256
257
        $this->driver->mergeConfigurationCapabilities($this->capabilities);
        try {
            $this->driver->processConfiguration();
258
        } catch (InvalidConfigurationException $e) {
259
260
261
262
263
264
265
266
267
268
            // Configuration error
            $this->isOnline = false;

            $message = sprintf(
                'Failed initializing storage [%d] "%s", error: %s',
                $this->getUid(),
                $this->getName(),
                $e->getMessage()
            );

269
270
            // create a dedicated logger instance because we need a logger in the constructor
            GeneralUtility::makeInstance(LogManager::class)->getLogger(static::class)->error($message);
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        }
        $this->driver->initialize();
        $this->capabilities = $this->driver->getCapabilities();

        $this->isDefault = (isset($storageRecord['is_default']) && $storageRecord['is_default'] == 1);
        $this->resetFileAndFolderNameFiltersToDefault();
    }

    /**
     * Gets the configuration.
     *
     * @return array
     */
    public function getConfiguration()
    {
        return $this->configuration;
    }

    /**
     * Sets the configuration.
     *
     * @param array $configuration
     */
    public function setConfiguration(array $configuration)
    {
        $this->configuration = $configuration;
    }

    /**
     * Gets the storage record.
     *
     * @return array
     */
    public function getStorageRecord()
    {
        return $this->storageRecord;
    }

    /**
     * Sets the storage that belongs to this storage.
     *
     * @param Driver\DriverInterface $driver
     * @return ResourceStorage
     */
315
    public function setDriver(DriverInterface $driver)
316
317
318
319
320
321
322
323
324
325
    {
        $this->driver = $driver;
        return $this;
    }

    /**
     * Returns the driver object belonging to this storage.
     *
     * @return Driver\DriverInterface
     */
326
    protected function getDriver()
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    {
        return $this->driver;
    }

    /**
     * Returns the name of this storage.
     *
     * @return string
     */
    public function getName()
    {
        return $this->storageRecord['name'];
    }

    /**
     * Returns the UID of this storage.
     *
     * @return int
     */
    public function getUid()
    {
348
        return (int)($this->storageRecord['uid'] ?? 0);
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    }

    /**
     * Tells whether there are children in this storage.
     *
     * @return bool
     */
    public function hasChildren()
    {
        return true;
    }

    /*********************************
     * Capabilities
     ********************************/
    /**
     * Returns the capabilities of this storage.
     *
     * @return int
368
369
370
371
     * @see \TYPO3\CMS\Core\Resource\ResourceStorageInterface::CAPABILITY_BROWSABLE
     * @see \TYPO3\CMS\Core\Resource\ResourceStorageInterface::CAPABILITY_PUBLIC
     * @see \TYPO3\CMS\Core\Resource\ResourceStorageInterface::CAPABILITY_WRITABLE
     * @see \TYPO3\CMS\Core\Resource\ResourceStorageInterface::CAPABILITY_HIERARCHICAL_IDENTIFIERS
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
     */
    public function getCapabilities()
    {
        return (int)$this->capabilities;
    }

    /**
     * Returns TRUE if this storage has the given capability.
     *
     * @param int $capability A capability, as defined in a CAPABILITY_* constant
     * @return bool
     */
    protected function hasCapability($capability)
    {
        return ($this->capabilities & $capability) == $capability;
    }

    /**
     * Returns TRUE if this storage is publicly available. This is just a
     * configuration option and does not mean that it really *is* public. OTOH
     * a storage that is marked as not publicly available will trigger the file
     * publishing mechanisms of TYPO3.
     *
     * @return bool
     */
    public function isPublic()
    {
        return $this->hasCapability(self::CAPABILITY_PUBLIC);
    }

    /**
     * Returns TRUE if this storage is writable. This is determined by the
     * driver and the storage configuration; user permissions are not taken into account.
     *
     * @return bool
     */
    public function isWritable()
    {
        return $this->hasCapability(self::CAPABILITY_WRITABLE);
    }

    /**
     * Returns TRUE if this storage is browsable by a (backend) user of TYPO3.
     *
     * @return bool
     */
    public function isBrowsable()
    {
        return $this->isOnline() && $this->hasCapability(self::CAPABILITY_BROWSABLE);
    }

423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
    /**
     * Returns TRUE if this storage stores folder structure in file identifiers.
     *
     * @return bool
     */
    public function hasHierarchicalIdentifiers(): bool
    {
        return $this->hasCapability(self::CAPABILITY_HIERARCHICAL_IDENTIFIERS);
    }

    /**
     * Search for files in a storage based on given restrictions
     * and a possibly given folder.
     *
     * @param FileSearchDemand $searchDemand
     * @param Folder|null $folder
     * @param bool $useFilters Whether storage filters should be applied
     * @return FileSearchResultInterface
     */
    public function searchFiles(FileSearchDemand $searchDemand, Folder $folder = null, bool $useFilters = true): FileSearchResultInterface
    {
        $folder = $folder ?? $this->getRootLevelFolder();
        if (!$folder->checkActionPermission('read')) {
            return new EmptyFileSearchResult();
        }

        return new DriverFilteredSearchResult(
            new FileSearchResult(
                $searchDemand->withFolder($folder)
            ),
            $this->driver,
            $useFilters ? $this->getFileAndFolderNameFilters() : []
        );
    }

458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
    /**
     * Returns TRUE if the identifiers used by this storage are case-sensitive.
     *
     * @return bool
     */
    public function usesCaseSensitiveIdentifiers()
    {
        return $this->driver->isCaseSensitiveFileSystem();
    }

    /**
     * Returns TRUE if this storage is browsable by a (backend) user of TYPO3.
     *
     * @return bool
     */
    public function isOnline()
    {
475
476
477
478
479
480
481
482
483
        if ($this->isOnline === null) {
            if ($this->getUid() === 0) {
                $this->isOnline = true;
            }
            // the storage is not marked as online for a longer time
            if ($this->storageRecord['is_online'] == 0) {
                $this->isOnline = false;
            }
            if ($this->isOnline !== false) {
484
485
486
487
                if (($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface
                    && ApplicationType::fromRequest($GLOBALS['TYPO3_REQUEST'])->isFrontend()
                ) {
                    // All files are ALWAYS available in the frontend
488
489
490
491
492
493
494
495
496
497
498
499
                    $this->isOnline = true;
                } else {
                    // check if the storage is disabled temporary for now
                    $registryObject = GeneralUtility::makeInstance(Registry::class);
                    $offlineUntil = $registryObject->get('core', 'sys_file_storage-' . $this->getUid() . '-offline-until');
                    if ($offlineUntil && $offlineUntil > time()) {
                        $this->isOnline = false;
                    } else {
                        $this->isOnline = true;
                    }
                }
            }
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
        }
        return $this->isOnline;
    }

    /**
     * Returns TRUE if auto extracting of metadata is enabled
     *
     * @return bool
     */
    public function autoExtractMetadataEnabled()
    {
        return !empty($this->storageRecord['auto_extract_metadata']);
    }

    /**
     * Blows the "fuse" and marks the storage as offline.
     *
     * Can only be modified by an admin.
     *
     * Typically, this is only done if the configuration is wrong.
     */
    public function markAsPermanentlyOffline()
    {
        if ($this->getUid() > 0) {
            // @todo: move this to the storage repository
525
526
527
528
529
530
531
            GeneralUtility::makeInstance(ConnectionPool::class)
                ->getConnectionForTable('sys_file_storage')
                ->update(
                    'sys_file_storage',
                    ['is_online' => 0],
                    ['uid' => (int)$this->getUid()]
                );
532
533
534
535
536
        }
        $this->storageRecord['is_online'] = 0;
        $this->isOnline = false;
    }

537
538
539
540
541
542
543
544
545
546
547
548
549
550
    /**
     * Marks this storage as offline for the next 5 minutes.
     *
     * Non-permanent: This typically happens for remote storages
     * that are "flaky" and not available all the time.
     */
    public function markAsTemporaryOffline()
    {
        $registryObject = GeneralUtility::makeInstance(Registry::class);
        $registryObject->set('core', 'sys_file_storage-' . $this->getUid() . '-offline-until', time() + 60 * 5);
        $this->storageRecord['is_online'] = 0;
        $this->isOnline = false;
    }

551
552
553
554
555
556
557
558
559
560
561
562
    /*********************************
     * User Permissions / File Mounts
     ********************************/
    /**
     * Adds a filemount as a "filter" for users to only work on a subset of a
     * storage object
     *
     * @param string $folderIdentifier
     * @param array $additionalData
     *
     * @throws Exception\FolderDoesNotExistException
     */
563
    public function addFileMount($folderIdentifier, $additionalData = [])
564
565
566
567
568
    {
        // check for the folder before we add it as a filemount
        if ($this->driver->folderExists($folderIdentifier) === false) {
            // if there is an error, this is important and should be handled
            // as otherwise the user would see the whole storage without any restrictions for the filemounts
569
            throw new FolderDoesNotExistException('Folder for file mount ' . $folderIdentifier . ' does not exist.', 1334427099);
570
571
        }
        $data = $this->driver->getFolderInfoByIdentifier($folderIdentifier);
572
        $folderObject = $this->createFolderObject($data['identifier'], $data['name']);
573
574
575
576
577
578
579
580
581
582
583
        // Use the canonical identifier instead of the user provided one!
        $folderIdentifier = $folderObject->getIdentifier();
        if (
            !empty($this->fileMounts[$folderIdentifier])
            && empty($this->fileMounts[$folderIdentifier]['read_only'])
            && !empty($additionalData['read_only'])
        ) {
            // Do not overwrite a regular mount with a read only mount
            return;
        }
        if (empty($additionalData)) {
584
            $additionalData = [
585
586
                'path' => $folderIdentifier,
                'title' => $folderIdentifier,
587
                'folder' => $folderObject,
588
            ];
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
        } else {
            $additionalData['folder'] = $folderObject;
            if (!isset($additionalData['title'])) {
                $additionalData['title'] = $folderIdentifier;
            }
        }
        $this->fileMounts[$folderIdentifier] = $additionalData;
    }

    /**
     * Returns all file mounts that are registered with this storage.
     *
     * @return array
     */
    public function getFileMounts()
    {
        return $this->fileMounts;
    }

    /**
     * Checks if the given subject is within one of the registered user
     * file mounts. If not, working with the file is not permitted for the user.
     *
     * @param ResourceInterface $subject file or folder
     * @param bool $checkWriteAccess If true, it is not only checked if the subject is within the file mount but also whether it isn't a read only file mount
     * @return bool
     */
    public function isWithinFileMountBoundaries($subject, $checkWriteAccess = false)
    {
        if (!$this->evaluatePermissions) {
            return true;
        }
        $isWithinFileMount = false;
        if (!$subject) {
            $subject = $this->getRootLevelFolder();
        }
        $identifier = $subject->getIdentifier();

        // Allow access to processing folder
        if ($this->isWithinProcessingFolder($identifier)) {
            $isWithinFileMount = true;
        } else {
            // Check if the identifier of the subject is within at
            // least one of the file mounts
            $writableFileMountAvailable = false;
            foreach ($this->fileMounts as $fileMount) {
Benni Mack's avatar
Benni Mack committed
635
636
637
                /** @var Folder $folder */
                $folder = $fileMount['folder'];
                if ($this->driver->isWithin($folder->getIdentifier(), $identifier)) {
638
639
640
                    $isWithinFileMount = true;
                    if (!$checkWriteAccess) {
                        break;
641
642
                    }
                    if (empty($fileMount['read_only'])) {
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
                        $writableFileMountAvailable = true;
                        break;
                    }
                }
            }
            $isWithinFileMount = $checkWriteAccess ? $writableFileMountAvailable : $isWithinFileMount;
        }
        return $isWithinFileMount;
    }

    /**
     * Sets whether the permissions to access or write
     * into this storage should be checked or not.
     *
     * @param bool $evaluatePermissions
     */
    public function setEvaluatePermissions($evaluatePermissions)
    {
        $this->evaluatePermissions = (bool)$evaluatePermissions;
    }

    /**
     * Gets whether the permissions to access or write
     * into this storage should be checked or not.
     *
     * @return bool $evaluatePermissions
     */
    public function getEvaluatePermissions()
    {
        return $this->evaluatePermissions;
    }

    /**
     * Sets the user permissions of the storage.
     *
     * @param array $userPermissions
     */
    public function setUserPermissions(array $userPermissions)
    {
        $this->userPermissions = $userPermissions;
    }

    /**
     * Checks if the ACL settings allow for a certain action
     * (is a user allowed to read a file or copy a folder).
     *
     * @param string $action
     * @param string $type either File or Folder
     * @return bool
     */
    public function checkUserActionPermission($action, $type)
    {
        if (!$this->evaluatePermissions) {
            return true;
        }

        $allow = false;
        if (!empty($this->userPermissions[strtolower($action) . ucfirst(strtolower($type))])) {
            $allow = true;
        }

        return $allow;
    }

    /**
     * Checks if a file operation (= action) is allowed on a
     * File/Folder/Storage (= subject).
     *
     * This method, by design, does not throw exceptions or do logging.
     * Besides the usage from other methods in this class, it is also used by
     * the Filelist UI to check whether an action is allowed and whether action
     * related UI elements should thus be shown (move icon, edit icon, etc.)
     *
716
     * @param string $action action, can be read, write, delete, editMeta
717
718
719
720
721
722
     * @param FileInterface $file
     * @return bool
     */
    public function checkFileActionPermission($action, FileInterface $file)
    {
        $isProcessedFile = $file instanceof ProcessedFile;
723
724
725
726
727
        // Check 1: Allow editing meta data of a file if it is in mount boundaries of a writable file mount
        if ($action === 'editMeta') {
            return !$isProcessedFile && $this->isWithinFileMountBoundaries($file, true);
        }
        // Check 2: Does the user have permission to perform the action? e.g. "readFile"
728
729
730
        if (!$isProcessedFile && $this->checkUserActionPermission($action, 'File') === false) {
            return false;
        }
731
        // Check 3: No action allowed on files for denied file extensions
732
733
734
735
        if (!$this->checkFileExtensionPermission($file->getName())) {
            return false;
        }
        $isReadCheck = false;
736
        if (in_array($action, ['read', 'copy', 'move', 'replace'], true)) {
737
738
739
            $isReadCheck = true;
        }
        $isWriteCheck = false;
740
        if (in_array($action, ['add', 'write', 'move', 'rename', 'replace', 'delete'], true)) {
741
742
            $isWriteCheck = true;
        }
743
        // Check 4: Does the user have the right to perform the action?
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
        // (= is he within the file mount borders)
        if (!$isProcessedFile && !$this->isWithinFileMountBoundaries($file, $isWriteCheck)) {
            return false;
        }

        $isMissing = false;
        if (!$isProcessedFile && $file instanceof File) {
            $isMissing = $file->isMissing();
        }

        if ($this->driver->fileExists($file->getIdentifier()) === false) {
            $file->setMissing(true);
            $isMissing = true;
        }

759
        // Check 5: Check the capabilities of the storage (and the driver)
760
761
762
763
        if ($isWriteCheck && ($isMissing || !$this->isWritable())) {
            return false;
        }

764
        // Check 6: "File permissions" of the driver (only when file isn't marked as missing)
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
        if (!$isMissing) {
            $filePermissions = $this->driver->getPermissions($file->getIdentifier());
            if ($isReadCheck && !$filePermissions['r']) {
                return false;
            }
            if ($isWriteCheck && !$filePermissions['w']) {
                return false;
            }
        }
        return true;
    }

    /**
     * Checks if a folder operation (= action) is allowed on a Folder.
     *
     * This method, by design, does not throw exceptions or do logging.
     * See the checkFileActionPermission() method above for the reasons.
     *
     * @param string $action
     * @param Folder $folder
     * @return bool
     */
    public function checkFolderActionPermission($action, Folder $folder = null)
    {
        // Check 1: Does the user have permission to perform the action? e.g. "writeFolder"
        if ($this->checkUserActionPermission($action, 'Folder') === false) {
            return false;
        }

        // If we do not have a folder here, we cannot do further checks
        if ($folder === null) {
            return true;
        }

        $isReadCheck = false;
800
        if (in_array($action, ['read', 'copy'], true)) {
801
802
803
            $isReadCheck = true;
        }
        $isWriteCheck = false;
804
        if (in_array($action, ['add', 'move', 'write', 'delete', 'rename'], true)) {
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
            $isWriteCheck = true;
        }
        // Check 2: Does the user has the right to perform the action?
        // (= is he within the file mount borders)
        if (!$this->isWithinFileMountBoundaries($folder, $isWriteCheck)) {
            return false;
        }
        // Check 3: Check the capabilities of the storage (and the driver)
        if ($isReadCheck && !$this->isBrowsable()) {
            return false;
        }
        if ($isWriteCheck && !$this->isWritable()) {
            return false;
        }

        // Check 4: "Folder permissions" of the driver
        $folderPermissions = $this->driver->getPermissions($folder->getIdentifier());
        if ($isReadCheck && !$folderPermissions['r']) {
            return false;
        }
        if ($isWriteCheck && !$folderPermissions['w']) {
            return false;
        }
        return true;
    }

    /**
     * If the fileName is given, checks it against the
     * TYPO3_CONF_VARS[BE][fileDenyPattern] + and if the file extension is allowed.
     *
     * @param string $fileName full filename
     * @return bool TRUE if extension/filename is allowed
     */
    protected function checkFileExtensionPermission($fileName)
    {
        $fileName = $this->driver->sanitizeFileName($fileName);
841
        return GeneralUtility::makeInstance(FileNameValidator::class)->isValid($fileName);
842
843
844
845
846
847
848
849
850
851
852
853
    }

    /**
     * Assures read permission for given folder.
     *
     * @param Folder $folder If a folder is given, mountpoints are checked. If not only user folder read permissions are checked.
     * @throws Exception\InsufficientFolderAccessPermissionsException
     */
    protected function assureFolderReadPermission(Folder $folder = null)
    {
        if (!$this->checkFolderActionPermission('read', $folder)) {
            if ($folder === null) {
854
                throw new InsufficientFolderAccessPermissionsException(
855
856
857
                    'You are not allowed to read folders',
                    1430657869
                );
858
            }
859
            throw new InsufficientFolderAccessPermissionsException(
Benni Mack's avatar
Benni Mack committed
860
861
                'You are not allowed to access the given folder: "' . $folder->getName() . '"',
                1375955684
862
            );
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
        }
    }

    /**
     * Assures delete permission for given folder.
     *
     * @param Folder $folder If a folder is given, mountpoints are checked. If not only user folder delete permissions are checked.
     * @param bool $checkDeleteRecursively
     * @throws Exception\InsufficientFolderAccessPermissionsException
     * @throws Exception\InsufficientFolderWritePermissionsException
     * @throws Exception\InsufficientUserPermissionsException
     */
    protected function assureFolderDeletePermission(Folder $folder, $checkDeleteRecursively)
    {
        // Check user permissions for recursive deletion if it is requested
        if ($checkDeleteRecursively && !$this->checkUserActionPermission('recursivedelete', 'Folder')) {
879
            throw new InsufficientUserPermissionsException('You are not allowed to delete folders recursively', 1377779423);
880
881
882
        }
        // Check user action permission
        if (!$this->checkFolderActionPermission('delete', $folder)) {
883
            throw new InsufficientFolderAccessPermissionsException(
884
885
886
887
888
                'You are not allowed to delete the given folder: "' . $folder->getName() . '"',
                1377779039
            );
        }
        // Check if the user has write permissions to folders
889
        // Would be good if we could check for actual write permissions in the containing folder
890
891
        // but we cannot since we have no access to the containing folder of this file.
        if (!$this->checkUserActionPermission('write', 'Folder')) {
892
            throw new InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377779111);
893
894
895
896
897
898
899
900
901
902
903
904
905
        }
    }

    /**
     * Assures read permission for given file.
     *
     * @param FileInterface $file
     * @throws Exception\InsufficientFileAccessPermissionsException
     * @throws Exception\IllegalFileExtensionException
     */
    protected function assureFileReadPermission(FileInterface $file)
    {
        if (!$this->checkFileActionPermission('read', $file)) {
906
            throw new InsufficientFileAccessPermissionsException(
907
908
909
910
911
                'You are not allowed to access that file: "' . $file->getName() . '"',
                1375955429
            );
        }
        if (!$this->checkFileExtensionPermission($file->getName())) {
912
            throw new IllegalFileExtensionException(
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
                'You are not allowed to use that file extension. File: "' . $file->getName() . '"',
                1375955430
            );
        }
    }

    /**
     * Assures write permission for given file.
     *
     * @param FileInterface $file
     * @throws Exception\IllegalFileExtensionException
     * @throws Exception\InsufficientFileWritePermissionsException
     * @throws Exception\InsufficientUserPermissionsException
     */
    protected function assureFileWritePermissions(FileInterface $file)
    {
        // Check if user is allowed to write the file and $file is writable
        if (!$this->checkFileActionPermission('write', $file)) {
931
            throw new InsufficientFileWritePermissionsException('Writing to file "' . $file->getIdentifier() . '" is not allowed.', 1330121088);
932
933
        }
        if (!$this->checkFileExtensionPermission($file->getName())) {
934
            throw new IllegalFileExtensionException('You are not allowed to edit a file with extension "' . $file->getExtension() . '"', 1366711933);
935
936
937
938
939
940
941
942
943
944
945
946
947
948
        }
    }

    /**
     * Assure replace permission for given file.
     *
     * @param FileInterface $file
     * @throws Exception\InsufficientFileWritePermissionsException
     * @throws Exception\InsufficientFolderWritePermissionsException
     */
    protected function assureFileReplacePermissions(FileInterface $file)
    {
        // Check if user is allowed to replace the file and $file is writable
        if (!$this->checkFileActionPermission('replace', $file)) {
949
            throw new InsufficientFileWritePermissionsException('Replacing file "' . $file->getIdentifier() . '" is not allowed.', 1436899571);
950
951
952
        }
        // Check if parentFolder is writable for the user
        if (!$this->checkFolderActionPermission('write', $file->getParentFolder())) {
953
            throw new InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $file->getIdentifier() . '"', 1436899572);
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
        }
    }

    /**
     * Assures delete permission for given file.
     *
     * @param FileInterface $file
     * @throws Exception\IllegalFileExtensionException
     * @throws Exception\InsufficientFileWritePermissionsException
     * @throws Exception\InsufficientFolderWritePermissionsException
     */
    protected function assureFileDeletePermissions(FileInterface $file)
    {
        // Check for disallowed file extensions
        if (!$this->checkFileExtensionPermission($file->getName())) {
969
            throw new IllegalFileExtensionException('You are not allowed to delete a file with extension "' . $file->getExtension() . '"', 1377778916);
970
971
972
973
974
        }
        // Check further permissions if file is not a processed file
        if (!$file instanceof ProcessedFile) {
            // Check if user is allowed to delete the file and $file is writable
            if (!$this->checkFileActionPermission('delete', $file)) {
975
                throw new InsufficientFileWritePermissionsException('You are not allowed to delete the file "' . $file->getIdentifier() . '"', 1319550425);
976
977
            }
            // Check if the user has write permissions to folders
978
            // Would be good if we could check for actual write permissions in the containing folder
979
980
            // but we cannot since we have no access to the containing folder of this file.
            if (!$this->checkUserActionPermission('write', 'Folder')) {
981
                throw new InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377778702);
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
            }
        }
    }

    /**
     * Checks if a file/user has the permission to be written to a Folder/Storage.
     * If not, throws an exception.
     *
     * @param Folder $targetFolder The target folder where the file should be written
     * @param string $targetFileName The file name which should be written into the storage
     *
     * @throws Exception\InsufficientFolderWritePermissionsException
     * @throws Exception\IllegalFileExtensionException
     * @throws Exception\InsufficientUserPermissionsException
     */
    protected function assureFileAddPermissions($targetFolder, $targetFileName)
    {
        // Check for a valid file extension
        if (!$this->checkFileExtensionPermission($targetFileName)) {