8d8bd35d2b0240b5ce8f6d71db1022a545901302
[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 = [];
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 [$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 DataHandler afterwards
116 $allowedFileExtensions = GeneralUtility::trimExplode(',', explode('|', $this->bparams)[3], true);
117 if (!empty($allowedFileExtensions) && $allowedFileExtensions[0] !== 'sys_file' && $allowedFileExtensions[0] !== '*') {
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([$filterObject, 'filterFileList']);
126 }
127 }
128 if ($this->expandFolder) {
129 $fileOrFolderObject = null;
130
131 // Try to fetch the folder the user had open the last time he browsed files
132 // Fallback to the default folder in case the last used folder is not existing
133 try {
134 $fileOrFolderObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($this->expandFolder);
135 } catch (Exception $accessException) {
136 // We're just catching the exception here, nothing to be done if folder does not exist or is not accessible.
137 } catch (\InvalidArgumentException $driverMissingExecption) {
138 // We're just catching the exception here, nothing to be done if the driver does not exist anymore.
139 }
140
141 if ($fileOrFolderObject instanceof Folder) {
142 // It's a folder
143 $this->selectedFolder = $fileOrFolderObject;
144 } elseif ($fileOrFolderObject instanceof FileInterface) {
145 // It's a file
146 $this->selectedFolder = $fileOrFolderObject->getParentFolder();
147 }
148 }
149 // Or get the user's default upload folder
150 if (!$this->selectedFolder) {
151 try {
152 $this->selectedFolder = $backendUser->getDefaultUploadFolder();
153 } catch (\Exception $e) {
154 // The configured default user folder does not exist
155 }
156 }
157 // Build the file upload and folder creation form
158 $uploadForm = '';
159 $createFolder = '';
160 if ($this->selectedFolder) {
161 $folderUtilityRenderer = GeneralUtility::makeInstance(FolderUtilityRenderer::class, $this);
162 $uploadForm = $folderUtilityRenderer->uploadForm($this->selectedFolder, $allowedFileExtensions);
163 $createFolder = $folderUtilityRenderer->createFolder($this->selectedFolder);
164 }
165
166 // Getting flag for showing/not showing thumbnails:
167 $noThumbs = $backendUser->getTSConfigVal('options.noThumbsInEB');
168 $_MOD_SETTINGS = [];
169 if (!$noThumbs) {
170 // MENU-ITEMS, fetching the setting for thumbnails from File>List module:
171 $_MOD_MENU = ['displayThumbs' => ''];
172 $_MCONF['name'] = 'file_list';
173 $_MOD_SETTINGS = BackendUtility::getModuleData($_MOD_MENU, GeneralUtility::_GP('SET'), $_MCONF['name']);
174 }
175 $noThumbs = $noThumbs ?: !$_MOD_SETTINGS['displayThumbs'];
176 // Create folder tree:
177 /** @var ElementBrowserFolderTreeView $folderTree */
178 $folderTree = GeneralUtility::makeInstance(ElementBrowserFolderTreeView::class);
179 $folderTree->setLinkParameterProvider($this);
180 $tree = $folderTree->getBrowsableTree();
181 if ($this->selectedFolder) {
182 $files = $this->renderFilesInFolder($this->selectedFolder, $allowedFileExtensions, $noThumbs);
183 } else {
184 $files = '';
185 }
186
187 $this->initDocumentTemplate();
188 // Starting content:
189 $content = $this->doc->startPage('TBE file selector');
190 $content .= $this->doc->getFlashMessages();
191
192 // Insert the upload form on top, if so configured
193 if ($backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
194 $content .= $uploadForm;
195 }
196 // Putting the parts together, side by side:
197 $content .= '
198
199 <!--
200 Wrapper table for folder tree / filelist:
201 -->
202 <div class="element-browser-section element-browser-filetree">
203 <table border="0" cellpadding="0" cellspacing="0" id="typo3-EBfiles">
204 <tr>
205 <td class="c-wCell" valign="top"><h3>' . htmlspecialchars($this->getLanguageService()->getLL('folderTree')) . ':</h3>' . $tree . '</td>
206 <td class="c-wCell" valign="top">' . $files . '</td>
207 </tr>
208 </table>
209 </div>
210 ';
211 // Adding create folder + upload forms if applicable:
212 if (!$backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
213 $content .= $uploadForm;
214 }
215 $content .= $createFolder;
216 // Add some space
217 $content .= '<br /><br />';
218 // Ending page, returning content:
219 $content .= $this->doc->endPage();
220 return $this->doc->insertStylesAndJS($content);
221 }
222
223 /**
224 * For TYPO3 Element Browser: Expand folder of files.
225 *
226 * @param Folder $folder The folder path to expand
227 * @param array $extensionList List of fileextensions to show
228 * @param bool $noThumbs Whether to show thumbnails or not. If set, no thumbnails are shown.
229 * @return string HTML output
230 */
231 public function renderFilesInFolder(Folder $folder, array $extensionList = [], $noThumbs = false)
232 {
233 if (!$folder->checkActionPermission('read')) {
234 return '';
235 }
236 $lang = $this->getLanguageService();
237 $titleLen = (int)$this->getBackendUser()->uc['titleLen'];
238
239 if ($this->searchWord !== '') {
240 $files = $this->fileRepository->searchByName($folder, $this->searchWord);
241 } else {
242 $extensionList = !empty($extensionList) && $extensionList[0] === '*' ? [] : $extensionList;
243 $files = $this->getFilesInFolder($folder, $extensionList);
244 }
245 $filesCount = count($files);
246
247 $lines = [];
248
249 // Create the header of current folder:
250 $folderIcon = $this->iconFactory->getIconForResource($folder, Icon::SIZE_SMALL);
251
252 $lines[] = '
253 <tr>
254 <th class="col-title" nowrap="nowrap">' . $folderIcon . ' ' . htmlspecialchars(GeneralUtility::fixed_lgd_cs($folder->getIdentifier(), $titleLen)) . '</th>
255 <th class="col-control" nowrap="nowrap"></th>
256 <th class="col-clipboard" nowrap="nowrap">
257 <a href="#" class="btn btn-default" id="t3js-importSelection" title="' . htmlspecialchars($lang->getLL('importSelection')) . '">' . $this->iconFactory->getIcon('actions-document-import-t3d', Icon::SIZE_SMALL) . '</a>
258 <a href="#" class="btn btn-default" id="t3js-toggleSelection" title="' . htmlspecialchars($lang->getLL('toggleSelection')) . '">' . $this->iconFactory->getIcon('actions-document-select', Icon::SIZE_SMALL) . '</a>
259 </th>
260 <th nowrap="nowrap">&nbsp;</th>
261 </tr>';
262
263 if ($filesCount === 0) {
264 $lines[] = '
265 <tr>
266 <td colspan="4">No files found.</td>
267 </tr>';
268 }
269
270 foreach ($files as $fileObject) {
271 $fileExtension = $fileObject->getExtension();
272 // Thumbnail/size generation:
273 $imgInfo = [];
274 if (!$noThumbs && GeneralUtility::inList(strtolower($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] . ',' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext']), strtolower($fileExtension))) {
275 $processedFile = $fileObject->process(
276 ProcessedFile::CONTEXT_IMAGEPREVIEW,
277 ['width' => 64, 'height' => 64]
278 );
279 $imageUrl = $processedFile->getPublicUrl(true);
280 $imgInfo = [
281 $fileObject->getProperty('width'),
282 $fileObject->getProperty('height')
283 ];
284 $pDim = $imgInfo[0] . 'x' . $imgInfo[1] . ' pixels';
285 $clickIcon = '<img src="' . $imageUrl . '"'
286 . ' width="' . $processedFile->getProperty('width') . '"'
287 . ' height="' . $processedFile->getProperty('height') . '"'
288 . ' hspace="5" vspace="5" border="1" />';
289 } else {
290 $clickIcon = '';
291 $pDim = '';
292 }
293 // Create file icon:
294 $size = ' (' . GeneralUtility::formatSize($fileObject->getSize(), $this->getLanguageService()->sL('LLL:EXT:lang/locallang_common.xlf:byteSizeUnits')) . ($pDim ? ', ' . $pDim : '') . ')';
295 $icon = '<span title="' . htmlspecialchars($fileObject->getName() . $size) . '">' . $this->iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL) . '</span>';
296 // Create links for adding the file:
297 $filesIndex = count($this->elements);
298 $this->elements['file_' . $filesIndex] = [
299 'type' => 'file',
300 'table' => 'sys_file',
301 'uid' => $fileObject->getUid(),
302 'fileName' => $fileObject->getName(),
303 'filePath' => $fileObject->getUid(),
304 'fileExt' => $fileExtension,
305 'fileIcon' => $icon
306 ];
307 if ($this->fileIsSelectableInFileList($fileObject, $imgInfo)) {
308 $ATag = '<a href="#" class="btn btn-default" title="' . htmlspecialchars($fileObject->getName()) . '" data-file-index="' . htmlspecialchars($filesIndex) . '" data-close="0">';
309 $ATag_alt = '<a href="#" title="' . htmlspecialchars($fileObject->getName()) . '" data-file-index="' . htmlspecialchars($filesIndex) . '" data-close="1">';
310 $ATag_e = '</a>';
311 $bulkCheckBox = '<label class="btn btn-default btn-checkbox"><input type="checkbox" class="typo3-bulk-item" name="file_' . $filesIndex . '" value="0" /><span class="t3-icon fa"></span></label>';
312 } else {
313 $ATag = '';
314 $ATag_alt = '';
315 $ATag_e = '';
316 $bulkCheckBox = '';
317 }
318 // Create link to showing details about the file in a window:
319 $Ahref = BackendUtility::getModuleUrl('show_item', [
320 'type' => 'file',
321 'table' => '_FILE',
322 'uid' => $fileObject->getCombinedIdentifier(),
323 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
324 ]);
325
326 // Combine the stuff:
327 $filenameAndIcon = $ATag_alt . $icon . htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileObject->getName(), $titleLen)) . $ATag_e;
328 // Show element:
329 $lines[] = '
330 <tr class="file_list_normal">
331 <td class="col-title" nowrap="nowrap">' . $filenameAndIcon . '&nbsp;</td>
332 <td class="col-control">
333 <div class="btn-group">' . $ATag . '<span title="' . htmlspecialchars($lang->getLL('addToList')) . '">' . $this->iconFactory->getIcon('actions-edit-add', Icon::SIZE_SMALL)->render() . '</span>' . $ATag_e . '
334 <a href="' . htmlspecialchars($Ahref) . '" class="btn btn-default" title="' . htmlspecialchars($lang->getLL('info')) . '">' . $this->iconFactory->getIcon('actions-document-info', Icon::SIZE_SMALL) . '</a>
335 </td>
336 <td class="col-clipboard" valign="top">' . $bulkCheckBox . '</td>
337 <td nowrap="nowrap">&nbsp;' . $pDim . '</td>
338 </tr>';
339 if ($pDim) {
340 $lines[] = '
341 <tr>
342 <td class="filelistThumbnail" colspan="4">' . $ATag_alt . $clickIcon . $ATag_e . '</td>
343 </tr>';
344 }
345 }
346
347 $out = '<h3>' . htmlspecialchars($lang->getLL('files')) . ' ' . $filesCount . ':</h3>';
348 $out .= GeneralUtility::makeInstance(FolderUtilityRenderer::class, $this)->getFileSearchField($this->searchWord);
349 $out .= '<div id="filelist">';
350 $out .= $this->getBulkSelector($filesCount);
351
352 // Wrap all the rows in table tags:
353 $out .= '
354
355 <!--
356 Filelisting
357 -->
358 <table class="table table-striped table-hover" id="typo3-filelist">
359 ' . implode('', $lines) . '
360 </table>';
361 // Return accumulated content for filelisting:
362 $out .= '</div>';
363 return $out;
364 }
365
366 /**
367 * Get a list of Files in a folder filtered by extension
368 *
369 * @param Folder $folder
370 * @param array $extensionList
371 * @return File[]
372 */
373 protected function getFilesInFolder(Folder $folder, array $extensionList)
374 {
375 if (!empty($extensionList)) {
376 /** @var FileExtensionFilter $filter */
377 $filter = GeneralUtility::makeInstance(FileExtensionFilter::class);
378 $filter->setAllowedFileExtensions($extensionList);
379 $folder->setFileAndFolderNameFilters([[$filter, 'filterFileList']]);
380 }
381 return $folder->getFiles();
382 }
383
384 /**
385 * Get the HTML data required for a bulk selection of files of the TYPO3 Element Browser.
386 *
387 * @param int $filesCount Number of files currently displayed
388 * @return string HTML data required for a bulk selection of files - if $filesCount is 0, nothing is returned
389 */
390 protected function getBulkSelector($filesCount)
391 {
392 if (!$filesCount) {
393 return '';
394 }
395
396 $lang = $this->getLanguageService();
397 $out = '';
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 = ['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 . htmlspecialchars($lang->sL('LLL:EXT:lang/locallang_mod_file_list.xlf:displayThumbs')) . '</label></div>';
417 $out .= $thumbNailCheck;
418 } else {
419 $out .= '<div style="padding-top: 15px;"></div>';
420 }
421 return $out;
422 }
423
424 /**
425 * Checks if the given file is selectable in the filelist.
426 *
427 * By default all files are selectable. This method may be overwritten in child classes.
428 *
429 * @param FileInterface $file
430 * @param mixed[] $imgInfo Image dimensions from \TYPO3\CMS\Core\Imaging\GraphicalFunctions::getImageDimensions()
431 * @return bool TRUE if file is selectable.
432 */
433 protected function fileIsSelectableInFileList(FileInterface $file, array $imgInfo)
434 {
435 return true;
436 }
437
438 /**
439 * @return string[] Array of body-tag attributes
440 */
441 protected function getBodyTagAttributes()
442 {
443 return [
444 'data-mode' => 'file',
445 'data-elements' => json_encode($this->elements)
446 ];
447 }
448
449 /**
450 * @param array $values Array of values to include into the parameters
451 * @return string[] Array of parameters which have to be added to URLs
452 */
453 public function getUrlParameters(array $values)
454 {
455 return [
456 'mode' => 'file',
457 'expandFolder' => isset($values['identifier']) ? $values['identifier'] : $this->expandFolder,
458 'bparams' => $this->bparams
459 ];
460 }
461
462 /**
463 * @param array $values Values to be checked
464 * @return bool Returns TRUE if the given values match the currently selected item
465 */
466 public function isCurrentlySelectedItem(array $values)
467 {
468 return false;
469 }
470
471 /**
472 * Returns the URL of the current script
473 *
474 * @return string
475 */
476 public function getScriptUrl()
477 {
478 return $this->thisScript;
479 }
480 }