4c95a4faa9994fb5a41410ecc76dda92abcee7e8
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / File / FileController.php
1 <?php
2 namespace TYPO3\CMS\Backend\Controller\File;
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 Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Utility\BackendUtility;
20 use TYPO3\CMS\Core\Imaging\Icon;
21 use TYPO3\CMS\Core\Imaging\IconFactory;
22 use TYPO3\CMS\Core\Resource\DuplicationBehavior;
23 use TYPO3\CMS\Core\Resource\Folder;
24 use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
25 use TYPO3\CMS\Core\Utility\GeneralUtility;
26
27 /**
28 * Gateway for TCE (TYPO3 Core Engine) file-handling through POST forms.
29 * This script serves as the file administration part of the TYPO3 Core Engine.
30 * Basically it includes two libraries which are used to manipulate files on the server.
31 * Before TYPO3 4.3, it was located in typo3/tce_file.php and redirected back to a
32 * $redirectURL. Since 4.3 this class is also used for accessing via AJAX
33 */
34 class FileController
35 {
36 /**
37 * Array of file-operations.
38 *
39 * @var array
40 */
41 protected $file;
42
43 /**
44 * Clipboard operations array
45 *
46 * @var array
47 */
48 protected $CB;
49
50 /**
51 * Defines behaviour when uploading files with names that already exist; possible values are
52 * the values of the \TYPO3\CMS\Core\Resource\DuplicationBehavior enumeration
53 *
54 * @var \TYPO3\CMS\Core\Resource\DuplicationBehavior
55 */
56 protected $overwriteExistingFiles;
57
58 /**
59 * VeriCode - a hash of server specific value and other things which
60 * identifies if a submission is OK. (see $GLOBALS['BE_USER']->veriCode())
61 *
62 * @var string
63 */
64 protected $vC;
65
66 /**
67 * The page where the user should be redirected after everything is done
68 *
69 * @var string
70 */
71 protected $redirect;
72
73 /**
74 * Internal, dynamic:
75 * File processor object
76 *
77 * @var ExtendedFileUtility
78 */
79 protected $fileProcessor;
80
81 /**
82 * The result array from the file processor
83 *
84 * @var array
85 */
86 protected $fileData;
87
88 /**
89 * Constructor
90 */
91 public function __construct()
92 {
93 $GLOBALS['SOBE'] = $this;
94 $this->init();
95 }
96
97 /**
98 * Registering incoming data
99 *
100 * @return void
101 */
102 protected function init()
103 {
104 // Set the GPvars from outside
105 $this->file = GeneralUtility::_GP('file');
106 $this->CB = GeneralUtility::_GP('CB');
107 $this->overwriteExistingFiles = DuplicationBehavior::cast(GeneralUtility::_GP('overwriteExistingFiles'));
108 $this->vC = GeneralUtility::_GP('vC');
109 $this->redirect = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('redirect'));
110 $this->initClipboard();
111 $this->fileProcessor = GeneralUtility::makeInstance(ExtendedFileUtility::class);
112 }
113
114 /**
115 * Initialize the Clipboard. This will fetch the data about files to paste/delete if such an action has been sent.
116 *
117 * @return void
118 */
119 public function initClipboard()
120 {
121 if (is_array($this->CB)) {
122 $clipObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Clipboard\Clipboard::class);
123 $clipObj->initializeClipboard();
124 if ($this->CB['paste']) {
125 $clipObj->setCurrentPad($this->CB['pad']);
126 $this->file = $clipObj->makePasteCmdArray_file($this->CB['paste'], $this->file);
127 }
128 if ($this->CB['delete']) {
129 $clipObj->setCurrentPad($this->CB['pad']);
130 $this->file = $clipObj->makeDeleteCmdArray_file($this->file);
131 }
132 }
133 }
134
135 /**
136 * Performing the file admin action:
137 * Initializes the objects, setting permissions, sending data to object.
138 *
139 * @return void
140 */
141 public function main()
142 {
143 // Initializing:
144 $this->fileProcessor->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
145 $this->fileProcessor->setActionPermissions();
146 $this->fileProcessor->setExistingFilesConflictMode($this->overwriteExistingFiles);
147 // Checking referrer / executing:
148 $refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
149 $httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
150 if ($httpHost !== $refInfo['host'] && $this->vC !== $this->getBackendUser()->veriCode() && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']) {
151 $this->fileProcessor->writeLog(0, 2, 1, 'Referrer host "%s" and server host "%s" did not match!', array($refInfo['host'], $httpHost));
152 } else {
153 $this->fileProcessor->start($this->file);
154 $this->fileData = $this->fileProcessor->processData();
155 }
156 }
157
158 /**
159 * Redirecting the user after the processing has been done.
160 * Might also display error messages directly, if any.
161 *
162 * @return void
163 */
164 public function finish()
165 {
166 // Push errors to flash message queue, if there are any
167 $this->fileProcessor->pushErrorMessagesToFlashMessageQueue();
168 BackendUtility::setUpdateSignal('updateFolderTree');
169 if ($this->redirect) {
170 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($this->redirect);
171 }
172 }
173
174 /**
175 * Injects the request object for the current request or subrequest
176 * As this controller goes only through the main() method, it just redirects to the given URL afterwards.
177 *
178 * @param ServerRequestInterface $request the current request
179 * @param ResponseInterface $response
180 * @return ResponseInterface the response with the content
181 */
182 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
183 {
184 $this->main();
185
186 // Push errors to flash message queue, if there are any
187 $this->fileProcessor->pushErrorMessagesToFlashMessageQueue();
188 BackendUtility::setUpdateSignal('updateFolderTree');
189
190 if ($this->redirect) {
191 return $response
192 ->withHeader('Location', GeneralUtility::locationHeaderUrl($this->redirect))
193 ->withStatus(303);
194 } else {
195 // empty response
196 return $response;
197 }
198 }
199
200 /**
201 * Handles the actual process from within the ajaxExec function
202 * therefore, it does exactly the same as the real typo3/tce_file.php
203 * but without calling the "finish" method, thus makes it simpler to deal with the
204 * actual return value
205 *
206 * @param ServerRequestInterface $request
207 * @param ResponseInterface $response
208 * @return ResponseInterface
209 */
210 public function processAjaxRequest(ServerRequestInterface $request, ResponseInterface $response)
211 {
212 $this->main();
213 $errors = $this->fileProcessor->getErrorMessages();
214 if (!empty($errors)) {
215 $response->getBody()->write(implode(',', $errors));
216 $response = $response->withHeader('Content-Type', 'text/html; charset=utf-8');
217 } else {
218 $flatResult = array();
219 foreach ($this->fileData as $action => $results) {
220 foreach ($results as $result) {
221 if (is_array($result)) {
222 foreach ($result as $subResult) {
223 $flatResult[$action][] = $this->flattenResultDataValue($subResult);
224 }
225 } else {
226 $flatResult[$action][] = $this->flattenResultDataValue($result);
227 }
228 }
229 }
230 $response->getBody()->write(json_encode($flatResult));
231 }
232 return $response;
233 }
234
235 /**
236 * Ajax entry point to check if a file exists in a folder
237 *
238 * @param ServerRequestInterface $request
239 * @param ResponseInterface $response
240 * @return ResponseInterface
241 */
242 public function fileExistsInFolderAction(ServerRequestInterface $request, ResponseInterface $response)
243 {
244 $fileName = isset($request->getParsedBody()['fileName']) ? $request->getParsedBody()['fileName'] : $request->getQueryParams()['fileName'];
245 $fileTarget = isset($request->getParsedBody()['fileTarget']) ? $request->getParsedBody()['fileTarget'] : $request->getQueryParams()['fileTarget'];
246
247 /** @var \TYPO3\CMS\Core\Resource\ResourceFactory $fileFactory */
248 $fileFactory = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ResourceFactory::class);
249 /** @var Folder $fileTargetObject */
250 $fileTargetObject = $fileFactory->retrieveFileOrFolderObject($fileTarget);
251 $processedFileName = $fileTargetObject->getStorage()->sanitizeFileName($fileName, $fileTargetObject);
252
253 $result = false;
254 if ($fileTargetObject->hasFile($processedFileName)) {
255 $result = $this->flattenResultDataValue($fileTargetObject->getStorage()->getFileInFolder($processedFileName, $fileTargetObject));
256 }
257 $response->getBody()->write(json_encode($result));
258 return $response;
259 }
260
261 /**
262 * Flatten result value from FileProcessor
263 *
264 * The value can be a File, Folder or boolean
265 *
266 * @param bool|\TYPO3\CMS\Core\Resource\File|\TYPO3\CMS\Core\Resource\Folder $result
267 * @return bool|string|array
268 */
269 protected function flattenResultDataValue($result)
270 {
271 if ($result instanceof \TYPO3\CMS\Core\Resource\File) {
272 $thumbUrl = '';
273 if (GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $result->getExtension())) {
274 $processedFile = $result->process(\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGEPREVIEW, array());
275 if ($processedFile) {
276 $thumbUrl = $processedFile->getPublicUrl(true);
277 }
278 }
279 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
280 $result = array_merge(
281 $result->toArray(),
282 array(
283 'date' => BackendUtility::date($result->getModificationTime()),
284 'icon' => $iconFactory->getIconForFileExtension($result->getExtension(), Icon::SIZE_SMALL)->render(),
285 'thumbUrl' => $thumbUrl
286 )
287 );
288 } elseif ($result instanceof \TYPO3\CMS\Core\Resource\Folder) {
289 $result = $result->getIdentifier();
290 }
291
292 return $result;
293 }
294
295 /**
296 * Returns the current BE user.
297 *
298 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
299 */
300 protected function getBackendUser()
301 {
302 return $GLOBALS['BE_USER'];
303 }
304 }