[BUGFIX] EXT:filelist Deleting a folder shows "Yes, delete this folder"
[Packages/TYPO3.CMS.git] / typo3 / sysext / filelist / Classes / FileList.php
1 <?php
2 namespace TYPO3\CMS\Filelist;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Clipboard\Clipboard;
18 use TYPO3\CMS\Backend\Configuration\TranslationConfigurationProvider;
19 use TYPO3\CMS\Backend\RecordList\AbstractRecordList;
20 use TYPO3\CMS\Backend\Utility\BackendUtility;
21 use TYPO3\CMS\Core\Database\DatabaseConnection;
22 use TYPO3\CMS\Core\Imaging\Icon;
23 use TYPO3\CMS\Core\Imaging\IconFactory;
24 use TYPO3\CMS\Core\Messaging\FlashMessage;
25 use TYPO3\CMS\Core\Messaging\FlashMessageService;
26 use TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException;
27 use TYPO3\CMS\Core\Resource\File;
28 use TYPO3\CMS\Core\Resource\Folder;
29 use TYPO3\CMS\Core\Resource\FolderInterface;
30 use TYPO3\CMS\Core\Resource\InaccessibleFolder;
31 use TYPO3\CMS\Core\Resource\ProcessedFile;
32 use TYPO3\CMS\Core\Resource\ResourceFactory;
33 use TYPO3\CMS\Core\Resource\Utility\ListUtility;
34 use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
35 use TYPO3\CMS\Core\Utility\GeneralUtility;
36 use TYPO3\CMS\Filelist\Controller\FileListController;
37
38 /**
39 * Class for rendering of File>Filelist
40 */
41 class FileList extends AbstractRecordList
42 {
43 /**
44 * Default Max items shown
45 *
46 * @var int
47 */
48 public $iLimit = 40;
49
50 /**
51 * Thumbnails on records containing files (pictures)
52 *
53 * @var bool
54 */
55 public $thumbs = false;
56
57 /**
58 * Space icon used for alignment when no button is available
59 *
60 * @var string
61 */
62 public $spaceIcon;
63
64 /**
65 * Max length of strings
66 *
67 * @var int
68 */
69 public $fixedL = 30;
70
71 /**
72 * If TRUE click menus are generated on files and folders
73 *
74 * @var bool
75 */
76 public $clickMenus = 1;
77
78 /**
79 * The field to sort by
80 *
81 * @var string
82 */
83 public $sort = '';
84
85 /**
86 * Reverse sorting flag
87 *
88 * @var bool
89 */
90 public $sortRev = 1;
91
92 /**
93 * @var int
94 */
95 public $firstElementNumber = 0;
96
97 /**
98 * @var bool
99 */
100 public $clipBoard = 0;
101
102 /**
103 * @var bool
104 */
105 public $bigControlPanel = 0;
106
107 /**
108 * @var string
109 */
110 public $JScode = '';
111
112 /**
113 * @var string
114 */
115 public $HTMLcode = '';
116
117 /**
118 * @var int
119 */
120 public $totalbytes = 0;
121
122 /**
123 * @var array
124 */
125 public $dirs = array();
126
127 /**
128 * @var array
129 */
130 public $files = array();
131
132 /**
133 * @var string
134 */
135 public $path = '';
136
137 /**
138 * @var Folder
139 */
140 protected $folderObject;
141
142 /**
143 * Counting the elements no matter what
144 *
145 * @var int
146 */
147 public $eCounter = 0;
148
149 /**
150 * @var string
151 */
152 public $totalItems = '';
153
154 /**
155 * @var array
156 */
157 public $CBnames = array();
158
159 /**
160 * @var Clipboard $clipObj
161 */
162 public $clipObj;
163
164 /**
165 * @var ResourceFactory
166 */
167 protected $resourceFactory;
168
169 /**
170 * @param ResourceFactory $resourceFactory
171 */
172 public function injectResourceFactory(ResourceFactory $resourceFactory)
173 {
174 $this->resourceFactory = $resourceFactory;
175 }
176
177 /**
178 * @var IconFactory
179 */
180 protected $iconFactory;
181
182 /**
183 * @var FileListController
184 */
185 protected $fileListController;
186
187 /**
188 * Construct
189 *
190 * @param FileListController $fileListController
191 */
192 public function __construct(FileListController $fileListController)
193 {
194 parent::__construct();
195 $this->fileListController = $fileListController;
196 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
197 }
198
199 /**
200 * Initialization of class
201 *
202 * @param Folder $folderObject The folder to work on
203 * @param int $pointer Pointer
204 * @param bool $sort Sorting column
205 * @param bool $sortRev Sorting direction
206 * @param bool $clipBoard
207 * @param bool $bigControlPanel Show clipboard flag
208 * @return void
209 */
210 public function start(Folder $folderObject, $pointer, $sort, $sortRev, $clipBoard = false, $bigControlPanel = false)
211 {
212 $this->folderObject = $folderObject;
213 $this->counter = 0;
214 $this->totalbytes = 0;
215 $this->JScode = '';
216 $this->HTMLcode = '';
217 $this->path = $folderObject->getReadablePath();
218 $this->sort = $sort;
219 $this->sortRev = $sortRev;
220 $this->firstElementNumber = $pointer;
221 $this->clipBoard = $clipBoard;
222 $this->bigControlPanel = $bigControlPanel;
223 // Setting the maximum length of the filenames to the user's settings or minimum 30 (= $this->fixedL)
224 $this->fixedL = max($this->fixedL, $this->getBackendUser()->uc['titleLen']);
225 $this->getLanguageService()->includeLLFile('EXT:lang/locallang_common.xlf');
226 $this->resourceFactory = ResourceFactory::getInstance();
227 }
228
229 /**
230 * Reading files and directories, counting elements and generating the list in ->HTMLcode
231 *
232 * @return void
233 */
234 public function generateList()
235 {
236 $this->HTMLcode .= $this->getTable('fileext,tstamp,size,rw,_REF_');
237 }
238
239 /**
240 * Wrapping input string in a link with clipboard command.
241 *
242 * @param string $string String to be linked - must be htmlspecialchar'ed / prepared before.
243 * @param string $_ unused
244 * @param string $cmd "cmd" value
245 * @param string $warning Warning for JS confirm message
246 * @return string Linked string
247 */
248 public function linkClipboardHeaderIcon($string, $_, $cmd, $warning = '')
249 {
250 $jsCode = 'document.dblistForm.cmd.value=' . GeneralUtility::quoteJSvalue($cmd)
251 . ';document.dblistForm.submit();';
252
253 $attributes = [];
254 if ($warning) {
255 $attributes['class'] = 'btn btn-default t3js-modal-trigger';
256 $attributes['data-href'] = 'javascript:' . $jsCode;
257 $attributes['data-severity'] = 'warning';
258 $attributes['data-content'] = $warning;
259 } else {
260 $attributes['class'] = 'btn btn-default';
261 $attributes['onclick'] = $jsCode . 'return false;';
262 }
263
264 $attributesString = '';
265 foreach ($attributes as $key => $value) {
266 $attributesString .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
267 }
268 return '<a href="#" ' . $attributesString . '>' . $string . '</a>';
269 }
270
271 /**
272 * Returns a table with directories and files listed.
273 *
274 * @param array $rowlist Array of files from path
275 * @return string HTML-table
276 */
277 public function getTable($rowlist)
278 {
279 // prepare space icon
280 $this->spaceIcon = '<span class="btn btn-default disabled">' . $this->iconFactory->getIcon('empty-empty', Icon::SIZE_SMALL)->render() . '</span>';
281
282 // @todo use folder methods directly when they support filters
283 $storage = $this->folderObject->getStorage();
284 $storage->resetFileAndFolderNameFiltersToDefault();
285
286 // Only render the contents of a browsable storage
287 if ($this->folderObject->getStorage()->isBrowsable()) {
288 try {
289 $foldersCount = $storage->countFoldersInFolder($this->folderObject);
290 $filesCount = $storage->countFilesInFolder($this->folderObject);
291 } catch (InsufficientFolderAccessPermissionsException $e) {
292 $foldersCount = 0;
293 $filesCount = 0;
294 }
295
296 if ($foldersCount <= $this->firstElementNumber) {
297 $foldersFrom = false;
298 $foldersNum = false;
299 } else {
300 $foldersFrom = $this->firstElementNumber;
301 if ($this->firstElementNumber + $this->iLimit > $foldersCount) {
302 $foldersNum = $foldersCount - $this->firstElementNumber;
303 } else {
304 $foldersNum = $this->iLimit;
305 }
306 }
307 if ($foldersCount >= $this->firstElementNumber + $this->iLimit) {
308 $filesFrom = false;
309 $filesNum = false;
310 } else {
311 if ($this->firstElementNumber <= $foldersCount) {
312 $filesFrom = 0;
313 $filesNum = $this->iLimit - $foldersNum;
314 } else {
315 $filesFrom = $this->firstElementNumber - $foldersCount;
316 if ($filesFrom + $this->iLimit > $filesCount) {
317 $filesNum = $filesCount - $filesFrom;
318 } else {
319 $filesNum = $this->iLimit;
320 }
321 }
322 }
323 $folders = $storage->getFoldersInFolder($this->folderObject, $foldersFrom, $foldersNum, true, false, trim($this->sort), (bool)$this->sortRev);
324 $files = $this->folderObject->getFiles($filesFrom, $filesNum, Folder::FILTER_MODE_USE_OWN_AND_STORAGE_FILTERS, false, trim($this->sort), (bool)$this->sortRev);
325 $this->totalItems = $foldersCount + $filesCount;
326 // Adds the code of files/dirs
327 $out = '';
328 $titleCol = 'file';
329 // Cleaning rowlist for duplicates and place the $titleCol as the first column always!
330 $rowlist = '_LOCALIZATION_,' . $rowlist;
331 $rowlist = GeneralUtility::rmFromList($titleCol, $rowlist);
332 $rowlist = GeneralUtility::uniqueList($rowlist);
333 $rowlist = $rowlist ? $titleCol . ',' . $rowlist : $titleCol;
334 if ($this->clipBoard) {
335 $rowlist = str_replace('_LOCALIZATION_,', '_LOCALIZATION_,_CLIPBOARD_,', $rowlist);
336 $this->addElement_tdCssClass['_CLIPBOARD_'] = 'col-clipboard';
337 }
338 if ($this->bigControlPanel) {
339 $rowlist = str_replace('_LOCALIZATION_,', '_LOCALIZATION_,_CONTROL_,', $rowlist);
340 $this->addElement_tdCssClass['_CONTROL_'] = 'col-control';
341 }
342 $this->fieldArray = explode(',', $rowlist);
343
344 // Add classes to table cells
345 $this->addElement_tdCssClass[$titleCol] = 'col-title';
346 $this->addElement_tdCssClass['_LOCALIZATION_'] = 'col-localizationa';
347
348 $folders = ListUtility::resolveSpecialFolderNames($folders);
349
350 $iOut = '';
351 // Directories are added
352 $this->eCounter = $this->firstElementNumber;
353 list(, $code) = $this->fwd_rwd_nav();
354 $iOut .= $code;
355
356 $iOut .= $this->formatDirList($folders);
357 // Files are added
358 $iOut .= $this->formatFileList($files);
359
360 $this->eCounter = $this->firstElementNumber + $this->iLimit <= $this->totalItems
361 ? $this->firstElementNumber + $this->iLimit
362 : $this->totalItems;
363 list(, $code) = $this->fwd_rwd_nav();
364 $iOut .= $code;
365
366 // Header line is drawn
367 $theData = array();
368 foreach ($this->fieldArray as $v) {
369 if ($v == '_CLIPBOARD_' && $this->clipBoard) {
370 $cells = array();
371 $table = '_FILE';
372 $elFromTable = $this->clipObj->elFromTable($table);
373 if (!empty($elFromTable) && $this->folderObject->checkActionPermission('write')) {
374 $addPasteButton = true;
375 $elToConfirm = array();
376 foreach ($elFromTable as $key => $element) {
377 $clipBoardElement = $this->resourceFactory->retrieveFileOrFolderObject($element);
378 if ($clipBoardElement instanceof Folder && $clipBoardElement->getStorage()->isWithinFolder($clipBoardElement, $this->folderObject)) {
379 $addPasteButton = false;
380 }
381 $elToConfirm[$key] = $clipBoardElement->getName();
382 }
383 if ($addPasteButton) {
384 $cells[] = '<a class="btn btn-default t3js-modal-trigger"'.
385 ' href="' . htmlspecialchars($this->clipObj->pasteUrl(
386 '_FILE',
387 $this->folderObject->getCombinedIdentifier()
388 )) . '"'
389 . ' data-content="' . htmlspecialchars($this->clipObj->confirmMsgText(
390 '_FILE',
391 $this->path,
392 'into',
393 $elToConfirm
394 )) . '"'
395 . ' data-severity="warning"'
396 . ' data-title="' . $this->getLanguageService()->getLL('clip_paste', true) . '"'
397 . ' title="' . $this->getLanguageService()->getLL('clip_paste', true) . '">'
398 . $this->iconFactory->getIcon('actions-document-paste-after', Icon::SIZE_SMALL)
399 ->render()
400 . '</a>';
401 }
402 }
403 if ($this->clipObj->current !== 'normal' && $iOut) {
404 $cells[] = $this->linkClipboardHeaderIcon('<span title="' . $this->getLanguageService()->getLL('clip_selectMarked', true) . '">' . $this->iconFactory->getIcon('actions-edit-copy', Icon::SIZE_SMALL)->render() . '</span>', $table, 'setCB');
405 $cells[] = $this->linkClipboardHeaderIcon('<span title="' . $this->getLanguageService()->getLL('clip_deleteMarked', true) . '">' . $this->iconFactory->getIcon('actions-edit-delete', Icon::SIZE_SMALL)->render(), $table, 'delete', $this->getLanguageService()->getLL('clip_deleteMarkedWarning'));
406 $onClick = 'checkOffCB(' . GeneralUtility::quoteJSvalue(implode(',', $this->CBnames)) . ', this); return false;';
407 $cells[] = '<a class="btn btn-default" rel="" href="#" onclick="' . htmlspecialchars($onClick) . '" title="' . $this->getLanguageService()->getLL('clip_markRecords', true) . '">' . $this->iconFactory->getIcon('actions-document-select', Icon::SIZE_SMALL)->render() . '</a>';
408 }
409 $theData[$v] = implode('', $cells);
410 } else {
411 // Normal row:
412 $theT = $this->linkWrapSort($this->getLanguageService()->getLL('c_' . $v, true), $this->folderObject->getCombinedIdentifier(), $v);
413 $theData[$v] = $theT;
414 }
415 }
416
417 $out .= '<thead>' . $this->addelement(1, '', $theData, '', '', '', 'th') . '</thead>';
418 $out .= '<tbody>' . $iOut . '</tbody>';
419 // half line is drawn
420 // finish
421 $out = '
422 <!--
423 Filelist table:
424 -->
425 <div class="table-fit">
426 <table class="table table-striped table-hover" id="typo3-filelist">
427 ' . $out . '
428 </table>
429 </div>';
430 } else {
431 /** @var $flashMessage FlashMessage */
432 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('storageNotBrowsableMessage'), $this->getLanguageService()->getLL('storageNotBrowsableTitle'), FlashMessage::INFO);
433 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
434 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
435 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
436 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
437 $defaultFlashMessageQueue->enqueue($flashMessage);
438 $out = '';
439 }
440 return $out;
441 }
442
443 /**
444 * If there is a parent folder and user has access to it, return an icon
445 * which is linked to the filelist of the parent folder.
446 *
447 * @param Folder $currentFolder
448 * @return string
449 */
450 protected function getLinkToParentFolder(Folder $currentFolder)
451 {
452 $levelUp = '';
453 try {
454 $currentStorage = $currentFolder->getStorage();
455 $parentFolder = $currentFolder->getParentFolder();
456 if ($parentFolder->getIdentifier() !== $currentFolder->getIdentifier() && $currentStorage->isWithinFileMountBoundaries($parentFolder)) {
457 $levelUp = $this->linkWrapDir(
458 '<span title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.upOneLevel', true) . '">'
459 . $this->iconFactory->getIcon('actions-view-go-up', Icon::SIZE_SMALL)->render()
460 . '</span>',
461 $parentFolder
462 );
463 }
464 } catch (\Exception $e) {
465 }
466 return $levelUp;
467 }
468
469 /**
470 * Gets the number of files and total size of a folder
471 *
472 * @return string
473 */
474 public function getFolderInfo()
475 {
476 if ($this->counter == 1) {
477 $fileLabel = $this->getLanguageService()->getLL('file', true);
478 } else {
479 $fileLabel = $this->getLanguageService()->getLL('files', true);
480 }
481 return $this->counter . ' ' . $fileLabel . ', ' . GeneralUtility::formatSize($this->totalbytes, $this->getLanguageService()->getLL('byteSizeUnits', true));
482 }
483
484 /**
485 * This returns tablerows for the directories in the array $items['sorting'].
486 *
487 * @param Folder[] $folders Folders of \TYPO3\CMS\Core\Resource\Folder
488 * @return string HTML table rows.
489 */
490 public function formatDirList(array $folders)
491 {
492 $out = '';
493 foreach ($folders as $folderName => $folderObject) {
494 $role = $folderObject->getRole();
495 if ($role === FolderInterface::ROLE_PROCESSING) {
496 // don't show processing-folder
497 continue;
498 }
499 if ($role !== FolderInterface::ROLE_DEFAULT) {
500 $displayName = '<strong>' . htmlspecialchars($folderName) . '</strong>';
501 } else {
502 $displayName = htmlspecialchars($folderName);
503 }
504
505 $isLocked = $folderObject instanceof InaccessibleFolder;
506 $isWritable = $folderObject->checkActionPermission('write');
507
508 // Initialization
509 $this->counter++;
510
511 // The icon with link
512 $theIcon = '<span title="' . htmlspecialchars($folderName) . '">' . $this->iconFactory->getIconForResource($folderObject, Icon::SIZE_SMALL)->render() . '</span>';
513 if (!$isLocked && $this->clickMenus) {
514 $theIcon = BackendUtility::wrapClickMenuOnIcon($theIcon, $folderObject->getCombinedIdentifier());
515 }
516
517 // Preparing and getting the data-array
518 $theData = array();
519 if ($isLocked) {
520 foreach ($this->fieldArray as $field) {
521 $theData[$field] = '';
522 }
523 $theData['file'] = $displayName;
524 } else {
525 foreach ($this->fieldArray as $field) {
526 switch ($field) {
527 case 'size':
528 try {
529 $numFiles = $folderObject->getFileCount();
530 } catch (InsufficientFolderAccessPermissionsException $e) {
531 $numFiles = 0;
532 }
533 $theData[$field] = $numFiles . ' ' . $this->getLanguageService()->getLL(($numFiles === 1 ? 'file' : 'files'), true);
534 break;
535 case 'rw':
536 $theData[$field] = '<strong class="text-danger">' . $this->getLanguageService()->getLL('read', true) . '</strong>' . (!$isWritable ? '' : '<strong class="text-danger">' . $this->getLanguageService()->getLL('write', true) . '</strong>');
537 break;
538 case 'fileext':
539 $theData[$field] = $this->getLanguageService()->getLL('folder', true);
540 break;
541 case 'tstamp':
542 $tstamp = $folderObject->getModificationTime();
543 $theData[$field] = $tstamp ? BackendUtility::date($tstamp) : '-';
544 break;
545 case 'file':
546 $theData[$field] = $this->linkWrapDir($displayName, $folderObject);
547 break;
548 case '_CONTROL_':
549 $theData[$field] = $this->makeEdit($folderObject);
550 break;
551 case '_CLIPBOARD_':
552 $theData[$field] = $this->makeClip($folderObject);
553 break;
554 case '_REF_':
555 $theData[$field] = $this->makeRef($folderObject);
556 break;
557 default:
558 $theData[$field] = GeneralUtility::fixed_lgd_cs($theData[$field], $this->fixedL);
559 }
560 }
561 }
562 $out .= $this->addelement(1, $theIcon, $theData);
563 }
564 return $out;
565 }
566
567 /**
568 * Wraps the directory-titles
569 *
570 * @param string $title String to be wrapped in links
571 * @param Folder $folderObject Folder to work on
572 * @return string HTML
573 */
574 public function linkWrapDir($title, Folder $folderObject)
575 {
576 $href = BackendUtility::getModuleUrl('file_FilelistList', ['id' => $folderObject->getCombinedIdentifier()]);
577 $onclick = ' onclick="' . htmlspecialchars(('top.document.getElementsByName("navigation")[0].contentWindow.Tree.highlightActiveItem("file","folder' . GeneralUtility::md5int($folderObject->getCombinedIdentifier()) . '_"+top.fsMod.currentBank)')) . '"';
578 // Sometimes $code contains plain HTML tags. In such a case the string should not be modified!
579 if ((string)$title === strip_tags($title)) {
580 return '<a href="' . htmlspecialchars($href) . '"' . $onclick . ' title="' . htmlspecialchars($title) . '">' . GeneralUtility::fixed_lgd_cs($title, $this->fixedL) . '</a>';
581 } else {
582 return '<a href="' . htmlspecialchars($href) . '"' . $onclick . '>' . $title . '</a>';
583 }
584 }
585
586 /**
587 * Wraps filenames in links which opens the metadata editor.
588 *
589 * @param string $code String to be wrapped in links
590 * @param File $fileObject File to be linked
591 * @return string HTML
592 */
593 public function linkWrapFile($code, File $fileObject)
594 {
595 try {
596 if ($fileObject instanceof File && $fileObject->isIndexed() && $fileObject->checkActionPermission('write') && $this->getBackendUser()->check('tables_modify', 'sys_file_metadata')) {
597 $metaData = $fileObject->_getMetaData();
598 $urlParameters = [
599 'edit' => [
600 'sys_file_metadata' => [
601 $metaData['uid'] => 'edit'
602 ]
603 ],
604 'returnUrl' => $this->listURL()
605 ];
606 $url = BackendUtility::getModuleUrl('record_edit', $urlParameters);
607 $title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.editMetadata'));
608 $code = '<a href="' . htmlspecialchars($url) . '" title="' . $title . '">' . GeneralUtility::fixed_lgd_cs($code, $this->fixedL) . '</a>';
609 }
610 } catch (\Exception $e) {
611 // intentional fall-through
612 }
613 return $code;
614 }
615
616 /**
617 * Returns list URL; This is the URL of the current script with id and imagemode parameters, that's all.
618 * The URL however is not relative, otherwise GeneralUtility::sanitizeLocalUrl() would say that
619 * the URL would be invalid
620 *
621 * @param string $altId
622 * @param string $table Table name to display. Enter "-1" for the current table.
623 * @param string $exclList Comma separated list of fields NOT to include ("sortField", "sortRev" or "firstElementNumber")
624 *
625 * @return string URL
626 */
627 public function listURL($altId = '', $table = '-1', $exclList = '')
628 {
629 return GeneralUtility::linkThisScript(array(
630 'target' => rawurlencode($this->folderObject->getCombinedIdentifier()),
631 'imagemode' => $this->thumbs
632 ));
633 }
634
635 /**
636 * This returns tablerows for the files in the array $items['sorting'].
637 *
638 * @param File[] $files File items
639 * @return string HTML table rows.
640 */
641 public function formatFileList(array $files)
642 {
643 $out = '';
644 // first two keys are "0" (default) and "-1" (multiple), after that comes the "other languages"
645 $allSystemLanguages = GeneralUtility::makeInstance(TranslationConfigurationProvider::class)->getSystemLanguages();
646 $systemLanguages = array_filter($allSystemLanguages, function ($languageRecord) {
647 if ($languageRecord['uid'] === -1 || $languageRecord['uid'] === 0 || !$this->getBackendUser()->checkLanguageAccess($languageRecord['uid'])) {
648 return false;
649 } else {
650 return true;
651 }
652 });
653
654 foreach ($files as $fileObject) {
655 // Initialization
656 $this->counter++;
657 $this->totalbytes += $fileObject->getSize();
658 $ext = $fileObject->getExtension();
659 $fileName = trim($fileObject->getName());
660 // The icon with link
661 $theIcon = '<span title="' . htmlspecialchars($fileName . ' [' . (int)$fileObject->getUid() . ']') . '">'
662 . $this->iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render() . '</span>';
663 if ($this->clickMenus) {
664 $theIcon = BackendUtility::wrapClickMenuOnIcon($theIcon, $fileObject->getCombinedIdentifier());
665 }
666 // Preparing and getting the data-array
667 $theData = array();
668 foreach ($this->fieldArray as $field) {
669 switch ($field) {
670 case 'size':
671 $theData[$field] = GeneralUtility::formatSize($fileObject->getSize(), $this->getLanguageService()->getLL('byteSizeUnits', true));
672 break;
673 case 'rw':
674 $theData[$field] = '' . (!$fileObject->checkActionPermission('read') ? ' ' : '<strong class="text-danger">' . $this->getLanguageService()->getLL('read', true) . '</strong>') . (!$fileObject->checkActionPermission('write') ? '' : '<strong class="text-danger">' . $this->getLanguageService()->getLL('write', true) . '</strong>');
675 break;
676 case 'fileext':
677 $theData[$field] = strtoupper($ext);
678 break;
679 case 'tstamp':
680 $theData[$field] = BackendUtility::date($fileObject->getModificationTime());
681 break;
682 case '_CONTROL_':
683 $theData[$field] = $this->makeEdit($fileObject);
684 break;
685 case '_CLIPBOARD_':
686 $theData[$field] = $this->makeClip($fileObject);
687 break;
688 case '_LOCALIZATION_':
689 if (!empty($systemLanguages) && $fileObject->isIndexed() && $fileObject->checkActionPermission('write') && $this->getBackendUser()->check('tables_modify', 'sys_file_metadata')) {
690 $metaDataRecord = $fileObject->_getMetaData();
691 $translations = $this->getTranslationsForMetaData($metaDataRecord);
692 $languageCode = '';
693
694 foreach ($systemLanguages as $language) {
695 $languageId = $language['uid'];
696 $flagIcon = $language['flagIcon'];
697 if (array_key_exists($languageId, $translations)) {
698 $title = htmlspecialchars(sprintf($this->getLanguageService()->getLL('editMetadataForLanguage'), $language['title']));
699 // @todo the overlay for the flag needs to be added ($flagIcon . '-overlay')
700 $urlParameters = [
701 'edit' => [
702 'sys_file_metadata' => [
703 $translations[$languageId]['uid'] => 'edit'
704 ]
705 ],
706 'returnUrl' => $this->listURL()
707 ];
708 $flagButtonIcon = $this->iconFactory->getIcon($flagIcon, Icon::SIZE_SMALL, 'overlay-edit')->render();
709 $url = BackendUtility::getModuleUrl('record_edit', $urlParameters);
710 $languageCode .= '<a href="' . htmlspecialchars($url) . '" class="btn btn-default" title="' . $title . '">'
711 . $flagButtonIcon . '</a>';
712 } else {
713 $parameters = [
714 'justLocalized' => 'sys_file_metadata:' . $metaDataRecord['uid'] . ':' . $languageId,
715 'returnUrl' => $this->listURL()
716 ];
717 $returnUrl = BackendUtility::getModuleUrl('record_edit', $parameters);
718 $href = BackendUtility::getLinkToDataHandlerAction(
719 '&cmd[sys_file_metadata][' . $metaDataRecord['uid'] . '][localize]=' . $languageId,
720 $returnUrl
721 );
722 $flagButtonIcon = '<span title="' . htmlspecialchars(sprintf($this->getLanguageService()->getLL('createMetadataForLanguage'), $language['title'])) . '">' . $this->iconFactory->getIcon($flagIcon, Icon::SIZE_SMALL, 'overlay-new')->render() . '</span>';
723 $languageCode .= '<a href="' . htmlspecialchars($href) . '" class="btn btn-default">' . $flagButtonIcon . '</a> ';
724 }
725 }
726
727 // Hide flag button bar when not translated yet
728 $theData[$field] = ' <div class="localisationData btn-group" data-fileid="' . $fileObject->getUid() . '"' .
729 (empty($translations) ? ' style="display: none;"' : '') . '>' . $languageCode . '</div>';
730 $theData[$field] .= '<a class="btn btn-default filelist-translationToggler" data-fileid="' . $fileObject->getUid() . '">' .
731 '<span title="' . $this->getLanguageService()->getLL('translateMetadata', true) . '">'
732 . $this->iconFactory->getIcon('mimetypes-x-content-page-language-overlay', Icon::SIZE_SMALL)->render() . '</span>'
733 . '</a>';
734 }
735 break;
736 case '_REF_':
737 $theData[$field] = $this->makeRef($fileObject);
738 break;
739 case 'file':
740 // Edit metadata of file
741 $theData[$field] = $this->linkWrapFile(htmlspecialchars($fileName), $fileObject);
742
743 if ($fileObject->isMissing()) {
744 $theData[$field] .= '<span class="label label-danger label-space-left">'
745 . htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing'))
746 . '</span>';
747 // Thumbnails?
748 } elseif ($this->thumbs && ($this->isImage($ext) || $this->isMediaFile($ext))) {
749 $processedFile = $fileObject->process(ProcessedFile::CONTEXT_IMAGEPREVIEW, array());
750 if ($processedFile) {
751 $thumbUrl = $processedFile->getPublicUrl(true);
752 $theData[$field] .= '<br /><img src="' . $thumbUrl . '" ' .
753 'width="' . $processedFile->getProperty('width') . '" ' .
754 'height="' . $processedFile->getProperty('height') . '" ' .
755 'title="' . htmlspecialchars($fileName) . '" alt="" />';
756 }
757 }
758 break;
759 default:
760 $theData[$field] = '';
761 if ($fileObject->hasProperty($field)) {
762 $theData[$field] = htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileObject->getProperty($field), $this->fixedL));
763 }
764 }
765 }
766 $out .= $this->addelement(1, $theIcon, $theData);
767 }
768 return $out;
769 }
770
771 /**
772 * Fetch the translations for a sys_file_metadata record
773 *
774 * @param $metaDataRecord
775 * @return array keys are the sys_language uids, values are the $rows
776 */
777 protected function getTranslationsForMetaData($metaDataRecord)
778 {
779 $where = $GLOBALS['TCA']['sys_file_metadata']['ctrl']['transOrigPointerField'] . '=' . (int)$metaDataRecord['uid'] .
780 ' AND ' . $GLOBALS['TCA']['sys_file_metadata']['ctrl']['languageField'] . '>0';
781 $translationRecords = $this->getDatabaseConnection()->exec_SELECTgetRows('*', 'sys_file_metadata', $where);
782 $translations = array();
783 foreach ($translationRecords as $record) {
784 $translations[$record[$GLOBALS['TCA']['sys_file_metadata']['ctrl']['languageField']]] = $record;
785 }
786 return $translations;
787 }
788
789 /**
790 * Returns TRUE if $ext is an image-extension according to $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
791 *
792 * @param string $ext File extension
793 * @return bool
794 */
795 public function isImage($ext)
796 {
797 return GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], strtolower($ext));
798 }
799
800 /**
801 * Returns TRUE if $ext is an media-extension according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext']
802 *
803 * @param string $ext File extension
804 * @return bool
805 */
806 public function isMediaFile($ext)
807 {
808 return GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext'], strtolower($ext));
809 }
810
811 /**
812 * Wraps the directory-titles ($code) in a link to filelist/Modules/Filelist/index.php (id=$path) and sorting commands...
813 *
814 * @param string $code String to be wrapped
815 * @param string $folderIdentifier ID (path)
816 * @param string $col Sorting column
817 * @return string HTML
818 */
819 public function linkWrapSort($code, $folderIdentifier, $col)
820 {
821 $params = ['id' => $folderIdentifier, 'SET' => [ 'sort' => $col ]];
822
823 if ($this->sort === $col) {
824 // Check reverse sorting
825 $params['SET']['reverse'] = ($this->sortRev ? '0' : '1');
826 $sortArrow = $this->iconFactory->getIcon('status-status-sorting-light-' . ($this->sortRev ? 'desc' : 'asc'), Icon::SIZE_SMALL)->render();
827 } else {
828 $params['SET']['reverse'] = 0;
829 $sortArrow = '';
830 }
831 $href = BackendUtility::getModuleUrl('file_FilelistList', $params);
832 return '<a href="' . htmlspecialchars($href) . '">' . $code . ' ' . $sortArrow . '</a>';
833 }
834
835 /**
836 * Creates the clipboard control pad
837 *
838 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the clipboard panel for the listing.
839 * @return string HTML-table
840 */
841 public function makeClip($fileOrFolderObject)
842 {
843 if (!$fileOrFolderObject->checkActionPermission('read')) {
844 return '';
845 }
846 $cells = array();
847 $fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
848 $fullName = $fileOrFolderObject->getName();
849 $md5 = GeneralUtility::shortmd5($fullIdentifier);
850 // For normal clipboard, add copy/cut buttons:
851 if ($this->clipObj->current === 'normal') {
852 $isSel = $this->clipObj->isSelected('_FILE', $md5);
853 $copyTitle = $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.copy', true);
854 $cutTitle = $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.cut', true);
855 $copyIcon = $this->iconFactory->getIcon('actions-edit-copy', Icon::SIZE_SMALL)->render();
856 $cutIcon = $this->iconFactory->getIcon('actions-edit-cut', Icon::SIZE_SMALL)->render();
857
858 if ($isSel === 'copy') {
859 $copyIcon = $this->iconFactory->getIcon('actions-edit-copy-release', Icon::SIZE_SMALL)->render();
860 } elseif ($isSel === 'cut') {
861 $cutIcon = $this->iconFactory->getIcon('actions-edit-cut-release', Icon::SIZE_SMALL)->render();
862 }
863
864 $cells[] = '<a class="btn btn-default"" href="' . htmlspecialchars($this->clipObj->selUrlFile($fullIdentifier, 1, ($isSel === 'copy'))) . '" title="' . $copyTitle . '">' . $copyIcon . '</a>';
865 // we can only cut if file can be moved
866 if ($fileOrFolderObject->checkActionPermission('move')) {
867 $cells[] = '<a class="btn btn-default" href="' . htmlspecialchars($this->clipObj->selUrlFile($fullIdentifier, 0, ($isSel === 'cut'))) . '" title="' . $cutTitle . '">' . $cutIcon . '</a>';
868 } else {
869 $cells[] = $this->spaceIcon;
870 }
871 } else {
872 // For numeric pads, add select checkboxes:
873 $n = '_FILE|' . $md5;
874 $this->CBnames[] = $n;
875 $checked = $this->clipObj->isSelected('_FILE', $md5) ? ' checked="checked"' : '';
876 $cells[] = '<input type="hidden" name="CBH[' . $n . ']" value="0" /><label class="btn btn-default btn-checkbox"><input type="checkbox" name="CBC[' . $n . ']" value="' . htmlspecialchars($fullIdentifier) . '" ' . $checked . ' /><span class="t3-icon fa"></span></label>';
877 }
878 // Display PASTE button, if directory:
879 $elFromTable = $this->clipObj->elFromTable('_FILE');
880 if ($fileOrFolderObject instanceof Folder && !empty($elFromTable) && $fileOrFolderObject->checkActionPermission('write')) {
881 $addPasteButton = true;
882 $elToConfirm = array();
883 foreach ($elFromTable as $key => $element) {
884 $clipBoardElement = $this->resourceFactory->retrieveFileOrFolderObject($element);
885 if ($clipBoardElement instanceof Folder && $clipBoardElement->getStorage()->isWithinFolder($clipBoardElement, $fileOrFolderObject)) {
886 $addPasteButton = false;
887 }
888 $elToConfirm[$key] = $clipBoardElement->getName();
889 }
890 if ($addPasteButton) {
891 $cells[] = '<a class="btn btn-default t3js-modal-trigger" '
892 . ' href="' . htmlspecialchars($this->clipObj->pasteUrl('_FILE', $fullIdentifier)) . '"'
893 . ' data-content="' . htmlspecialchars($this->clipObj->confirmMsgText('_FILE', $fullName, 'into', $elToConfirm)) . '"'
894 . ' data-severity="warning"'
895 . ' data-title="' . $this->getLanguageService()->getLL('clip_pasteInto', true) . '"'
896 . ' title="' . $this->getLanguageService()->getLL('clip_pasteInto', true) . '"'
897 .'>'
898 . $this->iconFactory->getIcon('actions-document-paste-into', Icon::SIZE_SMALL)->render()
899 . '</a>';
900 }
901 }
902 // Compile items into a DIV-element:
903 return ' <div class="btn-group" role="group">' . implode('', $cells) . '</div>';
904 }
905
906 /**
907 * Creates the edit control section
908 *
909 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the edit control section for the listing.
910 * @return string HTML-table
911 */
912 public function makeEdit($fileOrFolderObject)
913 {
914 $cells = array();
915 $fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
916
917 // Edit file content (if editable)
918 if ($fileOrFolderObject instanceof File && $fileOrFolderObject->checkActionPermission('write') && GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['SYS']['textfile_ext'], $fileOrFolderObject->getExtension())) {
919 $url = BackendUtility::getModuleUrl('file_edit', array('target' => $fullIdentifier));
920 $editOnClick = 'top.content.list_frame.location.href=' . GeneralUtility::quoteJSvalue($url) . '+\'&returnUrl=\'+top.rawurlencode(top.content.list_frame.document.location.pathname+top.content.list_frame.document.location.search);return false;';
921 $cells['edit'] = '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($editOnClick) . '" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.editcontent') . '">'
922 . $this->iconFactory->getIcon('actions-page-open', Icon::SIZE_SMALL)->render()
923 . '</a>';
924 } else {
925 $cells['edit'] = $this->spaceIcon;
926 }
927 if ($fileOrFolderObject instanceof File) {
928 $fileUrl = $fileOrFolderObject->getPublicUrl(true);
929 if ($fileUrl) {
930 $aOnClick = 'return top.openUrlInWindow(' . GeneralUtility::quoteJSvalue($fileUrl) . ', \'WebFile\');';
931 $cells['view'] = '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($aOnClick) . '" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.view') . '">' . $this->iconFactory->getIcon('actions-document-view', Icon::SIZE_SMALL)->render() . '</a>';
932 } else {
933 $cells['view'] = $this->spaceIcon;
934 }
935 } else {
936 $cells['view'] = $this->spaceIcon;
937 }
938
939 // replace file
940 if ($fileOrFolderObject instanceof File && $fileOrFolderObject->checkActionPermission('replace')) {
941 $url = BackendUtility::getModuleUrl('file_replace', array('target' => $fullIdentifier, 'uid' => $fileOrFolderObject->getUid()));
942 $replaceOnClick = 'top.content.list_frame.location.href = ' . GeneralUtility::quoteJSvalue($url) . '+\'&returnUrl=\'+top.rawurlencode(top.content.list_frame.document.location.pathname+top.content.list_frame.document.location.search);return false;';
943 $cells['replace'] = '<a href="#" class="btn btn-default" onclick="' . $replaceOnClick . '" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.replace') . '">' . $this->iconFactory->getIcon('actions-edit-replace', Icon::SIZE_SMALL)->render() . '</a>';
944 }
945
946 // rename the file
947 if ($fileOrFolderObject->checkActionPermission('rename')) {
948 $url = BackendUtility::getModuleUrl('file_rename', array('target' => $fullIdentifier));
949 $renameOnClick = 'top.content.list_frame.location.href = ' . GeneralUtility::quoteJSvalue($url) . '+\'&returnUrl=\'+top.rawurlencode(top.content.list_frame.document.location.pathname+top.content.list_frame.document.location.search);return false;';
950 $cells['rename'] = '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($renameOnClick) . '" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.rename') . '">' . $this->iconFactory->getIcon('actions-edit-rename', Icon::SIZE_SMALL)->render() . '</a>';
951 } else {
952 $cells['rename'] = $this->spaceIcon;
953 }
954 if ($fileOrFolderObject->checkActionPermission('read')) {
955 $infoOnClick = '';
956 if ($fileOrFolderObject instanceof Folder) {
957 $infoOnClick = 'top.launchView( \'_FOLDER\', ' . GeneralUtility::quoteJSvalue($fullIdentifier) . ');return false;';
958 } elseif ($fileOrFolderObject instanceof File) {
959 $infoOnClick = 'top.launchView( \'_FILE\', ' . GeneralUtility::quoteJSvalue($fullIdentifier) . ');return false;';
960 }
961 $cells['info'] = '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($infoOnClick) . '" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.info') . '">' . $this->iconFactory->getIcon('actions-document-info', Icon::SIZE_SMALL)->render() . '</a>';
962 } else {
963 $cells['info'] = $this->spaceIcon;
964 }
965
966 // delete the file
967 if ($fileOrFolderObject->checkActionPermission('delete')) {
968 $identifier = $fileOrFolderObject->getIdentifier();
969 if ($fileOrFolderObject instanceof Folder) {
970 $referenceCountText = BackendUtility::referenceCount('_FILE', $identifier, ' ' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.referencesToFolder'));
971 $deleteType = 'delete_folder';
972 } else {
973 $referenceCountText = BackendUtility::referenceCount('sys_file', $fileOrFolderObject->getUid(), ' ' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.referencesToFile'));
974 $deleteType = 'delete_file';
975 }
976
977 if ($this->getBackendUser()->jsConfirmation(JsConfirmation::DELETE)) {
978 $confirmationCheck = '1';
979 } else {
980 $confirmationCheck = '0';
981 }
982
983 $deleteUrl = BackendUtility::getModuleUrl('tce_file');
984 $confirmationMessage = sprintf($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:mess.delete'), $fileOrFolderObject->getName()) . $referenceCountText;
985 $title = $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.delete');
986 $cells['delete'] = '<a href="#" class="btn btn-default t3js-filelist-delete" data-content="' . htmlspecialchars($confirmationMessage)
987 . '" data-check="' . $confirmationCheck
988 . '" data-delete-url="' . htmlspecialchars($deleteUrl)
989 . '" data-title="' . htmlspecialchars($title)
990 . '" data-identifier="' . htmlspecialchars($fileOrFolderObject->getCombinedIdentifier())
991 . '" data-veri-code="' . $this->getBackendUser()->veriCode()
992 . '" data-delete-type="' . $deleteType
993 . '" title="' . htmlspecialchars($title) . '">'
994 . $this->iconFactory->getIcon('actions-edit-delete', Icon::SIZE_SMALL)->render() . '</a>';
995 } else {
996 $cells['delete'] = $this->spaceIcon;
997 }
998
999 // Hook for manipulating edit icons.
1000 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['fileList']['editIconsHook'])) {
1001 $cells['__fileOrFolderObject'] = $fileOrFolderObject;
1002 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['fileList']['editIconsHook'] as $classData) {
1003 $hookObject = GeneralUtility::getUserObj($classData);
1004 if (!$hookObject instanceof FileListEditIconHookInterface) {
1005 throw new \UnexpectedValueException(
1006 '$hookObject must implement interface \\TYPO3\\CMS\\Filelist\\FileListEditIconHookInterface',
1007 1235225797
1008 );
1009 }
1010 $hookObject->manipulateEditIcons($cells, $this);
1011 }
1012 unset($cells['__fileOrFolderObject']);
1013 }
1014 // Compile items into a DIV-element:
1015 return '<div class="btn-group">' . implode('', $cells) . '</div>';
1016 }
1017
1018 /**
1019 * Make reference count
1020 *
1021 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the clipboard panel for the listing.
1022 * @return string HTML
1023 */
1024 public function makeRef($fileOrFolderObject)
1025 {
1026 if ($fileOrFolderObject instanceof FolderInterface) {
1027 return '-';
1028 }
1029 // Look up the file in the sys_refindex.
1030 // Exclude sys_file_metadata records as these are no use references
1031 $databaseConnection = $this->getDatabaseConnection();
1032 $table = 'sys_refindex';
1033 $referenceCount = $databaseConnection->exec_SELECTcountRows(
1034 '*',
1035 $table,
1036 'ref_table=' . $databaseConnection->fullQuoteStr('sys_file', $table)
1037 . ' AND ref_uid=' . (int)$fileOrFolderObject->getUid()
1038 . ' AND deleted=0'
1039 . ' AND tablename != ' . $databaseConnection->fullQuoteStr('sys_file_metadata', $table)
1040 );
1041 return $this->generateReferenceToolTip($referenceCount, '\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileOrFolderObject->getCombinedIdentifier()));
1042 }
1043
1044 /**
1045 * Returns the database connection
1046 *
1047 * @return DatabaseConnection
1048 */
1049 protected function getDatabaseConnection()
1050 {
1051 return $GLOBALS['TYPO3_DB'];
1052 }
1053
1054 /**
1055 * Returns an instance of LanguageService
1056 *
1057 * @return \TYPO3\CMS\Lang\LanguageService
1058 */
1059 protected function getLanguageService()
1060 {
1061 return $GLOBALS['LANG'];
1062 }
1063
1064 /**
1065 * Returns the current BE user.
1066 *
1067 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1068 */
1069 protected function getBackendUser()
1070 {
1071 return $GLOBALS['BE_USER'];
1072 }
1073 }