5383a5db451cd66f4fa31b3afd5db622ead14993
[Packages/TYPO3.CMS.git] / typo3 / sysext / filelist / Classes / Controller / FileListController.php
1 <?php
2 namespace TYPO3\CMS\Filelist\Controller;
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\Template\DocumentTemplate;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Backend\Utility\IconUtility;
20 use TYPO3\CMS\Core\Messaging\FlashMessage;
21 use TYPO3\CMS\Core\Page\PageRenderer;
22 use TYPO3\CMS\Core\Resource\Exception;
23 use TYPO3\CMS\Core\Resource\ResourceFactory;
24 use TYPO3\CMS\Core\Resource\Utility\ListUtility;
25 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
26 use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
27 use TYPO3\CMS\Core\Utility\GeneralUtility;
28 use TYPO3\CMS\Core\Utility\MathUtility;
29 use TYPO3\CMS\Filelist\FileList;
30
31 /**
32 * Script Class for creating the list of files in the File > Filelist module
33 */
34 class FileListController {
35
36 /**
37 * Module configuration
38 *
39 * @var array
40 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. The Module gets configured by ExtensionManagementUtility::addModule() in ext_tables.php
41 */
42 public $MCONF = array();
43
44 /**
45 * @var array
46 */
47 public $MOD_MENU = array();
48
49 /**
50 * @var array
51 */
52 public $MOD_SETTINGS = array();
53
54 /**
55 * Accumulated HTML output
56 *
57 * @var string
58 */
59 public $content;
60
61 /**
62 * Document template object
63 *
64 * @var DocumentTemplate
65 */
66 public $doc;
67
68 /**
69 * "id" -> the path to list.
70 *
71 * @var string
72 */
73 public $id;
74
75 /**
76 * @var \TYPO3\CMS\Core\Resource\Folder
77 */
78 protected $folderObject;
79
80 /**
81 * @var FlashMessage
82 */
83 protected $errorMessage;
84
85 /**
86 * Pointer to listing
87 *
88 * @var int
89 */
90 public $pointer;
91
92 /**
93 * "Table"
94 *
95 * @var string
96 */
97 public $table;
98
99 /**
100 * Thumbnail mode.
101 *
102 * @var string
103 */
104 public $imagemode;
105
106 /**
107 * @var string
108 */
109 public $cmd;
110
111 /**
112 * Defines behaviour when uploading files with names that already exist; possible value are 'cancel', 'replace', 'changeName'
113 *
114 * @var string
115 */
116 protected $overwriteExistingFiles;
117
118 /**
119 * The filelist object
120 *
121 * @var FileList
122 */
123 public $filelist = NULL;
124
125 /**
126 * The name of the module
127 *
128 * @var string
129 */
130 protected $moduleName = 'file_list';
131
132 /**
133 * Constructor
134 */
135 public function __construct() {
136 $this->getLanguageService()->includeLLFile('EXT:lang/locallang_mod_file_list.xlf');
137 $this->getLanguageService()->includeLLFile('EXT:lang/locallang_misc.xlf');
138 }
139
140 /**
141 * Initialize variables, file object
142 * Incoming GET vars include id, pointer, table, imagemode
143 *
144 * @return void
145 * @throws \RuntimeException
146 * @throws Exception\InsufficientFolderAccessPermissionsException
147 */
148 public function init() {
149 // Setting GPvars:
150 $this->id = ($combinedIdentifier = GeneralUtility::_GP('id'));
151 $this->pointer = GeneralUtility::_GP('pointer');
152 $this->table = GeneralUtility::_GP('table');
153 $this->imagemode = GeneralUtility::_GP('imagemode');
154 $this->cmd = GeneralUtility::_GP('cmd');
155 $this->overwriteExistingFiles = GeneralUtility::_GP('overwriteExistingFiles');
156
157 if ($this->overwriteExistingFiles === '1') {
158 GeneralUtility::deprecationLog('overwriteExitingFiles = 1 is deprecated. Use overwriteExitingFiles = "replace". Support for old behavior will be removed in TYPO3 CMS 8.');
159 $this->overwriteExistingFiles = 'replace';
160 }
161
162 try {
163 if ($combinedIdentifier) {
164 /** @var $fileFactory ResourceFactory */
165 $fileFactory = GeneralUtility::makeInstance(ResourceFactory::class);
166 $storage = $fileFactory->getStorageObjectFromCombinedIdentifier($combinedIdentifier);
167 $identifier = substr($combinedIdentifier, strpos($combinedIdentifier, ':') + 1);
168 if (!$storage->hasFolder($identifier)) {
169 $identifier = $storage->getFolderIdentifierFromFileIdentifier($identifier);
170 }
171
172 $this->folderObject = $fileFactory->getFolderObjectFromCombinedIdentifier($storage->getUid() . ':' . $identifier);
173 // Disallow access to fallback storage 0
174 if ($storage->getUid() === 0) {
175 throw new Exception\InsufficientFolderAccessPermissionsException('You are not allowed to access files outside your storages', 1434539815);
176 }
177 // Disallow the rendering of the processing folder (e.g. could be called manually)
178 if ($this->folderObject && $storage->isProcessingFolder($this->folderObject)) {
179 $this->folderObject = $storage->getRootLevelFolder();
180 }
181 } else {
182 // Take the first object of the first storage
183 $fileStorages = $this->getBackendUser()->getFileStorages();
184 $fileStorage = reset($fileStorages);
185 if ($fileStorage) {
186 $this->folderObject = $fileStorage->getRootLevelFolder();
187 } else {
188 throw new \RuntimeException('Could not find any folder to be displayed.', 1349276894);
189 }
190 }
191
192 if ($this->folderObject && !$this->folderObject->getStorage()->isWithinFileMountBoundaries($this->folderObject)) {
193 throw new \RuntimeException('Folder not accessible.', 1430409089);
194 }
195 } catch (Exception\InsufficientFolderAccessPermissionsException $permissionException) {
196 $this->folderObject = NULL;
197 $this->errorMessage = GeneralUtility::makeInstance(FlashMessage::class,
198 sprintf(
199 $this->getLanguageService()->getLL('missingFolderPermissionsMessage', TRUE),
200 htmlspecialchars($this->id)
201 ),
202 $this->getLanguageService()->getLL('missingFolderPermissionsTitle', TRUE),
203 FlashMessage::NOTICE
204 );
205 } catch (Exception $fileException) {
206 // Set folder object to null and throw a message later on
207 $this->folderObject = NULL;
208 // Take the first object of the first storage
209 $fileStorages = $this->getBackendUser()->getFileStorages();
210 $fileStorage = reset($fileStorages);
211 if ($fileStorage instanceof \TYPO3\CMS\Core\Resource\ResourceStorage) {
212 $this->folderObject = $fileStorage->getRootLevelFolder();
213 if (!$fileStorage->isWithinFileMountBoundaries($this->folderObject)) {
214 $this->folderObject = NULL;
215 }
216 }
217 $this->errorMessage = GeneralUtility::makeInstance(FlashMessage::class,
218 sprintf(
219 $this->getLanguageService()->getLL('folderNotFoundMessage', TRUE),
220 htmlspecialchars($this->id)
221 ),
222 $this->getLanguageService()->getLL('folderNotFoundTitle', TRUE),
223 FlashMessage::NOTICE
224 );
225 } catch (\RuntimeException $e) {
226 $this->folderObject = NULL;
227 $this->errorMessage = GeneralUtility::makeInstance(FlashMessage::class,
228 $e->getMessage() . ' (' . $e->getCode() . ')',
229 $this->getLanguageService()->getLL('folderNotFoundTitle', TRUE),
230 FlashMessage::NOTICE
231 );
232 }
233
234 if ($this->folderObject && !$this->folderObject->getStorage()->checkFolderActionPermission('read', $this->folderObject)) {
235 $this->folderObject = NULL;
236 }
237
238 // Configure the "menu" - which is used internally to save the values of sorting, displayThumbs etc.
239 $this->menuConfig();
240 }
241
242 /**
243 * Setting the menu/session variables
244 *
245 * @return void
246 */
247 public function menuConfig() {
248 // MENU-ITEMS:
249 // If array, then it's a selector box menu
250 // If empty string it's just a variable, that will be saved.
251 // Values NOT in this array will not be saved in the settings-array for the module.
252 $this->MOD_MENU = array(
253 'sort' => '',
254 'reverse' => '',
255 'displayThumbs' => '',
256 'clipBoard' => '',
257 'bigControlPanel' => ''
258 );
259 // CLEANSE SETTINGS
260 $this->MOD_SETTINGS = BackendUtility::getModuleData(
261 $this->MOD_MENU,
262 GeneralUtility::_GP('SET'),
263 $this->moduleName
264 );
265 }
266
267 /**
268 * Main function, creating the listing
269 *
270 * @return void
271 */
272 public function main() {
273 // Initialize the template object
274 $this->doc = GeneralUtility::makeInstance(DocumentTemplate::class);
275 $this->doc->backPath = $GLOBALS['BACK_PATH'];
276 $this->doc->setModuleTemplate('EXT:filelist/Resources/Private/Templates/file_list.html');
277
278 $pageRenderer = $this->getPageRenderer();
279 $pageRenderer->loadJQuery();
280 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Filelist/FileListLocalisation');
281
282 // There there was access to this file path, continue, make the list
283 if ($this->folderObject) {
284
285 // Create filelisting object
286 $this->filelist = GeneralUtility::makeInstance(FileList::class);
287 $this->filelist->backPath = $GLOBALS['BACK_PATH'];
288 // Apply predefined values for hidden checkboxes
289 // Set predefined value for DisplayBigControlPanel:
290 $backendUser = $this->getBackendUser();
291 if ($backendUser->getTSConfigVal('options.file_list.enableDisplayBigControlPanel') === 'activated') {
292 $this->MOD_SETTINGS['bigControlPanel'] = TRUE;
293 } elseif ($backendUser->getTSConfigVal('options.file_list.enableDisplayBigControlPanel') === 'deactivated') {
294 $this->MOD_SETTINGS['bigControlPanel'] = FALSE;
295 }
296 // Set predefined value for DisplayThumbnails:
297 if ($backendUser->getTSConfigVal('options.file_list.enableDisplayThumbnails') === 'activated') {
298 $this->MOD_SETTINGS['displayThumbs'] = TRUE;
299 } elseif ($backendUser->getTSConfigVal('options.file_list.enableDisplayThumbnails') === 'deactivated') {
300 $this->MOD_SETTINGS['displayThumbs'] = FALSE;
301 }
302 // Set predefined value for Clipboard:
303 if ($backendUser->getTSConfigVal('options.file_list.enableClipBoard') === 'activated') {
304 $this->MOD_SETTINGS['clipBoard'] = TRUE;
305 } elseif ($backendUser->getTSConfigVal('options.file_list.enableClipBoard') === 'deactivated') {
306 $this->MOD_SETTINGS['clipBoard'] = FALSE;
307 }
308 // If user never opened the list module, set the value for displayThumbs
309 if (!isset($this->MOD_SETTINGS['displayThumbs'])) {
310 $this->MOD_SETTINGS['displayThumbs'] = $backendUser->uc['thumbnailsByDefault'];
311 }
312 $this->filelist->thumbs = $this->MOD_SETTINGS['displayThumbs'];
313 // Create clipboard object and initialize that
314 $this->filelist->clipObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Clipboard\Clipboard::class);
315 $this->filelist->clipObj->fileMode = 1;
316 $this->filelist->clipObj->initializeClipboard();
317 $CB = GeneralUtility::_GET('CB');
318 if ($this->cmd == 'setCB') {
319 $CB['el'] = $this->filelist->clipObj->cleanUpCBC(array_merge(GeneralUtility::_POST('CBH'), (array)GeneralUtility::_POST('CBC')), '_FILE');
320 }
321 if (!$this->MOD_SETTINGS['clipBoard']) {
322 $CB['setP'] = 'normal';
323 }
324 $this->filelist->clipObj->setCmd($CB);
325 $this->filelist->clipObj->cleanCurrent();
326 // Saves
327 $this->filelist->clipObj->endClipboard();
328 // If the "cmd" was to delete files from the list (clipboard thing), do that:
329 if ($this->cmd == 'delete') {
330 $items = $this->filelist->clipObj->cleanUpCBC(GeneralUtility::_POST('CBC'), '_FILE', 1);
331 if (!empty($items)) {
332 // Make command array:
333 $FILE = array();
334 foreach ($items as $v) {
335 $FILE['delete'][] = array('data' => $v);
336 }
337 switch ($this->overwriteExistingFiles) {
338 case 'replace':
339 case 'changeName':
340 $conflictMode = $this->overwriteExistingFiles;
341 break;
342 default:
343 $conflictMode = 'cancel';
344 break;
345 }
346
347 // Init file processing object for deleting and pass the cmd array.
348 /** @var ExtendedFileUtility $fileProcessor */
349 $fileProcessor = GeneralUtility::makeInstance(ExtendedFileUtility::class);
350 $fileProcessor->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
351 $fileProcessor->setActionPermissions();
352 $fileProcessor->setExistingFilesConflictMode($conflictMode);
353 $fileProcessor->start($FILE);
354 $fileProcessor->processData();
355 $fileProcessor->pushErrorMessagesToFlashMessageQueue();
356 }
357 }
358 if (!isset($this->MOD_SETTINGS['sort'])) {
359 // Set default sorting
360 $this->MOD_SETTINGS['sort'] = 'file';
361 $this->MOD_SETTINGS['reverse'] = 0;
362 }
363 // Start up filelisting object, include settings.
364 $this->pointer = MathUtility::forceIntegerInRange($this->pointer, 0, 100000);
365 $this->filelist->start($this->folderObject, $this->pointer, $this->MOD_SETTINGS['sort'], $this->MOD_SETTINGS['reverse'], $this->MOD_SETTINGS['clipBoard'], $this->MOD_SETTINGS['bigControlPanel']);
366 // Generate the list
367 $this->filelist->generateList();
368 // Set top JavaScript:
369 $this->doc->JScode = $this->doc->wrapScriptTags('if (top.fsMod) top.fsMod.recentIds["file"] = "' . rawurlencode($this->id) . '";' . $this->filelist->CBfunctions());
370 // This will return content necessary for the context sensitive clickmenus to work: bodytag events, JavaScript functions and DIV-layers.
371 $this->doc->getContextMenuCode();
372 // Setting up the buttons and markers for docheader
373 list($buttons, $otherMarkers) = $this->filelist->getButtonsAndOtherMarkers($this->folderObject);
374 // add the folder info to the marker array
375 $otherMarkers['FOLDER_INFO'] = $this->filelist->getFolderInfo();
376 $docHeaderButtons = array_merge($this->getButtons(), $buttons);
377
378 // Include DragUploader only if we have write access
379 if ($this->folderObject->getStorage()->checkUserActionPermission('add', 'File')
380 && $this->folderObject->checkActionPermission('write')
381 ) {
382 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DragUploader');
383 $pageRenderer->addInlineLanguagelabelFile(
384 ExtensionManagementUtility::extPath('lang') . 'locallang_core.xlf',
385 'file_upload'
386 );
387 }
388
389 // Build the <body> for the module
390 $moduleHeadline = $this->getModuleHeadline();
391 // Create output
392 $pageContent = $moduleHeadline !== '' ? '<h1>' . $moduleHeadline . '</h1>' : '';
393
394 $pageContent .= '<form action="' . htmlspecialchars($this->filelist->listURL()) . '" method="post" name="dblistForm">';
395 $pageContent .= $this->filelist->HTMLcode;
396 $pageContent .= '<input type="hidden" name="cmd" /></form>';
397
398 // Making listing options:
399 if ($this->filelist->HTMLcode) {
400 $pageContent .= '
401
402 <!--
403 Listing options for extended view, clipboard and thumbnails
404 -->
405 <div class="typo3-listOptions">
406 ';
407 // Add "display bigControlPanel" checkbox:
408 if ($backendUser->getTSConfigVal('options.file_list.enableDisplayBigControlPanel') === 'selectable') {
409 $pageContent .= '<div class="checkbox">' .
410 '<label for="bigControlPanel">' .
411 BackendUtility::getFuncCheck($this->id, 'SET[bigControlPanel]', $this->MOD_SETTINGS['bigControlPanel'], '', '', 'id="bigControlPanel"') .
412 $this->getLanguageService()->getLL('bigControlPanel', TRUE) .
413 '</label>' .
414 '</div>';
415 }
416 // Add "display thumbnails" checkbox:
417 if ($backendUser->getTSConfigVal('options.file_list.enableDisplayThumbnails') === 'selectable') {
418 $pageContent .= '<div class="checkbox">' .
419 '<label for="checkDisplayThumbs">' .
420 BackendUtility::getFuncCheck($this->id, 'SET[displayThumbs]', $this->MOD_SETTINGS['displayThumbs'], '', '', 'id="checkDisplayThumbs"') .
421 $this->getLanguageService()->getLL('displayThumbs', TRUE) .
422 '</label>' .
423 '</div>';
424 }
425 // Add "clipboard" checkbox:
426 if ($backendUser->getTSConfigVal('options.file_list.enableClipBoard') === 'selectable') {
427 $pageContent .= '<div class="checkbox">' .
428 '<label for="checkClipBoard">' .
429 BackendUtility::getFuncCheck($this->id, 'SET[clipBoard]', $this->MOD_SETTINGS['clipBoard'], '', '', 'id="checkClipBoard"') .
430 $this->getLanguageService()->getLL('clipBoard', TRUE) .
431 '</label>' .
432 '</div>';
433 }
434 $pageContent .= '
435 </div>
436 ';
437 // Set clipboard:
438 if ($this->MOD_SETTINGS['clipBoard']) {
439 $pageContent .= $this->filelist->clipObj->printClipboard();
440 $pageContent .= BackendUtility::cshItem('xMOD_csh_corebe', 'filelist_clipboard');
441 }
442 }
443 $markerArray = array(
444 'CSH' => $docHeaderButtons['csh'],
445 'FUNC_MENU' => BackendUtility::getFuncMenu($this->id, 'SET[function]', $this->MOD_SETTINGS['function'], $this->MOD_MENU['function']),
446 'CONTENT' => ($this->errorMessage ? $this->errorMessage->render() : '') . $pageContent,
447 'FOLDER_IDENTIFIER' => $this->folderObject->getCombinedIdentifier(),
448 'FILEDENYPATERN' => $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],
449 'MAXFILESIZE' => GeneralUtility::getMaxUploadFileSize() * 1024,
450 );
451 $this->content = $this->doc->moduleBody(array(), $docHeaderButtons, array_merge($markerArray, $otherMarkers));
452 // Renders the module page
453 $this->content = $this->doc->render($this->getLanguageService()->getLL('files'), $this->content);
454 } else {
455 $content = '';
456 if ($this->errorMessage) {
457 $this->errorMessage->setSeverity(FlashMessage::ERROR);
458 $content = $this->doc->moduleBody(array(), array_merge(array('REFRESH' => '', 'PASTE' => '', 'LEVEL_UP' => ''), $this->getButtons()), array('CSH' => '', 'TITLE' => '', 'FOLDER_INFO' => '', 'PAGE_ICON' => '', 'FUNC_MENU' => '', 'CONTENT' => $this->errorMessage->render()));
459 }
460 // Create output - no access (no warning though)
461 $this->content = $this->doc->render($this->getLanguageService()->getLL('files'), $content);
462 }
463 }
464
465 /**
466 * Get main headline based on active folder or storage for backend module
467 *
468 * Folder names are resolved to their special names like done in the tree view.
469 *
470 * @return string
471 */
472 protected function getModuleHeadline() {
473 $name = $this->folderObject->getName();
474 if ($name === '') {
475 // Show storage name on storage root
476 if ($this->folderObject->getIdentifier() === '/') {
477 $name = $this->folderObject->getStorage()->getName();
478 }
479 } else {
480 $name = key(ListUtility::resolveSpecialFolderNames(
481 array($name => $this->folderObject)
482 ));
483 }
484 return $name;
485 }
486
487 /**
488 * Outputting the accumulated content to screen
489 *
490 * @return void
491 */
492 public function printContent() {
493 echo $this->content;
494 }
495
496 /**
497 * Create the panel of buttons for submitting the form or otherwise perform operations.
498 *
499 * @return array All available buttons as an assoc. array
500 */
501 public function getButtons() {
502 $buttons = array(
503 'csh' => '',
504 'shortcut' => '',
505 'upload' => '',
506 'new' => ''
507 );
508 // Add shortcut
509 if ($this->getBackendUser()->mayMakeShortcut()) {
510 $buttons['shortcut'] = $this->doc->makeShortcutIcon('pointer,id,target,table', implode(',', array_keys($this->MOD_MENU)), $this->moduleName);
511 }
512 // FileList Module CSH:
513 $buttons['csh'] = BackendUtility::cshItem('xMOD_csh_corebe', 'filelist_module');
514 // Upload button (only if upload to this directory is allowed)
515 if ($this->folderObject && $this->folderObject->getStorage()->checkUserActionPermission('add', 'File') && $this->folderObject->checkActionPermission('write')) {
516 $buttons['upload'] = '<a href="' . htmlspecialchars($GLOBALS['BACK_PATH']
517 . BackendUtility::getModuleUrl(
518 'file_upload',
519 array(
520 'target' => $this->folderObject->getCombinedIdentifier(),
521 'returnUrl' => $this->filelist->listURL(),
522 )
523 )) . '" id="button-upload" title="' . $this->getLanguageService()->makeEntities($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.upload', TRUE)) . '">' . IconUtility::getSpriteIcon('actions-edit-upload') . '</a>';
524 }
525 // New folder button
526 if ($this->folderObject && $this->folderObject->checkActionPermission('write')
527 && ($this->folderObject->getStorage()->checkUserActionPermission('add', 'File') || $this->folderObject->checkActionPermission('add'))
528 ) {
529 $buttons['new'] = '<a href="' . htmlspecialchars($GLOBALS['BACK_PATH']
530 . BackendUtility::getModuleUrl(
531 'file_newfolder',
532 array(
533 'target' => $this->folderObject->getCombinedIdentifier(),
534 'returnUrl' => $this->filelist->listURL(),
535 )
536 )) . '" title="' . $this->getLanguageService()->makeEntities($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.new', TRUE)) . '">' . IconUtility::getSpriteIcon('actions-document-new') . '</a>';
537 }
538 return $buttons;
539 }
540
541 /**
542 * Returns an instance of LanguageService
543 *
544 * @return \TYPO3\CMS\Lang\LanguageService
545 */
546 protected function getLanguageService() {
547 return $GLOBALS['LANG'];
548 }
549
550 /**
551 * Returns the current BE user.
552 *
553 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
554 */
555 protected function getBackendUser() {
556 return $GLOBALS['BE_USER'];
557 }
558
559 /**
560 * @return PageRenderer
561 */
562 protected function getPageRenderer() {
563 return GeneralUtility::makeInstance(PageRenderer::class);
564 }
565
566 }