[TASK] Use JsonResponse for all Backend AJAX calls
[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\Http\JsonResponse;
21 use TYPO3\CMS\Core\Imaging\Icon;
22 use TYPO3\CMS\Core\Imaging\IconFactory;
23 use TYPO3\CMS\Core\Resource\DuplicationBehavior;
24 use TYPO3\CMS\Core\Resource\Folder;
25 use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27
28 /**
29 * Gateway for TCE (TYPO3 Core Engine) file-handling through POST forms.
30 * This script serves as the file administration part of the TYPO3 Core Engine.
31 * Basically it includes two libraries which are used to manipulate files on the server.
32 * Before TYPO3 4.3, it was located in typo3/tce_file.php and redirected back to a
33 * $redirectURL. Since 4.3 this class is also used for accessing via AJAX
34 */
35 class FileController
36 {
37 /**
38 * Array of file-operations.
39 *
40 * @var array
41 */
42 protected $file;
43
44 /**
45 * Clipboard operations array
46 *
47 * @var array
48 */
49 protected $CB;
50
51 /**
52 * Defines behaviour when uploading files with names that already exist; possible values are
53 * the values of the \TYPO3\CMS\Core\Resource\DuplicationBehavior enumeration
54 *
55 * @var \TYPO3\CMS\Core\Resource\DuplicationBehavior
56 */
57 protected $overwriteExistingFiles;
58
59 /**
60 * The page where the user should be redirected after everything is done
61 *
62 * @var string
63 */
64 protected $redirect;
65
66 /**
67 * Internal, dynamic:
68 * File processor object
69 *
70 * @var ExtendedFileUtility
71 */
72 protected $fileProcessor;
73
74 /**
75 * The result array from the file processor
76 *
77 * @var array
78 */
79 protected $fileData;
80
81 /**
82 * Constructor
83 */
84 public function __construct()
85 {
86 $GLOBALS['SOBE'] = $this;
87 $this->init();
88 }
89
90 /**
91 * Registering incoming data
92 */
93 protected function init()
94 {
95 // Set the GPvars from outside
96 $this->file = GeneralUtility::_GP('data');
97 if ($this->file === null) {
98 // This happens in clipboard mode only
99 $this->redirect = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('redirect'));
100 } else {
101 $mode = key($this->file);
102 $elementKey = key($this->file[$mode]);
103 $this->redirect = GeneralUtility::sanitizeLocalUrl($this->file[$mode][$elementKey]['redirect']);
104 }
105 $this->CB = GeneralUtility::_GP('CB');
106
107 if (isset($this->file['rename'][0]['conflictMode'])) {
108 $conflictMode = $this->file['rename'][0]['conflictMode'];
109 unset($this->file['rename'][0]['conflictMode']);
110 $this->overwriteExistingFiles = DuplicationBehavior::cast($conflictMode);
111 } else {
112 $this->overwriteExistingFiles = DuplicationBehavior::cast(GeneralUtility::_GP('overwriteExistingFiles'));
113 }
114 $this->initClipboard();
115 $this->fileProcessor = GeneralUtility::makeInstance(ExtendedFileUtility::class);
116 }
117
118 /**
119 * Initialize the Clipboard. This will fetch the data about files to paste/delete if such an action has been sent.
120 */
121 public function initClipboard()
122 {
123 if (is_array($this->CB)) {
124 $clipObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Clipboard\Clipboard::class);
125 $clipObj->initializeClipboard();
126 if ($this->CB['paste']) {
127 $clipObj->setCurrentPad($this->CB['pad']);
128 $this->file = $clipObj->makePasteCmdArray_file($this->CB['paste'], $this->file);
129 }
130 if ($this->CB['delete']) {
131 $clipObj->setCurrentPad($this->CB['pad']);
132 $this->file = $clipObj->makeDeleteCmdArray_file($this->file);
133 }
134 }
135 }
136
137 /**
138 * Performing the file admin action:
139 * Initializes the objects, setting permissions, sending data to object.
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'] && !$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 public function finish()
162 {
163 BackendUtility::setUpdateSignal('updateFolderTree');
164 if ($this->redirect) {
165 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($this->redirect);
166 }
167 }
168
169 /**
170 * Injects the request object for the current request or subrequest
171 * As this controller goes only through the main() method, it just redirects to the given URL afterwards.
172 *
173 * @param ServerRequestInterface $request the current request
174 * @param ResponseInterface $response
175 * @return ResponseInterface the response with the content
176 */
177 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
178 {
179 $this->main();
180
181 BackendUtility::setUpdateSignal('updateFolderTree');
182
183 // go and edit the new created file
184 if ($request->getParsedBody()['edit']) {
185 $urlParameters = [
186 'target' => $this->file['newfile'][0]['target'] . $this->file['newfile'][0]['data']
187 ];
188 if ($this->redirect) {
189 $urlParameters['returnUrl'] = $this->redirect;
190 }
191 /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
192 $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
193 $this->redirect = (string)$uriBuilder->buildUriFromRoute('file_edit', $urlParameters);
194 }
195 if ($this->redirect) {
196 return $response
197 ->withHeader('Location', GeneralUtility::locationHeaderUrl($this->redirect))
198 ->withStatus(303);
199 }
200 // empty response
201 return $response;
202 }
203
204 /**
205 * Handles the actual process from within the ajaxExec function
206 * therefore, it does exactly the same as the real typo3/tce_file.php
207 * but without calling the "finish" method, thus makes it simpler to deal with the
208 * actual return value
209 *
210 * @param ServerRequestInterface $request
211 * @param ResponseInterface $response
212 * @return ResponseInterface
213 */
214 public function processAjaxRequest(ServerRequestInterface $request, ResponseInterface $response)
215 {
216 $this->main();
217 $errors = $this->fileProcessor->getErrorMessages();
218 if (!empty($errors)) {
219 $response->getBody()->write('<t3err>' . implode(',', $errors) . '</t3err>');
220 $response = $response
221 ->withHeader('Content-Type', 'text/html; charset=utf-8')
222 ->withStatus(500, '(AJAX)');
223 } else {
224 $flatResult = [];
225 foreach ($this->fileData as $action => $results) {
226 foreach ($results as $result) {
227 if (is_array($result)) {
228 foreach ($result as $subResult) {
229 $flatResult[$action][] = $this->flattenResultDataValue($subResult);
230 }
231 } else {
232 $flatResult[$action][] = $this->flattenResultDataValue($result);
233 }
234 }
235 }
236 return GeneralUtility::makeInstance(JsonResponse::class)->setPayload($flatResult);
237 }
238 return $response;
239 }
240
241 /**
242 * Ajax entry point to check if a file exists in a folder
243 *
244 * @param ServerRequestInterface $request
245 * @return ResponseInterface
246 */
247 public function fileExistsInFolderAction(ServerRequestInterface $request)
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 return GeneralUtility::makeInstance(JsonResponse::class)->setPayload([$result]);
263 }
264
265 /**
266 * Flatten result value from FileProcessor
267 *
268 * The value can be a File, Folder or boolean
269 *
270 * @param bool|\TYPO3\CMS\Core\Resource\File|\TYPO3\CMS\Core\Resource\Folder $result
271 * @return bool|string|array
272 */
273 protected function flattenResultDataValue($result)
274 {
275 if ($result instanceof \TYPO3\CMS\Core\Resource\File) {
276 $thumbUrl = '';
277 if (GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $result->getExtension())) {
278 $processedFile = $result->process(\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGEPREVIEW, []);
279 if ($processedFile) {
280 $thumbUrl = $processedFile->getPublicUrl(true);
281 }
282 }
283 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
284 $result = array_merge(
285 $result->toArray(),
286 [
287 'date' => BackendUtility::date($result->getModificationTime()),
288 'icon' => $iconFactory->getIconForFileExtension($result->getExtension(), Icon::SIZE_SMALL)->render(),
289 'thumbUrl' => $thumbUrl
290 ]
291 );
292 } elseif ($result instanceof \TYPO3\CMS\Core\Resource\Folder) {
293 $result = $result->getIdentifier();
294 }
295
296 return $result;
297 }
298
299 /**
300 * Returns the current BE user.
301 *
302 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
303 */
304 protected function getBackendUser()
305 {
306 return $GLOBALS['BE_USER'];
307 }
308 }