[TASK] Replace sprite icon "actions-document-view" with the new 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
36 /**
37 * Class for rendering of File>Filelist
38 */
39 class FileList extends AbstractRecordList {
40
41 /**
42 * Default Max items shown
43 *
44 * @var int
45 */
46 public $iLimit = 40;
47
48 /**
49 * Thumbnails on records containing files (pictures)
50 *
51 * @var bool
52 */
53 public $thumbs = FALSE;
54
55 /**
56 * Space icon used for alignment when no button is available
57 *
58 * @var string
59 */
60 public $spaceIcon;
61
62 /**
63 * Max length of strings
64 *
65 * @var int
66 */
67 public $fixedL = 30;
68
69 /**
70 * @var string
71 */
72 public $script = '';
73
74 /**
75 * If TRUE click menus are generated on files and folders
76 *
77 * @var bool
78 */
79 public $clickMenus = 1;
80
81 /**
82 * The field to sort by
83 *
84 * @var string
85 */
86 public $sort = '';
87
88 /**
89 * Reverse sorting flag
90 *
91 * @var bool
92 */
93 public $sortRev = 1;
94
95 /**
96 * @var int
97 */
98 public $firstElementNumber = 0;
99
100 /**
101 * @var bool
102 */
103 public $clipBoard = 0;
104
105 /**
106 * @var bool
107 */
108 public $bigControlPanel = 0;
109
110 /**
111 * @var string
112 */
113 public $JScode = '';
114
115 /**
116 * @var string
117 */
118 public $HTMLcode = '';
119
120 /**
121 * @var int
122 */
123 public $totalbytes = 0;
124
125 /**
126 * @var array
127 */
128 public $dirs = array();
129
130 /**
131 * @var array
132 */
133 public $files = array();
134
135 /**
136 * @var string
137 */
138 public $path = '';
139
140 /**
141 * @var Folder
142 */
143 protected $folderObject;
144
145 /**
146 * Counting the elements no matter what
147 *
148 * @var int
149 */
150 public $eCounter = 0;
151
152 /**
153 * @var string
154 */
155 public $totalItems = '';
156
157 /**
158 * @var array
159 */
160 public $CBnames = array();
161
162 /**
163 * @var Clipboard $clipObj
164 */
165 public $clipObj;
166
167 /**
168 * @var ResourceFactory
169 */
170 protected $resourceFactory;
171
172 /**
173 * @param ResourceFactory $resourceFactory
174 */
175 public function injectResourceFactory(ResourceFactory $resourceFactory) {
176 $this->resourceFactory = $resourceFactory;
177 }
178
179 /**
180 * @var IconFactory
181 */
182 protected $iconFactory;
183
184 /**
185 * Constructor
186 */
187 public function __construct() {
188 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
189 }
190
191 /**
192 * Initialization of class
193 *
194 * @param Folder $folderObject The folder to work on
195 * @param int $pointer Pointer
196 * @param bool $sort Sorting column
197 * @param bool $sortRev Sorting direction
198 * @param bool $clipBoard
199 * @param bool $bigControlPanel Show clipboard flag
200 * @return void
201 */
202 public function start(Folder $folderObject, $pointer, $sort, $sortRev, $clipBoard = FALSE, $bigControlPanel = FALSE) {
203 $this->script = BackendUtility::getModuleUrl('file_list');
204 $this->folderObject = $folderObject;
205 $this->counter = 0;
206 $this->totalbytes = 0;
207 $this->JScode = '';
208 $this->HTMLcode = '';
209 $this->path = $folderObject->getReadablePath();
210 $this->sort = $sort;
211 $this->sortRev = $sortRev;
212 $this->firstElementNumber = $pointer;
213 $this->clipBoard = $clipBoard;
214 $this->bigControlPanel = $bigControlPanel;
215 // Setting the maximum length of the filenames to the user's settings or minimum 30 (= $this->fixedL)
216 $this->fixedL = max($this->fixedL, $this->getBackendUser()->uc['titleLen']);
217 $this->getLanguageService()->includeLLFile('EXT:lang/locallang_common.xlf');
218 $this->resourceFactory = ResourceFactory::getInstance();
219 }
220
221 /**
222 * Reading files and directories, counting elements and generating the list in ->HTMLcode
223 *
224 * @return void
225 */
226 public function generateList() {
227 $this->HTMLcode .= $this->getTable('fileext,tstamp,size,rw,_REF_');
228 }
229
230 /**
231 * Return the buttons used by the filelist to include in the top header
232 *
233 * @param Folder $folderObject
234 * @return array
235 */
236 public function getButtonsAndOtherMarkers(Folder $folderObject) {
237 $otherMarkers = array(
238 'PAGE_ICON' => '',
239 'TITLE' => ''
240 );
241 $buttons = array(
242 'level_up' => $this->getLinkToParentFolder($folderObject),
243 'refresh' => '',
244 'title' => '',
245 'page_icon' => '',
246 'PASTE' => ''
247 );
248 // Makes the code for the folder icon in the top
249 if ($folderObject) {
250 $title = htmlspecialchars($folderObject->getReadablePath());
251 // Start compiling the HTML
252 // If this is some subFolder under the mount root....
253 if ($folderObject->getStorage()->isWithinFileMountBoundaries($folderObject)) {
254 // The icon with link
255 $otherMarkers['PAGE_ICON'] = IconUtility::getSpriteIconForResource($folderObject, array('title' => $title));
256 // No HTML specialchars here - HTML like <strong> </strong> is allowed
257 $otherMarkers['TITLE'] .= GeneralUtility::removeXSS(GeneralUtility::fixed_lgd_cs($title, -($this->fixedL + 20)));
258 } else {
259 // This is the root folder
260 $otherMarkers['PAGE_ICON'] = IconUtility::getSpriteIconForResource($folderObject, array('title' => $title, 'mount-root' => TRUE));
261 $otherMarkers['TITLE'] .= htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, -($this->fixedL + 20)));
262 }
263 if ($this->clickMenus) {
264 $otherMarkers['PAGE_ICON'] = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($otherMarkers['PAGE_ICON'], $folderObject->getCombinedIdentifier());
265 }
266 // Add paste button if clipboard is initialized
267 if ($this->clipObj instanceof Clipboard && $folderObject->checkActionPermission('write')) {
268 $elFromTable = $this->clipObj->elFromTable('_FILE');
269 if (!empty($elFromTable)) {
270 $addPasteButton = TRUE;
271 $elToConfirm = array();
272 foreach ($elFromTable as $key => $element) {
273 $clipBoardElement = $this->resourceFactory->retrieveFileOrFolderObject($element);
274 if ($clipBoardElement instanceof Folder && $clipBoardElement->getStorage()->isWithinFolder($clipBoardElement, $folderObject)) {
275 $addPasteButton = FALSE;
276 }
277 $fileInfo = $clipBoardElement->getStorage()->getFileInfoByIdentifier(substr(strstr($element, ':'), 1));
278 $elToConfirm[$key] = $fileInfo['name'];
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) . '">' . IconUtility::getSpriteIcon('actions-document-paste-after') . '</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 $fileInfo = $clipBoardElement->getStorage()->getFileInfoByIdentifier(substr(strstr($element, ':'), 1));
418 $elToConfirm[$key] = $fileInfo['name'];
419 }
420 if ($addPasteButton) {
421 $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) . '">' . IconUtility::getSpriteIcon('actions-document-paste-after') . '</a>';
422 }
423 }
424 if ($this->clipObj->current !== 'normal' && $iOut) {
425 $cells[] = $this->linkClipboardHeaderIcon(IconUtility::getSpriteIcon('actions-edit-copy', array('title' => $this->getLanguageService()->getLL('clip_selectMarked', TRUE))), $table, 'setCB');
426 $cells[] = $this->linkClipboardHeaderIcon(IconUtility::getSpriteIcon('actions-edit-delete', array('title' => $this->getLanguageService()->getLL('clip_deleteMarked'))), $table, 'delete', $this->getLanguageService()->getLL('clip_deleteMarkedWarning'));
427 $onClick = 'checkOffCB(\'' . implode(',', $this->CBnames) . '\', this); return false;';
428 $cells[] = '<a class="btn btn-default" rel="" href="#" onclick="' . htmlspecialchars($onClick) . '" title="' . $this->getLanguageService()->getLL('clip_markRecords', TRUE) . '">' . IconUtility::getSpriteIcon('actions-document-select') . '</a>';
429 }
430 $theData[$v] = implode('', $cells);
431 } else {
432 // Normal row:
433 $theT = $this->linkWrapSort($this->getLanguageService()->getLL('c_' . $v, TRUE), $this->folderObject->getCombinedIdentifier(), $v);
434 $theData[$v] = $theT;
435 }
436 }
437
438 $out .= '<thead>' . $this->addelement(1, '', $theData, '', '', '', 'th') . '</thead>';
439 $out .= '<tbody>' . $iOut . '</tbody>';
440 // half line is drawn
441 // finish
442 $out = '
443 <!--
444 Filelist table:
445 -->
446 <div class="table-fit">
447 <table class="table table-striped table-hover" id="typo3-filelist">
448 ' . $out . '
449 </table>
450 </div>';
451
452 } else {
453 /** @var $flashMessage FlashMessage */
454 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('storageNotBrowsableMessage'), $this->getLanguageService()->getLL('storageNotBrowsableTitle'), FlashMessage::INFO);
455 $out = $flashMessage->render();
456 }
457 return $out;
458 }
459
460 /**
461 * If there is a parent folder and user has access to it, return an icon
462 * which is linked to the filelist of the parent folder.
463 *
464 * @param Folder $currentFolder
465 * @return string
466 */
467 protected function getLinkToParentFolder(Folder $currentFolder) {
468 $levelUp = '';
469 try {
470 $currentStorage = $currentFolder->getStorage();
471 $parentFolder = $currentFolder->getParentFolder();
472 if ($parentFolder->getIdentifier() !== $currentFolder->getIdentifier() && $currentStorage->isWithinFileMountBoundaries($parentFolder)) {
473 $levelUp = $this->linkWrapDir(
474 IconUtility::getSpriteIcon(
475 'actions-view-go-up',
476 array('title' => $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.php:labels.upOneLevel', TRUE))
477 ),
478 $parentFolder
479 );
480 }
481 } catch (\Exception $e) {}
482 return $levelUp;
483 }
484
485 /**
486 * Gets the number of files and total size of a folder
487 *
488 * @return string
489 */
490 public function getFolderInfo() {
491 if ($this->counter == 1) {
492 $fileLabel = $this->getLanguageService()->getLL('file', TRUE);
493 } else {
494 $fileLabel = $this->getLanguageService()->getLL('files', TRUE);
495 }
496 return $this->counter . ' ' . $fileLabel . ', ' . GeneralUtility::formatSize($this->totalbytes, $this->getLanguageService()->getLL('byteSizeUnits', TRUE));
497 }
498
499 /**
500 * This returns tablerows for the directories in the array $items['sorting'].
501 *
502 * @param Folder[] $folders Folders of \TYPO3\CMS\Core\Resource\Folder
503 * @return string HTML table rows.
504 */
505 public function formatDirList(array $folders) {
506 $out = '';
507 foreach ($folders as $folderName => $folderObject) {
508 $role = $folderObject->getRole();
509 if ($role === FolderInterface::ROLE_PROCESSING) {
510 // don't show processing-folder
511 continue;
512 }
513 if ($role !== FolderInterface::ROLE_DEFAULT) {
514 $displayName = '<strong>' . htmlspecialchars($folderName) . '</strong>';
515 } else {
516 $displayName = htmlspecialchars($folderName);
517 }
518
519 $isLocked = $folderObject instanceof InaccessibleFolder;
520 $isWritable = $folderObject->checkActionPermission('write');
521
522 // Initialization
523 $this->counter++;
524
525 // The icon with link
526 $theIcon = IconUtility::getSpriteIconForResource($folderObject, array('title' => $folderName));
527 if (!$isLocked && $this->clickMenus) {
528 $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($theIcon, $folderObject->getCombinedIdentifier());
529 }
530
531 // Preparing and getting the data-array
532 $theData = array();
533 if ($isLocked) {
534 foreach ($this->fieldArray as $field) {
535 $theData[$field] = '';
536 }
537 $theData['file'] = $displayName;
538 } else {
539 foreach ($this->fieldArray as $field) {
540 switch ($field) {
541 case 'size':
542 try {
543 $numFiles = $folderObject->getFileCount();
544 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException $e) {
545 $numFiles = 0;
546 }
547 $theData[$field] = $numFiles . ' ' . $this->getLanguageService()->getLL(($numFiles === 1 ? 'file' : 'files'), TRUE);
548 break;
549 case 'rw':
550 $theData[$field] = '<strong class="text-danger">' . $this->getLanguageService()->getLL('read', TRUE) . '</strong>' . (!$isWritable ? '' : '<strong class="text-danger">' . $this->getLanguageService()->getLL('write', TRUE) . '</strong>');
551 break;
552 case 'fileext':
553 $theData[$field] = $this->getLanguageService()->getLL('folder', TRUE);
554 break;
555 case 'tstamp':
556 // @todo: FAL: how to get the mtime info -- $theData[$field] = \TYPO3\CMS\Backend\Utility\BackendUtility::date($theFile['tstamp']);
557 $theData[$field] = '-';
558 break;
559 case 'file':
560 $theData[$field] = $this->linkWrapDir($displayName, $folderObject);
561 break;
562 case '_CONTROL_':
563 $theData[$field] = $this->makeEdit($folderObject);
564 break;
565 case '_CLIPBOARD_':
566 $theData[$field] = $this->makeClip($folderObject);
567 break;
568 case '_REF_':
569 $theData[$field] = $this->makeRef($folderObject);
570 break;
571 default:
572 $theData[$field] = GeneralUtility::fixed_lgd_cs($theData[$field], $this->fixedL);
573 }
574 }
575 }
576 $out .= $this->addelement(1, $theIcon, $theData);
577 }
578 return $out;
579 }
580
581 /**
582 * Wraps the directory-titles
583 *
584 * @param string $title String to be wrapped in links
585 * @param Folder $folderObject Folder to work on
586 * @return string HTML
587 */
588 public function linkWrapDir($title, Folder $folderObject) {
589 $href = $this->script . '&id=' . rawurlencode($folderObject->getCombinedIdentifier());
590 $onclick = ' onclick="' . htmlspecialchars(('top.document.getElementsByName("navigation")[0].contentWindow.Tree.highlightActiveItem("file","folder' . GeneralUtility::md5int($folderObject->getCombinedIdentifier()) . '_"+top.fsMod.currentBank)')) . '"';
591 // Sometimes $code contains plain HTML tags. In such a case the string should not be modified!
592 if ((string)$title === strip_tags($title)) {
593 return '<a href="' . htmlspecialchars($href) . '"' . $onclick . ' title="' . htmlspecialchars($title) . '">' . GeneralUtility::fixed_lgd_cs($title, $this->fixedL) . '</a>';
594 } else {
595 return '<a href="' . htmlspecialchars($href) . '"' . $onclick . '>' . $title . '</a>';
596 }
597 }
598
599 /**
600 * Wraps filenames in links which opens the metadata editor.
601 *
602 * @param string $code String to be wrapped in links
603 * @param File $fileObject File to be linked
604 * @return string HTML
605 */
606 public function linkWrapFile($code, File $fileObject) {
607 try {
608 if ($fileObject instanceof File && $fileObject->isIndexed() && $fileObject->checkActionPermission('write') && $this->getBackendUser()->check('tables_modify', 'sys_file_metadata')) {
609 $metaData = $fileObject->_getMetaData();
610 $data = array(
611 'sys_file_metadata' => array($metaData['uid'] => 'edit')
612 );
613 $editOnClick = BackendUtility::editOnClick(GeneralUtility::implodeArrayForUrl('edit', $data), '', $this->listUrl());
614 $title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.editMetadata'));
615 $code = '<a href="#" title="' . $title . '" onclick="' . htmlspecialchars($editOnClick) . '">' . GeneralUtility::fixed_lgd_cs($code, $this->fixedL) . '</a>';
616 }
617 } catch (\Exception $e) {
618 // intentional fall-through
619 }
620 return $code;
621 }
622
623 /**
624 * Returns list URL; This is the URL of the current script with id and imagemode parameters, that's all.
625 * The URL however is not relative, otherwise GeneralUtility::sanitizeLocalUrl() would say that
626 * the URL would be invalid
627 *
628 * @return string URL
629 */
630 public function listURL($altId = '') {
631 return GeneralUtility::linkThisScript(array(
632 'target' => rawurlencode($this->folderObject->getCombinedIdentifier()),
633 'imagemode' => $this->thumbs
634 ));
635 }
636
637 /**
638 * This returns tablerows for the files in the array $items['sorting'].
639 *
640 * @param File[] $files File items
641 * @return string HTML table rows.
642 */
643 public function formatFileList(array $files) {
644 $out = '';
645 // first two keys are "0" (default) and "-1" (multiple), after that comes the "other languages"
646 $allSystemLanguages = GeneralUtility::makeInstance(TranslationConfigurationProvider::class)->getSystemLanguages();
647 $systemLanguages = array_filter($allSystemLanguages, function($languageRecord) {
648 if ($languageRecord['uid'] === -1 || $languageRecord['uid'] === 0 || !$this->getBackendUser()->checkLanguageAccess($languageRecord['uid'])) {
649 return FALSE;
650 } else {
651 return TRUE;
652 }
653 });
654
655 foreach ($files as $fileObject) {
656 // Initialization
657 $this->counter++;
658 $this->totalbytes += $fileObject->getSize();
659 $ext = $fileObject->getExtension();
660 $fileName = trim($fileObject->getName());
661 // The icon with link
662 $theIcon = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileName . ' [' . (int)$fileObject->getUid() . ']'));
663 if ($this->clickMenus) {
664 $theIcon = $GLOBALS['SOBE']->doc->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 $flagButtonIcon = IconUtility::getSpriteIcon(
699 'actions-document-open',
700 array('title' => sprintf($GLOBALS['LANG']->getLL('editMetadataForLanguage'), $language['title'])),
701 array($flagIcon . '-overlay' => array()));
702 $data = array(
703 'sys_file_metadata' => array($translations[$languageId]['uid'] => 'edit')
704 );
705 $editOnClick = BackendUtility::editOnClick(GeneralUtility::implodeArrayForUrl('edit', $data), '', $this->listUrl());
706 $languageCode .= '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($editOnClick) . '">' . $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 = $GLOBALS['SOBE']->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 if ($this->sort === $col) {
809 // Check reverse sorting
810 $params = '&SET[sort]=' . $col . '&SET[reverse]=' . ($this->sortRev ? '0' : '1');
811 $sortArrow = IconUtility::getSpriteIcon('status-status-sorting-light-' . ($this->sortRev ? 'desc' : 'asc'));
812 } else {
813 $params = '&SET[sort]=' . $col . '&SET[reverse]=0';
814 $sortArrow = '';
815 }
816 $href = GeneralUtility::resolveBackPath($this->script) . '&id=' . rawurlencode($folderIdentifier) . $params;
817 return '<a href="' . htmlspecialchars($href) . '">' . $code . ' ' . $sortArrow . '</a>';
818 }
819
820 /**
821 * Creates the clipboard control pad
822 *
823 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the clipboard panel for the listing.
824 * @return string HTML-table
825 */
826 public function makeClip($fileOrFolderObject) {
827 if (!$fileOrFolderObject->checkActionPermission('read')) {
828 return '';
829 }
830 $cells = array();
831 $fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
832 $fullName = $fileOrFolderObject->getName();
833 $md5 = GeneralUtility::shortmd5($fullIdentifier);
834 // For normal clipboard, add copy/cut buttons:
835 if ($this->clipObj->current == 'normal') {
836 $isSel = $this->clipObj->isSelected('_FILE', $md5);
837 $cells[] = '<a class="btn btn-default"" href="' . htmlspecialchars($this->clipObj->selUrlFile($fullIdentifier, 1, ($isSel == 'copy'))) . '">' . IconUtility::getSpriteIcon(('actions-edit-copy' . ($isSel == 'copy' ? '-release' : '')), array('title' => $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.copy', TRUE))) . '</a>';
838 // we can only cut if file can be moved
839 if ($fileOrFolderObject->checkActionPermission('move')) {
840 $cells[] = '<a class="btn btn-default" href="' . htmlspecialchars($this->clipObj->selUrlFile($fullIdentifier, 0, ($isSel == 'cut'))) . '">' . IconUtility::getSpriteIcon(('actions-edit-cut' . ($isSel == 'cut' ? '-release' : '')), array('title' => $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.cut', TRUE))) . '</a>';
841 } else {
842 $cells[] = $this->spaceIcon;
843 }
844 } else {
845 // For numeric pads, add select checkboxes:
846 $n = '_FILE|' . $md5;
847 $this->CBnames[] = $n;
848 $checked = $this->clipObj->isSelected('_FILE', $md5) ? ' checked="checked"' : '';
849 $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>';
850 }
851 // Display PASTE button, if directory:
852 $elFromTable = $this->clipObj->elFromTable('_FILE');
853 if ($fileOrFolderObject instanceof Folder && !empty($elFromTable) && $fileOrFolderObject->checkActionPermission('write')) {
854 $addPasteButton = TRUE;
855 $elToConfirm = array();
856 foreach ($elFromTable as $key => $element) {
857 $clipBoardElement = $this->resourceFactory->retrieveFileOrFolderObject($element);
858 if ($clipBoardElement instanceof Folder && $clipBoardElement->getStorage()->isWithinFolder($clipBoardElement, $fileOrFolderObject)) {
859 $addPasteButton = FALSE;
860 }
861 $fileInfo = $clipBoardElement->getStorage()->getFileInfoByIdentifier(substr(strstr($element, ':'), 1));
862 $elToConfirm[$key] = $fileInfo['name'];
863 }
864 if ($addPasteButton) {
865 $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) . '">' . IconUtility::getSpriteIcon('actions-document-paste-into') . '</a>';
866 }
867 }
868 // Compile items into a DIV-element:
869 return ' <div class="btn-group" role="group">' . implode('', $cells) . '</div>';
870 }
871
872 /**
873 * Creates the edit control section
874 *
875 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the edit control section for the listing.
876 * @return string HTML-table
877 */
878 public function makeEdit($fileOrFolderObject) {
879 $cells = array();
880 $fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
881
882 // Edit file content (if editable)
883 if ($fileOrFolderObject instanceof File && $fileOrFolderObject->checkActionPermission('write') && GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['SYS']['textfile_ext'], $fileOrFolderObject->getExtension())) {
884 $url = BackendUtility::getModuleUrl('file_edit', array('target' => $fullIdentifier));
885 $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;';
886 $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>';
887 } else {
888 $cells['edit'] = $this->spaceIcon;
889 }
890 if ($fileOrFolderObject instanceof File) {
891 $fileUrl = $fileOrFolderObject->getPublicUrl(TRUE);
892 if ($fileUrl) {
893 $aOnClick = 'return top.openUrlInWindow(' . GeneralUtility::quoteJSvalue($fileUrl) . ', \'WebFile\');';
894 $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>';
895 } else {
896 $cells['view'] = $this->spaceIcon;
897 }
898 } else {
899 $cells['view'] = $this->spaceIcon;
900 }
901
902 // replace file
903 if ($fileOrFolderObject instanceof File && $fileOrFolderObject->checkActionPermission('replace')) {
904 $url = BackendUtility::getModuleUrl('file_replace', array('target' => $fullIdentifier, 'uid' => $fileOrFolderObject->getUid()));
905 $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;';
906 $cells['replace'] = '<a href="#" class="btn btn-default" onclick="' . $replaceOnClick . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:cm.replace') . '">' . IconUtility::getSpriteIcon('actions-edit-replace') . '</a>';
907 }
908
909 // rename the file
910 if ($fileOrFolderObject->checkActionPermission('rename')) {
911 $url = BackendUtility::getModuleUrl('file_rename', array('target' => $fullIdentifier));
912 $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;';
913 $cells['rename'] = '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($renameOnClick) . '" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.rename') . '">' . IconUtility::getSpriteIcon('actions-edit-rename') . '</a>';
914 } else {
915 $cells['rename'] = $this->spaceIcon;
916 }
917 if ($fileOrFolderObject->checkActionPermission('read')) {
918 $infoOnClick = '';
919 if ($fileOrFolderObject instanceof Folder) {
920 $infoOnClick = 'top.launchView( \'_FOLDER\', ' . GeneralUtility::quoteJSvalue($fullIdentifier) . ');return false;';
921 } elseif ($fileOrFolderObject instanceof File) {
922 $infoOnClick = 'top.launchView( \'_FILE\', ' . GeneralUtility::quoteJSvalue($fullIdentifier) . ');return false;';
923 }
924 $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>';
925 } else {
926 $cells['info'] = $this->spaceIcon;
927 }
928
929 // delete the file
930 if ($fileOrFolderObject->checkActionPermission('delete')) {
931 $identifier = $fileOrFolderObject->getIdentifier();
932 if ($fileOrFolderObject instanceof Folder) {
933 $referenceCountText = BackendUtility::referenceCount('_FILE', $identifier, ' (There are %s reference(s) to this folder!)');
934 } else {
935 $referenceCountText = BackendUtility::referenceCount('sys_file', $fileOrFolderObject->getUid(), ' (There are %s reference(s) to this file!)');
936 }
937
938 if ($this->getBackendUser()->jsConfirmation(JsConfirmation::DELETE)) {
939 $confirmationCheck = 'confirm(' . GeneralUtility::quoteJSvalue(sprintf($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:mess.delete'), $fileOrFolderObject->getName()) . $referenceCountText) . ')';
940 } else {
941 $confirmationCheck = '1 == 1';
942 }
943
944 $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);};';
945
946 $cells['delete'] = '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($removeOnClick) . '" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.delete') . '">' . IconUtility::getSpriteIcon('actions-edit-delete') . '</a>';
947 } else {
948 $cells['delete'] = $this->spaceIcon;
949 }
950
951 // Hook for manipulating edit icons.
952 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['fileList']['editIconsHook'])) {
953 $cells['__fileOrFolderObject'] = $fileOrFolderObject;
954 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['fileList']['editIconsHook'] as $classData) {
955 $hookObject = GeneralUtility::getUserObj($classData);
956 if (!$hookObject instanceof FileListEditIconHookInterface) {
957 throw new \UnexpectedValueException(
958 '$hookObject must implement interface \\TYPO3\\CMS\\Filelist\\FileListEditIconHookInterface',
959 1235225797
960 );
961 }
962 $hookObject->manipulateEditIcons($cells, $this);
963 }
964 unset($cells['__fileOrFolderObject']);
965 }
966 // Compile items into a DIV-element:
967 return '<div class="btn-group">' . implode('', $cells) . '</div>';
968 }
969
970 /**
971 * Make reference count
972 *
973 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the clipboard panel for the listing.
974 * @return string HTML
975 */
976 public function makeRef($fileOrFolderObject) {
977 if ($fileOrFolderObject instanceof FolderInterface) {
978 return '-';
979 }
980 // Look up the file in the sys_refindex.
981 // Exclude sys_file_metadata records as these are no use references
982 $databaseConnection = $this->getDatabaseConnection();
983 $table = 'sys_refindex';
984 $referenceCount = $databaseConnection->exec_SELECTcountRows(
985 '*',
986 $table,
987 'ref_table=' . $databaseConnection->fullQuoteStr('sys_file', $table)
988 . ' AND ref_uid=' . (int)$fileOrFolderObject->getUid()
989 . ' AND deleted=0'
990 . ' AND tablename != ' . $databaseConnection->fullQuoteStr('sys_file_metadata', $table)
991 );
992 return $this->generateReferenceToolTip($referenceCount, '\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileOrFolderObject->getCombinedIdentifier()));
993 }
994
995 /**
996 * Returns the database connection
997 * @return DatabaseConnection
998 */
999 protected function getDatabaseConnection() {
1000 return $GLOBALS['TYPO3_DB'];
1001 }
1002
1003 /**
1004 * Returns an instance of LanguageService
1005 *
1006 * @return \TYPO3\CMS\Lang\LanguageService
1007 */
1008 protected function getLanguageService() {
1009 return $GLOBALS['LANG'];
1010 }
1011
1012 /**
1013 * Returns the current BE user.
1014 *
1015 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1016 */
1017 protected function getBackendUser() {
1018 return $GLOBALS['BE_USER'];
1019 }
1020
1021 }