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