[FEATURE] Add SVG support
[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\Messaging\FlashMessage;
24 use TYPO3\CMS\Core\Resource\File;
25 use TYPO3\CMS\Core\Resource\Folder;
26 use TYPO3\CMS\Core\Resource\InaccessibleFolder;
27 use TYPO3\CMS\Core\Resource\ProcessedFile;
28 use TYPO3\CMS\Core\Resource\ResourceFactory;
29 use TYPO3\CMS\Core\Resource\Utility\ListUtility;
30 use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
31 use TYPO3\CMS\Core\Utility\GeneralUtility;
32 use TYPO3\CMS\Core\Resource\FolderInterface;
33
34 /**
35 * Class for rendering of File>Filelist
36 *
37 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
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 * Initialization of class
181 *
182 * @param Folder $folderObject The folder to work on
183 * @param int $pointer Pointer
184 * @param bool $sort Sorting column
185 * @param bool $sortRev Sorting direction
186 * @param bool $clipBoard
187 * @param bool $bigControlPanel Show clipboard flag
188 * @return void
189 */
190 public function start(Folder $folderObject, $pointer, $sort, $sortRev, $clipBoard = FALSE, $bigControlPanel = FALSE) {
191 $this->script = BackendUtility::getModuleUrl('file_list');
192 $this->folderObject = $folderObject;
193 $this->counter = 0;
194 $this->totalbytes = 0;
195 $this->JScode = '';
196 $this->HTMLcode = '';
197 $this->path = $folderObject->getIdentifier();
198 $this->sort = $sort;
199 $this->sortRev = $sortRev;
200 $this->firstElementNumber = $pointer;
201 $this->clipBoard = $clipBoard;
202 $this->bigControlPanel = $bigControlPanel;
203 // Setting the maximum length of the filenames to the user's settings or minimum 30 (= $this->fixedL)
204 $this->fixedL = max($this->fixedL, $this->getBackendUser()->uc['titleLen']);
205 $this->getLanguageService()->includeLLFile('EXT:lang/locallang_common.xlf');
206 $this->resourceFactory = ResourceFactory::getInstance();
207 }
208
209 /**
210 * Reading files and directories, counting elements and generating the list in ->HTMLcode
211 *
212 * @return void
213 */
214 public function generateList() {
215 $this->HTMLcode .= $this->getTable('fileext,tstamp,size,rw,_REF_');
216 }
217
218 /**
219 * Return the buttons used by the file list to include in the top header
220 *
221 * @param Folder $folderObject
222 * @return array
223 */
224 public function getButtonsAndOtherMarkers(Folder $folderObject) {
225 $otherMarkers = array(
226 'PAGE_ICON' => '',
227 'TITLE' => ''
228 );
229 $buttons = array(
230 'level_up' => $this->getLinkToParentFolder($folderObject),
231 'refresh' => '',
232 'title' => '',
233 'page_icon' => '',
234 'PASTE' => ''
235 );
236 // Makes the code for the folder icon in the top
237 if ($folderObject) {
238 $title = htmlspecialchars($folderObject->getIdentifier());
239 // Start compiling the HTML
240 // If this is some subFolder under the mount root....
241 if ($folderObject->getStorage()->isWithinFileMountBoundaries($folderObject)) {
242 // The icon with link
243 $otherMarkers['PAGE_ICON'] = IconUtility::getSpriteIconForResource($folderObject, array('title' => $title));
244 // No HTML specialchars here - HTML like <strong> </strong> is allowed
245 $otherMarkers['TITLE'] .= GeneralUtility::removeXSS(GeneralUtility::fixed_lgd_cs($title, -($this->fixedL + 20)));
246 } else {
247 // This is the root folder
248 $otherMarkers['PAGE_ICON'] = IconUtility::getSpriteIconForResource($folderObject, array('title' => $title, 'mount-root' => TRUE));
249 $otherMarkers['TITLE'] .= htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, -($this->fixedL + 20)));
250 }
251 if ($this->clickMenus) {
252 $otherMarkers['PAGE_ICON'] = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($otherMarkers['PAGE_ICON'], $folderObject->getCombinedIdentifier());
253 }
254 // Add paste button if clipboard is initialized
255 if ($this->clipObj instanceof Clipboard && $folderObject->checkActionPermission('write')) {
256 $elFromTable = $this->clipObj->elFromTable('_FILE');
257 if (count($elFromTable)) {
258 $addPasteButton = TRUE;
259 foreach ($elFromTable as $element) {
260 $clipBoardElement = $this->resourceFactory->retrieveFileOrFolderObject($element);
261 if ($clipBoardElement instanceof Folder && $clipBoardElement->getStorage()->isWithinFolder($clipBoardElement, $folderObject)) {
262 $addPasteButton = FALSE;
263 }
264 }
265 if ($addPasteButton) {
266 $buttons['PASTE'] = '<a href="' . htmlspecialchars($this->clipObj->pasteUrl('_FILE', $folderObject->getCombinedIdentifier())) . '" onclick="return ' . htmlspecialchars($this->clipObj->confirmMsg('_FILE', $this->path, 'into', $elFromTable)) . '" title="' . $this->getLanguageService()->getLL('clip_paste', TRUE) . '">' . IconUtility::getSpriteIcon('actions-document-paste-after') . '</a>';
267 }
268 }
269 }
270
271 }
272 $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>';
273 return array($buttons, $otherMarkers);
274 }
275
276 /**
277 * Wrapping input string in a link with clipboard command.
278 *
279 * @param string $string String to be linked - must be htmlspecialchar'ed / prepared before.
280 * @param string $table table - NOT USED
281 * @param string $cmd "cmd" value
282 * @param string $warning Warning for JS confirm message
283 * @return string Linked string
284 */
285 public function linkClipboardHeaderIcon($string, $table, $cmd, $warning = '') {
286 $onClickEvent = 'document.dblistForm.cmd.value=\'' . $cmd . '\';document.dblistForm.submit();';
287 if ($warning) {
288 $onClickEvent = 'if (confirm(' . GeneralUtility::quoteJSvalue($warning) . ')){' . $onClickEvent . '}';
289 }
290 return '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($onClickEvent) . 'return false;">' . $string . '</a>';
291 }
292
293 /**
294 * Returns a table with directories and files listed.
295 *
296 * @param array $rowlist Array of files from path
297 * @return string HTML-table
298 */
299 public function getTable($rowlist) {
300 // prepare space icon
301 $this->spaceIcon = '<span class="btn btn-default disabled">' . IconUtility::getSpriteIcon('empty-empty') . '</span>';
302
303 // @todo use folder methods directly when they support filters
304 $storage = $this->folderObject->getStorage();
305 $storage->resetFileAndFolderNameFiltersToDefault();
306
307 // Only render the contents of a browsable storage
308 if ($this->folderObject->getStorage()->isBrowsable()) {
309 $foldersCount = $storage->countFoldersInFolder($this->folderObject);
310 $filesCount = $storage->countFilesInFolder($this->folderObject);
311
312 if ($foldersCount <= $this->firstElementNumber) {
313 $foldersFrom = FALSE;
314 $foldersNum = FALSE;
315 } else {
316 $foldersFrom = $this->firstElementNumber;
317 if ($this->firstElementNumber + $this->iLimit > $foldersCount) {
318 $foldersNum = $foldersCount - $this->firstElementNumber;
319 } else {
320 $foldersNum = $this->iLimit;
321 }
322 }
323 if ($foldersCount >= $this->firstElementNumber + $this->iLimit) {
324 $filesFrom = FALSE;
325 $filesNum = FALSE;
326 } else {
327 if ($this->firstElementNumber <= $foldersCount) {
328 $filesFrom = 0;
329 $filesNum = $this->iLimit - $foldersNum;
330 } else {
331 $filesFrom = $this->firstElementNumber - $foldersCount;
332 if ($filesFrom + $this->iLimit > $filesCount) {
333 $filesNum = $filesCount - $filesFrom;
334 } else {
335 $filesNum = $this->iLimit;
336 }
337 }
338 }
339 $folders = $storage->getFoldersInFolder($this->folderObject, $foldersFrom, $foldersNum, TRUE, FALSE, trim($this->sort), (bool)$this->sortRev);
340 $files = $this->folderObject->getFiles($filesFrom, $filesNum, Folder::FILTER_MODE_USE_OWN_AND_STORAGE_FILTERS, FALSE, trim($this->sort), (bool)$this->sortRev);
341 $this->totalItems = $foldersCount + $filesCount;
342 // Adds the code of files/dirs
343 $out = '';
344 $titleCol = 'file';
345 // Cleaning rowlist for duplicates and place the $titleCol as the first column always!
346 $rowlist = '_LOCALIZATION_,' . $rowlist;
347 $rowlist = GeneralUtility::rmFromList($titleCol, $rowlist);
348 $rowlist = GeneralUtility::uniqueList($rowlist);
349 $rowlist = $rowlist ? $titleCol . ',' . $rowlist : $titleCol;
350 if ($this->clipBoard) {
351 $rowlist = str_replace('_LOCALIZATION_,', '_LOCALIZATION_,_CLIPBOARD_,', $rowlist);
352 $this->addElement_tdCssClass['_CLIPBOARD_'] = 'col-clipboard';
353 }
354 if ($this->bigControlPanel) {
355 $rowlist = str_replace('_LOCALIZATION_,', '_LOCALIZATION_,_CONTROL_,', $rowlist);
356 $this->addElement_tdCssClass['_CONTROL_'] = 'col-control';
357 }
358 $this->fieldArray = explode(',', $rowlist);
359
360 // Add classes to table cells
361 $this->addElement_tdCssClass[$titleCol] = 'col-title';
362 $this->addElement_tdCssClass['_LOCALIZATION_'] = 'col-localizationa';
363
364 $folders = ListUtility::resolveSpecialFolderNames($folders);
365
366 $iOut = '';
367 // Directories are added
368 $this->eCounter = $this->firstElementNumber;
369 list($flag, $code) = $this->fwd_rwd_nav();
370 $iOut .= $code;
371
372 $iOut .= $this->formatDirList($folders);
373 // Files are added
374 $iOut .= $this->formatFileList($files);
375
376 $this->eCounter = $this->firstElementNumber + $this->iLimit <= $this->totalItems
377 ? $this->firstElementNumber + $this->iLimit
378 : $this->totalItems;
379 list($flag, $code) = $this->fwd_rwd_nav();
380 $iOut .= $code;
381
382 // Header line is drawn
383 $theData = array();
384 foreach ($this->fieldArray as $v) {
385 if ($v == '_CLIPBOARD_' && $this->clipBoard) {
386 $cells = array();
387 $table = '_FILE';
388 $elFromTable = $this->clipObj->elFromTable($table);
389 if (count($elFromTable) && $this->folderObject->checkActionPermission('write')) {
390 $addPasteButton = TRUE;
391 foreach ($elFromTable as $element) {
392 $clipBoardElement = $this->resourceFactory->retrieveFileOrFolderObject($element);
393 if ($clipBoardElement instanceof Folder && $clipBoardElement->getStorage()->isWithinFolder($clipBoardElement, $this->folderObject)) {
394 $addPasteButton = FALSE;
395 }
396 }
397 if ($addPasteButton) {
398 $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', $elFromTable)) . '" title="' . $this->getLanguageService()->getLL('clip_paste', 1) . '">' . IconUtility::getSpriteIcon('actions-document-paste-after') . '</a>';
399 }
400 }
401 if ($this->clipObj->current !== 'normal' && $iOut) {
402 $cells[] = $this->linkClipboardHeaderIcon(IconUtility::getSpriteIcon('actions-edit-copy', array('title' => $this->getLanguageService()->getLL('clip_selectMarked', TRUE))), $table, 'setCB');
403 $cells[] = $this->linkClipboardHeaderIcon(IconUtility::getSpriteIcon('actions-edit-delete', array('title' => $this->getLanguageService()->getLL('clip_deleteMarked'))), $table, 'delete', $this->getLanguageService()->getLL('clip_deleteMarkedWarning'));
404 $onClick = 'checkOffCB(\'' . implode(',', $this->CBnames) . '\', this); return false;';
405 $cells[] = '<a class="btn btn-default" rel="" href="#" onclick="' . htmlspecialchars($onClick) . '" title="' . $this->getLanguageService()->getLL('clip_markRecords', TRUE) . '">' . IconUtility::getSpriteIcon('actions-document-select') . '</a>';
406 }
407 $theData[$v] = implode('', $cells);
408 } else {
409 // Normal row:
410 $theT = $this->linkWrapSort($this->getLanguageService()->getLL('c_' . $v, TRUE), $this->folderObject->getCombinedIdentifier(), $v);
411 $theData[$v] = $theT;
412 }
413 }
414
415 $out .= '<thead>' . $this->addelement(1, '', $theData, '', '', '', 'th') . '</thead>';
416 $out .= '<tbody>' . $iOut . '</tbody>';
417 // half line is drawn
418 // finish
419 $out = '
420 <!--
421 File list table:
422 -->
423 <div class="table-fit">
424 <table class="table table-striped table-hover" id="typo3-filelist">
425 ' . $out . '
426 </table>
427 </div>';
428
429 } else {
430 /** @var $flashMessage FlashMessage */
431 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('storageNotBrowsableMessage'), $this->getLanguageService()->getLL('storageNotBrowsableTitle'), FlashMessage::INFO);
432 $out = $flashMessage->render();
433 }
434 return $out;
435 }
436
437 /**
438 * If there is a parent folder and user has access to it, return an icon
439 * which is linked to the filelist of the parent folder.
440 *
441 * @param Folder $currentFolder
442 * @return string
443 */
444 protected function getLinkToParentFolder(Folder $currentFolder) {
445 $levelUp = '';
446 try {
447 $currentStorage = $currentFolder->getStorage();
448 $parentFolder = $currentFolder->getParentFolder();
449 if ($parentFolder->getIdentifier() !== $currentFolder->getIdentifier() && $currentStorage->isWithinFileMountBoundaries($parentFolder)) {
450 $levelUp = $this->linkWrapDir(
451 IconUtility::getSpriteIcon(
452 'actions-view-go-up',
453 array('title' => $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.php:labels.upOneLevel', TRUE))
454 ),
455 $parentFolder
456 );
457 }
458 } catch (\Exception $e) {}
459 return $levelUp;
460 }
461
462 /**
463 * Gets the number of files and total size of a folder
464 *
465 * @return string
466 */
467 public function getFolderInfo() {
468 if ($this->counter == 1) {
469 $fileLabel = $this->getLanguageService()->getLL('file', TRUE);
470 } else {
471 $fileLabel = $this->getLanguageService()->getLL('files', TRUE);
472 }
473 return $this->counter . ' ' . $fileLabel . ', ' . GeneralUtility::formatSize($this->totalbytes, $this->getLanguageService()->getLL('byteSizeUnits', TRUE));
474 }
475
476 /**
477 * This returns tablerows for the directories in the array $items['sorting'].
478 *
479 * @param Folder[] $folders Folders of \TYPO3\CMS\Core\Resource\Folder
480 * @return string HTML table rows.
481 */
482 public function formatDirList(array $folders) {
483 $out = '';
484 foreach ($folders as $folderName => $folderObject) {
485 $role = $folderObject->getRole();
486 if ($role === FolderInterface::ROLE_PROCESSING) {
487 // don't show processing-folder
488 continue;
489 }
490 if ($role !== FolderInterface::ROLE_DEFAULT) {
491 $displayName = '<strong>' . htmlspecialchars($folderName) . '</strong>';
492 } else {
493 $displayName = htmlspecialchars($folderName);
494 }
495
496 $isLocked = $folderObject instanceof InaccessibleFolder;
497 $isWritable = $folderObject->checkActionPermission('write');
498
499 // Initialization
500 $this->counter++;
501
502 // The icon with link
503 $theIcon = IconUtility::getSpriteIconForResource($folderObject, array('title' => $folderName));
504 if (!$isLocked && $this->clickMenus) {
505 $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($theIcon, $folderObject->getCombinedIdentifier());
506 }
507
508 // Preparing and getting the data-array
509 $theData = array();
510 if ($isLocked) {
511 foreach ($this->fieldArray as $field) {
512 $theData[$field] = '';
513 }
514 $theData['file'] = $displayName;
515 } else {
516 foreach ($this->fieldArray as $field) {
517 switch ($field) {
518 case 'size':
519 $numFiles = $folderObject->getFileCount();
520 $theData[$field] = $numFiles . ' ' . $this->getLanguageService()->getLL(($numFiles === 1 ? 'file' : 'files'), TRUE);
521 break;
522 case 'rw':
523 $theData[$field] = '<strong class="text-danger">' . $this->getLanguageService()->getLL('read', TRUE) . '</strong>' . (!$isWritable ? '' : '<strong class="text-danger">' . $this->getLanguageService()->getLL('write', TRUE) . '</strong>');
524 break;
525 case 'fileext':
526 $theData[$field] = $this->getLanguageService()->getLL('folder', TRUE);
527 break;
528 case 'tstamp':
529 // @todo: FAL: how to get the mtime info -- $theData[$field] = \TYPO3\CMS\Backend\Utility\BackendUtility::date($theFile['tstamp']);
530 $theData[$field] = '-';
531 break;
532 case 'file':
533 $theData[$field] = $this->linkWrapDir($displayName, $folderObject);
534 break;
535 case '_CONTROL_':
536 $theData[$field] = $this->makeEdit($folderObject);
537 break;
538 case '_CLIPBOARD_':
539 $theData[$field] = $this->makeClip($folderObject);
540 break;
541 case '_REF_':
542 $theData[$field] = $this->makeRef($folderObject);
543 break;
544 default:
545 $theData[$field] = GeneralUtility::fixed_lgd_cs($theData[$field], $this->fixedL);
546 }
547 }
548 }
549 $out .= $this->addelement(1, $theIcon, $theData);
550 }
551 return $out;
552 }
553
554 /**
555 * Wraps the directory-titles
556 *
557 * @param string $title String to be wrapped in links
558 * @param Folder $folderObject Folder to work on
559 * @return string HTML
560 */
561 public function linkWrapDir($title, Folder $folderObject) {
562 $href = $this->backPath . $this->script . '&id=' . rawurlencode($folderObject->getCombinedIdentifier());
563 $onclick = ' onclick="' . htmlspecialchars(('top.document.getElementsByName("navigation")[0].contentWindow.Tree.highlightActiveItem("file","folder' . GeneralUtility::md5int($folderObject->getCombinedIdentifier()) . '_"+top.fsMod.currentBank)')) . '"';
564 // Sometimes $code contains plain HTML tags. In such a case the string should not be modified!
565 if ((string)$title === strip_tags($title)) {
566 return '<a href="' . htmlspecialchars($href) . '"' . $onclick . ' title="' . htmlspecialchars($title) . '">' . GeneralUtility::fixed_lgd_cs($title, $this->fixedL) . '</a>';
567 } else {
568 return '<a href="' . htmlspecialchars($href) . '"' . $onclick . '>' . $title . '</a>';
569 }
570 }
571
572 /**
573 * Wraps filenames in links which opens the metadata editor.
574 *
575 * @param string $code String to be wrapped in links
576 * @param File $fileObject File to be linked
577 * @return string HTML
578 */
579 public function linkWrapFile($code, File $fileObject) {
580 try {
581 if ($fileObject instanceof File && $fileObject->isIndexed() && $fileObject->checkActionPermission('write') && $this->getBackendUser()->check('tables_modify', 'sys_file_metadata')) {
582 $metaData = $fileObject->_getMetaData();
583 $data = array(
584 'sys_file_metadata' => array($metaData['uid'] => 'edit')
585 );
586 $editOnClick = BackendUtility::editOnClick(GeneralUtility::implodeArrayForUrl('edit', $data), '', $this->listUrl());
587 $title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.editMetadata'));
588 $code = '<a href="#" title="' . $title . '" onclick="' . htmlspecialchars($editOnClick) . '">' . GeneralUtility::fixed_lgd_cs($code, $this->fixedL) . '</a>';
589 }
590 } catch (\Exception $e) {
591 // intentional fall-through
592 }
593 return $code;
594 }
595
596 /**
597 * Returns list URL; This is the URL of the current script with id and imagemode parameters, that's all.
598 * The URL however is not relative (with the backpath), otherwise GeneralUtility::sanitizeLocalUrl() would say that
599 * the URL would be invalid
600 *
601 * @return string URL
602 */
603 public function listURL() {
604 return GeneralUtility::linkThisScript(array(
605 'target' => rawurlencode($this->folderObject->getCombinedIdentifier()),
606 'imagemode' => $this->thumbs
607 ));
608 }
609
610 /**
611 * This returns tablerows for the files in the array $items['sorting'].
612 *
613 * @param File[] $files File items
614 * @return string HTML table rows.
615 */
616 public function formatFileList(array $files) {
617 $out = '';
618 // first two keys are "0" (default) and "-1" (multiple), after that comes the "other languages"
619 $allSystemLanguages = GeneralUtility::makeInstance(TranslationConfigurationProvider::class)->getSystemLanguages();
620 $systemLanguages = array_filter($allSystemLanguages, function($languageRecord) {
621 if ($languageRecord['uid'] === -1 || $languageRecord['uid'] === 0 || !$this->getBackendUser()->checkLanguageAccess($languageRecord['uid'])) {
622 return FALSE;
623 } else {
624 return TRUE;
625 }
626 });
627
628 foreach ($files as $fileObject) {
629 // Initialization
630 $this->counter++;
631 $this->totalbytes += $fileObject->getSize();
632 $ext = $fileObject->getExtension();
633 $fileName = trim($fileObject->getName());
634 // The icon with link
635 $theIcon = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileName . ' [' . (int)$fileObject->getUid() . ']'));
636 if ($this->clickMenus) {
637 $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($theIcon, $fileObject->getCombinedIdentifier());
638 }
639 // Preparing and getting the data-array
640 $theData = array();
641 foreach ($this->fieldArray as $field) {
642 switch ($field) {
643 case 'size':
644 $theData[$field] = GeneralUtility::formatSize($fileObject->getSize(), $this->getLanguageService()->getLL('byteSizeUnits', TRUE));
645 break;
646 case 'rw':
647 $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>');
648 break;
649 case 'fileext':
650 $theData[$field] = strtoupper($ext);
651 break;
652 case 'tstamp':
653 $theData[$field] = BackendUtility::date($fileObject->getModificationTime());
654 break;
655 case '_CONTROL_':
656 $theData[$field] = $this->makeEdit($fileObject);
657 break;
658 case '_CLIPBOARD_':
659 $theData[$field] = $this->makeClip($fileObject);
660 break;
661 case '_LOCALIZATION_':
662 if (!empty($systemLanguages) && $fileObject->isIndexed() && $fileObject->checkActionPermission('write') && $this->getBackendUser()->check('tables_modify', 'sys_file_metadata')) {
663 $metaDataRecord = $fileObject->_getMetaData();
664 $translations = $this->getTranslationsForMetaData($metaDataRecord);
665 $languageCode = '';
666
667 foreach ($systemLanguages as $language) {
668 $languageId = $language['uid'];
669 $flagIcon = $language['flagIcon'];
670 if (array_key_exists($languageId, $translations)) {
671 $flagButtonIcon = IconUtility::getSpriteIcon(
672 'actions-document-open',
673 array('title' => sprintf($GLOBALS['LANG']->getLL('editMetadataForLanguage'), $language['title'])),
674 array($flagIcon . '-overlay' => array()));
675 $data = array(
676 'sys_file_metadata' => array($translations[$languageId]['uid'] => 'edit')
677 );
678 $editOnClick = BackendUtility::editOnClick(GeneralUtility::implodeArrayForUrl('edit', $data), $GLOBALS['BACK_PATH'], $this->listUrl());
679 $languageCode .= '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($editOnClick) . '">' . $flagButtonIcon . '</a>';
680 } else {
681 $href = $GLOBALS['SOBE']->doc->issueCommand(
682 '&cmd[sys_file_metadata][' . $metaDataRecord['uid'] . '][localize]=' . $languageId,
683 $this->backPath . 'alt_doc.php?justLocalized=' . rawurlencode(('sys_file_metadata:' . $metaDataRecord['uid'] . ':' . $languageId)) .
684 '&returnUrl=' . rawurlencode($this->listURL()) . BackendUtility::getUrlToken('editRecord')
685 );
686 $flagButtonIcon = IconUtility::getSpriteIcon(
687 $flagIcon,
688 array('title' => sprintf($GLOBALS['LANG']->getLL('createMetadataForLanguage'), $language['title'])),
689 array($flagIcon . '-overlay' => array())
690 );
691 $languageCode .= '<a href="' . htmlspecialchars($href) . '" class="btn btn-default">' . $flagButtonIcon . '</a> ';
692 }
693 }
694
695 // Hide flag button bar when not translated yet
696 $theData[$field] = ' <div class="localisationData btn-group" data-fileid="' . $fileObject->getUid() . '"' .
697 (empty($translations) ? ' style="display: none;"' : '') . '>' . $languageCode . '</div>';
698 $theData[$field] .= '<a class="btn btn-default filelist-translationToggler" data-fileid="' . $fileObject->getUid() . '">' .
699 IconUtility::getSpriteIcon(
700 'mimetypes-x-content-page-language-overlay',
701 array(
702 'title' => $GLOBALS['LANG']->getLL('translateMetadata')
703 )
704 ) . '</a>';
705 }
706 break;
707 case '_REF_':
708 $theData[$field] = $this->makeRef($fileObject);
709 break;
710 case 'file':
711 // Edit metadata of file
712 $theData[$field] = $this->linkWrapFile(htmlspecialchars($fileName), $fileObject);
713
714 if ($fileObject->isMissing()) {
715 $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
716 $theData[$field] .= $flashMessage->render();
717 // Thumbnails?
718 } elseif ($this->thumbs && $this->isImage($ext)) {
719 $processedFile = $fileObject->process(ProcessedFile::CONTEXT_IMAGEPREVIEW, array());
720 if ($processedFile) {
721 $thumbUrl = $processedFile->getPublicUrl(TRUE);
722 $theData[$field] .= '<br /><img src="' . $thumbUrl . '" ' .
723 'width="' . $processedFile->getProperty('width') . '" ' .
724 'height="' . $processedFile->getProperty('height') . '" ' .
725 'title="' . htmlspecialchars($fileName) . '" alt="" />';
726 }
727 }
728 break;
729 default:
730 $theData[$field] = '';
731 if ($fileObject->hasProperty($field)) {
732 $theData[$field] = htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileObject->getProperty($field), $this->fixedL));
733 }
734 }
735 }
736 $out .= $this->addelement(1, $theIcon, $theData);
737 }
738 return $out;
739 }
740
741 /**
742 * Fetch the translations for a sys_file_metadata record
743 *
744 * @param $metaDataRecord
745 * @return array keys are the sys_language uids, values are the $rows
746 */
747 protected function getTranslationsForMetaData($metaDataRecord) {
748 $where = $GLOBALS['TCA']['sys_file_metadata']['ctrl']['transOrigPointerField'] . '=' . (int)$metaDataRecord['uid'] .
749 ' AND ' . $GLOBALS['TCA']['sys_file_metadata']['ctrl']['languageField'] . '>0';
750 $translationRecords = $this->getDatabaseConnection()->exec_SELECTgetRows('*', 'sys_file_metadata', $where);
751 $translations = array();
752 foreach ($translationRecords as $record) {
753 $translations[$record[$GLOBALS['TCA']['sys_file_metadata']['ctrl']['languageField']]] = $record;
754 }
755 return $translations;
756 }
757
758 /**
759 * Returns TRUE if $ext is an image-extension according to $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
760 *
761 * @param string $ext File extension
762 * @return bool
763 */
764 public function isImage($ext) {
765 return GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], strtolower($ext));
766 }
767
768 /**
769 * Wraps the directory-titles ($code) in a link to filelist/mod1/index.php (id=$path) and sorting commands...
770 *
771 * @param string $code String to be wrapped
772 * @param string $folderIdentifier ID (path)
773 * @param string $col Sorting column
774 * @return string HTML
775 */
776 public function linkWrapSort($code, $folderIdentifier, $col) {
777 if ($this->sort === $col) {
778 // Check reverse sorting
779 $params = '&SET[sort]=' . $col . '&SET[reverse]=' . ($this->sortRev ? '0' : '1');
780 $sortArrow = IconUtility::getSpriteIcon('status-status-sorting-light-' . ($this->sortRev ? 'desc' : 'asc'));
781 } else {
782 $params = '&SET[sort]=' . $col . '&SET[reverse]=0';
783 $sortArrow = '';
784 }
785 $href = GeneralUtility::resolveBackPath(($GLOBALS['BACK_PATH'] . $this->script)) . '&id=' . rawurlencode($folderIdentifier) . $params;
786 return '<a href="' . htmlspecialchars($href) . '">' . $code . ' ' . $sortArrow . '</a>';
787 }
788
789 /**
790 * Creates the clipboard control pad
791 *
792 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the clipboard panel for the listing.
793 * @return string HTML-table
794 */
795 public function makeClip($fileOrFolderObject) {
796 if (!$fileOrFolderObject->checkActionPermission('read')) {
797 return '';
798 }
799 $cells = array();
800 $fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
801 $md5 = GeneralUtility::shortmd5($fullIdentifier);
802 // For normal clipboard, add copy/cut buttons:
803 if ($this->clipObj->current == 'normal') {
804 $isSel = $this->clipObj->isSelected('_FILE', $md5);
805 $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>';
806 // we can only cut if file can be moved
807 if ($fileOrFolderObject->checkActionPermission('move')) {
808 $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>';
809 } else {
810 $cells[] = $this->spaceIcon;
811 }
812 } else {
813 // For numeric pads, add select checkboxes:
814 $n = '_FILE|' . $md5;
815 $this->CBnames[] = $n;
816 $checked = $this->clipObj->isSelected('_FILE', $md5) ? ' checked="checked"' : '';
817 $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>';
818 }
819 // Display PASTE button, if directory:
820 $elFromTable = $this->clipObj->elFromTable('_FILE');
821 if ($fileOrFolderObject instanceof Folder && count($elFromTable) && $fileOrFolderObject->checkActionPermission('write')) {
822 $addPasteButton = TRUE;
823 foreach ($elFromTable as $element) {
824 $clipBoardElement = $this->resourceFactory->retrieveFileOrFolderObject($element);
825 if ($clipBoardElement instanceof Folder && $clipBoardElement->getStorage()->isWithinFolder($clipBoardElement, $fileOrFolderObject)) {
826 $addPasteButton = FALSE;
827 }
828 }
829 if ($addPasteButton) {
830 $cells[] = '<a class="btn btn-default" href="' . htmlspecialchars($this->clipObj->pasteUrl('_FILE', $fullIdentifier)) . '" onclick="return ' . htmlspecialchars($this->clipObj->confirmMsg('_FILE', $fullIdentifier, 'into', $elFromTable)) . '" title="' . $this->getLanguageService()->getLL('clip_pasteInto', TRUE) . '">' . IconUtility::getSpriteIcon('actions-document-paste-into') . '</a>';
831 }
832 }
833 // Compile items into a DIV-element:
834 return ' <div class="btn-group" role="group">' . implode('', $cells) . '</div>';
835 }
836
837 /**
838 * Creates the edit control section
839 *
840 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the edit control section for the listing.
841 * @return string HTML-table
842 */
843 public function makeEdit($fileOrFolderObject) {
844 $cells = array();
845 $fullIdentifier = $fileOrFolderObject->getCombinedIdentifier();
846 // Edit file content (if editable)
847 if ($fileOrFolderObject instanceof File && $fileOrFolderObject->checkActionPermission('write') && GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['SYS']['textfile_ext'], $fileOrFolderObject->getExtension())) {
848 $url = BackendUtility::getModuleUrl('file_edit', array('target' => $fullIdentifier));
849 $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;';
850 $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>';
851 } else {
852 $cells['edit'] = $this->spaceIcon;
853 }
854 if ($fileOrFolderObject instanceof File) {
855 $fileUrl = $fileOrFolderObject->getPublicUrl(TRUE);
856 if ($fileUrl) {
857 $aOnClick = 'return top.openUrlInWindow(' . GeneralUtility::quoteJSvalue($fileUrl) . ', \'WebFile\');';
858 $cells['view'] = '<a href="#" class="btn btn-default" onclick="' . htmlspecialchars($aOnClick) . '" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.view') . '">' . IconUtility::getSpriteIcon('actions-document-view') . '</a>';
859 } else {
860 $cells['view'] = $this->spaceIcon;
861 }
862 } else {
863 $cells['view'] = $this->spaceIcon;
864 }
865 // rename the file
866 if ($fileOrFolderObject->checkActionPermission('rename')) {
867 $url = BackendUtility::getModuleUrl('file_rename', array('target' => $fullIdentifier));
868 $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;';
869 $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>';
870 } else {
871 $cells['rename'] = $this->spaceIcon;
872 }
873 if ($fileOrFolderObject->checkActionPermission('read')) {
874 $infoOnClick = '';
875 if ($fileOrFolderObject instanceof Folder) {
876 $infoOnClick = 'top.launchView( \'_FOLDER\', ' . GeneralUtility::quoteJSvalue($fullIdentifier) . ');return false;';
877 } elseif ($fileOrFolderObject instanceof File) {
878 $infoOnClick = 'top.launchView( \'_FILE\', ' . GeneralUtility::quoteJSvalue($fullIdentifier) . ');return false;';
879 }
880 $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>';
881 } else {
882 $cells['info'] = $this->spaceIcon;
883 }
884
885 // delete the file
886 if ($fileOrFolderObject->checkActionPermission('delete')) {
887 $identifier = $fileOrFolderObject->getIdentifier();
888 if ($fileOrFolderObject instanceof Folder) {
889 $referenceCountText = BackendUtility::referenceCount('_FILE', $identifier, ' (There are %s reference(s) to this folder!)');
890 } else {
891 $referenceCountText = BackendUtility::referenceCount('sys_file', $fileOrFolderObject->getUid(), ' (There are %s reference(s) to this file!)');
892 }
893
894 if ($this->getBackendUser()->jsConfirmation(JsConfirmation::DELETE)) {
895 $confirmationCheck = 'confirm(' . GeneralUtility::quoteJSvalue(sprintf($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:mess.delete'), $fileOrFolderObject->getName()) . $referenceCountText) . ')';
896 } else {
897 $confirmationCheck = '1 == 1';
898 }
899
900 $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);};';
901
902 $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>';
903 } else {
904 $cells['delete'] = $this->spaceIcon;
905 }
906
907 // Hook for manipulating edit icons.
908 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['fileList']['editIconsHook'])) {
909 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['fileList']['editIconsHook'] as $classData) {
910 $hookObject = GeneralUtility::getUserObj($classData);
911 if (!$hookObject instanceof FileListEditIconHookInterface) {
912 throw new \UnexpectedValueException(
913 '$hookObject must implement interface \\TYPO3\\CMS\\Filelist\\FileListEditIconHookInterface',
914 1235225797
915 );
916 }
917 $hookObject->manipulateEditIcons($cells, $this);
918 }
919 }
920 // Compile items into a DIV-element:
921 return '<div class="btn-group">' . implode('', $cells) . '</div>';
922 }
923
924 /**
925 * Make reference count
926 *
927 * @param File|Folder $fileOrFolderObject Array with information about the file/directory for which to make the clipboard panel for the listing.
928 * @return string HTML
929 */
930 public function makeRef($fileOrFolderObject) {
931 if ($fileOrFolderObject instanceof FolderInterface) {
932 return '-';
933 }
934 // Look up the file in the sys_refindex.
935 // Exclude sys_file_metadata records as these are no use references
936 $referenceCount = $this->getDatabaseConnection()->exec_SELECTcountRows(
937 '*',
938 'sys_refindex',
939 'ref_table=\'sys_file\' AND ref_uid = ' . (int)$fileOrFolderObject->getUid() . ' AND deleted=0 AND tablename != "sys_file_metadata"'
940 );
941 return $this->generateReferenceToolTip($referenceCount, '\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileOrFolderObject->getCombinedIdentifier()));
942 }
943
944 /**
945 * Returns the database connection
946 * @return DatabaseConnection
947 */
948 protected function getDatabaseConnection() {
949 return $GLOBALS['TYPO3_DB'];
950 }
951
952 /**
953 * Returns an instance of LanguageService
954 *
955 * @return \TYPO3\CMS\Lang\LanguageService
956 */
957 protected function getLanguageService() {
958 return $GLOBALS['LANG'];
959 }
960
961 /**
962 * Returns the current BE user.
963 *
964 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
965 */
966 protected function getBackendUser() {
967 return $GLOBALS['BE_USER'];
968 }
969
970 }