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