[TASK] Update php-cs-fixer to 2.5.0
[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 * The page where the user should be redirected after everything is done
60 *
61 * @var string
62 */
63 protected $redirect;
64
65 /**
66 * Internal, dynamic:
67 * File processor object
68 *
69 * @var ExtendedFileUtility
70 */
71 protected $fileProcessor;
72
73 /**
74 * The result array from the file processor
75 *
76 * @var array
77 */
78 protected $fileData;
79
80 /**
81 * Constructor
82 */
83 public function __construct()
84 {
85 $GLOBALS['SOBE'] = $this;
86 $this->init();
87 }
88
89 /**
90 * Registering incoming data
91 */
92 protected function init()
93 {
94 // Set the GPvars from outside
95 $this->file = GeneralUtility::_GP('data');
96 if ($this->file === null) {
97 // This happens in clipboard mode only
98 $this->redirect = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('redirect'));
99 } else {
100 $mode = key($this->file);
101 $this->redirect = GeneralUtility::sanitizeLocalUrl($this->file[$mode][0]['redirect']);
102 }
103 $this->CB = GeneralUtility::_GP('CB');
104
105 if (isset($this->file['rename'][0]['conflictMode'])) {
106 $conflictMode = $this->file['rename'][0]['conflictMode'];
107 unset($this->file['rename'][0]['conflictMode']);
108 $this->overwriteExistingFiles = DuplicationBehavior::cast($conflictMode);
109 } else {
110 $this->overwriteExistingFiles = DuplicationBehavior::cast(GeneralUtility::_GP('overwriteExistingFiles'));
111 }
112 $this->initClipboard();
113 $this->fileProcessor = GeneralUtility::makeInstance(ExtendedFileUtility::class);
114 }
115
116 /**
117 * Initialize the Clipboard. This will fetch the data about files to paste/delete if such an action has been sent.
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 public function main()
140 {
141 // Initializing:
142 $this->fileProcessor->setActionPermissions();
143 $this->fileProcessor->setExistingFilesConflictMode($this->overwriteExistingFiles);
144 // Checking referrer / executing:
145 $refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
146 $httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
147 if ($httpHost !== $refInfo['host'] && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']) {
148 $this->fileProcessor->writeLog(0, 2, 1, 'Referrer host "%s" and server host "%s" did not match!', [$refInfo['host'], $httpHost]);
149 } else {
150 $this->fileProcessor->start($this->file);
151 $this->fileData = $this->fileProcessor->processData();
152 }
153 }
154
155 /**
156 * Redirecting the user after the processing has been done.
157 * Might also display error messages directly, if any.
158 */
159 public function finish()
160 {
161 BackendUtility::setUpdateSignal('updateFolderTree');
162 if ($this->redirect) {
163 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($this->redirect);
164 }
165 }
166
167 /**
168 * Injects the request object for the current request or subrequest
169 * As this controller goes only through the main() method, it just redirects to the given URL afterwards.
170 *
171 * @param ServerRequestInterface $request the current request
172 * @param ResponseInterface $response
173 * @return ResponseInterface the response with the content
174 */
175 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
176 {
177 $this->main();
178
179 BackendUtility::setUpdateSignal('updateFolderTree');
180
181 // go and edit the new created file
182 if ($request->getParsedBody()['edit']) {
183 $urlParameters = [
184 'target' => $this->file['newfile'][0]['target'] . $this->file['newfile'][0]['data']
185 ];
186 if ($this->redirect) {
187 $urlParameters['returnUrl'] = $this->redirect;
188 }
189 $this->redirect = BackendUtility::getModuleUrl('file_edit', $urlParameters);
190 }
191 if ($this->redirect) {
192 return $response
193 ->withHeader('Location', GeneralUtility::locationHeaderUrl($this->redirect))
194 ->withStatus(303);
195 }
196 // empty response
197 return $response;
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('<t3err>' . implode(',', $errors) . '</t3err>');
216 $response = $response
217 ->withHeader('Content-Type', 'text/html; charset=utf-8')
218 ->withStatus(500, '(AJAX)');
219 } else {
220 $flatResult = [];
221 foreach ($this->fileData as $action => $results) {
222 foreach ($results as $result) {
223 if (is_array($result)) {
224 foreach ($result as $subResult) {
225 $flatResult[$action][] = $this->flattenResultDataValue($subResult);
226 }
227 } else {
228 $flatResult[$action][] = $this->flattenResultDataValue($result);
229 }
230 }
231 }
232 $response->getBody()->write(json_encode($flatResult));
233 }
234 return $response;
235 }
236
237 /**
238 * Ajax entry point to check if a file exists in a folder
239 *
240 * @param ServerRequestInterface $request
241 * @param ResponseInterface $response
242 * @return ResponseInterface
243 */
244 public function fileExistsInFolderAction(ServerRequestInterface $request, ResponseInterface $response)
245 {
246 $fileName = isset($request->getParsedBody()['fileName']) ? $request->getParsedBody()['fileName'] : $request->getQueryParams()['fileName'];
247 $fileTarget = isset($request->getParsedBody()['fileTarget']) ? $request->getParsedBody()['fileTarget'] : $request->getQueryParams()['fileTarget'];
248
249 /** @var \TYPO3\CMS\Core\Resource\ResourceFactory $fileFactory */
250 $fileFactory = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ResourceFactory::class);
251 /** @var Folder $fileTargetObject */
252 $fileTargetObject = $fileFactory->retrieveFileOrFolderObject($fileTarget);
253 $processedFileName = $fileTargetObject->getStorage()->sanitizeFileName($fileName, $fileTargetObject);
254
255 $result = false;
256 if ($fileTargetObject->hasFile($processedFileName)) {
257 $result = $this->flattenResultDataValue($fileTargetObject->getStorage()->getFileInFolder($processedFileName, $fileTargetObject));
258 }
259 $response->getBody()->write(json_encode($result));
260 return $response;
261 }
262
263 /**
264 * Flatten result value from FileProcessor
265 *
266 * The value can be a File, Folder or boolean
267 *
268 * @param bool|\TYPO3\CMS\Core\Resource\File|\TYPO3\CMS\Core\Resource\Folder $result
269 * @return bool|string|array
270 */
271 protected function flattenResultDataValue($result)
272 {
273 if ($result instanceof \TYPO3\CMS\Core\Resource\File) {
274 $thumbUrl = '';
275 if (GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $result->getExtension())) {
276 $processedFile = $result->process(\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGEPREVIEW, []);
277 if ($processedFile) {
278 $thumbUrl = $processedFile->getPublicUrl(true);
279 }
280 }
281 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
282 $result = array_merge(
283 $result->toArray(),
284 [
285 'date' => BackendUtility::date($result->getModificationTime()),
286 'icon' => $iconFactory->getIconForFileExtension($result->getExtension(), Icon::SIZE_SMALL)->render(),
287 'thumbUrl' => $thumbUrl
288 ]
289 );
290 } elseif ($result instanceof \TYPO3\CMS\Core\Resource\Folder) {
291 $result = $result->getIdentifier();
292 }
293
294 return $result;
295 }
296
297 /**
298 * Returns the current BE user.
299 *
300 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
301 */
302 protected function getBackendUser()
303 {
304 return $GLOBALS['BE_USER'];
305 }
306 }