[!!!][TASK] Fluidification of EditFileController
[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->setActionPermissions();
145 $this->fileProcessor->setExistingFilesConflictMode($this->overwriteExistingFiles);
146 // Checking referrer / executing:
147 $refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
148 $httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
149 if ($httpHost !== $refInfo['host'] && $this->vC !== $this->getBackendUser()->veriCode() && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']) {
150 $this->fileProcessor->writeLog(0, 2, 1, 'Referrer host "%s" and server host "%s" did not match!', [$refInfo['host'], $httpHost]);
151 } else {
152 $this->fileProcessor->start($this->file);
153 $this->fileData = $this->fileProcessor->processData();
154 }
155 }
156
157 /**
158 * Redirecting the user after the processing has been done.
159 * Might also display error messages directly, if any.
160 *
161 * @return void
162 */
163 public function finish()
164 {
165 BackendUtility::setUpdateSignal('updateFolderTree');
166 if ($this->redirect) {
167 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($this->redirect);
168 }
169 }
170
171 /**
172 * Injects the request object for the current request or subrequest
173 * As this controller goes only through the main() method, it just redirects to the given URL afterwards.
174 *
175 * @param ServerRequestInterface $request the current request
176 * @param ResponseInterface $response
177 * @return ResponseInterface the response with the content
178 */
179 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
180 {
181 $this->main();
182
183 BackendUtility::setUpdateSignal('updateFolderTree');
184
185 // go and edit the new created file
186 if ($request->getParsedBody()['edit']) {
187 $urlParameters = [
188 'target' => $this->file['newfile'][0]['target'] . $this->file['newfile'][0]['data']
189 ];
190 if ($this->redirect) {
191 $urlParameters['returnUrl'] = $this->redirect;
192 }
193 $this->redirect = BackendUtility::getModuleUrl('file_edit', $urlParameters);
194 }
195 if ($this->redirect) {
196 return $response
197 ->withHeader('Location', GeneralUtility::locationHeaderUrl($this->redirect))
198 ->withStatus(303);
199 } else {
200 // empty response
201 return $response;
202 }
203 }
204
205 /**
206 * Handles the actual process from within the ajaxExec function
207 * therefore, it does exactly the same as the real typo3/tce_file.php
208 * but without calling the "finish" method, thus makes it simpler to deal with the
209 * actual return value
210 *
211 * @param ServerRequestInterface $request
212 * @param ResponseInterface $response
213 * @return ResponseInterface
214 */
215 public function processAjaxRequest(ServerRequestInterface $request, ResponseInterface $response)
216 {
217 $this->main();
218 $errors = $this->fileProcessor->getErrorMessages();
219 if (!empty($errors)) {
220 $response->getBody()->write(implode(',', $errors));
221 $response = $response->withHeader('Content-Type', 'text/html; charset=utf-8');
222 } else {
223 $flatResult = [];
224 foreach ($this->fileData as $action => $results) {
225 foreach ($results as $result) {
226 if (is_array($result)) {
227 foreach ($result as $subResult) {
228 $flatResult[$action][] = $this->flattenResultDataValue($subResult);
229 }
230 } else {
231 $flatResult[$action][] = $this->flattenResultDataValue($result);
232 }
233 }
234 }
235 $response->getBody()->write(json_encode($flatResult));
236 }
237 return $response;
238 }
239
240 /**
241 * Ajax entry point to check if a file exists in a folder
242 *
243 * @param ServerRequestInterface $request
244 * @param ResponseInterface $response
245 * @return ResponseInterface
246 */
247 public function fileExistsInFolderAction(ServerRequestInterface $request, ResponseInterface $response)
248 {
249 $fileName = isset($request->getParsedBody()['fileName']) ? $request->getParsedBody()['fileName'] : $request->getQueryParams()['fileName'];
250 $fileTarget = isset($request->getParsedBody()['fileTarget']) ? $request->getParsedBody()['fileTarget'] : $request->getQueryParams()['fileTarget'];
251
252 /** @var \TYPO3\CMS\Core\Resource\ResourceFactory $fileFactory */
253 $fileFactory = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ResourceFactory::class);
254 /** @var Folder $fileTargetObject */
255 $fileTargetObject = $fileFactory->retrieveFileOrFolderObject($fileTarget);
256 $processedFileName = $fileTargetObject->getStorage()->sanitizeFileName($fileName, $fileTargetObject);
257
258 $result = false;
259 if ($fileTargetObject->hasFile($processedFileName)) {
260 $result = $this->flattenResultDataValue($fileTargetObject->getStorage()->getFileInFolder($processedFileName, $fileTargetObject));
261 }
262 $response->getBody()->write(json_encode($result));
263 return $response;
264 }
265
266 /**
267 * Flatten result value from FileProcessor
268 *
269 * The value can be a File, Folder or boolean
270 *
271 * @param bool|\TYPO3\CMS\Core\Resource\File|\TYPO3\CMS\Core\Resource\Folder $result
272 * @return bool|string|array
273 */
274 protected function flattenResultDataValue($result)
275 {
276 if ($result instanceof \TYPO3\CMS\Core\Resource\File) {
277 $thumbUrl = '';
278 if (GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $result->getExtension())) {
279 $processedFile = $result->process(\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGEPREVIEW, []);
280 if ($processedFile) {
281 $thumbUrl = $processedFile->getPublicUrl(true);
282 }
283 }
284 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
285 $result = array_merge(
286 $result->toArray(),
287 [
288 'date' => BackendUtility::date($result->getModificationTime()),
289 'icon' => $iconFactory->getIconForFileExtension($result->getExtension(), Icon::SIZE_SMALL)->render(),
290 'thumbUrl' => $thumbUrl
291 ]
292 );
293 } elseif ($result instanceof \TYPO3\CMS\Core\Resource\Folder) {
294 $result = $result->getIdentifier();
295 }
296
297 return $result;
298 }
299
300 /**
301 * Returns the current BE user.
302 *
303 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
304 */
305 protected function getBackendUser()
306 {
307 return $GLOBALS['BE_USER'];
308 }
309 }