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