-
Notifications
You must be signed in to change notification settings - Fork 638
/
LocalDriver.php
1421 lines (1341 loc) · 56.1 KB
/
LocalDriver.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
namespace TYPO3\CMS\Core\Resource\Driver;
/*
* 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!
*/
use TYPO3\CMS\Core\Resource\Exception;
use TYPO3\CMS\Core\Resource\FolderInterface;
use TYPO3\CMS\Core\Resource\ResourceStorage;
use TYPO3\CMS\Core\Type\File\FileInfo;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
/**
* Driver for the local file system
*/
class LocalDriver extends AbstractHierarchicalFilesystemDriver
{
/**
* @var string
*/
const UNSAFE_FILENAME_CHARACTER_EXPRESSION = '\\x00-\\x2C\\/\\x3A-\\x3F\\x5B-\\x60\\x7B-\\xBF';
/**
* The absolute base path. It always contains a trailing slash.
*
* @var string
*/
protected $absoluteBasePath;
/**
* A list of all supported hash algorithms, written all lower case.
*
* @var array
*/
protected $supportedHashAlgorithms = ['sha1', 'md5'];
/**
* 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 $baseUri = null;
/** @var array */
protected $mappingFolderNameToRole = [
'_recycler_' => FolderInterface::ROLE_RECYCLER,
'_temp_' => FolderInterface::ROLE_TEMPORARY,
'user_upload' => FolderInterface::ROLE_USERUPLOAD,
];
/**
* @param array $configuration
*/
public function __construct(array $configuration = [])
{
parent::__construct($configuration);
// The capabilities default of this driver. See CAPABILITY_* constants for possible values
$this->capabilities =
ResourceStorage::CAPABILITY_BROWSABLE
| ResourceStorage::CAPABILITY_PUBLIC
| ResourceStorage::CAPABILITY_WRITABLE;
}
/**
* Merges the capabilites merged by the user at the storage
* configuration into the actual capabilities of the driver
* and returns the result.
*
* @param int $capabilities
* @return int
*/
public function mergeConfigurationCapabilities($capabilities)
{
$this->capabilities &= $capabilities;
return $this->capabilities;
}
/**
* Processes the configuration for this driver.
*/
public function processConfiguration()
{
$this->absoluteBasePath = $this->calculateBasePath($this->configuration);
$this->determineBaseUrl();
if ($this->baseUri === null) {
// remove public flag
$this->capabilities &= ~ResourceStorage::CAPABILITY_PUBLIC;
}
}
/**
* Initializes this object. This is called by the storage after the driver
* has been attached.
*/
public function initialize()
{
}
/**
* Determines the base URL for this driver, from the configuration or
* the TypoScript frontend object
*/
protected function determineBaseUrl()
{
// only calculate baseURI if the storage does not enforce jumpUrl Script
if ($this->hasCapability(ResourceStorage::CAPABILITY_PUBLIC)) {
if (GeneralUtility::isFirstPartOfStr($this->absoluteBasePath, PATH_site)) {
// use site-relative URLs
$temporaryBaseUri = rtrim(PathUtility::stripPathSitePrefix($this->absoluteBasePath), '/');
if ($temporaryBaseUri !== '') {
$uriParts = explode('/', $temporaryBaseUri);
$uriParts = array_map('rawurlencode', $uriParts);
$temporaryBaseUri = implode('/', $uriParts) . '/';
}
$this->baseUri = $temporaryBaseUri;
} elseif (isset($this->configuration['baseUri']) && GeneralUtility::isValidUrl($this->configuration['baseUri'])) {
$this->baseUri = rtrim($this->configuration['baseUri'], '/') . '/';
}
}
}
/**
* Calculates the absolute path to this drivers storage location.
*
* @throws Exception\InvalidConfigurationException
* @param array $configuration
* @return string
*/
protected function calculateBasePath(array $configuration)
{
if (!array_key_exists('basePath', $configuration) || empty($configuration['basePath'])) {
throw new Exception\InvalidConfigurationException(
'Configuration must contain base path.',
1346510477
);
}
if ($configuration['pathType'] === 'relative') {
$relativeBasePath = $configuration['basePath'];
$absoluteBasePath = PATH_site . $relativeBasePath;
} else {
$absoluteBasePath = $configuration['basePath'];
}
$absoluteBasePath = $this->canonicalizeAndCheckFilePath($absoluteBasePath);
$absoluteBasePath = rtrim($absoluteBasePath, '/') . '/';
if (!is_dir($absoluteBasePath)) {
throw new Exception\InvalidConfigurationException(
'Base path "' . $absoluteBasePath . '" does not exist or is no directory.',
1299233097
);
}
return $absoluteBasePath;
}
/**
* Returns the public URL to a file.
* For the local driver, this will always return a path relative to PATH_site.
*
* @param string $identifier
* @return string
* @throws \TYPO3\CMS\Core\Resource\Exception
*/
public function getPublicUrl($identifier)
{
$publicUrl = null;
if ($this->baseUri !== null) {
$uriParts = explode('/', ltrim($identifier, '/'));
$uriParts = array_map('rawurlencode', $uriParts);
$identifier = implode('/', $uriParts);
$publicUrl = $this->baseUri . $identifier;
}
return $publicUrl;
}
/**
* Returns the Identifier of the root level folder of the storage.
*
* @return string
*/
public function getRootLevelFolder()
{
return '/';
}
/**
* Returns identifier of the default folder new files should be put into.
*
* @return string
*/
public function getDefaultFolder()
{
$identifier = '/user_upload/';
$createFolder = !$this->folderExists($identifier);
if ($createFolder === true) {
$identifier = $this->createFolder('user_upload');
}
return $identifier;
}
/**
* Creates a folder, within a parent folder.
* If no parent folder is given, a rootlevel folder will be created
*
* @param string $newFolderName
* @param string $parentFolderIdentifier
* @param bool $recursive
* @return string the Identifier of the new folder
*/
public function createFolder($newFolderName, $parentFolderIdentifier = '', $recursive = false)
{
$parentFolderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($parentFolderIdentifier);
$newFolderName = trim($newFolderName, '/');
if ($recursive == false) {
$newFolderName = $this->sanitizeFileName($newFolderName);
$newIdentifier = $parentFolderIdentifier . $newFolderName . '/';
GeneralUtility::mkdir($this->getAbsolutePath($newIdentifier));
} else {
$parts = GeneralUtility::trimExplode('/', $newFolderName);
$parts = array_map([$this, 'sanitizeFileName'], $parts);
$newFolderName = implode('/', $parts);
$newIdentifier = $parentFolderIdentifier . $newFolderName . '/';
GeneralUtility::mkdir_deep($this->getAbsolutePath($parentFolderIdentifier) . '/' . $newFolderName);
}
return $newIdentifier;
}
/**
* Returns information about a file.
*
* @param string $fileIdentifier In the case of the LocalDriver, this is the (relative) path to the file.
* @param array $propertiesToExtract Array of properties which should be extracted, if empty all will be extracted
* @return array
* @throws \InvalidArgumentException
*/
public function getFileInfoByIdentifier($fileIdentifier, array $propertiesToExtract = [])
{
$absoluteFilePath = $this->getAbsolutePath($fileIdentifier);
// don't use $this->fileExists() because we need the absolute path to the file anyways, so we can directly
// use PHP's filesystem method.
if (!file_exists($absoluteFilePath) || !is_file($absoluteFilePath)) {
throw new \InvalidArgumentException('File ' . $fileIdentifier . ' does not exist.', 1314516809);
}
$dirPath = PathUtility::dirname($fileIdentifier);
$dirPath = $this->canonicalizeAndCheckFolderIdentifier($dirPath);
return $this->extractFileInformation($absoluteFilePath, $dirPath, $propertiesToExtract);
}
/**
* Returns information about a folder.
*
* @param string $folderIdentifier In the case of the LocalDriver, this is the (relative) path to the file.
* @return array
* @throws Exception\FolderDoesNotExistException
*/
public function getFolderInfoByIdentifier($folderIdentifier)
{
$folderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($folderIdentifier);
if (!$this->folderExists($folderIdentifier)) {
throw new Exception\FolderDoesNotExistException(
'Folder "' . $folderIdentifier . '" does not exist.',
1314516810
);
}
$absolutePath = $this->getAbsolutePath($folderIdentifier);
return [
'identifier' => $folderIdentifier,
'name' => PathUtility::basename($folderIdentifier),
'mtime' => filemtime($absolutePath),
'ctime' => filectime($absolutePath),
'storage' => $this->storageUid
];
}
/**
* Returns a string where any character not matching [.a-zA-Z0-9_-] is
* substituted by '_'
* Trailing dots are removed
*
* Previously in \TYPO3\CMS\Core\Utility\File\BasicFileUtility::cleanFileName()
*
* @param string $fileName Input string, typically the body of a fileName
* @param string $charset Charset of the a fileName (defaults to utf-8)
* @return string Output string with any characters not matching [.a-zA-Z0-9_-] is substituted by '_' and trailing dots removed
* @throws Exception\InvalidFileNameException
*/
public function sanitizeFileName($fileName, $charset = 'utf-8')
{
// Handle UTF-8 characters
if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
// Allow ".", "-", 0-9, a-z, A-Z and everything beyond U+C0 (latin capital letter a with grave)
$cleanFileName = preg_replace('/[' . self::UNSAFE_FILENAME_CHARACTER_EXPRESSION . ']/u', '_', trim($fileName));
} else {
$fileName = $this->getCharsetConversion()->specCharsToASCII($charset, $fileName);
// Replace unwanted characters by underscores
$cleanFileName = preg_replace('/[' . self::UNSAFE_FILENAME_CHARACTER_EXPRESSION . '\\xC0-\\xFF]/', '_', trim($fileName));
}
// Strip trailing dots and return
$cleanFileName = rtrim($cleanFileName, '.');
if ($cleanFileName === '') {
throw new Exception\InvalidFileNameException(
'File name ' . $fileName . ' is invalid.',
1320288991
);
}
return $cleanFileName;
}
/**
* Generic wrapper for extracting a list of items from a path.
*
* @param string $folderIdentifier
* @param int $start The position to start the listing; if not set, start from the beginning
* @param int $numberOfItems The number of items to list; if set to zero, all items are returned
* @param array $filterMethods The filter methods used to filter the directory items
* @param bool $includeFiles
* @param bool $includeDirs
* @param bool $recursive
* @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
* @throws \InvalidArgumentException
*/
protected function getDirectoryItemList($folderIdentifier, $start = 0, $numberOfItems = 0, array $filterMethods, $includeFiles = true, $includeDirs = true, $recursive = false, $sort = '', $sortRev = false)
{
$folderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($folderIdentifier);
$realPath = $this->getAbsolutePath($folderIdentifier);
if (!is_dir($realPath)) {
throw new \InvalidArgumentException(
'Cannot list items in directory ' . $folderIdentifier . ' - does not exist or is no directory',
1314349666
);
}
$items = $this->retrieveFileAndFoldersInPath($realPath, $recursive, $includeFiles, $includeDirs, $sort, $sortRev);
$iterator = new \ArrayIterator($items);
if ($iterator->count() === 0) {
return [];
}
// $c is the counter for how many items we still have to fetch (-1 is unlimited)
$c = $numberOfItems > 0 ? $numberOfItems : - 1;
$items = [];
while ($iterator->valid() && ($numberOfItems === 0 || $c > 0)) {
// $iteratorItem is the file or folder name
$iteratorItem = $iterator->current();
// go on to the next iterator item now as we might skip this one early
$iterator->next();
try {
if (
!$this->applyFilterMethodsToDirectoryItem(
$filterMethods,
$iteratorItem['name'],
$iteratorItem['identifier'],
$this->getParentFolderIdentifierOfIdentifier($iteratorItem['identifier'])
)
) {
continue;
}
if ($start > 0) {
$start--;
} else {
$items[$iteratorItem['identifier']] = $iteratorItem['identifier'];
// Decrement item counter to make sure we only return $numberOfItems
// we cannot do this earlier in the method (unlike moving the iterator forward) because we only add the
// item here
--$c;
}
} catch (Exception\InvalidPathException $e) {
}
}
return $items;
}
/**
* Applies a set of filter methods to a file name to find out if it should be used or not. This is e.g. used by
* directory listings.
*
* @param array $filterMethods The filter methods to use
* @param string $itemName
* @param string $itemIdentifier
* @param string $parentIdentifier
* @throws \RuntimeException
* @return bool
*/
protected function applyFilterMethodsToDirectoryItem(array $filterMethods, $itemName, $itemIdentifier, $parentIdentifier)
{
foreach ($filterMethods as $filter) {
if (is_callable($filter)) {
$result = call_user_func($filter, $itemName, $itemIdentifier, $parentIdentifier, [], $this);
// We have to use -1 as the „don't include“ return value, as call_user_func() will return FALSE
// If calling the method succeeded and thus we can't use that as a return value.
if ($result === -1) {
return false;
}
if ($result === false) {
throw new \RuntimeException(
'Could not apply file/folder name filter ' . $filter[0] . '::' . $filter[1],
1476046425
);
}
}
}
return true;
}
/**
* Returns a file inside the specified path
*
* @param string $fileName
* @param string $folderIdentifier
* @return string File Identifier
*/
public function getFileInFolder($fileName, $folderIdentifier)
{
return $this->canonicalizeAndCheckFileIdentifier($folderIdentifier . '/' . $fileName);
}
/**
* Returns a list of files inside the specified path
*
* @param string $folderIdentifier
* @param int $start
* @param int $numberOfItems
* @param bool $recursive
* @param array $filenameFilterCallbacks The method callbacks to use 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
*/
public function getFilesInFolder($folderIdentifier, $start = 0, $numberOfItems = 0, $recursive = false, array $filenameFilterCallbacks = [], $sort = '', $sortRev = false)
{
return $this->getDirectoryItemList($folderIdentifier, $start, $numberOfItems, $filenameFilterCallbacks, true, false, $recursive, $sort, $sortRev);
}
/**
* 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($folderIdentifier, $recursive = false, array $filenameFilterCallbacks = [])
{
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 The method callbacks to use 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
*/
public function getFoldersInFolder($folderIdentifier, $start = 0, $numberOfItems = 0, $recursive = false, array $folderNameFilterCallbacks = [], $sort = '', $sortRev = false)
{
return $this->getDirectoryItemList($folderIdentifier, $start, $numberOfItems, $folderNameFilterCallbacks, false, true, $recursive, $sort, $sortRev);
}
/**
* Returns the number of folders inside the specified path
*
* @param string $folderIdentifier
* @param bool $recursive
* @param array $folderNameFilterCallbacks callbacks for filtering the items
* @return int Number of folders in folder
*/
public function countFoldersInFolder($folderIdentifier, $recursive = false, array $folderNameFilterCallbacks = [])
{
return count($this->getFoldersInFolder($folderIdentifier, 0, 0, $recursive, $folderNameFilterCallbacks));
}
/**
* Returns a list with the names of all files and folders in a path, optionally recursive.
*
* @param string $path The absolute path
* @param bool $recursive If TRUE, recursively fetches files and folders
* @param bool $includeFiles
* @param bool $includeDirs
* @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
*/
protected function retrieveFileAndFoldersInPath($path, $recursive = false, $includeFiles = true, $includeDirs = true, $sort = '', $sortRev = false)
{
$pathLength = strlen($this->getAbsoluteBasePath());
$iteratorMode = \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::FOLLOW_SYMLINKS;
if ($recursive) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, $iteratorMode),
\RecursiveIteratorIterator::SELF_FIRST,
\RecursiveIteratorIterator::CATCH_GET_CHILD
);
} else {
$iterator = new \RecursiveDirectoryIterator($path, $iteratorMode);
}
$directoryEntries = [];
while ($iterator->valid()) {
/** @var $entry \SplFileInfo */
$entry = $iterator->current();
$isFile = $entry->isFile();
$isDirectory = $isFile ? false : $entry->isDir();
if (
(!$isFile && !$isDirectory) // skip non-files/non-folders
|| ($isFile && !$includeFiles) // skip files if they are excluded
|| ($isDirectory && !$includeDirs) // skip directories if they are excluded
|| $entry->getFilename() === '' // skip empty entries
) {
$iterator->next();
continue;
}
$entryIdentifier = '/' . substr($entry->getPathname(), $pathLength);
$entryName = PathUtility::basename($entryIdentifier);
if ($isDirectory) {
$entryIdentifier .= '/';
}
$entryArray = [
'identifier' => $entryIdentifier,
'name' => $entryName,
'type' => $isDirectory ? 'dir' : 'file'
];
$directoryEntries[$entryIdentifier] = $entryArray;
$iterator->next();
}
return $this->sortDirectoryEntries($directoryEntries, $sort, $sortRev);
}
/**
* Sort the directory entries by a certain key
*
* @param array $directoryEntries Array of directory entry arrays from
* retrieveFileAndFoldersInPath()
* @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 Sorted entries. Content of the keys is undefined.
*/
protected function sortDirectoryEntries($directoryEntries, $sort = '', $sortRev = false)
{
$entriesToSort = [];
foreach ($directoryEntries as $entryArray) {
$dir = pathinfo($entryArray['name'], PATHINFO_DIRNAME) . '/';
$fullPath = $this->getAbsoluteBasePath() . $entryArray['identifier'];
switch ($sort) {
case 'size':
$sortingKey = '0';
if ($entryArray['type'] === 'file') {
$sortingKey = $this->getSpecificFileInformation($fullPath, $dir, 'size');
}
// Add a character for a natural order sorting
$sortingKey .= 's';
break;
case 'rw':
$perms = $this->getPermissions($entryArray['identifier']);
$sortingKey = ($perms['r'] ? 'R' : '')
. ($perms['w'] ? 'W' : '');
break;
case 'fileext':
$sortingKey = pathinfo($entryArray['name'], PATHINFO_EXTENSION);
break;
case 'tstamp':
$sortingKey = '0';
if ($entryArray['type'] === 'file') {
$sortingKey = $this->getSpecificFileInformation($fullPath, $dir, 'mtime');
}
// Add a character for a natural order sorting
$sortingKey .= 't';
break;
case 'name':
case 'file':
default:
$sortingKey = $entryArray['name'];
}
$i = 0;
while (isset($entriesToSort[$sortingKey . $i])) {
$i++;
}
$entriesToSort[$sortingKey . $i] = $entryArray;
}
uksort($entriesToSort, 'strnatcasecmp');
if ($sortRev) {
$entriesToSort = array_reverse($entriesToSort);
}
return $entriesToSort;
}
/**
* Extracts information about a file from the filesystem.
*
* @param string $filePath The absolute path to the file
* @param string $containerPath The relative path to the file's container
* @param array $propertiesToExtract array of properties which should be returned, if empty all will be extracted
* @return array
*/
protected function extractFileInformation($filePath, $containerPath, array $propertiesToExtract = [])
{
if (empty($propertiesToExtract)) {
$propertiesToExtract = [
'size', 'atime', 'mtime', 'ctime', 'mimetype', 'name',
'identifier', 'identifier_hash', 'storage', 'folder_hash'
];
}
$fileInformation = [];
foreach ($propertiesToExtract as $property) {
$fileInformation[$property] = $this->getSpecificFileInformation($filePath, $containerPath, $property);
}
return $fileInformation;
}
/**
* Extracts a specific FileInformation from the FileSystems.
*
* @param string $fileIdentifier
* @param string $containerPath
* @param string $property
*
* @return bool|int|string
* @throws \InvalidArgumentException
*/
public function getSpecificFileInformation($fileIdentifier, $containerPath, $property)
{
$identifier = $this->canonicalizeAndCheckFileIdentifier($containerPath . PathUtility::basename($fileIdentifier));
/** @var FileInfo $fileInfo */
$fileInfo = GeneralUtility::makeInstance(FileInfo::class, $fileIdentifier);
switch ($property) {
case 'size':
return $fileInfo->getSize();
case 'atime':
return $fileInfo->getATime();
case 'mtime':
return $fileInfo->getMTime();
case 'ctime':
return $fileInfo->getCTime();
case 'name':
return PathUtility::basename($fileIdentifier);
case 'mimetype':
return (string)$fileInfo->getMimeType();
case 'identifier':
return $identifier;
case 'storage':
return $this->storageUid;
case 'identifier_hash':
return $this->hashIdentifier($identifier);
case 'folder_hash':
return $this->hashIdentifier($this->getParentFolderIdentifierOfIdentifier($identifier));
default:
throw new \InvalidArgumentException(sprintf('The information "%s" is not available.', $property), 1476047422);
}
}
/**
* Returns the absolute path of the folder this driver operates on.
*
* @return string
*/
protected function getAbsoluteBasePath()
{
return $this->absoluteBasePath;
}
/**
* Returns the absolute path of a file or folder.
*
* @param string $fileIdentifier
* @return string
* @throws Exception\InvalidPathException
*/
protected function getAbsolutePath($fileIdentifier)
{
$relativeFilePath = ltrim($this->canonicalizeAndCheckFileIdentifier($fileIdentifier), '/');
$path = $this->absoluteBasePath . $relativeFilePath;
return $path;
}
/**
* Creates a (cryptographic) hash for a file.
*
* @param string $fileIdentifier
* @param string $hashAlgorithm The hash algorithm to use
* @return string
* @throws \RuntimeException
* @throws \InvalidArgumentException
*/
public function hash($fileIdentifier, $hashAlgorithm)
{
if (!in_array($hashAlgorithm, $this->supportedHashAlgorithms)) {
throw new \InvalidArgumentException('Hash algorithm "' . $hashAlgorithm . '" is not supported.', 1304964032);
}
switch ($hashAlgorithm) {
case 'sha1':
$hash = sha1_file($this->getAbsolutePath($fileIdentifier));
break;
case 'md5':
$hash = md5_file($this->getAbsolutePath($fileIdentifier));
break;
default:
throw new \RuntimeException('Hash algorithm ' . $hashAlgorithm . ' is not implemented.', 1329644451);
}
return $hash;
}
/**
* Adds a file from the local server hard disk to a given path in TYPO3s virtual file system.
* This assumes that the local file exists, so no further check is done here!
* After a successful the original file must not exist anymore.
*
* @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 \RuntimeException
* @throws \InvalidArgumentException
*/
public function addFile($localFilePath, $targetFolderIdentifier, $newFileName = '', $removeOriginal = true)
{
$localFilePath = $this->canonicalizeAndCheckFilePath($localFilePath);
// as for the "virtual storage" for backwards-compatibility, this check always fails, as the file probably lies under PATH_site
// thus, it is not checked here
// @todo is check in storage
if (GeneralUtility::isFirstPartOfStr($localFilePath, $this->absoluteBasePath) && $this->storageUid > 0) {
throw new \InvalidArgumentException('Cannot add a file that is already part of this storage.', 1314778269);
}
$newFileName = $this->sanitizeFileName($newFileName !== '' ? $newFileName : PathUtility::basename($localFilePath));
$newFileIdentifier = $this->canonicalizeAndCheckFolderIdentifier($targetFolderIdentifier) . $newFileName;
$targetPath = $this->getAbsolutePath($newFileIdentifier);
if ($removeOriginal) {
if (is_uploaded_file($localFilePath)) {
$result = move_uploaded_file($localFilePath, $targetPath);
} else {
$result = rename($localFilePath, $targetPath);
}
} else {
$result = copy($localFilePath, $targetPath);
}
if ($result === false || !file_exists($targetPath)) {
throw new \RuntimeException(
'Adding file ' . $localFilePath . ' at ' . $newFileIdentifier . ' failed.',
1476046453
);
}
clearstatcache();
// Change the permissions of the file
GeneralUtility::fixPermissions($targetPath);
return $newFileIdentifier;
}
/**
* Checks if a file exists.
*
* @param string $fileIdentifier
*
* @return bool
*/
public function fileExists($fileIdentifier)
{
$absoluteFilePath = $this->getAbsolutePath($fileIdentifier);
return is_file($absoluteFilePath);
}
/**
* Checks if a file inside a folder exists
*
* @param string $fileName
* @param string $folderIdentifier
* @return bool
*/
public function fileExistsInFolder($fileName, $folderIdentifier)
{
$identifier = $folderIdentifier . '/' . $fileName;
$identifier = $this->canonicalizeAndCheckFileIdentifier($identifier);
return $this->fileExists($identifier);
}
/**
* Checks if a folder exists.
*
* @param string $folderIdentifier
*
* @return bool
*/
public function folderExists($folderIdentifier)
{
$absoluteFilePath = $this->getAbsolutePath($folderIdentifier);
return is_dir($absoluteFilePath);
}
/**
* Checks if a folder inside a folder exists.
*
* @param string $folderName
* @param string $folderIdentifier
* @return bool
*/
public function folderExistsInFolder($folderName, $folderIdentifier)
{
$identifier = $folderIdentifier . '/' . $folderName;
$identifier = $this->canonicalizeAndCheckFolderIdentifier($identifier);
return $this->folderExists($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($folderName, $folderIdentifier)
{
$folderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($folderIdentifier . '/' . $folderName);
return $folderIdentifier;
}
/**
* Replaces the contents (and file-specific metadata) of a file object with a local file.
*
* @param string $fileIdentifier
* @param string $localFilePath
* @return bool TRUE if the operation succeeded
* @throws \RuntimeException
*/
public function replaceFile($fileIdentifier, $localFilePath)
{
$filePath = $this->getAbsolutePath($fileIdentifier);
if (is_uploaded_file($localFilePath)) {
$result = move_uploaded_file($localFilePath, $filePath);
} else {
$result = rename($localFilePath, $filePath);
}
GeneralUtility::fixPermissions($filePath);
if ($result === false) {
throw new \RuntimeException('Replacing file ' . $fileIdentifier . ' with ' . $localFilePath . ' failed.', 1315314711);
}
return $result;
}
/**
* Copies a file *within* the current storage.
* Note that this is only about an intra-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($fileIdentifier, $targetFolderIdentifier, $fileName)
{
$sourcePath = $this->getAbsolutePath($fileIdentifier);
$newIdentifier = $targetFolderIdentifier . '/' . $fileName;
$newIdentifier = $this->canonicalizeAndCheckFileIdentifier($newIdentifier);
$absoluteFilePath = $this->getAbsolutePath($newIdentifier);
copy($sourcePath, $absoluteFilePath);
GeneralUtility::fixPermissions($absoluteFilePath);
return $newIdentifier;
}
/**
* Moves a file *within* the current storage.
* Note that this is only about an inner-storage move action, where a file is just
* moved to another folder in the same storage.
*
* @param string $fileIdentifier
* @param string $targetFolderIdentifier
* @param string $newFileName
* @return string
* @throws \RuntimeException
*/
public function moveFileWithinStorage($fileIdentifier, $targetFolderIdentifier, $newFileName)
{
$sourcePath = $this->getAbsolutePath($fileIdentifier);
$targetIdentifier = $targetFolderIdentifier . '/' . $newFileName;
$targetIdentifier = $this->canonicalizeAndCheckFileIdentifier($targetIdentifier);
$result = rename($sourcePath, $this->getAbsolutePath($targetIdentifier));
if ($result === false) {
throw new \RuntimeException('Moving file ' . $sourcePath . ' to ' . $targetIdentifier . ' failed.', 1315314712);
}
return $targetIdentifier;
}
/**
* Copies a file to a temporary path and returns that path.
*
* @param string $fileIdentifier
* @return string The temporary path
* @throws \RuntimeException
*/
protected function copyFileToTemporaryPath($fileIdentifier)
{
$sourcePath = $this->getAbsolutePath($fileIdentifier);
$temporaryPath = $this->getTemporaryPathForFile($fileIdentifier);
$result = copy($sourcePath, $temporaryPath);
touch($temporaryPath, filemtime($sourcePath));
if ($result === false) {
throw new \RuntimeException(
'Copying file "' . $fileIdentifier . '" to temporary path "' . $temporaryPath . '" failed.',
1320577649
);
}
return $temporaryPath;
}
/**
* Moves a file or folder to the given directory, renaming the source in the process if
* a file or folder of the same name already exists in the target path.
*
* @param string $filePath
* @param string $recycleDirectory
* @return bool
*/
protected function recycleFileOrFolder($filePath, $recycleDirectory)
{
$destinationFile = $recycleDirectory . '/' . PathUtility::basename($filePath);
if (file_exists($destinationFile)) {
$timeStamp = \DateTimeImmutable::createFromFormat('U.u', microtime(true))->format('YmdHisu');
$destinationFile = $recycleDirectory . '/' . $timeStamp . '_' . PathUtility::basename($filePath);
}
$result = rename($filePath, $destinationFile);
// Update the mtime for the file, so the recycler garbage collection task knows which files to delete
// Using ctime() is not possible there since this is not supported on Windows
if ($result) {
touch($destinationFile);
}
return $result;
}
/**
* Creates a map of old and new file/folder identifiers after renaming or
* moving a folder. The old identifier is used as the key, the new one as the value.
*
* @param array $filesAndFolders
* @param string $sourceFolderIdentifier
* @param string $targetFolderIdentifier
*
* @return array
* @throws Exception\FileOperationErrorException
*/
protected function createIdentifierMap(array $filesAndFolders, $sourceFolderIdentifier, $targetFolderIdentifier)
{
$identifierMap = [];
$identifierMap[$sourceFolderIdentifier] = $targetFolderIdentifier;
foreach ($filesAndFolders as $oldItem) {
if ($oldItem['type'] === 'dir') {
$oldIdentifier = $oldItem['identifier'];
$newIdentifier = $this->canonicalizeAndCheckFolderIdentifier(
str_replace($sourceFolderIdentifier, $targetFolderIdentifier, $oldItem['identifier'])
);
} else {
$oldIdentifier = $oldItem['identifier'];
$newIdentifier = $this->canonicalizeAndCheckFileIdentifier(
str_replace($sourceFolderIdentifier, $targetFolderIdentifier, $oldItem['identifier'])
);
}
if (!file_exists($this->getAbsolutePath($newIdentifier))) {