-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathAmazonS3Driver.php
More file actions
1932 lines (1753 loc) · 69.3 KB
/
Copy pathAmazonS3Driver.php
File metadata and controls
1932 lines (1753 loc) · 69.3 KB
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 an extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2023 Markus Hölzle <typo3@markus-hoelzle.de>
*
***/
namespace AUS\AusDriverAmazonS3\Driver;
use AUS\AusDriverAmazonS3\Event\GetFileForLocalProcessingEvent;
use AUS\AusDriverAmazonS3\S3Adapter\MetaInfoDownloadAdapter;
use AUS\AusDriverAmazonS3\S3Adapter\MultipartUploaderAdapter;
use AUS\AusDriverAmazonS3\Service\CompatibilityService;
use AUS\AusDriverAmazonS3\Service\FileNameService;
use Aws\S3\S3Client;
use Aws\S3\StreamWrapper;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Http\Response;
use TYPO3\CMS\Core\Log\LogLevel;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Resource\Driver\AbstractHierarchicalFilesystemDriver;
use TYPO3\CMS\Core\Resource\Driver\StreamableDriverInterface;
use TYPO3\CMS\Core\Resource\Exception;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Core\Resource\Folder;
use TYPO3\CMS\Core\Resource\ResourceStorage;
use TYPO3\CMS\Core\Resource\ResourceStorageInterface;
use TYPO3\CMS\Core\Resource\StorageRepository;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
use TYPO3\CMS\Core\Resource\Capabilities;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
/**
* Class AmazonS3Driver
* Driver for Amazon Simple Storage Service (S3)
*
* @author Markus Hölzle <typo3@markus-hoelzle.de>
* @package AUS\AusDriverAmazonS3\Driver
*/
class AmazonS3Driver extends AbstractHierarchicalFilesystemDriver implements StreamableDriverInterface
{
const DRIVER_TYPE = 'AusDriverAmazonS3';
const EXTENSION_KEY = 'aus_driver_amazon_s3';
const EXTENSION_NAME = 'AusDriverAmazonS3';
const FILTER_ALL = 'all';
const FILTER_FOLDERS = 'folders';
const FILTER_FILES = 'files';
const ROOT_FOLDER_IDENTIFIER = '/';
const FILE_CONTENT_HASH_IGNORE = 0;
const FILE_CONTENT_HASH_RECEIVE = 1;
const FILE_CONTENT_HASH_FORCE = 2;
/**
* @var S3Client
*/
protected $s3Client = null;
/**
* The base URL that points to this driver's storage. As long is this is not set, it is assumed that this folder
* is not publicly available
*
* @var string
*/
protected $baseUrl = '';
/**
* Folder that is used as root folder.
* Must be empty or have a trailing slash.
*
* @var string
*/
protected $baseFolder = '';
/**
* Stream wrapper protocol: Will be set in the constructor
*
* @var string
*/
protected $streamWrapperProtocol = '';
/**
* The identifier map used for renaming
*
* @var array
*/
protected $identifierMap = [];
/**
* Object meta data is cached here as array or null
* $identifier => [meta info as array]
*
* @var FrontendInterface
*/
protected FrontendInterface $metaInfoCache;
/**
* Generic request -> response cache
* Used for 'listObjectsV2' until now
*
* @var FrontendInterface
*/
protected FrontendInterface $requestCache;
/**
* To differentiate between multiple drivers
*/
protected string $cachePrefix = '';
/**
* Object permissions are cached here in subarrays like:
* $identifier => ['r' => bool, 'w' => bool]
*
* @var array
*/
protected $objectPermissionsCache = [];
/**
* Processing folder
*
* @var string
*/
protected $processingFolder = '';
/**
* Default processing folder
*
* @var string
*/
protected $processingFolderDefault = '_processed_';
/**
* @var \TYPO3\CMS\Core\Resource\ResourceStorage
*/
protected $storage = null;
/**
* @var array
*/
protected static $settings = null;
/**
* @var string
*/
protected $languageFile = 'EXT:aus_driver_amazon_s3/Resources/Private/Language/locallang_flexform.xlf';
/**
* @var array
*/
protected $temporaryPaths = [];
protected EventDispatcherInterface $eventDispatcher;
/**
* @var CompatibilityService
*/
protected $compatibilityService;
protected $fileContentHash = self::FILE_CONTENT_HASH_IGNORE;
/**
* @param array $configuration
* @param S3Client $s3Client
*/
public function __construct(array $configuration = [], $s3Client = null, EventDispatcherInterface $eventDispatcher = null)
{
parent::__construct($configuration);
$this->eventDispatcher = $eventDispatcher ?? GeneralUtility::makeInstance(EventDispatcherInterface::class);
$this->compatibilityService = GeneralUtility::makeInstance(CompatibilityService::class);
// The capabilities default of this driver. See CAPABILITY_* constants for possible values
$this->capabilities = GeneralUtility::makeInstance(Capabilities::class)->addCapabilities(
Capabilities::CAPABILITY_BROWSABLE,
Capabilities::CAPABILITY_PUBLIC,
Capabilities::CAPABILITY_WRITABLE,
Capabilities::CAPABILITY_HIERARCHICAL_IDENTIFIERS
);
$this->streamWrapperProtocol = 's3-' . substr(md5(uniqid()), 0, 7);
$this->s3Client = $s3Client;
$this->metaInfoCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('ausdriveramazons3_metainfocache');
$this->requestCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('ausdriveramazons3_requestcache');
}
/**
* Remove temporary used files.
* This is a poor software architecture style: temp files should be deleted by the FAL users and not by the FAL drivers
* @see https://forge.typo3.org/issues/56982
* @see https://review.typo3.org/#/c/36446/
*/
public function __destruct()
{
foreach ($this->temporaryPaths as $temporaryPath) {
@unlink($temporaryPath);
}
}
/**
* loadExternalClasses
* @throws \Exception
*/
public static function loadExternalClasses(): void
{
// Backwards compatibility: for TYPO3 versions lower than 10.0
$loadSdk = !Environment::isComposerMode() && !function_exists('Aws\\manifest');
if ($loadSdk) {
require ExtensionManagementUtility::extPath(self::EXTENSION_KEY) . '/Resources/Private/PHP/vendor/autoload.php';
}
}
/**
* @return void
*/
public function processConfiguration(): void
{
}
/**
* @return void
*/
public function initialize(): void
{
$this->initializeSettings()
->initializeClient();
// Test connection if we are in the edit view of this storage
if (
$this->compatibilityService->isBackend()
&& isset($_GET['edit']['sys_file_storage']) && !empty($_GET['edit']['sys_file_storage'])
) {
$this->testConnection();
}
}
/**
* @param string $identifier
* @return string
*/
public function getPublicUrl(string $identifier): ?string
{
$uriParts = GeneralUtility::trimExplode('/', ltrim($identifier, '/'), true);
$uriParts = array_map('rawurlencode', $uriParts);
return $this->baseUrl . '/' . $this->addBaseFolder(implode('/', $uriParts));
}
/**
* Creates a (cryptographic) hash for a file.
*
* @param string $fileIdentifier
* @param string $hashAlgorithm
* @return string
*/
public function hash(string $fileIdentifier, string $hashAlgorithm): string
{
if ($this->fileContentHash) {
$result = $this->s3Client->headObject([
'Bucket' => $this->configuration['bucket'],
'Key' => $fileIdentifier,
]);
$key = 'hash-' . $hashAlgorithm;
if (isset($result['Metadata'][$key])) {
return $result['Metadata'][$key];
}
if ($this->fileContentHash === self::FILE_CONTENT_HASH_FORCE) {
$result = $this->s3Client->getObject([
'Bucket' => $this->configuration['bucket'],
'Key' => $fileIdentifier,
]);
$bodyStream = $result['Body']->detach();
$hashContext = hash_init($hashAlgorithm);
while (!feof($bodyStream)) {
$chunk = fread($bodyStream, 32768);
if ($chunk === false) {
break;
}
hash_update($hashContext, $chunk);
}
fclose($bodyStream);
return hash_final($hashContext);
}
}
return $this->hashIdentifier($fileIdentifier);
}
/**
* Returns the identifier of the default folder new files should be put into.
*
* @return string
*/
public function getDefaultFolder(): string
{
return $this->getRootLevelFolder();
}
/**
* Returns the identifier of the root level folder of the storage.
*
* @return string
*/
public function getRootLevelFolder(): string
{
return '/';
}
/**
* Returns information about a file.
*
* @param string $fileIdentifier
* @param array $propertiesToExtract Array of properties which are be extracted
* If empty all will be extracted
* @return array
* @throws \InvalidArgumentException If the file does not exist
*/
public function getFileInfoByIdentifier(string $fileIdentifier, array $propertiesToExtract = []): array
{
if (count($propertiesToExtract) === 0 || in_array('mimetype', $propertiesToExtract)) {
// force to reload the infos from S3 if the mime type was requested
$this->flushMetaInfoCache($fileIdentifier);
}
$return = $this->getMetaInfo($fileIdentifier);
if ($return === null) {
throw new \InvalidArgumentException('File ' . $fileIdentifier . ' does not exist', 1503500470);
}
if (count($propertiesToExtract) > 0) {
$return = array_intersect_key($return, array_flip($propertiesToExtract));
}
return $return;
}
/**
* Checks if a file exists
*
* @param string $identifier
* @return bool
*/
public function fileExists(string $identifier): bool
{
if (substr($identifier, -1) === '/' || $identifier === '') {
return false;
}
return $this->objectExists($identifier);
}
/**
* Checks if a folder exists
*
* @param string $identifier
* @return bool
*/
public function folderExists(string $identifier): bool
{
if ($identifier === self::ROOT_FOLDER_IDENTIFIER) {
return true;
}
if (substr($identifier, -1) !== '/') {
$identifier .= '/';
}
return $this->prefixExists($identifier);
}
/**
* @param string $fileName
* @param string $folderIdentifier
* @return bool
*/
public function fileExistsInFolder(string $fileName, string $folderIdentifier): bool
{
return $this->objectExists(rtrim($folderIdentifier, '/') . '/' . $fileName);
}
/**
* Checks if a folder exists inside a storage folder
*
* @param string $folderName
* @param string $folderIdentifier Parent folder
* @return bool
*/
public function folderExistsInFolder(string $folderName, string $folderIdentifier): bool
{
$identifier = rtrim($folderIdentifier, '/') . '/' . $folderName;
$this->normalizeFolderIdentifier($identifier);
return $this->prefixExists($identifier);
}
/**
* Returns the Identifier for a folder within a given folder.
*
* @param string $folderName The name of the target folder
* @param string $folderIdentifier
* @return string
*/
public function getFolderInFolder(string $folderName, string $folderIdentifier): string
{
$identifier = $folderIdentifier . '/' . $folderName;
$this->normalizeFolderIdentifier($identifier);
return $identifier;
}
/**
* @param string $localFilePath (within PATH_site)
* @param string $targetFolderIdentifier
* @param string $newFileName optional, if not given original name is used
* @param bool $removeOriginal if set the original file will be removed
* after successful operation
* @return string the identifier of the new file
* @throws \Exception
*/
public function addFile(string $localFilePath, string $targetFolderIdentifier, string $newFileName = '', bool $removeOriginal = true): string
{
$newFileName = $this->sanitizeFileName($newFileName !== '' ? $newFileName : PathUtility::basename($localFilePath));
$targetIdentifier = $targetFolderIdentifier . $newFileName;
$localIdentifier = $localFilePath;
$this->normalizeIdentifier($localIdentifier);
// if the source file is also in this driver
if (!is_uploaded_file($localFilePath) && $this->objectExists($localIdentifier)) {
if ($removeOriginal) {
rename($this->getStreamWrapperPath($localIdentifier), $this->getStreamWrapperPath($targetIdentifier));
} else {
copy($this->getStreamWrapperPath($localIdentifier), $this->getStreamWrapperPath($targetIdentifier));
}
} else { // upload local file
$this->normalizeIdentifier($targetIdentifier);
if (filesize($localFilePath) === 0) { // Multipart uploader would fail to upload empty files
$this->s3Client->upload(
$this->configuration['bucket'],
$this->addBaseFolder($targetIdentifier),
''
);
} else {
$multipartUploadAdapter = GeneralUtility::makeInstance(MultipartUploaderAdapter::class, $this->s3Client);
$multipartUploadAdapter->upload(
$localFilePath,
$this->addBaseFolder($targetIdentifier),
$this->configuration['bucket'],
$this->getCacheControl($targetIdentifier),
$this->fileContentHash
);
}
if ($removeOriginal) {
unlink($localFilePath);
}
}
$this->flushMetaInfoCache($targetIdentifier);
return $targetIdentifier;
}
/**
* @param string $fileIdentifier
* @param string $targetFolderIdentifier
* @param string $newFileName
*
* @return string
*/
public function moveFileWithinStorage(string $fileIdentifier, string $targetFolderIdentifier, string $newFileName): string
{
$this->normalizeFolderIdentifier($targetFolderIdentifier);
$targetIdentifier = $targetFolderIdentifier . $newFileName;
$this->renameObject($fileIdentifier, $targetIdentifier);
return $targetIdentifier;
}
/**
* Copies a file *within* the current storage.
* Note that this is only about an inner storage copy action,
* where a file is just copied to another folder in the same storage.
*
* @param string $fileIdentifier
* @param string $targetFolderIdentifier
* @param string $fileName
* @return string the Identifier of the new file
*/
public function copyFileWithinStorage(string $fileIdentifier, string $targetFolderIdentifier, string $fileName): string
{
$targetIdentifier = $targetFolderIdentifier . $fileName;
$this->copyObject($fileIdentifier, $targetIdentifier);
return $targetIdentifier;
}
/**
* Replaces a file with file in local file system.
*
* @param string $fileIdentifier
* @param string $localFilePath
* @return bool TRUE if the operation succeeded
* @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException
*/
public function replaceFile(string $fileIdentifier, string $localFilePath): bool
{
$contents = file_get_contents($localFilePath);
$written = $this->setFileContents($fileIdentifier, $contents);
$this->flushMetaInfoCache($fileIdentifier);
return $written > 0;
}
/**
* Removes a file from the filesystem. This does not check if the file is
* still used or if it is a bad idea to delete it for some other reason
* this has to be taken care of in the upper layers (e.g. the Storage)!
*
* @param string $fileIdentifier
* @return bool TRUE if deleting the file succeeded
*/
public function deleteFile(string $fileIdentifier): bool
{
return $this->deleteObject($fileIdentifier);
}
/**
* Removes a folder in filesystem.
*
* @param string $folderIdentifier
* @param bool $deleteRecursively
* @return bool
*/
public function deleteFolder(string $folderIdentifier, bool $deleteRecursively = false): bool
{
if ($deleteRecursively) {
$items = $this->getListObjects($folderIdentifier);
foreach ($items['Contents'] ?? [] as $object) {
// Filter the folder itself
if ($object['Key'] !== $folderIdentifier) {
if ($this->isDir($object['Key'])) {
$subFolder = $this->getFolder($object['Key']);
if ($subFolder) {
$this->deleteFolder($subFolder->getIdentifier(), $deleteRecursively);
}
} else {
unlink($this->getStreamWrapperPath($object['Key']));
}
}
}
}
return $this->deleteObject($folderIdentifier);
}
/**
* Returns a path to a local copy of a file for processing it. When changing the
* file, you have to take care of replacing the current version yourself!
* The file will be removed by the driver automatically on destruction.
*
* @param string $fileIdentifier
* @param bool $writable Set this to FALSE if you only need the file for read
* operations. This might speed up things, e.g. by using
* a cached local version. Never modify the file if you
* have set this flag!
* @return string The path to the file on the local disk
* @throws \RuntimeException
* @todo take care of replacing the file on change
*/
public function getFileForLocalProcessing(string $fileIdentifier, bool $writable = true): string
{
$temporaryPath = $this->getTemporaryPathForFile($fileIdentifier);
try {
$this->s3Client->getObject([
'Bucket' => $this->configuration['bucket'],
'Key' => $this->addBaseFolder($fileIdentifier),
'SaveAs' => $temporaryPath,
]);
} catch (\Exception $exception) {
// Just prevent the exception content to be written in the temporary file. See next condition below
}
if (!is_file($temporaryPath)) {
throw new \RuntimeException('Copying file ' . $fileIdentifier . ' to temporary path failed.', 1320577649);
}
/** @var GetFileForLocalProcessingEvent $event */
$event = $this->eventDispatcher->dispatch(
new GetFileForLocalProcessingEvent($fileIdentifier, $temporaryPath, $writable)
);
$temporaryPath = $event->getTemporaryPath();
if (!isset($this->temporaryPaths[$temporaryPath])) {
$this->temporaryPaths[$temporaryPath] = $temporaryPath;
}
return $temporaryPath;
}
/**
* Creates a new (empty) file and returns the identifier.
*
* @param string $fileName
* @param string $parentFolderIdentifier
* @return string
*/
public function createFile(string $fileName, string $parentFolderIdentifier): string
{
$parentFolderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($parentFolderIdentifier);
$identifier = $this->canonicalizeAndCheckFileIdentifier(
$parentFolderIdentifier . $this->sanitizeFileName(ltrim($fileName, '/'))
);
$this->createObject($identifier);
return $identifier;
}
/**
* Creates a folder, within a parent folder.
* If no parent folder is given, a root level folder will be created
*
* @param string $newFolderName
* @param string $parentFolderIdentifier
* @param bool $recursive
* @return string the Identifier of the new folder
*/
public function createFolder(string $newFolderName, string $parentFolderIdentifier = '', bool $recursive = false): string
{
$parentFolderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($parentFolderIdentifier);
$newFolderName = trim($newFolderName, '/');
if ($recursive === false) {
$newFolderName = $this->sanitizeFileName($newFolderName);
$identifier = $parentFolderIdentifier . $newFolderName . '/';
} else {
$parts = GeneralUtility::trimExplode('/', $newFolderName);
$parts = array_map([$this, 'sanitizeFileName'], $parts);
$newFolderName = implode('/', $parts);
$identifier = $parentFolderIdentifier . $newFolderName . '/';
}
$this->createObject($identifier);
return $identifier;
}
/**
* Returns the contents of a file. Beware that this requires to load the
* complete file into memory and also may require fetching the file from an
* external location. So this might be an expensive operation (both in terms
* of processing resources and money) for large files.
*
* @param string $fileIdentifier
* @return string The file contents
*/
public function getFileContents(string $fileIdentifier): string
{
$result = $this->s3Client->getObject([
'Bucket' => $this->configuration['bucket'],
'Key' => $this->addBaseFolder($fileIdentifier)
]);
return (string)$result['Body'];
}
/**
* Sets the contents of a file to the specified value.
*
* @param string $fileIdentifier
* @param string $contents
* @return int The number of bytes written to the file
*/
public function setFileContents(string $fileIdentifier, string $contents): int
{
return file_put_contents($this->getStreamWrapperPath($fileIdentifier), $contents);
}
/**
* Renames a file in this storage.
*
* @param string $fileIdentifier
* @param string $newName The target path (including the file name!)
* @return string The identifier of the file after renaming
*/
public function renameFile(string $fileIdentifier, string $newName): string
{
$newName = $this->sanitizeFileName($newName);
$newIdentifier = rtrim(PathUtility::dirname($fileIdentifier), '/') . '/' . $newName;
$this->renameObject($fileIdentifier, $newIdentifier);
return $newIdentifier;
}
/**
* Renames a folder in this storage.
*
* @param string $folderIdentifier
* @param string $newName
* @return array A map of old to new file identifiers of all affected resources
*/
public function renameFolder(string $folderIdentifier, string $newName): array
{
$this->resetIdentifierMap();
$newName = $this->sanitizeFileName($newName);
$parentFolderName = PathUtility::dirname($folderIdentifier);
if ($parentFolderName === '.') {
$parentFolderName = '';
} else {
$parentFolderName .= '/';
}
$newIdentifier = $parentFolderName . $newName . '/';
foreach ($this->getSubObjects($folderIdentifier, false) as $object) {
$subObjectIdentifier = $object['Key'];
if ($this->isDir($subObjectIdentifier)) {
$this->renameSubFolder($this->getFolder($subObjectIdentifier), $newIdentifier);
} else {
$newSubObjectIdentifier = $newIdentifier . basename($subObjectIdentifier);
$this->renameObject($subObjectIdentifier, $newSubObjectIdentifier);
}
}
$this->renameObject($folderIdentifier, $newIdentifier);
return $this->identifierMap;
}
/**
* Folder equivalent to moveFileWithinStorage().
*
* @param string $sourceFolderIdentifier
* @param string $targetFolderIdentifier
* @param string $newFolderName
*
* @return array All files which are affected, map of old => new file identifiers
*/
public function moveFolderWithinStorage(string $sourceFolderIdentifier, string $targetFolderIdentifier, string $newFolderName): array
{
$this->resetIdentifierMap();
$newIdentifier = $targetFolderIdentifier . $newFolderName . '/';
$this->renameObject($sourceFolderIdentifier, $newIdentifier);
$subObjects = $this->getSubObjects($sourceFolderIdentifier);
$this->sortObjectsForNestedFolderOperations($subObjects);
foreach ($subObjects as $subObject) {
$newIdentifier = $targetFolderIdentifier . $newFolderName . '/' . substr(
$subObject['Key'],
strlen($sourceFolderIdentifier)
);
$this->renameObject($subObject['Key'], $newIdentifier);
}
return $this->identifierMap;
}
/**
* Folder equivalent to copyFileWithinStorage().
*
* @param string $sourceFolderIdentifier
* @param string $targetFolderIdentifier
* @param string $newFolderName
*
* @return bool
*/
public function copyFolderWithinStorage(string $sourceFolderIdentifier, string $targetFolderIdentifier, string $newFolderName): bool
{
$newIdentifier = $targetFolderIdentifier . $newFolderName . '/';
$this->copyObject($sourceFolderIdentifier, $newIdentifier);
$subObjects = $this->getSubObjects($sourceFolderIdentifier);
$this->sortObjectsForNestedFolderOperations($subObjects);
foreach ($subObjects as $subObject) {
$newIdentifier = $targetFolderIdentifier . $newFolderName . '/' . substr(
$subObject['Key'],
strlen($sourceFolderIdentifier)
);
$this->copyObject($subObject['Key'], $newIdentifier);
}
return true;
}
/**
* Checks if a folder contains files and (if supported) other folders.
*
* @param string $folderIdentifier
* @return bool TRUE if there are no files and folders within $folder
*/
public function isFolderEmpty(string $folderIdentifier): bool
{
$result = $this->getListObjects(
$folderIdentifier,
[
'MaxKeys' => 2
]
);
//MinIO does not return the folder itself, but S3 does.
// Unify the results and remove the folder itself.
if (isset($result['Contents']) && count($result['Contents'])) {
if ($result['Contents'][0]['Key'] == $folderIdentifier) {
unset($result['Contents'][0]);
}
}
if (isset($result['Contents']) && count($result['Contents']) > 0) {
return false;
}
return true;
}
/**
* Checks if a given identifier is within a container, e.g. if
* a file or folder is within another folder.
* This can e.g. be used to check for web-mounts.
*
* Hint: this also needs to return TRUE if the given identifier
* matches the container identifier to allow access to the root
* folder of a filemount.
*
* @param string $folderIdentifier
* @param string $identifier identifier to be checked against $folderIdentifier
* @return bool TRUE if $content is within or matches $folderIdentifier
*/
public function isWithin(string $folderIdentifier, string $identifier): bool
{
$folderIdentifier = $this->canonicalizeAndCheckFileIdentifier($folderIdentifier);
$entryIdentifier = $this->canonicalizeAndCheckFileIdentifier($identifier);
if ($folderIdentifier === $entryIdentifier) {
return true;
}
// File identifier canonicalization will not modify a single slash so
// we must not append another slash in that case.
if ($folderIdentifier !== '/') {
$folderIdentifier .= '/';
}
return $this->compatibilityService->isFirstPartOfStr($entryIdentifier, $folderIdentifier);
}
/**
* Returns information about a file.
*
* @param string $folderIdentifier
*/
public function getFolderInfoByIdentifier(string $folderIdentifier): array
{
$this->normalizeIdentifier($folderIdentifier);
return [
'identifier' => rtrim($folderIdentifier, '/') . '/',
'name' => basename(rtrim($folderIdentifier, '/')),
'storage' => $this->storageUid,
'ctime' => null,
'mtime' => null,
];
}
/**
* Returns a file inside the specified path
*
* @param string $fileName
* @param string $folderIdentifier
* @return string File Identifier
*/
public function getFileInFolder(string $fileName, string $folderIdentifier): string
{
$folderIdentifier = $folderIdentifier . '/' . $fileName;
$this->normalizeIdentifier($folderIdentifier);
return $folderIdentifier;
}
/**
* Returns a list of files inside the specified path
*
* @param string $folderIdentifier
* @param int $start
* @param int $numberOfItems
* @param bool $recursive
* @param array $filenameFilterCallbacks callbacks for filtering the items
* @param string $sort Property name used to sort the items.
* Among them may be: '' (empty, no sorting), name,
* fileext, size, tstamp and rw.
* If a driver does not support the given property, it
* should fall back to "name".
* @param bool $sortRev TRUE to indicate reverse sorting (last to first)
*
* @return array of FileIdentifiers
* @toDo: Implement $start, $numberOfItems, $sort and $sortRev
*/
public function getFilesInFolder(string $folderIdentifier, int $start = 0, int $numberOfItems = 0, bool $recursive = false, array $filenameFilterCallbacks = [], string $sort = '', bool $sortRev = false): array
{
$this->normalizeFolderIdentifier($folderIdentifier);
$files = [];
if ($folderIdentifier === self::ROOT_FOLDER_IDENTIFIER) {
$folderIdentifier = '';
}
$overrideArgs = [];
if (!$recursive) {
$overrideArgs['Delimiter'] = '/';
}
$response = $this->getListObjects($folderIdentifier, $overrideArgs);
if (isset($response['Contents'])) {
foreach ($response['Contents'] as $fileCandidate) {
// skip directory entries
if (substr($fileCandidate['Key'], -1) === '/') {
continue;
}
// skip subdirectory entries
if (!$recursive && substr_count($fileCandidate['Key'], '/') > substr_count($folderIdentifier, '/')) {
continue;
}
$fileName = basename($fileCandidate['Key']);
// check filter
if (
!$this->applyFilterMethodsToDirectoryItem(
$filenameFilterCallbacks,
$fileName,
$fileCandidate['Key'],
dirname($fileCandidate['Key'])
)
) {
continue;
}
$files[$fileCandidate['Key']] = $fileCandidate['Key'];
}
}
if ($numberOfItems > 0) {
return array_splice($files, $start, $numberOfItems);
} else {
return $files;
}
}
/**
* Returns the number of files inside the specified path
*
* @param string $folderIdentifier
* @param bool $recursive
* @param array $filenameFilterCallbacks callbacks for filtering the items
* @return int Number of files in folder
*/
public function countFilesInFolder(string $folderIdentifier, bool $recursive = false, array $filenameFilterCallbacks = []): int
{
return count($this->getFilesInFolder($folderIdentifier, 0, 0, $recursive, $filenameFilterCallbacks));
}
/**
* Returns a list of folders inside the specified path
* @param string $folderIdentifier
* @param int $start
* @param int $numberOfItems
* @param bool $recursive
* @param array $folderNameFilterCallbacks callbacks for filtering the items
* @param string $sort Property name used to sort the items.
* Among them may be: '' (empty, no sorting), name,
* fileext, size, tstamp and rw.
* If a driver does not support the given property, it
* should fall back to "name".
* @param bool $sortRev TRUE to indicate reverse sorting (last to first)
*
* @return array of Folder Identifier
* @toDo: Implement params $start, $numberOfItems, $sort, $sortRev
*/
public function getFoldersInFolder(string $folderIdentifier, int $start = 0, int $numberOfItems = 0, bool $recursive = false, array $folderNameFilterCallbacks = [], string $sort = '', bool $sortRev = false): array
{
$this->normalizeIdentifier($folderIdentifier);
$folders = [];
$folderIdentifier = $folderIdentifier === self::ROOT_FOLDER_IDENTIFIER ? '' : $folderIdentifier;
if ($recursive) {
// search folders recursive
$response = $this->getListObjects($folderIdentifier);
if ($response['Contents']) {
foreach ($response['Contents'] as $folderCandidate) {
$key = '/' . $folderCandidate['Key'];
$folderName = basename(rtrim($key, '/'));
// filter only folders
if (substr($key, -1) !== '/') {
continue;
}
if (!$this->applyFilterMethodsToDirectoryItem($folderNameFilterCallbacks, $folderName, $key, dirname($folderName))) {