[!!!][TASK] Remove deprecated code from EXT:recordlist
[Packages/TYPO3.CMS.git] / typo3 / sysext / recordlist / Classes / Browser / FileBrowser.php
1 <?php
2 namespace TYPO3\CMS\Recordlist\Browser;
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\Tree\View\ElementBrowserFolderTreeView;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Core\Imaging\Icon;
20 use TYPO3\CMS\Core\Resource\Exception;
21 use TYPO3\CMS\Core\Resource\File;
22 use TYPO3\CMS\Core\Resource\FileInterface;
23 use TYPO3\CMS\Core\Resource\FileRepository;
24 use TYPO3\CMS\Core\Resource\Filter\FileExtensionFilter;
25 use TYPO3\CMS\Core\Resource\Folder;
26 use TYPO3\CMS\Core\Resource\ProcessedFile;
27 use TYPO3\CMS\Core\Resource\ResourceFactory;
28 use TYPO3\CMS\Core\Utility\GeneralUtility;
29 use TYPO3\CMS\Recordlist\Tree\View\LinkParameterProviderInterface;
30 use TYPO3\CMS\Recordlist\View\FolderUtilityRenderer;
31
32 /**
33 * Browser for files
34 */
35 class FileBrowser extends AbstractElementBrowser implements ElementBrowserInterface, LinkParameterProviderInterface
36 {
37 /**
38 * When you click a folder name/expand icon to see the content of a certain file folder,
39 * this value will contain the path of the expanded file folder.
40 * If the value is NOT set, then it will be restored from the module session data.
41 * Example value: "/www/htdocs/typo3/32/3dsplm/fileadmin/css/"
42 *
43 * @var string|NULL
44 */
45 protected $expandFolder;
46
47 /**
48 * @var Folder
49 */
50 protected $selectedFolder;
51
52 /**
53 * Holds information about files
54 *
55 * @var mixed[][]
56 */
57 protected $elements = array();
58
59 /**
60 * @var string
61 */
62 protected $searchWord;
63
64 /**
65 * @var FileRepository
66 */
67 protected $fileRepository;
68
69 /**
70 * @return void
71 */
72 protected function initialize()
73 {
74 parent::initialize();
75 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Recordlist/BrowseFiles');
76 $this->fileRepository = GeneralUtility::makeInstance(FileRepository::class);
77 }
78
79 /**
80 * @return void
81 */
82 protected function initVariables()
83 {
84 parent::initVariables();
85 $this->expandFolder = GeneralUtility::_GP('expandFolder');
86 $this->searchWord = (string)GeneralUtility::_GP('searchWord');
87 }
88
89 /**
90 * Session data for this class can be set from outside with this method.
91 *
92 * @param mixed[] $data Session data array
93 * @return array[] Session data and boolean which indicates that data needs to be stored in session because it's changed
94 */
95 public function processSessionData($data)
96 {
97 if ($this->expandFolder !== null) {
98 $data['expandFolder'] = $this->expandFolder;
99 $store = true;
100 } else {
101 $this->expandFolder = $data['expandFolder'];
102 $store = false;
103 }
104 return array($data, $store);
105 }
106
107 /**
108 * @return string HTML content
109 */
110 public function render()
111 {
112 $backendUser = $this->getBackendUser();
113
114 // The key number 3 of the bparams contains the "allowed" string. Disallowed is not passed to
115 // the element browser at all but only filtered out in TCEMain afterwards
116 $allowedFileExtensions = explode('|', $this->bparams)[3];
117 if (!empty($allowedFileExtensions) && $allowedFileExtensions !== 'sys_file' && $allowedFileExtensions !== '*') {
118 // Create new filter object
119 $filterObject = GeneralUtility::makeInstance(FileExtensionFilter::class);
120 $filterObject->setAllowedFileExtensions($allowedFileExtensions);
121 // Set file extension filters on all storages
122 $storages = $backendUser->getFileStorages();
123 /** @var $storage \TYPO3\CMS\Core\Resource\ResourceStorage */
124 foreach ($storages as $storage) {
125 $storage->addFileAndFolderNameFilter(array($filterObject, 'filterFileList'));
126 }
127 }
128 // Create upload/create folder forms, if a path is given
129 if ($this->expandFolder) {
130 $fileOrFolderObject = null;
131
132 // Try to fetch the folder the user had open the last time he browsed files
133 // Fallback to the default folder in case the last used folder is not existing
134 try {
135 $fileOrFolderObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($this->expandFolder);
136 } catch (Exception $accessException) {
137 // We're just catching the exception here, nothing to be done if folder does not exist or is not accessible.
138 } catch (\InvalidArgumentException $driverMissingExecption) {
139 // We're just catching the exception here, nothing to be done if the driver does not exist anymore.
140 }
141
142 if ($fileOrFolderObject instanceof Folder) {
143 // It's a folder
144 $this->selectedFolder = $fileOrFolderObject;
145 } elseif ($fileOrFolderObject instanceof FileInterface) {
146 // It's a file
147 $this->selectedFolder = $fileOrFolderObject->getParentFolder();
148 }
149 }
150 // Or get the user's default upload folder
151 if (!$this->selectedFolder) {
152 try {
153 $this->selectedFolder = $backendUser->getDefaultUploadFolder();
154 } catch (\Exception $e) {
155 // The configured default user folder does not exist
156 }
157 }
158 // Build the file upload and folder creation form
159 $uploadForm = '';
160 $createFolder = '';
161 if ($this->selectedFolder) {
162 $pArr = explode('|', $this->bparams);
163 $allowedExtensions = isset($pArr[3]) ? GeneralUtility::trimExplode(',', $pArr[3], true) : [];
164 $folderUtilityRenderer = GeneralUtility::makeInstance(FolderUtilityRenderer::class, $this);
165 $uploadForm = $folderUtilityRenderer->uploadForm($this->selectedFolder, $allowedExtensions);
166 $createFolder = $folderUtilityRenderer->createFolder($this->selectedFolder);
167 }
168
169 // Getting flag for showing/not showing thumbnails:
170 $noThumbs = $backendUser->getTSConfigVal('options.noThumbsInEB');
171 $_MOD_SETTINGS = array();
172 if (!$noThumbs) {
173 // MENU-ITEMS, fetching the setting for thumbnails from File>List module:
174 $_MOD_MENU = array('displayThumbs' => '');
175 $_MCONF['name'] = 'file_list';
176 $_MOD_SETTINGS = BackendUtility::getModuleData($_MOD_MENU, GeneralUtility::_GP('SET'), $_MCONF['name']);
177 }
178 $noThumbs = $noThumbs ?: !$_MOD_SETTINGS['displayThumbs'];
179 // Create folder tree:
180 /** @var ElementBrowserFolderTreeView $folderTree */
181 $folderTree = GeneralUtility::makeInstance(ElementBrowserFolderTreeView::class);
182 $folderTree->setLinkParameterProvider($this);
183 $tree = $folderTree->getBrowsableTree();
184 if ($this->selectedFolder) {
185 $files = $this->renderFilesInFolder($this->selectedFolder, $allowedFileExtensions, $noThumbs);
186 } else {
187 $files = '';
188 }
189
190 $this->initDocumentTemplate();
191 // Starting content:
192 $content = $this->doc->startPage('TBE file selector');
193 $content .= $this->doc->getFlashMessages();
194
195 // Insert the upload form on top, if so configured
196 if ($backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
197 $content .= $uploadForm;
198 }
199 // Putting the parts together, side by side:
200 $content .= '
201
202 <!--
203 Wrapper table for folder tree / filelist:
204 -->
205 <div class="element-browser-section element-browser-filetree">
206 <table border="0" cellpadding="0" cellspacing="0" id="typo3-EBfiles">
207 <tr>
208 <td class="c-wCell" valign="top"><h3>' . $this->getLanguageService()->getLL('folderTree', true) . ':</h3>' . $tree . '</td>
209 <td class="c-wCell" valign="top">' . $files . '</td>
210 </tr>
211 </table>
212 </div>
213 ';
214 // Adding create folder + upload forms if applicable:
215 if (!$backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
216 $content .= $uploadForm;
217 }
218 $content .= $createFolder;
219 // Add some space
220 $content .= '<br /><br />';
221 // Ending page, returning content:
222 $content .= $this->doc->endPage();
223 return $this->doc->insertStylesAndJS($content);
224 }
225
226 /**
227 * For TYPO3 Element Browser: Expand folder of files.
228 *
229 * @param Folder $folder The folder path to expand
230 * @param string $extensionList List of fileextensions to show
231 * @param bool $noThumbs Whether to show thumbnails or not. If set, no thumbnails are shown.
232 * @return string HTML output
233 */
234 public function renderFilesInFolder(Folder $folder, $extensionList = '', $noThumbs = false)
235 {
236 if (!$folder->checkActionPermission('read')) {
237 return '';
238 }
239 $lang = $this->getLanguageService();
240 $titleLen = (int)$this->getBackendUser()->uc['titleLen'];
241
242 if ($this->searchWord !== '') {
243 $files = $this->fileRepository->searchByName($folder, $this->searchWord);
244 } else {
245 $extensionList = $extensionList === '*' ? '' : $extensionList;
246 $files = $this->getFilesInFolder($folder, $extensionList);
247 }
248 $filesCount = count($files);
249
250 $lines = array();
251
252 // Create the header of current folder:
253 $folderIcon = $this->iconFactory->getIconForResource($folder, Icon::SIZE_SMALL);
254 $lines[] = '<tr class="t3-row-header"><th colspan="4">'
255 . $folderIcon . ' ' . htmlspecialchars(GeneralUtility::fixed_lgd_cs($folder->getIdentifier(), $titleLen))
256 . '</th></tr>';
257
258 if ($filesCount === 0) {
259 $lines[] = '
260 <tr>
261 <td colspan="4">No files found.</td>
262 </tr>';
263 }
264
265 foreach ($files as $fileObject) {
266 $fileExtension = $fileObject->getExtension();
267 // Thumbnail/size generation:
268 $imgInfo = array();
269 if (!$noThumbs && GeneralUtility::inList(strtolower($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] . ',' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext']), strtolower($fileExtension))) {
270 $processedFile = $fileObject->process(
271 ProcessedFile::CONTEXT_IMAGEPREVIEW,
272 array('width' => 64, 'height' => 64)
273 );
274 $imageUrl = $processedFile->getPublicUrl(true);
275 $imgInfo = array(
276 $fileObject->getProperty('width'),
277 $fileObject->getProperty('height')
278 );
279 $pDim = $imgInfo[0] . 'x' . $imgInfo[1] . ' pixels';
280 $clickIcon = '<img src="' . $imageUrl . '"'
281 . ' width="' . $processedFile->getProperty('width') . '"'
282 . ' height="' . $processedFile->getProperty('height') . '"'
283 . ' hspace="5" vspace="5" border="1" />';
284 } else {
285 $clickIcon = '';
286 $pDim = '';
287 }
288 // Create file icon:
289 $size = ' (' . GeneralUtility::formatSize($fileObject->getSize()) . 'bytes' . ($pDim ? ', ' . $pDim : '') . ')';
290 $icon = '<span title="' . htmlspecialchars($fileObject->getName() . $size) . '">' . $this->iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL) . '</span>';
291 // Create links for adding the file:
292 $filesIndex = count($this->elements);
293 $this->elements['file_' . $filesIndex] = array(
294 'type' => 'file',
295 'table' => 'sys_file',
296 'uid' => $fileObject->getUid(),
297 'fileName' => $fileObject->getName(),
298 'filePath' => $fileObject->getUid(),
299 'fileExt' => $fileExtension,
300 'fileIcon' => $icon
301 );
302 if ($this->fileIsSelectableInFileList($fileObject, $imgInfo)) {
303 $ATag = '<a href="#" title="' . htmlspecialchars($fileObject->getName()) . '" data-file-index="' . htmlspecialchars($filesIndex) . '" data-close="0">';
304 $ATag_alt = '<a href="#" title="' . htmlspecialchars($fileObject->getName()) . '" data-file-index="' . htmlspecialchars($filesIndex) . '" data-close="1">';
305 $ATag_e = '</a>';
306 $bulkCheckBox = '<input type="checkbox" class="typo3-bulk-item" name="file_' . $filesIndex . '" value="0" /> ';
307 } else {
308 $ATag = '';
309 $ATag_alt = '';
310 $ATag_e = '';
311 $bulkCheckBox = '';
312 }
313 // Create link to showing details about the file in a window:
314 $Ahref = BackendUtility::getModuleUrl('show_item', array(
315 'type' => 'file',
316 'table' => '_FILE',
317 'uid' => $fileObject->getCombinedIdentifier(),
318 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
319 ));
320
321 // Combine the stuff:
322 $filenameAndIcon = $bulkCheckBox . $ATag_alt . $icon . htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileObject->getName(), $titleLen)) . $ATag_e;
323 // Show element:
324 $lines[] = '
325 <tr>
326 <td nowrap="nowrap">' . $filenameAndIcon . '&nbsp;</td>
327 <td>' . $ATag . '<span title="' . $lang->getLL('addToList', true) . '">' . $this->iconFactory->getIcon('actions-edit-add', Icon::SIZE_SMALL)->render() . '</span>' . $ATag_e . '</td>
328 <td nowrap="nowrap"><a href="' . htmlspecialchars($Ahref) . '" title="' . $lang->getLL('info', true) . '">' . $this->iconFactory->getIcon('actions-document-info', Icon::SIZE_SMALL) . $lang->getLL('info', true) . '</a></td>
329 <td nowrap="nowrap">&nbsp;' . $pDim . '</td>
330 </tr>';
331 if ($pDim) {
332 $lines[] = '
333 <tr>
334 <td class="filelistThumbnail" colspan="4">' . $ATag_alt . $clickIcon . $ATag_e . '</td>
335 </tr>';
336 }
337 }
338
339 $out = '<h3>' . $lang->getLL('files', true) . ' ' . $filesCount . ':</h3>';
340 $out .= $this->getFileSearchField();
341 $out .= '<div id="filelist">';
342 $out .= $this->getBulkSelector($filesCount);
343
344 // Wrap all the rows in table tags:
345 $out .= '
346
347 <!--
348 Filelisting
349 -->
350 <table class="table table-striped table-hover" id="typo3-filelist">
351 ' . implode('', $lines) . '
352 </table>';
353 // Return accumulated content for filelisting:
354 $out .= '</div>';
355 return $out;
356 }
357
358 /**
359 * Get a list of Files in a folder filtered by extension
360 *
361 * @param Folder $folder
362 * @param string $extensionList
363 * @return File[]
364 */
365 protected function getFilesInFolder(Folder $folder, $extensionList)
366 {
367 if ($extensionList !== '') {
368 /** @var FileExtensionFilter $filter */
369 $filter = GeneralUtility::makeInstance(FileExtensionFilter::class);
370 $filter->setAllowedFileExtensions($extensionList);
371 $folder->setFileAndFolderNameFilters(array(array($filter, 'filterFileList')));
372 }
373 return $folder->getFiles();
374 }
375
376 /**
377 * Get the HTML data required for a bulk selection of files of the TYPO3 Element Browser.
378 *
379 * @param int $filesCount Number of files currently displayed
380 * @return string HTML data required for a bulk selection of files - if $filesCount is 0, nothing is returned
381 */
382 protected function getBulkSelector($filesCount)
383 {
384 if (!$filesCount) {
385 return '';
386 }
387
388 $lang = $this->getLanguageService();
389 $labelToggleSelection = $lang->sL('LLL:EXT:lang/locallang_browse_links.xlf:toggleSelection', true);
390 $labelImportSelection = $lang->sL('LLL:EXT:lang/locallang_browse_links.xlf:importSelection', true);
391
392 $out = '<div style="padding-top:10px;">' . '<a href="#" id="t3js-importSelection" title="' . $labelImportSelection . '">'
393 . $this->iconFactory->getIcon('actions-document-import-t3d', Icon::SIZE_SMALL)
394 . $labelImportSelection . '</a>&nbsp;&nbsp;&nbsp;'
395 . '<a href="#" id="t3js-toggleSelection" title="' . $labelToggleSelection . '">'
396 . $this->iconFactory->getIcon('actions-document-select', Icon::SIZE_SMALL)
397 . $labelToggleSelection . '</a>' . '</div>';
398
399 // Getting flag for showing/not showing thumbnails:
400 $noThumbsInEB = $this->getBackendUser()->getTSConfigVal('options.noThumbsInEB');
401 if (!$noThumbsInEB && $this->selectedFolder) {
402 // MENU-ITEMS, fetching the setting for thumbnails from File>List module:
403 $_MOD_MENU = array('displayThumbs' => '');
404 $_MCONF['name'] = 'file_list';
405 $_MOD_SETTINGS = BackendUtility::getModuleData($_MOD_MENU, GeneralUtility::_GP('SET'), $_MCONF['name']);
406 $addParams = GeneralUtility::implodeArrayForUrl('', $this->getUrlParameters(['identifier' => $this->selectedFolder->getCombinedIdentifier()]));
407 $thumbNailCheck = '<div class="checkbox" style="padding:5px 0 15px 0"><label for="checkDisplayThumbs">'
408 . BackendUtility::getFuncCheck(
409 '',
410 'SET[displayThumbs]',
411 $_MOD_SETTINGS['displayThumbs'],
412 $this->thisScript,
413 $addParams,
414 'id="checkDisplayThumbs"'
415 )
416 . $lang->sL('LLL:EXT:lang/locallang_mod_file_list.xlf:displayThumbs', true) . '</label></div>';
417 $out .= $thumbNailCheck;
418 } else {
419 $out .= '<div style="padding-top: 15px;"></div>';
420 }
421 return $out;
422 }
423
424 /**
425 * Get the HTML data required for the file search field of the TYPO3 Element Browser.
426 *
427 * @return string HTML data required for the search field in the file list of the Element Browser
428 */
429 protected function getFileSearchField()
430 {
431 $action = $this->getScriptUrl() . GeneralUtility::implodeArrayForUrl('', $this->getUrlParameters([]));
432 $out = '
433 <form method="post" action="' . htmlspecialchars($action) . '" style="padding-bottom: 15px;">
434 <div class="input-group">
435 <input class="form-control" type="text" name="searchWord" value="' . htmlspecialchars($this->searchWord) . '">
436 <span class="input-group-btn">
437 <button class="btn btn-default" type="submit">' . $this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang.xlf:search', true) . '</button>
438 </span>
439 </div>
440 </form>';
441 return $out;
442 }
443
444 /**
445 * Checks if the given file is selectable in the filelist.
446 *
447 * By default all files are selectable. This method may be overwritten in child classes.
448 *
449 * @param FileInterface $file
450 * @param mixed[] $imgInfo Image dimensions from \TYPO3\CMS\Core\Imaging\GraphicalFunctions::getImageDimensions()
451 * @return bool TRUE if file is selectable.
452 */
453 protected function fileIsSelectableInFileList(FileInterface $file, array $imgInfo)
454 {
455 return true;
456 }
457
458 /**
459 * @return string[] Array of body-tag attributes
460 */
461 protected function getBodyTagAttributes()
462 {
463 return [
464 'data-mode' => 'file',
465 'data-elements' => json_encode($this->elements)
466 ];
467 }
468
469 /**
470 * @param array $values Array of values to include into the parameters
471 * @return string[] Array of parameters which have to be added to URLs
472 */
473 public function getUrlParameters(array $values)
474 {
475 return [
476 'mode' => 'file',
477 'expandFolder' => isset($values['identifier']) ? $values['identifier'] : $this->expandFolder,
478 'bparams' => $this->bparams
479 ];
480 }
481
482 /**
483 * @param array $values Values to be checked
484 * @return bool Returns TRUE if the given values match the currently selected item
485 */
486 public function isCurrentlySelectedItem(array $values)
487 {
488 return false;
489 }
490
491 /**
492 * Returns the URL of the current script
493 *
494 * @return string
495 */
496 public function getScriptUrl()
497 {
498 return $this->thisScript;
499 }
500 }