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