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