f1aa7ec6be15d3ffcb0064df09c18fbea8be9db6
[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->setModuleTemplate('EXT:filelist/Resources/Private/Templates/file_list.html');
276
277 $pageRenderer = $this->getPageRenderer();
278 $pageRenderer->loadJQuery();
279 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Filelist/FileListLocalisation');
280
281 // There there was access to this file path, continue, make the list
282 if ($this->folderObject) {
283
284 // Create filelisting object
285 $this->filelist = GeneralUtility::makeInstance(FileList::class);
286 // Apply predefined values for hidden checkboxes
287 // Set predefined value for DisplayBigControlPanel:
288 $backendUser = $this->getBackendUser();
289 if ($backendUser->getTSConfigVal('options.file_list.enableDisplayBigControlPanel') === 'activated') {
290 $this->MOD_SETTINGS['bigControlPanel'] = TRUE;
291 } elseif ($backendUser->getTSConfigVal('options.file_list.enableDisplayBigControlPanel') === 'deactivated') {
292 $this->MOD_SETTINGS['bigControlPanel'] = FALSE;
293 }
294 // Set predefined value for DisplayThumbnails:
295 if ($backendUser->getTSConfigVal('options.file_list.enableDisplayThumbnails') === 'activated') {
296 $this->MOD_SETTINGS['displayThumbs'] = TRUE;
297 } elseif ($backendUser->getTSConfigVal('options.file_list.enableDisplayThumbnails') === 'deactivated') {
298 $this->MOD_SETTINGS['displayThumbs'] = FALSE;
299 }
300 // Set predefined value for Clipboard:
301 if ($backendUser->getTSConfigVal('options.file_list.enableClipBoard') === 'activated') {
302 $this->MOD_SETTINGS['clipBoard'] = TRUE;
303 } elseif ($backendUser->getTSConfigVal('options.file_list.enableClipBoard') === 'deactivated') {
304 $this->MOD_SETTINGS['clipBoard'] = FALSE;
305 }
306 // If user never opened the list module, set the value for displayThumbs
307 if (!isset($this->MOD_SETTINGS['displayThumbs'])) {
308 $this->MOD_SETTINGS['displayThumbs'] = $backendUser->uc['thumbnailsByDefault'];
309 }
310 $this->filelist->thumbs = $this->MOD_SETTINGS['displayThumbs'];
311 // Create clipboard object and initialize that
312 $this->filelist->clipObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Clipboard\Clipboard::class);
313 $this->filelist->clipObj->fileMode = 1;
314 $this->filelist->clipObj->initializeClipboard();
315 $CB = GeneralUtility::_GET('CB');
316 if ($this->cmd == 'setCB') {
317 $CB['el'] = $this->filelist->clipObj->cleanUpCBC(array_merge(GeneralUtility::_POST('CBH'), (array)GeneralUtility::_POST('CBC')), '_FILE');
318 }
319 if (!$this->MOD_SETTINGS['clipBoard']) {
320 $CB['setP'] = 'normal';
321 }
322 $this->filelist->clipObj->setCmd($CB);
323 $this->filelist->clipObj->cleanCurrent();
324 // Saves
325 $this->filelist->clipObj->endClipboard();
326 // If the "cmd" was to delete files from the list (clipboard thing), do that:
327 if ($this->cmd == 'delete') {
328 $items = $this->filelist->clipObj->cleanUpCBC(GeneralUtility::_POST('CBC'), '_FILE', 1);
329 if (!empty($items)) {
330 // Make command array:
331 $FILE = array();
332 foreach ($items as $v) {
333 $FILE['delete'][] = array('data' => $v);
334 }
335 switch ($this->overwriteExistingFiles) {
336 case 'replace':
337 case 'changeName':
338 $conflictMode = $this->overwriteExistingFiles;
339 break;
340 default:
341 $conflictMode = 'cancel';
342 break;
343 }
344
345 // Init file processing object for deleting and pass the cmd array.
346 /** @var ExtendedFileUtility $fileProcessor */
347 $fileProcessor = GeneralUtility::makeInstance(ExtendedFileUtility::class);
348 $fileProcessor->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
349 $fileProcessor->setActionPermissions();
350 $fileProcessor->setExistingFilesConflictMode($conflictMode);
351 $fileProcessor->start($FILE);
352 $fileProcessor->processData();
353 $fileProcessor->pushErrorMessagesToFlashMessageQueue();
354 }
355 }
356 if (!isset($this->MOD_SETTINGS['sort'])) {
357 // Set default sorting
358 $this->MOD_SETTINGS['sort'] = 'file';
359 $this->MOD_SETTINGS['reverse'] = 0;
360 }
361 // Start up filelisting object, include settings.
362 $this->pointer = MathUtility::forceIntegerInRange($this->pointer, 0, 100000);
363 $this->filelist->start($this->folderObject, $this->pointer, $this->MOD_SETTINGS['sort'], $this->MOD_SETTINGS['reverse'], $this->MOD_SETTINGS['clipBoard'], $this->MOD_SETTINGS['bigControlPanel']);
364 // Generate the list
365 $this->filelist->generateList();
366 // Set top JavaScript:
367 $this->doc->JScode = $this->doc->wrapScriptTags('if (top.fsMod) top.fsMod.recentIds["file"] = "' . rawurlencode($this->id) . '";' . $this->filelist->CBfunctions());
368 // This will return content necessary for the context sensitive clickmenus to work: bodytag events, JavaScript functions and DIV-layers.
369 $this->doc->getContextMenuCode();
370 // Setting up the buttons and markers for docheader
371 list($buttons, $otherMarkers) = $this->filelist->getButtonsAndOtherMarkers($this->folderObject);
372 // add the folder info to the marker array
373 $otherMarkers['FOLDER_INFO'] = $this->filelist->getFolderInfo();
374 $docHeaderButtons = array_merge($this->getButtons(), $buttons);
375
376 // Include DragUploader only if we have write access
377 if ($this->folderObject->getStorage()->checkUserActionPermission('add', 'File')
378 && $this->folderObject->checkActionPermission('write')
379 ) {
380 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DragUploader');
381 $pageRenderer->addInlineLanguagelabelFile(
382 ExtensionManagementUtility::extPath('lang') . 'locallang_core.xlf',
383 'file_upload'
384 );
385 }
386
387 // Build the <body> for the module
388 $moduleHeadline = $this->getModuleHeadline();
389 // Create output
390 $pageContent = $moduleHeadline !== '' ? '<h1>' . $moduleHeadline . '</h1>' : '';
391
392 $pageContent .= '<form action="' . htmlspecialchars($this->filelist->listURL()) . '" method="post" name="dblistForm">';
393 $pageContent .= $this->filelist->HTMLcode;
394 $pageContent .= '<input type="hidden" name="cmd" /></form>';
395
396 // Making listing options:
397 if ($this->filelist->HTMLcode) {
398 $pageContent .= '
399
400 <!--
401 Listing options for extended view, clipboard and thumbnails
402 -->
403 <div class="typo3-listOptions">
404 ';
405 // Add "display bigControlPanel" checkbox:
406 if ($backendUser->getTSConfigVal('options.file_list.enableDisplayBigControlPanel') === 'selectable') {
407 $pageContent .= '<div class="checkbox">' .
408 '<label for="bigControlPanel">' .
409 BackendUtility::getFuncCheck($this->id, 'SET[bigControlPanel]', $this->MOD_SETTINGS['bigControlPanel'], '', '', 'id="bigControlPanel"') .
410 $this->getLanguageService()->getLL('bigControlPanel', TRUE) .
411 '</label>' .
412 '</div>';
413 }
414 // Add "display thumbnails" checkbox:
415 if ($backendUser->getTSConfigVal('options.file_list.enableDisplayThumbnails') === 'selectable') {
416 $pageContent .= '<div class="checkbox">' .
417 '<label for="checkDisplayThumbs">' .
418 BackendUtility::getFuncCheck($this->id, 'SET[displayThumbs]', $this->MOD_SETTINGS['displayThumbs'], '', '', 'id="checkDisplayThumbs"') .
419 $this->getLanguageService()->getLL('displayThumbs', TRUE) .
420 '</label>' .
421 '</div>';
422 }
423 // Add "clipboard" checkbox:
424 if ($backendUser->getTSConfigVal('options.file_list.enableClipBoard') === 'selectable') {
425 $pageContent .= '<div class="checkbox">' .
426 '<label for="checkClipBoard">' .
427 BackendUtility::getFuncCheck($this->id, 'SET[clipBoard]', $this->MOD_SETTINGS['clipBoard'], '', '', 'id="checkClipBoard"') .
428 $this->getLanguageService()->getLL('clipBoard', TRUE) .
429 '</label>' .
430 '</div>';
431 }
432 $pageContent .= '
433 </div>
434 ';
435 // Set clipboard:
436 if ($this->MOD_SETTINGS['clipBoard']) {
437 $pageContent .= $this->filelist->clipObj->printClipboard();
438 $pageContent .= BackendUtility::cshItem('xMOD_csh_corebe', 'filelist_clipboard');
439 }
440 }
441 $markerArray = array(
442 'CSH' => $docHeaderButtons['csh'],
443 'FUNC_MENU' => BackendUtility::getFuncMenu($this->id, 'SET[function]', $this->MOD_SETTINGS['function'], $this->MOD_MENU['function']),
444 'CONTENT' => ($this->errorMessage ? $this->errorMessage->render() : '') . $pageContent,
445 'FOLDER_IDENTIFIER' => $this->folderObject->getCombinedIdentifier(),
446 'FILEDENYPATERN' => $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],
447 'MAXFILESIZE' => GeneralUtility::getMaxUploadFileSize() * 1024,
448 );
449 $this->content = $this->doc->moduleBody(array(), $docHeaderButtons, array_merge($markerArray, $otherMarkers));
450 // Renders the module page
451 $this->content = $this->doc->render($this->getLanguageService()->getLL('files'), $this->content);
452 } else {
453 $content = '';
454 if ($this->errorMessage) {
455 $this->errorMessage->setSeverity(FlashMessage::ERROR);
456 $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()));
457 }
458 // Create output - no access (no warning though)
459 $this->content = $this->doc->render($this->getLanguageService()->getLL('files'), $content);
460 }
461 }
462
463 /**
464 * Get main headline based on active folder or storage for backend module
465 *
466 * Folder names are resolved to their special names like done in the tree view.
467 *
468 * @return string
469 */
470 protected function getModuleHeadline() {
471 $name = $this->folderObject->getName();
472 if ($name === '') {
473 // Show storage name on storage root
474 if ($this->folderObject->getIdentifier() === '/') {
475 $name = $this->folderObject->getStorage()->getName();
476 }
477 } else {
478 $name = key(ListUtility::resolveSpecialFolderNames(
479 array($name => $this->folderObject)
480 ));
481 }
482 return $name;
483 }
484
485 /**
486 * Outputting the accumulated content to screen
487 *
488 * @return void
489 */
490 public function printContent() {
491 echo $this->content;
492 }
493
494 /**
495 * Create the panel of buttons for submitting the form or otherwise perform operations.
496 *
497 * @return array All available buttons as an assoc. array
498 */
499 public function getButtons() {
500 $buttons = array(
501 'csh' => '',
502 'shortcut' => '',
503 'upload' => '',
504 'new' => ''
505 );
506 // Add shortcut
507 if ($this->getBackendUser()->mayMakeShortcut()) {
508 $buttons['shortcut'] = $this->doc->makeShortcutIcon('pointer,id,target,table', implode(',', array_keys($this->MOD_MENU)), $this->moduleName);
509 }
510 // FileList Module CSH:
511 $buttons['csh'] = BackendUtility::cshItem('xMOD_csh_corebe', 'filelist_module');
512 // Upload button (only if upload to this directory is allowed)
513 if ($this->folderObject && $this->folderObject->getStorage()->checkUserActionPermission('add', 'File') && $this->folderObject->checkActionPermission('write')) {
514 $buttons['upload'] = '<a href="' . htmlspecialchars($GLOBALS['BACK_PATH']
515 . BackendUtility::getModuleUrl(
516 'file_upload',
517 array(
518 'target' => $this->folderObject->getCombinedIdentifier(),
519 'returnUrl' => $this->filelist->listURL(),
520 )
521 )) . '" 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>';
522 }
523 // New folder button
524 if ($this->folderObject && $this->folderObject->checkActionPermission('write')
525 && ($this->folderObject->getStorage()->checkUserActionPermission('add', 'File') || $this->folderObject->checkActionPermission('add'))
526 ) {
527 $buttons['new'] = '<a href="' . htmlspecialchars($GLOBALS['BACK_PATH']
528 . BackendUtility::getModuleUrl(
529 'file_newfolder',
530 array(
531 'target' => $this->folderObject->getCombinedIdentifier(),
532 'returnUrl' => $this->filelist->listURL(),
533 )
534 )) . '" title="' . $this->getLanguageService()->makeEntities($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:cm.new', TRUE)) . '">' . IconUtility::getSpriteIcon('actions-document-new') . '</a>';
535 }
536 return $buttons;
537 }
538
539 /**
540 * Returns an instance of LanguageService
541 *
542 * @return \TYPO3\CMS\Lang\LanguageService
543 */
544 protected function getLanguageService() {
545 return $GLOBALS['LANG'];
546 }
547
548 /**
549 * Returns the current BE user.
550 *
551 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
552 */
553 protected function getBackendUser() {
554 return $GLOBALS['BE_USER'];
555 }
556
557 /**
558 * @return PageRenderer
559 */
560 protected function getPageRenderer() {
561 return GeneralUtility::makeInstance(PageRenderer::class);
562 }
563
564 }