/
ResourceStorage.php
2992 lines (2772 loc) · 120 KB
/
ResourceStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
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
635
636
637
638
639
640
641
642
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
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
800
801
802
803
804
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of the TYPO3 CMS project.
*
* 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.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Core\Resource;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Http\ApplicationType;
use TYPO3\CMS\Core\Http\FalDumpFileContentsDecoratorStream;
use TYPO3\CMS\Core\Http\Response;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\Registry;
use TYPO3\CMS\Core\Resource\Driver\DriverInterface;
use TYPO3\CMS\Core\Resource\Driver\StreamableDriverInterface;
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;
use TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException;
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;
use TYPO3\CMS\Core\Resource\Exception\InvalidHashException;
use TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException;
use TYPO3\CMS\Core\Resource\Exception\ResourcePermissionsUnavailableException;
use TYPO3\CMS\Core\Resource\Exception\UploadException;
use TYPO3\CMS\Core\Resource\Exception\UploadSizeException;
use TYPO3\CMS\Core\Resource\Filter\ImportExportFilter;
use TYPO3\CMS\Core\Resource\Index\FileIndexRepository;
use TYPO3\CMS\Core\Resource\Index\Indexer;
use TYPO3\CMS\Core\Resource\OnlineMedia\Helpers\OnlineMediaHelperRegistry;
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;
use TYPO3\CMS\Core\Resource\Security\FileNameValidator;
use TYPO3\CMS\Core\Resource\Service\FileProcessingService;
use TYPO3\CMS\Core\Service\FlexFormService;
use TYPO3\CMS\Core\Utility\Exception\NotImplementedMethodException;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\Core\Utility\StringUtility;
/**
* 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?]
*/
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
*/
protected $fileMounts = [];
/**
* The file permissions of the user (and their group) merged together and
* available as an array
*
* @var array
*/
protected $userPermissions = [];
/**
* The capabilities of this storage as defined in the storage record.
* Also see the CAPABILITY_* constants below
*
* @var int
*/
protected $capabilities;
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* @var Folder|null
*/
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
*/
protected $isOnline;
/**
* @var bool
*/
protected $isDefault = false;
/**
* The filters used for the files and folder names.
*
* @var array
*/
protected $fileAndFolderNameFilters = [];
/**
* Levels numbers used to generate hashed subfolders in the processing folder
*/
const PROCESSING_FOLDER_LEVELS = 2;
/**
* Constructor for a storage object.
*
* @param Driver\DriverInterface $driver
* @param array $storageRecord The storage record row from the database
* @param EventDispatcherInterface|null $eventDispatcher
*/
public function __construct(DriverInterface $driver, array $storageRecord, EventDispatcherInterface $eventDispatcher = null)
{
$this->storageRecord = $storageRecord;
$this->eventDispatcher = $eventDispatcher ?? GeneralUtility::makeInstance(EventDispatcherInterface::class);
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 = [];
}
$this->capabilities =
($this->storageRecord['is_browsable'] ?? null ? self::CAPABILITY_BROWSABLE : 0) |
($this->storageRecord['is_public'] ?? null ? self::CAPABILITY_PUBLIC : 0) |
($this->storageRecord['is_writable'] ?? null ? self::CAPABILITY_WRITABLE : 0) |
// Always let the driver decide whether to set this capability
self::CAPABILITY_HIERARCHICAL_IDENTIFIERS;
$this->driver = $driver;
$this->driver->setStorageUid($storageRecord['uid'] ?? null);
$this->driver->mergeConfigurationCapabilities($this->capabilities);
try {
$this->driver->processConfiguration();
} catch (InvalidConfigurationException $e) {
// Configuration error
$this->isOnline = false;
$message = sprintf(
'Failed initializing storage [%d] "%s", error: %s',
$this->getUid(),
$this->getName(),
$e->getMessage()
);
// create a dedicated logger instance because we need a logger in the constructor
GeneralUtility::makeInstance(LogManager::class)->getLogger(static::class)->error($message);
}
$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
*/
public function setDriver(DriverInterface $driver)
{
$this->driver = $driver;
return $this;
}
/**
* Returns the driver object belonging to this storage.
*
* @return Driver\DriverInterface
*/
protected function getDriver()
{
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()
{
return (int)($this->storageRecord['uid'] ?? 0);
}
/**
* Tells whether there are children in this storage.
*
* @return bool
*/
public function hasChildren()
{
return true;
}
/*********************************
* Capabilities
********************************/
/**
* Returns the capabilities of this storage.
*
* @return int
* @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
*/
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);
}
/**
* 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() : []
);
}
/**
* 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()
{
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) {
if (($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface
&& ApplicationType::fromRequest($GLOBALS['TYPO3_REQUEST'])->isFrontend()
) {
// All files are ALWAYS available in the frontend
$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;
}
}
}
}
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
GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable('sys_file_storage')
->update(
'sys_file_storage',
['is_online' => 0],
['uid' => (int)$this->getUid()]
);
}
$this->storageRecord['is_online'] = 0;
$this->isOnline = false;
}
/**
* 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;
}
/*********************************
* 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
*/
public function addFileMount($folderIdentifier, $additionalData = [])
{
// 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
throw new FolderDoesNotExistException('Folder for file mount ' . $folderIdentifier . ' does not exist.', 1334427099);
}
$data = $this->driver->getFolderInfoByIdentifier($folderIdentifier);
$folderObject = $this->createFolderObject($data['identifier'], $data['name']);
// 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)) {
$additionalData = [
'path' => $folderIdentifier,
'title' => $folderIdentifier,
'folder' => $folderObject,
];
} 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) {
/** @var Folder $folder */
$folder = $fileMount['folder'];
if ($this->driver->isWithin($folder->getIdentifier(), $identifier)) {
$isWithinFileMount = true;
if (!$checkWriteAccess) {
break;
}
if (empty($fileMount['read_only'])) {
$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.)
*
* @param string $action action, can be read, write, delete, editMeta
* @param FileInterface $file
* @return bool
*/
public function checkFileActionPermission($action, FileInterface $file)
{
$isProcessedFile = $file instanceof ProcessedFile;
// 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"
if (!$isProcessedFile && $this->checkUserActionPermission($action, 'File') === false) {
return false;
}
// Check 3: No action allowed on files for denied file extensions
if (!$this->checkFileExtensionPermission($file->getName())) {
return false;
}
$isReadCheck = false;
if (in_array($action, ['read', 'copy', 'move', 'replace'], true)) {
$isReadCheck = true;
}
$isWriteCheck = false;
if (in_array($action, ['add', 'write', 'move', 'rename', 'replace', 'delete'], true)) {
$isWriteCheck = true;
}
// Check 4: Does the user have the right to perform the action?
// (= 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;
}
// Check 5: Check the capabilities of the storage (and the driver)
if ($isWriteCheck && ($isMissing || !$this->isWritable())) {
return false;
}
// Check 6: "File permissions" of the driver (only when file isn't marked as missing)
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;
if (in_array($action, ['read', 'copy'], true)) {
$isReadCheck = true;
}
$isWriteCheck = false;
if (in_array($action, ['add', 'move', 'write', 'delete', 'rename'], true)) {
$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);
return GeneralUtility::makeInstance(FileNameValidator::class)->isValid($fileName);
}
/**
* 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) {
throw new InsufficientFolderAccessPermissionsException(
'You are not allowed to read folders',
1430657869
);
}
throw new InsufficientFolderAccessPermissionsException(
'You are not allowed to access the given folder: "' . $folder->getName() . '"',
1375955684
);
}
}
/**
* 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')) {
throw new InsufficientUserPermissionsException('You are not allowed to delete folders recursively', 1377779423);
}
// Check user action permission
if (!$this->checkFolderActionPermission('delete', $folder)) {
throw new InsufficientFolderAccessPermissionsException(
'You are not allowed to delete the given folder: "' . $folder->getName() . '"',
1377779039
);
}
// Check if the user has write permissions to folders
// Would be good if we could check for actual write permissions in the containing folder
// but we cannot since we have no access to the containing folder of this file.
if (!$this->checkUserActionPermission('write', 'Folder')) {
throw new InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377779111);
}
}
/**
* 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)) {
throw new InsufficientFileAccessPermissionsException(
'You are not allowed to access that file: "' . $file->getName() . '"',
1375955429
);
}
if (!$this->checkFileExtensionPermission($file->getName())) {
throw new IllegalFileExtensionException(
'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)) {
throw new InsufficientFileWritePermissionsException('Writing to file "' . $file->getIdentifier() . '" is not allowed.', 1330121088);
}
if (!$this->checkFileExtensionPermission($file->getName())) {
throw new IllegalFileExtensionException('You are not allowed to edit a file with extension "' . $file->getExtension() . '"', 1366711933);
}
}
/**
* 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)) {
throw new InsufficientFileWritePermissionsException('Replacing file "' . $file->getIdentifier() . '" is not allowed.', 1436899571);
}
// Check if parentFolder is writable for the user
if (!$this->checkFolderActionPermission('write', $file->getParentFolder())) {
throw new InsufficientFolderWritePermissionsException('You are not allowed to write to the target folder "' . $file->getIdentifier() . '"', 1436899572);
}
}
/**
* 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())) {
throw new IllegalFileExtensionException('You are not allowed to delete a file with extension "' . $file->getExtension() . '"', 1377778916);
}
// 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)) {
throw new InsufficientFileWritePermissionsException('You are not allowed to delete the file "' . $file->getIdentifier() . '"', 1319550425);
}
// Check if the user has write permissions to folders
// Would be good if we could check for actual write permissions in the containing folder
// but we cannot since we have no access to the containing folder of this file.
if (!$this->checkUserActionPermission('write', 'Folder')) {
throw new InsufficientFolderWritePermissionsException('Writing to folders is not allowed.', 1377778702);
}
}
}
/**
* 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)) {
throw new IllegalFileExtensionException('Extension of file name is not allowed in "' . $targetFileName . '"!', 1322120271);
}