-
Notifications
You must be signed in to change notification settings - Fork 638
/
FileList.php
1572 lines (1441 loc) · 70.2 KB
/
FileList.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\Filelist;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Backend\Backend\Avatar\Avatar;
use TYPO3\CMS\Backend\Clipboard\Clipboard;
use TYPO3\CMS\Backend\Configuration\TranslationConfigurationProvider;
use TYPO3\CMS\Backend\Routing\UriBuilder;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException;
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Core\Resource\Filter\FileExtensionFilter;
use TYPO3\CMS\Core\Resource\Folder;
use TYPO3\CMS\Core\Resource\FolderInterface;
use TYPO3\CMS\Core\Resource\InaccessibleFolder;
use TYPO3\CMS\Core\Resource\ProcessedFile;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Resource\ResourceInterface;
use TYPO3\CMS\Core\Resource\Search\FileSearchDemand;
use TYPO3\CMS\Core\Resource\StorageRepository;
use TYPO3\CMS\Core\Resource\Utility\ListUtility;
use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Filelist\Event\ProcessFileListActionsEvent;
/**
* Class for rendering of File>Filelist (basically used in FileListController)
* @see \TYPO3\CMS\Filelist\Controller\FileListController
* @internal this is a concrete TYPO3 controller implementation and solely used for EXT:filelist and not part of TYPO3's Core API.
*/
class FileList
{
/**
* Default Max items shown
*
* @var int
*/
public $iLimit = 40;
/**
* Thumbnails on records containing files (pictures)
*
* @var bool
*/
public $thumbs = false;
/**
* Space icon used for alignment when no button is available
*
* @var string
*/
public $spaceIcon;
/**
* Max length of strings
*
* @var int
*/
public $fixedL = 30;
/**
* The field to sort by
*
* @var string
*/
public $sort = '';
/**
* Reverse sorting flag
*
* @var bool
*/
public $sortRev = true;
/**
* @var int
*/
public $firstElementNumber = 0;
/**
* @var int
*/
public $totalbytes = 0;
/**
* This could be set to the total number of items. Used by the fwd_rew_navigation...
*
* @var int
*/
public $totalItems = 0;
/**
* Decides the columns shown. Filled with values that refers to the keys of the data-array. $this->fieldArray[0] is the title column.
*
* @var array
*/
public $fieldArray = [];
/**
* Counter increased for each element. Used to index elements for the JavaScript-code that transfers to the clipboard
*
* @var int
*/
public $counter = 0;
/**
* @var TranslationConfigurationProvider
*/
public $translateTools;
/**
* Keys are fieldnames and values are td-css-classes to add in addElement();
*
* @var array
*/
public $addElement_tdCssClass = [
'_CONTROL_' => 'col-control',
'_SELECTOR_' => 'col-selector',
'icon' => 'col-icon',
'name' => 'col-title col-responsive',
];
/**
* @var Folder
*/
protected $folderObject;
/**
* @var array
*/
public $CBnames = [];
/**
* @var Clipboard $clipObj
*/
public $clipObj;
/**
* @var ResourceFactory
*/
protected $resourceFactory;
/**
* @var IconFactory
*/
protected $iconFactory;
/**
* @var int
*/
protected $id = 0;
/**
* @var UriBuilder
*/
protected $uriBuilder;
protected ?FileSearchDemand $searchDemand = null;
protected ?FileExtensionFilter $fileExtensionFilter = null;
/**
* A runtime first-level cache to avoid unneeded calls to BackendUtility::getRecord()
* @var array
*/
protected array $backendUserCache = [];
protected EventDispatcherInterface $eventDispatcher;
public function __construct(?ServerRequestInterface $request = null)
{
// Setting the maximum length of the filenames to the user's settings or minimum 30 (= $this->fixedL)
$this->fixedL = max($this->fixedL, $this->getBackendUser()->uc['titleLen'] ?? 1);
$this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
$this->eventDispatcher = GeneralUtility::makeInstance(EventDispatcherInterface::class);
$this->translateTools = GeneralUtility::makeInstance(TranslationConfigurationProvider::class);
$this->iLimit = MathUtility::forceIntegerInRange(
$this->getBackendUser()->getTSConfig()['options.']['file_list.']['filesPerPage'] ?? $this->iLimit,
1
);
// Create clipboard object and initialize that
$this->clipObj = GeneralUtility::makeInstance(Clipboard::class);
$this->clipObj->initializeClipboard($request);
$this->resourceFactory = GeneralUtility::makeInstance(ResourceFactory::class);
$this->getLanguageService()->includeLLFile('EXT:filelist/Resources/Private/Language/locallang_mod_file_list.xlf');
$this->getLanguageService()->includeLLFile('EXT:core/Resources/Private/Language/locallang_common.xlf');
$this->uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
$this->spaceIcon = '<span class="btn btn-default disabled">' . $this->iconFactory->getIcon('empty-empty', Icon::SIZE_SMALL)->render() . '</span>';
// Initialize file extension filter, if configured
$fileDownloadConfiguration = (array)($this->getBackendUser()->getTSConfig()['options.']['file_list.']['fileDownload.'] ?? []);
if ($fileDownloadConfiguration !== []) {
$this->fileExtensionFilter = GeneralUtility::makeInstance(FileExtensionFilter::class);
$this->fileExtensionFilter->setAllowedFileExtensions(
GeneralUtility::trimExplode(',', (string)($fileDownloadConfiguration['allowedFileExtensions'] ?? ''), true)
);
$this->fileExtensionFilter->setDisallowedFileExtensions(
GeneralUtility::trimExplode(',', (string)($fileDownloadConfiguration['disallowedFileExtensions'] ?? ''), true)
);
}
}
/**
* Initialization of class
*
* @param Folder $folderObject The folder to work on
* @param int $pointer Pointer
* @param string $sort Sorting column
* @param bool $sortRev Sorting direction
*/
public function start(Folder $folderObject, $pointer, $sort, $sortRev)
{
$this->folderObject = $folderObject;
$this->counter = 0;
$this->totalbytes = 0;
$this->sort = $sort;
$this->sortRev = $sortRev;
$this->firstElementNumber = $pointer;
$this->fieldArray = [
'_SELECTOR_', 'icon', 'name', '_CONTROL_', 'record_type', 'size', 'rw', '_REF_',
];
}
public function setColumnsToRender(array $additionalFields = []): void
{
$this->fieldArray = array_unique(array_merge($this->fieldArray, $additionalFields));
}
/**
* Returns a table with directories and files listed.
*
* @param FileSearchDemand|null $searchDemand
* @return string HTML-table
*/
public function getTable(?FileSearchDemand $searchDemand = null): string
{
if ($searchDemand !== null) {
// Store given search demand
$this->searchDemand = $searchDemand;
// Search currently only works for files
$folders = [];
// Find files by the given search demand
$files = iterator_to_array($this->folderObject->searchFiles($this->searchDemand));
// @todo Currently files, which got deleted in the file system, are still found.
// Therefore we have to ask their parent folder if it still contains the file.
$files = array_filter($files, static function (FileInterface $file): bool {
try {
if ($file->getParentFolder()->hasFile($file->getName())) {
return true;
}
} catch (ResourceDoesNotExistException $e) {
// Nothing to do, file does not longer exist in folder
}
return false;
});
// @todo We have to manually slice the search result, since it may
// contain invalid files, which were manually filtered out above.
// This should be fixed, so we can use the $firstResult and $maxResults
// properties of the search demand directly.
$this->totalItems = count($files);
if (trim($this->sort) !== '') {
// Sort the files before applying the pagination
$files = $this->sortFiles($files);
}
$filesNum = $this->firstElementNumber + $this->iLimit > $this->totalItems
? $this->totalItems - $this->firstElementNumber
: $this->iLimit;
$files = array_slice($files, $this->firstElementNumber, $filesNum);
// Add special "Path" field for the search result
array_splice($this->fieldArray, 3, 0, '_PATH_');
} else {
// @todo use folder methods directly when they support filters
$storage = $this->folderObject->getStorage();
$storage->resetFileAndFolderNameFiltersToDefault();
// Only render the contents of a browsable storage
if (!$this->folderObject->getStorage()->isBrowsable()) {
return '';
}
try {
$foldersCount = $storage->countFoldersInFolder($this->folderObject);
$filesCount = $storage->countFilesInFolder($this->folderObject);
} catch (InsufficientFolderAccessPermissionsException $e) {
$foldersCount = 0;
$filesCount = 0;
}
if ($foldersCount <= $this->firstElementNumber) {
$foldersFrom = false;
$foldersNum = false;
} else {
$foldersFrom = $this->firstElementNumber;
if ($this->firstElementNumber + $this->iLimit > $foldersCount) {
$foldersNum = $foldersCount - $this->firstElementNumber;
} else {
$foldersNum = $this->iLimit;
}
}
if ($foldersCount >= $this->firstElementNumber + $this->iLimit) {
$filesFrom = false;
$filesNum = false;
} elseif ($this->firstElementNumber <= $foldersCount) {
$filesFrom = 0;
$filesNum = $this->iLimit - $foldersNum;
} else {
$filesFrom = $this->firstElementNumber - $foldersCount;
if ($filesFrom + $this->iLimit > $filesCount) {
$filesNum = $filesCount - $filesFrom;
} else {
$filesNum = $this->iLimit;
}
}
// Initialize files and folders
$files = [];
$folders = [];
if (trim($this->sort) !== '') {
// Note: In case sorting is requested, this can not be done by the driver because
// the sorting field might be a metadata field, which is not known to the
// driver (see #97443). This therefore requires to fetch all files and folders
// first. They are then sorted and sliced to respect the current pagination.
if ($foldersNum) {
// Only perform find/sort/slice in case at least one folder is available
$folders = $this->sortFolders($storage->getFoldersInFolder($this->folderObject));
$folders = array_slice($folders, $foldersFrom, $foldersNum);
}
if ($filesNum) {
// Only perform find/sort/slice in case at least one file is available
$files = $this->sortFiles($this->folderObject->getFiles());
$files = array_slice($files, $filesFrom, $filesNum);
}
} else {
$folders = $storage->getFoldersInFolder($this->folderObject, $foldersFrom, $foldersNum);
$files = $this->folderObject->getFiles($filesFrom, $filesNum, Folder::FILTER_MODE_USE_OWN_AND_STORAGE_FILTERS, false);
}
$this->totalItems = $foldersCount + $filesCount;
}
$iOut = '';
// Directories are added
$iOut .= $this->fwd_rwd_nav($this->firstElementNumber);
$iOut .= $this->formatDirList($folders);
// Files are added
$iOut .= $this->formatFileList($files);
$amountOfItemsShownOnCurrentPage = $this->firstElementNumber + $this->iLimit < $this->totalItems
? $this->firstElementNumber + $this->iLimit
: -1;
$iOut .= $this->fwd_rwd_nav($amountOfItemsShownOnCurrentPage);
// Header line is drawn
$theData = [];
foreach ($this->fieldArray as $fieldName) {
if ($fieldName === '_SELECTOR_') {
$theData[$fieldName] = $this->renderCheckboxActions();
} elseif ($fieldName === '_CONTROL_') {
// Special case: The control column header should not be wrapped into a sort link
$theData[$fieldName] = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels._CONTROL_');
} elseif ($specialLabel = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.' . $fieldName)) {
$theData[$fieldName] = $this->linkWrapSort($fieldName, $specialLabel);
} elseif ($customLabel = $this->getLanguageService()->getLL('c_' . $fieldName)) {
$theData[$fieldName] = $this->linkWrapSort($fieldName, $customLabel);
} elseif ($fieldName !== 'icon') {
// Normal database field
$theData[$fieldName] = $this->linkWrapSort($fieldName);
}
}
return '
<div class="table-fit mb-4">
<table class="table table-striped table-hover" id="typo3-filelist">
<thead>' . $this->addElement($theData, [], true) . '</thead>
<tbody data-multi-record-selection-row-selection="true">' . $iOut . '</tbody>
</table>
</div>';
}
/**
* Returns a table-row with the content from the fields in the input data array.
* OBS: $this->fieldArray MUST be set! (represents the list of fields to display)
*
* @param array $data Is the data array, record with the fields. Notice: These fields are (currently) NOT htmlspecialchar'ed before being wrapped in <td>-tags
* @param array $attributes Attributes for the table row. Values will be htmlspecialchar'ed!
* @param bool $isTableHeader Whether the element to be added is a table header
*
* @return string HTML content for the table row
*/
public function addElement(array $data, array $attributes = [], bool $isTableHeader = false): string
{
// Initialize rendering.
$cols = [];
$colType = $isTableHeader ? 'th' : 'td';
$colspan = '';
$colspanCounter = 0;
$lastField = '';
// Traverse field array which contains the data to present:
foreach ($this->fieldArray as $fieldName) {
if (isset($data[$fieldName])) {
if ($lastField && isset($data[$lastField])) {
$cssClass = $this->addElement_tdCssClass[$lastField] ?? '';
$cols[] = '<' . $colType . ' class="' . $cssClass . '"' . $colspan . '>' . $data[$lastField] . '</' . $colType . '>';
}
$lastField = $fieldName;
$colspanCounter = 1;
} else {
if (!$lastField) {
$lastField = $fieldName;
}
$colspanCounter++;
}
$colspan = ($colspanCounter > 1) ? ' colspan="' . $colspanCounter . '"' : '';
}
if ($lastField) {
$cssClass = $this->addElement_tdCssClass[$lastField] ?? '';
$cols[] = '<' . $colType . ' class="' . $cssClass . '"' . $colspan . '>' . $data[$lastField] . '</' . $colType . '>';
}
// Add the the table row
return '
<tr ' . GeneralUtility::implodeAttributes($attributes, true) . '>
' . implode(PHP_EOL, $cols) . '
</tr>';
}
/**
* Creates a forward/reverse button based on the status of ->eCounter, ->firstElementNumber, ->iLimit
*
* @return string the table-row code for the element
*/
public function fwd_rwd_nav(int $currentItemCount): string
{
$code = '';
if ($currentItemCount >= $this->firstElementNumber && $currentItemCount < $this->firstElementNumber + $this->iLimit) {
if ($this->firstElementNumber && $currentItemCount == $this->firstElementNumber) {
// Reverse
$theData = [];
$href = $this->listURL(['pointer' => ($currentItemCount - $this->iLimit)]);
$theData['_SELECTOR_'] = '<a href="' . htmlspecialchars($href) . '">' . $this->iconFactory->getIcon(
'actions-move-up',
Icon::SIZE_SMALL
)->render() . ' <i>[' . (max(0, $currentItemCount - $this->iLimit) + 1) . ' - ' . $currentItemCount . ']</i></a>';
$code = $this->addElement($theData);
}
return $code;
}
if ($currentItemCount === $this->firstElementNumber + $this->iLimit) {
// Forward
$theData = [];
$href = $this->listURL(['pointer' => $currentItemCount]);
$theData['_SELECTOR_'] = '<a href="' . htmlspecialchars($href) . '">' . $this->iconFactory->getIcon(
'actions-move-down',
Icon::SIZE_SMALL
)->render() . ' <i>[' . ($currentItemCount + 1) . ' - ' . $this->totalItems . ']</i></a>';
$code = $this->addElement($theData);
}
return $code;
}
/**
* Gets the number of files and total size of a folder
*
* @return string
*/
public function getFolderInfo()
{
if ($this->counter == 1) {
$fileLabel = htmlspecialchars($this->getLanguageService()->getLL('file'));
} else {
$fileLabel = htmlspecialchars($this->getLanguageService()->getLL('files'));
}
return $this->counter . ' ' . $fileLabel . ', ' . GeneralUtility::formatSize($this->totalbytes, htmlspecialchars($this->getLanguageService()->getLL('byteSizeUnits')));
}
/**
* This returns tablerows for the directories in the array $items['sorting'].
*
* @param Folder[] $folders Folders of \TYPO3\CMS\Core\Resource\Folder
* @return string HTML table rows.
*/
public function formatDirList(array $folders)
{
$out = '';
foreach (ListUtility::resolveSpecialFolderNames($folders) as $folderName => $folderObject) {
$role = $folderObject->getRole();
if ($role === FolderInterface::ROLE_PROCESSING) {
// don't show processing-folder
continue;
}
if ($role !== FolderInterface::ROLE_DEFAULT) {
$displayName = '<strong>' . htmlspecialchars($folderName) . '</strong>';
} else {
$displayName = htmlspecialchars($folderName);
}
$isLocked = $folderObject instanceof InaccessibleFolder;
$isWritable = $folderObject->checkActionPermission('write');
// Initialization
$this->counter++;
// The icon - will be linked later on, if not locked
$theIcon = $this->getFileOrFolderIcon($folderName, $folderObject);
// Preparing and getting the data-array
$theData = [];
// Preparing table row attributes
$attributes = [
'data-type' => 'folder',
'data-folder-identifier' => $folderObject->getIdentifier(),
'data-combined-identifier' => $folderObject->getCombinedIdentifier(),
];
if ($isLocked) {
foreach ($this->fieldArray as $field) {
$theData[$field] = '';
}
$theData['icon'] = $theIcon;
$theData['name'] = $displayName;
} else {
foreach ($this->fieldArray as $field) {
switch ($field) {
case 'size':
try {
$numFiles = $folderObject->getFileCount();
} catch (InsufficientFolderAccessPermissionsException $e) {
$numFiles = 0;
}
$theData[$field] = $numFiles . ' ' . htmlspecialchars($this->getLanguageService()->getLL(($numFiles === 1 ? 'file' : 'files')));
break;
case 'rw':
$theData[$field] = '<strong class="text-danger">' . htmlspecialchars($this->getLanguageService()->getLL('read')) . '</strong>' . (!$isWritable ? '' : '<strong class="text-danger">' . htmlspecialchars($this->getLanguageService()->getLL('write')) . '</strong>');
break;
case 'record_type':
$theData[$field] = htmlspecialchars($this->getLanguageService()->getLL('folder'));
break;
case 'icon':
$theData[$field] = (string)BackendUtility::wrapClickMenuOnIcon($theIcon, 'sys_file', $folderObject->getCombinedIdentifier());
break;
case 'name':
$theData[$field] = $this->linkWrapDir($displayName, $folderObject);
break;
case '_CONTROL_':
$theData[$field] = $this->makeEdit($folderObject);
break;
case '_SELECTOR_':
$theData[$field] = $this->makeCheckbox($folderObject);
break;
case '_REF_':
$theData[$field] = '-';
break;
case '_PATH_':
$theData[$field] = $this->makePath($folderObject);
break;
default:
$theData[$field] = GeneralUtility::fixed_lgd_cs($theData[$field] ?? '', $this->fixedL);
}
}
}
$out .= $this->addElement($theData, $attributes);
}
return $out;
}
/**
* Wraps the directory-titles
*
* @param string $title String to be wrapped in links
* @param Folder $folderObject Folder to work on
* @return string HTML
*/
public function linkWrapDir($title, Folder $folderObject)
{
$href = $this->listURL(['id' => $folderObject->getCombinedIdentifier(), 'searchTerm' => '', 'pointer' => 0]);
// Sometimes $code contains plain HTML tags. In such a case the string should not be modified!
if ((string)$title === strip_tags($title)) {
return '<a href="' . htmlspecialchars($href) . '" title="' . htmlspecialchars($title) . '">' . $title . '</a>';
}
return '<a href="' . htmlspecialchars($href) . '">' . $title . '</a>';
}
/**
* Wraps filenames in links which opens the metadata editor.
*
* @param string $code String to be wrapped in links
* @param File $fileObject File to be linked
* @return string HTML
*/
public function linkWrapFile($code, File $fileObject)
{
try {
if ($this->isEditMetadataAllowed($fileObject)
&& ($metaDataUid = $fileObject->getMetaData()->offsetGet('uid'))
) {
$urlParameters = [
'edit' => [
'sys_file_metadata' => [
$metaDataUid => 'edit',
],
],
'returnUrl' => $this->listURL(),
];
$url = (string)$this->uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
$title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.editMetadata'));
$code = '<a class="responsive-title" href="' . htmlspecialchars($url) . '" title="' . $title . '">' . $code . '</a>';
}
} catch (\Exception $e) {
// intentional fall-through
}
return $code;
}
/**
* Returns list URL; This is the URL of the current script with id and imagemode parameters, that's all.
*
* @return string URL
*/
public function listURL(array $params = []): string
{
$params = array_replace_recursive([
'pointer' => $this->firstElementNumber,
'id' => $this->folderObject->getCombinedIdentifier(),
'searchTerm' => $this->searchDemand ? $this->searchDemand->getSearchTerm() : '',
], $params);
$params = array_filter($params);
return (string)$this->uriBuilder->buildUriFromRoute('file_FilelistList', $params);
}
/**
* This returns tablerows for the files in the array $items['sorting'].
*
* @param File[] $files File items
* @return string HTML table rows.
*/
public function formatFileList(array $files)
{
$out = '';
foreach ($files as $fileObject) {
// Initialization
$this->counter++;
$this->totalbytes += $fileObject->getSize();
$ext = $fileObject->getExtension();
$fileUid = $fileObject->getUid();
$fileName = trim($fileObject->getName());
// Preparing and getting the data-array
$theData = [];
// Preparing table row attributes
$attributes = [
'data-type' => 'file',
'data-file-uid' => $fileUid,
];
if ($this->isEditMetadataAllowed($fileObject)
&& ($metaDataUid = $fileObject->getMetaData()->offsetGet('uid'))
) {
$attributes['data-metadata-uid'] = (string)$metaDataUid;
}
foreach ($this->fieldArray as $field) {
switch ($field) {
case 'size':
$theData[$field] = GeneralUtility::formatSize((int)$fileObject->getSize(), htmlspecialchars($this->getLanguageService()->getLL('byteSizeUnits')));
break;
case 'rw':
$theData[$field] = '' . (!$fileObject->checkActionPermission('read') ? ' ' : '<strong class="text-danger">' . htmlspecialchars($this->getLanguageService()->getLL('read')) . '</strong>') . (!$fileObject->checkActionPermission('write') ? '' : '<strong class="text-danger">' . htmlspecialchars($this->getLanguageService()->getLL('write')) . '</strong>');
break;
case 'record_type':
$theData[$field] = htmlspecialchars($this->getLanguageService()->getLL('file') . ($ext ? ' (' . strtoupper($ext) . ')' : ''));
break;
case '_CONTROL_':
$theData[$field] = $this->makeEdit($fileObject);
break;
case '_SELECTOR_':
$theData[$field] = $this->makeCheckbox($fileObject);
break;
case '_REF_':
$theData[$field] = $this->makeRef($fileObject);
break;
case '_PATH_':
$theData[$field] = $this->makePath($fileObject);
break;
case 'icon':
$theData[$field] = (string)BackendUtility::wrapClickMenuOnIcon($this->getFileOrFolderIcon($fileName, $fileObject), 'sys_file', $fileObject->getCombinedIdentifier());
break;
case 'name':
// Edit metadata of file
$theData[$field] = $this->linkWrapFile(htmlspecialchars($fileName), $fileObject);
if ($fileObject->isMissing()) {
$theData[$field] .= '<span class="label label-danger label-space-left">'
. htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:warning.file_missing'))
. '</span>';
// Thumbnails?
} elseif ($this->thumbs && ($fileObject->isImage() || $fileObject->isMediaFile())) {
$processedFile = $fileObject->process(
ProcessedFile::CONTEXT_IMAGEPREVIEW,
[
'width' => (int)($this->getBackendUser()->getTSConfig()['options.']['file_list.']['thumbnail.']['width'] ?? 64),
'height' => (int)($this->getBackendUser()->getTSConfig()['options.']['file_list.']['thumbnail.']['height'] ?? 64),
]
);
$theData[$field] .= '<br /><img src="' . htmlspecialchars($processedFile->getPublicUrl() ?? '') . '" ' .
'width="' . htmlspecialchars($processedFile->getProperty('width')) . '" ' .
'height="' . htmlspecialchars($processedFile->getProperty('height')) . '" ' .
'title="' . htmlspecialchars($fileName) . '" alt="" />';
}
break;
case 'crdate':
$crdate = $fileObject->getCreationTime();
$theData[$field] = $crdate ? BackendUtility::datetime($crdate) : '-';
break;
case 'tstamp':
$tstamp = $fileObject->getModificationTime();
$theData[$field] = $tstamp ? BackendUtility::datetime($tstamp) : '-';
break;
default:
$theData[$field] = '';
if ($fileObject->hasProperty($field)) {
$concreteTableName = $this->getConcreteTableName($field);
if ($field === ($GLOBALS['TCA'][$concreteTableName]['ctrl']['cruser_id'] ?? '')) {
// Handle cruser_id by adding the avatar along with the username
$theData[$field] = $this->getBackendUserInformation((int)$fileObject->getProperty($field));
} elseif ($field === 'storage') {
// Fetch storage name of the current file
$storage = GeneralUtility::makeInstance(StorageRepository::class)->findByUid((int)$fileObject->getProperty($field));
if ($storage !== null) {
$theData[$field] = htmlspecialchars($storage->getName());
}
} else {
$theData[$field] = htmlspecialchars(
(string)BackendUtility::getProcessedValueExtra(
$this->getConcreteTableName($field),
$field,
$fileObject->getProperty($field),
$this->fixedL,
$fileObject->getMetaData()->offsetGet('uid')
)
);
}
}
}
}
$out .= $this->addElement($theData, $attributes);
}
return $out;
}
/**
* Fetch the translations for a sys_file_metadata record
*
* @param array $metaDataRecord
* @return array<int, array<string, mixed>> keys are the sys_language uids, values are the $rows
*/
protected function getTranslationsForMetaData($metaDataRecord)
{
$languageField = $GLOBALS['TCA']['sys_file_metadata']['ctrl']['languageField'] ?? '';
$languageParentField = $GLOBALS['TCA']['sys_file_metadata']['ctrl']['transOrigPointerField'] ?? '';
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_metadata');
$queryBuilder->getRestrictions()->removeAll();
$translationRecords = $queryBuilder->select('*')
->from('sys_file_metadata')
->where(
$queryBuilder->expr()->eq(
$languageParentField,
$queryBuilder->createNamedParameter($metaDataRecord['uid'] ?? 0, Connection::PARAM_INT)
),
$queryBuilder->expr()->gt(
$languageField,
$queryBuilder->createNamedParameter(0, Connection::PARAM_INT)
)
)
->executeQuery()
->fetchAllAssociative();
$translations = [];
foreach ($translationRecords as $record) {
$languageId = $record[$languageField];
$translations[$languageId] = $record;
}
return $translations;
}
/**
* Wraps a field label for the header row into a link to the filelist with sorting commands
*
* @param string $fieldName The field to sort
* @param string $label The label to be wrapped - will be determined if not given
* @return string The constructed link - HTML
*/
public function linkWrapSort(string $fieldName, string $label = ''): string
{
// Determine label if not given
if ($label === '') {
$lang = $this->getLanguageService();
$concreteTableName = $this->getConcreteTableName($fieldName);
$label = $lang->sL(BackendUtility::getItemLabel($concreteTableName, $fieldName) ?? '');
if ($label !== '') {
// In case global TSconfig exists we have to check if the label is overridden there
$tsConfig = BackendUtility::getPagesTSconfig(0);
if (!empty($tsConfig['TCEFORM.'][$concreteTableName . '.'][$fieldName . '.']['label.'][$lang->lang])) {
$label = $tsConfig['TCEFORM.'][$concreteTableName . '.'][$fieldName . '.']['label.'][$lang->lang];
} elseif (!empty($tsConfig['TCEFORM.'][$concreteTableName . '.'][$fieldName . '.']['label'])) {
$label = $tsConfig['TCEFORM.'][$concreteTableName . '.'][$fieldName . '.']['label'];
}
}
}
$params = ['SET' => ['sort' => $fieldName], 'pointer' => 0];
if ($this->sort === $fieldName) {
// Check reverse sorting
$params['SET']['reverse'] = ($this->sortRev ? '0' : '1');
$sortArrow = $this->iconFactory->getIcon('status-status-sorting-' . ($this->sortRev ? 'desc' : 'asc'), Icon::SIZE_SMALL)->render();
} else {
$params['SET']['reverse'] = 0;
$sortArrow = '';
}
$href = $this->listURL($params);
return '<a href="' . htmlspecialchars($href) . '">' . htmlspecialchars($label) . ' ' . $sortArrow . '</a>';
}
/**
* Creates the clipboard actions
*
* @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the clipboard actions for the listing.
* @return array clipboard actions
*/
public function makeClip($fileOrFolderObject): array
{
if (!$fileOrFolderObject->checkActionPermission('read')) {
return [];
}
$actions = [];
$fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
$fullName = $fileOrFolderObject->getName();
$md5 = md5($fullIdentifier);
// Add copy/cut buttons in "normal" mode:
if ($this->clipObj->current === 'normal') {
$isSel = $this->clipObj->isSelected('_FILE', $md5);
if ($fileOrFolderObject->checkActionPermission('copy')) {
$copyTitle = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.' . ($isSel === 'copy' ? 'copyrelease' : 'copy'));
$copyUrl = $this->clipObj->selUrlFile($fullIdentifier, true, $isSel === 'copy');
$actions['copy'] = '
<a class="btn btn-default" href="' . htmlspecialchars($copyUrl) . '" title="' . htmlspecialchars($copyTitle) . '">
' . $this->iconFactory->getIcon($isSel === 'copy' ? 'actions-edit-copy-release' : 'actions-edit-copy', Icon::SIZE_SMALL)->render() . '
</a>';
}
if ($fileOrFolderObject->checkActionPermission('move')) {
$cutTitle = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.' . ($isSel === 'cut' ? 'cutrelease' : 'cut'));
$cutUrl = $this->clipObj->selUrlFile($fullIdentifier, false, $isSel === 'cut');
$actions['cut'] = '
<a class="btn btn-default" href="' . htmlspecialchars($cutUrl) . '" title="' . htmlspecialchars($cutTitle) . '">
' . $this->iconFactory->getIcon($isSel === 'cut' ? 'actions-edit-cut-release' : 'actions-edit-cut', Icon::SIZE_SMALL)->render() . '
</a>';
}
}
$elFromTable = $this->clipObj->elFromTable('_FILE');
$addPasteButton = $this->folderObject->checkActionPermission(
($this->clipObj->clipData[$this->clipObj->current]['mode'] ?? '') === 'copy' ? 'copy' : 'move'
);
if (!$fileOrFolderObject instanceof Folder
|| $elFromTable === []
|| !$addPasteButton
|| !$fileOrFolderObject->checkActionPermission('write')
) {
//early return actions, in case paste should not be displayed
return $actions;
}
$elToConfirm = [];
foreach ($elFromTable as $key => $element) {
$clipBoardElement = $this->resourceFactory->retrieveFileOrFolderObject($element);
if ($clipBoardElement instanceof Folder
&& $clipBoardElement->getStorage()->isWithinFolder($clipBoardElement, $fileOrFolderObject)
) {
// In case folder is already present in the target folder, return actions without paste button
return $actions;
}
$elToConfirm[$key] = $clipBoardElement->getName();
}
$pasteUrl = $this->clipObj->pasteUrl('_FILE', $fullIdentifier);
$pasteTitle = $this->getLanguageService()->getLL('clip_pasteInto');
$pasteContent = $this->clipObj->confirmMsgText('_FILE', $fullName, 'into', $elToConfirm);
$actions[] = '
<a class="btn btn-default t3js-modal-trigger" data-severity="warning" href="' . htmlspecialchars($pasteUrl) . '" data-bs-content="' . htmlspecialchars($pasteContent) . '" data-title="' . htmlspecialchars($pasteTitle) . '" title="' . htmlspecialchars($pasteTitle) . '">
' . $this->iconFactory->getIcon('actions-document-paste-into', Icon::SIZE_SMALL)->render() . '
</a>';
return $actions;
}
/**
* Adds the checkbox to select a file/folder in the listing
*
* @param File|Folder $fileOrFolderObject
* @return string
*/
protected function makeCheckbox($fileOrFolderObject): string
{
if (!$fileOrFolderObject->checkActionPermission('read')) {
return '';
}
$fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
$md5 = md5($fullIdentifier);
$identifier = '_FILE|' . $md5;
$this->CBnames[] = $identifier;
return '
<span class="form-check form-toggle">
<input class="form-check-input t3js-multi-record-selection-check" type="checkbox" name="CBC[' . $identifier . ']" value="' . htmlspecialchars($fullIdentifier) . '"/>
</span>';
}
/**
* Creates the edit control section
*
* @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the edit control section for the listing.
* @return string HTML-table
*/
public function makeEdit($fileOrFolderObject)
{
$cells = [];
$fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
// Edit file content (if editable)
if ($fileOrFolderObject instanceof File && $fileOrFolderObject->checkActionPermission('write') && $fileOrFolderObject->isTextFile()) {
$attributes = [
'href' => (string)$this->uriBuilder->buildUriFromRoute('file_edit', ['target' => $fullIdentifier, 'returnUrl' => $this->listURL()]),
'title' => $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.editcontent'),
];
$cells['edit'] = '<a class="btn btn-default" ' . GeneralUtility::implodeAttributes($attributes, true) . '>'
. $this->iconFactory->getIcon('actions-page-open', Icon::SIZE_SMALL)->render()
. '</a>';
} else {
$cells['edit'] = $this->spaceIcon;
}
// Edit metadata of file
if ($fileOrFolderObject instanceof File
&& $this->isEditMetadataAllowed($fileOrFolderObject)
&& ($metaDataUid = $fileOrFolderObject->getMetaData()->offsetGet('uid'))
) {
$urlParameters = [
'edit' => [
'sys_file_metadata' => [
$metaDataUid => 'edit',
],
],
'returnUrl' => $this->listURL(),
];
$url = (string)$this->uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
$title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.editMetadata'));
$cells['metadata'] = '<a class="btn btn-default" href="' . htmlspecialchars($url) . '" title="' . $title . '">' . $this->iconFactory->getIcon('actions-open', Icon::SIZE_SMALL)->render() . '</a>';
}
// Get translation actions
if ($fileOrFolderObject instanceof File && ($translations = $this->makeTranslations($fileOrFolderObject))) {
$cells['translations'] = $translations;
}
// document view
if ($fileOrFolderObject instanceof File) {
$fileUrl = $fileOrFolderObject->getPublicUrl();
if ($fileUrl) {
$cells['view'] = '<a href="' . htmlspecialchars($fileUrl) . '" target="_blank" class="btn btn-default" title="' . $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.view') . '">' . $this->iconFactory->getIcon('actions-document-view', Icon::SIZE_SMALL)->render() . '</a>';
} else {
$cells['view'] = $this->spaceIcon;
}