[BUGFIX] Allow recursive folder deletion
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / File / ExtendedFileUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility\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 TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Backend\Utility\IconUtility;
19 use TYPO3\CMS\Core\Messaging\FlashMessage;
20 use TYPO3\CMS\Core\Messaging\FlashMessageService;
21 use TYPO3\CMS\Core\Resource\File;
22 use TYPO3\CMS\Core\Resource\Folder;
23 use TYPO3\CMS\Core\Resource\ResourceFactory;
24 use TYPO3\CMS\Core\Resource\ResourceStorage;
25 use TYPO3\CMS\Core\Utility\CommandUtility;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\PathUtility;
28
29 /**
30 * Contains functions for performing file operations like copying, pasting, uploading, moving,
31 * deleting etc. through the TCE
32 *
33 * See document "TYPO3 Core API" for syntax
34 *
35 * This class contains functions primarily used by tce_file.php (TYPO3 Core Engine for file manipulation)
36 * Functions include copying, moving, deleting, uploading and so on...
37 *
38 * Important internal variables:
39 *
40 * $filemounts (see basicFileFunctions)
41 * $f_ext (see basicFileFunctions)
42 *
43 * All fileoperations must be within the filemount-paths. Further the fileextension
44 * MUST validate TRUE with the f_ext array
45 *
46 * The unzip-function allows unzip only if the destination path has it's f_ext[]['allow'] set to '*'!!
47 * You are allowed to copy/move folders within the same 'space' (web/ftp).
48 * You are allowed to copy/move folders between spaces (web/ftp) IF the destination has it's f_ext[]['allow'] set to '*'!
49 *
50 * Advice:
51 * You should always exclude php-files from the webspace. This will keep people from uploading, copy/moving and renaming files to become executable php scripts.
52 * You should never mount a ftp_space 'below' the webspace so that it reaches into the webspace. This is because if somebody unzips a zip-file in the ftp-space so that it reaches out into the webspace this will be a violation of the safety
53 * For example this is a bad idea: you have an ftp-space that is '/www/' and a web-space that is '/www/htdocs/'
54 *
55 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
56 */
57 class ExtendedFileUtility extends BasicFileUtility {
58
59 /**
60 * External static variables:
61 * Notice; some of these are overridden in the start() method with values from $GLOBALS['TYPO3_CONF_VARS']['BE']
62 * Path to unzip-program (with trailing '/')
63 *
64 * @var string
65 */
66 public $unzipPath = '';
67
68 /**
69 * If set, the uploaded files will overwrite existing files.
70 *
71 * @var bool
72 */
73 public $dontCheckForUnique = 0;
74
75 /**
76 * This array is self-explaining (look in the class below).
77 * It grants access to the functions. This could be set from outside in order to enabled functions to users.
78 * See also the function setActionPermissions() which takes input directly from the user-record
79 *
80 * @var array
81 */
82 public $actionPerms = array(
83 // File permissions
84 'addFile' => FALSE,
85 'readFile' => FALSE,
86 'writeFile' => FALSE,
87 'copyFile' => FALSE,
88 'moveFile' => FALSE,
89 'renameFile' => FALSE,
90 'unzipFile' => FALSE,
91 'deleteFile' => FALSE,
92 // Folder permissions
93 'addFolder' => FALSE,
94 'readFolder' => FALSE,
95 'writeFolder' => FALSE,
96 'copyFolder' => FALSE,
97 'moveFolder' => FALSE,
98 'renameFolder' => FALSE,
99 'deleteFolder' => FALSE,
100 'recursivedeleteFolder' => FALSE
101 );
102
103 /**
104 * This is regarded to be the recycler folder
105 *
106 * @var string
107 */
108 public $recyclerFN = '_recycler_';
109
110 /**
111 * Will contain map between upload ID and the final filename
112 *
113 * @var array
114 */
115 public $internalUploadMap = array();
116
117 /**
118 * @var string
119 */
120 public $lastError = '';
121
122 /**
123 * All error messages from the file operations of this script instance
124 *
125 * @var array
126 */
127 protected $errorMessages = array();
128
129 /**
130 * @var array
131 */
132 protected $fileCmdMap;
133
134 /**
135 * The File Factory
136 *
137 * @var \TYPO3\CMS\Core\Resource\ResourceFactory
138 */
139 protected $fileFactory;
140
141 /**
142 * Initialization of the class
143 *
144 * @param array $fileCmds Array with the commands to execute. See "TYPO3 Core API" document
145 * @return void
146 */
147 public function start($fileCmds) {
148 $unzipPath = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['unzip_path']);
149 if (substr($unzipPath, -1) !== '/' && is_dir($unzipPath)) {
150 // Make sure the path ends with a slash
151 $unzipPath .= '/';
152 }
153 $this->unzipPath = $unzipPath;
154 // Initialize Object Factory
155 $this->fileFactory = ResourceFactory::getInstance();
156 // Initializing file processing commands:
157 $this->fileCmdMap = $fileCmds;
158 }
159
160 /**
161 * Sets the file action permissions.
162 * If no argument is given, permissions of the currently logged in backend user are taken into account.
163 *
164 * @param array $permissions File Permissions.
165 */
166 public function setActionPermissions(array $permissions = array()) {
167 if (empty($permissions)) {
168 $permissions = $GLOBALS['BE_USER']->getFilePermissions();
169 }
170 $this->actionPerms = $permissions;
171 }
172
173 /**
174 * Processing the command array in $this->fileCmdMap
175 *
176 * @return mixed FALSE, if the file functions were not initialized
177 * @throws \UnexpectedValueException
178 */
179 public function processData() {
180 $result = array();
181 if (!$this->isInit) {
182 return FALSE;
183 }
184 if (is_array($this->fileCmdMap)) {
185 // Check if there were uploads expected, but no one made
186 if ($this->fileCmdMap['upload']) {
187 $uploads = $this->fileCmdMap['upload'];
188 foreach ($uploads as $upload) {
189 if (empty($_FILES[('upload_' . $upload['data'])]['name'])
190 || (is_array($_FILES[('upload_' . $upload['data'])]['name'])
191 && empty($_FILES[('upload_' . $upload['data'])]['name'][0])
192 )
193 ) {
194 unset($this->fileCmdMap['upload'][$upload['data']]);
195 }
196 }
197 if (count($this->fileCmdMap['upload']) == 0) {
198 $this->writelog(1, 1, 108, 'No file was uploaded!', '');
199 }
200 }
201
202 // Check if there were new folder names expected, but non given
203 if ($this->fileCmdMap['newfolder']) {
204 foreach ($this->fileCmdMap['newfolder'] as $key => $cmdArr) {
205 if (empty($cmdArr['data'])) {
206 unset($this->fileCmdMap['newfolder'][$key]);
207 }
208 }
209 if (count($this->fileCmdMap['newfolder']) === 0) {
210 $this->writeLog(6, 1, 108, 'No name for new folder given!', '');
211 }
212 }
213
214 // Traverse each set of actions
215 foreach ($this->fileCmdMap as $action => $actionData) {
216 // Traverse all action data. More than one file might be affected at the same time.
217 if (is_array($actionData)) {
218 $result[$action] = array();
219 foreach ($actionData as $cmdArr) {
220 // Clear file stats
221 clearstatcache();
222 // Branch out based on command:
223 switch ($action) {
224 case 'delete':
225 $result[$action][] = $this->func_delete($cmdArr);
226 break;
227 case 'copy':
228 $result[$action][] = $this->func_copy($cmdArr);
229 break;
230 case 'move':
231 $result[$action][] = $this->func_move($cmdArr);
232 break;
233 case 'rename':
234 $result[$action][] = $this->func_rename($cmdArr);
235 break;
236 case 'newfolder':
237 $result[$action][] = $this->func_newfolder($cmdArr);
238 break;
239 case 'newfile':
240 $result[$action][] = $this->func_newfile($cmdArr);
241 break;
242 case 'editfile':
243 $result[$action][] = $this->func_edit($cmdArr);
244 break;
245 case 'upload':
246 $result[$action][] = $this->func_upload($cmdArr);
247 break;
248 case 'unzip':
249 $result[$action][] = $this->func_unzip($cmdArr);
250 break;
251 }
252 // Hook for post-processing the action
253 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'])) {
254 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'] as $classRef) {
255 $hookObject = GeneralUtility::getUserObj($classRef);
256 if (!$hookObject instanceof ExtendedFileUtilityProcessDataHookInterface) {
257 throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\Utility\\File\\ExtendedFileUtilityProcessDataHookInterface', 1279719168);
258 }
259 $hookObject->processData_postProcessAction($action, $cmdArr, $result[$action], $this);
260 }
261 }
262 }
263 }
264 }
265 }
266 return $result;
267 }
268
269 /**
270 * Adds all log error messages from the operations of this script instance to the FlashMessageQueue
271 *
272 * @return void
273 */
274 public function pushErrorMessagesToFlashMessageQueue() {
275 foreach ($this->getErrorMessages() as $msg) {
276 $flashMessage = GeneralUtility::makeInstance(
277 FlashMessage::class,
278 $msg,
279 '',
280 FlashMessage::ERROR,
281 TRUE
282 );
283 $this->addFlashMessage($flashMessage);
284 }
285 }
286
287 /**
288 * Return all error messages from the file operations of this script instance
289 *
290 * @return array all errorMessages as a numerical array
291 */
292 public function getErrorMessages() {
293 return $this->errorMessages;
294 }
295
296 /**
297 * @param int $action The action number. See the functions in the class for a hint. Eg. edit is '9', upload is '1' ...
298 * @param int $error The severity: 0 = message, 1 = error, 2 = System Error, 3 = security notice (admin)
299 * @param int $details_nr This number is unique for every combination of $type and $action. This is the error-message number, which can later be used to translate error messages.
300 * @param string $details This is the default, raw error message in english
301 * @param array $data Array with special information that may go into $details by "%s" marks / sprintf() when the log is shown
302 * @return void
303 */
304 public function writeLog($action, $error, $details_nr, $details, $data) {
305 // Type value for tce_file.php
306 $type = 2;
307 if (is_object($this->getBackendUser())) {
308 $this->getBackendUser()->writelog($type, $action, $error, $details_nr, $details, $data);
309 }
310 if ($error > 0) {
311 $this->lastError = vsprintf($details, $data);
312 $this->errorMessages[] = $this->lastError;
313 }
314 }
315
316 /*************************************
317 *
318 * File operation functions
319 *
320 **************************************/
321 /**
322 * Deleting files and folders (action=4)
323 *
324 * @param array $cmds $cmds['data'] is the file/folder to delete
325 * @return bool Returns TRUE upon success
326 */
327 public function func_delete($cmds) {
328 $result = FALSE;
329 if (!$this->isInit) {
330 return $result;
331 }
332 // Example indentifier for $cmds['data'] => "4:mypath/tomyfolder/myfile.jpg"
333 // for backwards compatibility: the combined file identifier was the path+filename
334 $fileObject = $this->getFileObject($cmds['data']);
335 // @todo implement the recycler feature which has been removed from the original implementation
336 // checks to delete the file
337 if ($fileObject instanceof File) {
338 // check if the file still has references
339 // Exclude sys_file_metadata records as these are no use references
340 $refIndexRecords = $this->getDatabaseConnection()->exec_SELECTgetRows(
341 '*',
342 'sys_refindex',
343 'deleted=0 AND ref_table="sys_file" AND ref_uid=' . (int)$fileObject->getUid()
344 . ' AND tablename != "sys_file_metadata"'
345 );
346 if (count($refIndexRecords) > 0) {
347 $shortcutContent = array();
348 foreach ($refIndexRecords as $fileReferenceRow) {
349 $row = $fileReferenceRow;
350 if ($fileReferenceRow['tablename'] === 'sys_file_reference') {
351 $row = $this->transformFileReferenceToRecordReference($fileReferenceRow);
352 }
353 $shortcutRecord = BackendUtility::getRecord($row['tablename'], $row['recuid']);
354 $icon = IconUtility::getSpriteIconForRecord($row['tablename'], $shortcutRecord);
355 $icon = '<a href="#" class="t3-js-clickmenutrigger" data-table="' . $row['tablename'] . '" data-uid="' . $row['recuid'] . '" data-listframe="1" data-iteminfo="%2Binfo,history,edit">' . $icon . '</a>';
356 $shortcutContent[] = $icon . htmlspecialchars((BackendUtility::getRecordTitle($row['tablename'], $shortcutRecord) . ' [' . BackendUtility::getRecordPath($shortcutRecord['pid'], '', 80) . ']'));
357 }
358
359 // render a message that the file could not be deleted
360 $flashMessage = GeneralUtility::makeInstance(
361 FlashMessage::class,
362 sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:message.description.fileNotDeletedHasReferences'), $fileObject->getName()) . '<br />' . implode('<br />', $shortcutContent),
363 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:message.header.fileNotDeletedHasReferences'),
364 FlashMessage::WARNING,
365 TRUE
366 );
367 $this->addFlashMessage($flashMessage);
368 } else {
369 try {
370 $result = $fileObject->delete();
371
372 // show the user that the file was deleted
373 $flashMessage = GeneralUtility::makeInstance(
374 FlashMessage::class,
375 sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:message.description.fileDeleted'), $fileObject->getName()),
376 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:message.header.fileDeleted'),
377 FlashMessage::OK,
378 TRUE
379 );
380 $this->addFlashMessage($flashMessage);
381 // Log success
382 $this->writelog(4, 0, 1, 'File "%s" deleted', array($fileObject->getIdentifier()));
383 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
384 $this->writelog(4, 1, 112, 'You are not allowed to access the file', array($fileObject->getIdentifier()));
385 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
386 $this->writelog(4, 1, 111, 'Target was not within your mountpoints! T="%s"', array($fileObject->getIdentifier()));
387 } catch (\RuntimeException $e) {
388 $this->writelog(4, 1, 110, 'Could not delete file "%s". Write-permission problem?', array($fileObject->getIdentifier()));
389 }
390 }
391 } else {
392 try {
393 /** @var \TYPO3\CMS\Core\Resource\Folder $fileObject */
394 $result = $fileObject->delete(TRUE);
395 if ($result) {
396 // notify the user that the folder was deleted
397 /** @var FlashMessage $flashMessage */
398 $flashMessage = GeneralUtility::makeInstance(
399 FlashMessage::class,
400 sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:message.description.folderDeleted'), $fileObject->getName()),
401 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:message.header.folderDeleted'),
402 FlashMessage::OK,
403 TRUE
404 );
405 $this->addFlashMessage($flashMessage);
406 // Log success
407 $this->writelog(4, 0, 3, 'Directory "%s" deleted', array($fileObject->getIdentifier()));
408 }
409 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
410 $this->writelog(4, 1, 120, 'Could not delete directory! Is directory "%s" empty? (You are not allowed to delete directories recursively).', array($fileObject->getIdentifier()));
411 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException $e) {
412 $this->writelog(4, 1, 123, 'You are not allowed to access the directory', array($fileObject->getIdentifier()));
413 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
414 $this->writelog(4, 1, 121, 'Target was not within your mountpoints! T="%s"', array($fileObject->getIdentifier()));
415 } catch (\TYPO3\CMS\Core\Resource\Exception\FileOperationErrorException $e) {
416 $this->writelog(4, 1, 120, 'Could not delete directory "%s"! Write-permission problem?', array($fileObject->getIdentifier()));
417 }
418 }
419 return $result;
420 }
421
422 /**
423 * Maps results from the fal file reference table on the
424 * structure of the normal reference index table.
425 *
426 * @param array $referenceRecord
427 * @return array
428 */
429 protected function transformFileReferenceToRecordReference(array $referenceRecord) {
430 $fileReference = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
431 '*',
432 'sys_file_reference',
433 'uid=' . (int)$referenceRecord['recuid']
434 );
435 return array(
436 'recuid' => $fileReference['uid_foreign'],
437 'tablename' => $fileReference['tablenames'],
438 'field' => $fileReference['fieldname'],
439 'flexpointer' => '',
440 'softref_key' => '',
441 'sorting' => $fileReference['sorting_foreign']
442 );
443 }
444
445 /**
446 * Gets a File or a Folder object from an identifier [storage]:[fileId]
447 *
448 * @param string $identifier
449 * @return \TYPO3\CMS\Core\Resource\Folder|\TYPO3\CMS\Core\Resource\File
450 * @throws \TYPO3\CMS\Core\Resource\Exception\InvalidFileException
451 */
452 protected function getFileObject($identifier) {
453 $object = $this->fileFactory->retrieveFileOrFolderObject($identifier);
454 if (!is_object($object)) {
455 throw new \TYPO3\CMS\Core\Resource\Exception\InvalidFileException('The item ' . $identifier . ' was not a file or directory!!', 1320122453);
456 }
457 if ($object->getStorage()->getUid() === 0) {
458 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException('You are not allowed to access files outside your storages', 1375889830);
459 }
460 return $object;
461 }
462
463 /**
464 * Copying files and folders (action=2)
465 *
466 * $cmds['data'] (string): The file/folder to copy
467 * + example "4:mypath/tomyfolder/myfile.jpg")
468 * + for backwards compatibility: the identifier was the path+filename
469 * $cmds['target'] (string): The path where to copy to.
470 * + example "2:targetpath/targetfolder/"
471 * $cmds['altName'] (string): Use an alternative name if the target already exists
472 *
473 * @param array $cmds Command details as described above
474 * @return \TYPO3\CMS\Core\Resource\File
475 */
476 protected function func_copy($cmds) {
477 if (!$this->isInit) {
478 return FALSE;
479 }
480 $sourceFileObject = $this->getFileObject($cmds['data']);
481 /** @var $targetFolderObject \TYPO3\CMS\Core\Resource\Folder */
482 $targetFolderObject = $this->getFileObject($cmds['target']);
483 // Basic check
484 if (!$targetFolderObject instanceof Folder) {
485 $this->writelog(2, 2, 100, 'Destination "%s" was not a directory', array($cmds['target']));
486 return FALSE;
487 }
488 // If this is TRUE, we append _XX to the file name if
489 $appendSuffixOnConflict = (string)$cmds['altName'];
490 $resultObject = NULL;
491 // Copying the file
492 if ($sourceFileObject instanceof File) {
493 try {
494 $conflictMode = $appendSuffixOnConflict !== '' ? 'renameNewFile' : 'cancel';
495 $resultObject = $sourceFileObject->copyTo($targetFolderObject, NULL, $conflictMode);
496 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
497 $this->writelog(2, 1, 114, 'You are not allowed to copy files', '');
498 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
499 $this->writelog(2, 1, 110, 'Could not access all necessary resources. Source file or destination maybe was not within your mountpoints? T="%s", D="%s"', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
500 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
501 $this->writelog(2, 1, 111, 'Extension of file name "%s" is not allowed in "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
502 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
503 $this->writelog(2, 1, 112, 'File "%s" already exists in folder "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
504 } catch (\BadMethodCallException $e) {
505 $this->writelog(3, 1, 128, 'The function to copy a file between storages is not yet implemented', array());
506 } catch (\RuntimeException $e) {
507 $this->writelog(2, 2, 109, 'File "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
508 }
509 if ($resultObject) {
510 $this->writelog(2, 0, 1, 'File "%s" copied to "%s"', array($sourceFileObject->getIdentifier(), $resultObject->getIdentifier()));
511 }
512 } else {
513 // Else means this is a Folder
514 $sourceFolderObject = $sourceFileObject;
515 try {
516 $conflictMode = $appendSuffixOnConflict !== '' ? 'renameNewFile' : 'cancel';
517 $resultObject = $sourceFolderObject->copyTo($targetFolderObject, NULL, $conflictMode);
518 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
519 $this->writelog(2, 1, 125, 'You are not allowed to copy directories', '');
520 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
521 $this->writelog(2, 1, 110, 'Could not access all necessary resources. Source file or destination maybe was not within your mountpoints? T="%s", D="%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
522 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException $e) {
523 $this->writelog(2, 1, 121, 'You don\'t have full access to the destination directory "%s"!', array($targetFolderObject->getIdentifier()));
524 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException $e) {
525 $this->writelog(2, 1, 122, 'Destination cannot be inside the target! D="%s", T="%s"', array($targetFolderObject->getIdentifier(), $sourceFolderObject->getIdentifier()));
526 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException $e) {
527 $this->writelog(2, 1, 123, 'Target "%s" already exists!', array($targetFolderObject->getIdentifier()));
528 } catch (\BadMethodCallException $e) {
529 $this->writelog(3, 1, 129, 'The function to copy a folder between storages is not yet implemented', array());
530 } catch (\RuntimeException $e) {
531 $this->writelog(2, 2, 119, 'Directory "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
532 }
533 if ($resultObject) {
534 $this->writelog(2, 0, 2, 'Directory "%s" copied to "%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
535 }
536 }
537 return $resultObject;
538 }
539
540 /**
541 * Moving files and folders (action=3)
542 *
543 * $cmds['data'] (string): The file/folder to move
544 * + example "4:mypath/tomyfolder/myfile.jpg")
545 * + for backwards compatibility: the identifier was the path+filename
546 * $cmds['target'] (string): The path where to move to.
547 * + example "2:targetpath/targetfolder/"
548 * $cmds['altName'] (string): Use an alternative name if the target already exists
549 *
550 * @param array $cmds Command details as described above
551 * @return \TYPO3\CMS\Core\Resource\File
552 */
553 protected function func_move($cmds) {
554 if (!$this->isInit) {
555 return FALSE;
556 }
557 $sourceFileObject = $this->getFileObject($cmds['data']);
558 $targetFolderObject = $this->getFileObject($cmds['target']);
559 // Basic check
560 if (!$targetFolderObject instanceof Folder) {
561 $this->writelog(3, 2, 100, 'Destination "%s" was not a directory', array($cmds['target']));
562 return FALSE;
563 }
564 $alternativeName = (string)$cmds['altName'];
565 $resultObject = NULL;
566 // Moving the file
567 if ($sourceFileObject instanceof File) {
568 try {
569 if ($alternativeName !== '') {
570 // Don't allow overwriting existing files, but find a new name
571 $resultObject = $sourceFileObject->moveTo($targetFolderObject, $alternativeName, 'renameNewFile');
572 } else {
573 // Don't allow overwriting existing files
574 $resultObject = $sourceFileObject->moveTo($targetFolderObject, NULL, 'cancel');
575 }
576 $this->writelog(3, 0, 1, 'File "%s" moved to "%s"', array($sourceFileObject->getIdentifier(), $resultObject->getIdentifier()));
577 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
578 $this->writelog(3, 1, 114, 'You are not allowed to move files', '');
579 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
580 $this->writelog(3, 1, 110, 'Could not access all necessary resources. Source file or destination maybe was not within your mountpoints? T="%s", D="%s"', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
581 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
582 $this->writelog(3, 1, 111, 'Extension of file name "%s" is not allowed in "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
583 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
584 $this->writelog(3, 1, 112, 'File "%s" already exists in folder "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
585 } catch (\BadMethodCallException $e) {
586 $this->writelog(3, 1, 126, 'The function to move a file between storages is not yet implemented', array());
587 } catch (\RuntimeException $e) {
588 $this->writelog(3, 2, 109, 'File "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
589 }
590 } else {
591 // Else means this is a Folder
592 $sourceFolderObject = $sourceFileObject;
593 try {
594 if ($alternativeName !== '') {
595 // Don't allow overwriting existing files, but find a new name
596 $resultObject = $sourceFolderObject->moveTo($targetFolderObject, $alternativeName, 'renameNewFile');
597 } else {
598 // Don't allow overwriting existing files
599 $resultObject = $sourceFolderObject->moveTo($targetFolderObject, NULL, 'renameNewFile');
600 }
601 $this->writelog(3, 0, 2, 'Directory "%s" moved to "%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
602 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
603 $this->writelog(3, 1, 125, 'You are not allowed to move directories', '');
604 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
605 $this->writelog(3, 1, 110, 'Could not access all necessary resources. Source file or destination maybe was not within your mountpoints? T="%s", D="%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
606 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException $e) {
607 $this->writelog(3, 1, 121, 'You don\'t have full access to the destination directory "%s"!', array($targetFolderObject->getIdentifier()));
608 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException $e) {
609 $this->writelog(3, 1, 122, 'Destination cannot be inside the target! D="%s", T="%s"', array($targetFolderObject->getIdentifier(), $sourceFolderObject->getIdentifier()));
610 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException $e) {
611 $this->writelog(3, 1, 123, 'Target "%s" already exists!', array($targetFolderObject->getIdentifier()));
612 } catch (\BadMethodCallException $e) {
613 $this->writelog(3, 1, 127, 'The function to move a folder between storages is not yet implemented', array());
614 } catch (\RuntimeException $e) {
615 $this->writelog(3, 2, 119, 'Directory "%s" WAS NOT moved to "%s"! Write-permission problem?', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
616 }
617 }
618 return $resultObject;
619 }
620
621 /**
622 * Renaming files or foldes (action=5)
623 *
624 * $cmds['data'] (string): The file/folder to copy
625 * + example "4:mypath/tomyfolder/myfile.jpg")
626 * + for backwards compatibility: the identifier was the path+filename
627 * $cmds['target'] (string): New name of the file/folder
628 *
629 * @param array $cmds Command details as described above
630 * @return \TYPO3\CMS\Core\Resource\File Returns the new file upon success
631 */
632 public function func_rename($cmds) {
633 if (!$this->isInit) {
634 return FALSE;
635 }
636 $sourceFileObject = $this->getFileObject($cmds['data']);
637 $targetFile = $cmds['target'];
638 $resultObject = NULL;
639 if ($sourceFileObject instanceof File) {
640 try {
641 // Try to rename the File
642 $resultObject = $sourceFileObject->rename($targetFile);
643 $this->writelog(5, 0, 1, 'File renamed from "%s" to "%s"', array($sourceFileObject->getName(), $targetFile));
644 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
645 $this->writelog(5, 1, 102, 'You are not allowed to rename files!', '');
646 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
647 $this->writelog(5, 1, 101, 'Extension of file name "%s" or "%s" was not allowed!', array($sourceFileObject->getName(), $targetFile));
648 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
649 $this->writelog(5, 1, 120, 'Destination "%s" existed already!', array($targetFile));
650 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
651 $this->writelog(5, 1, 121, 'Destination path "%s" was not within your mountpoints!', array($targetFile));
652 } catch (\RuntimeException $e) {
653 $this->writelog(5, 1, 100, 'File "%s" was not renamed! Write-permission problem in "%s"?', array($sourceFileObject->getName(), $targetFile));
654 }
655 } else {
656 // Else means this is a Folder
657 try {
658 // Try to rename the Folder
659 $resultObject = $sourceFileObject->rename($targetFile);
660 $this->writelog(5, 0, 2, 'Directory renamed from "%s" to "%s"', array($sourceFileObject->getName(), $targetFile));
661 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
662 $this->writelog(5, 1, 111, 'You are not allowed to rename directories!', '');
663 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
664 $this->writelog(5, 1, 120, 'Destination "%s" existed already!', array($targetFile));
665 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
666 $this->writelog(5, 1, 121, 'Destination path "%s" was not within your mountpoints!', array($targetFile));
667 } catch (\RuntimeException $e) {
668 $this->writelog(5, 1, 110, 'Directory "%s" was not renamed! Write-permission problem in "%s"?', array($sourceFileObject->getName(), $targetFile));
669 }
670 }
671 return $resultObject;
672 }
673
674 /**
675 * This creates a new folder. (action=6)
676 *
677 * $cmds['data'] (string): The new folder name
678 * $cmds['target'] (string): The path where to copy to.
679 * + example "2:targetpath/targetfolder/"
680 *
681 * @param array $cmds Command details as described above
682 * @return \TYPO3\CMS\Core\Resource\Folder Returns the new foldername upon success
683 */
684 public function func_newfolder($cmds) {
685 if (!$this->isInit) {
686 return FALSE;
687 }
688 $targetFolderObject = $this->getFileObject($cmds['target']);
689 if (!$targetFolderObject instanceof Folder) {
690 $this->writelog(6, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
691 return FALSE;
692 }
693 $resultObject = NULL;
694 try {
695 $folderName = $cmds['data'];
696 $resultObject = $targetFolderObject->createFolder($folderName);
697 $this->writelog(6, 0, 1, 'Directory "%s" created in "%s"', array($folderName, $targetFolderObject->getIdentifier() . '/'));
698 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException $e) {
699 $this->writelog(6, 1, 103, 'You are not allowed to create directories!', '');
700 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
701 $this->writelog(6, 1, 102, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier() . '/'));
702 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException $e) {
703 $this->writelog(6, 1, 101, 'File or directory "%s" existed already!', array($folderName));
704 } catch (\RuntimeException $e) {
705 $this->writelog(6, 1, 100, 'Directory "%s" not created. Write-permission problem in "%s"?', array($folderName, $targetFolderObject->getIdentifier() . '/'));
706 }
707 return $resultObject;
708 }
709
710 /**
711 * This creates a new file. (action=8)
712 * $cmds['data'] (string): The new file name
713 * $cmds['target'] (string): The path where to create it.
714 * + example "2:targetpath/targetfolder/"
715 *
716 * @param array $cmds Command details as described above
717 * @return string Returns the new filename upon success
718 */
719 public function func_newfile($cmds) {
720 if (!$this->isInit) {
721 return FALSE;
722 }
723 $targetFolderObject = $this->getFileObject($cmds['target']);
724 if (!$targetFolderObject instanceof Folder) {
725 $this->writelog(8, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
726 return FALSE;
727 }
728 $resultObject = NULL;
729 try {
730 $fileName = $cmds['data'];
731 $resultObject = $targetFolderObject->createFile($fileName);
732 $this->writelog(8, 0, 1, 'File created: "%s"', array($fileName));
733 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
734 $this->writeLog(8, 1, 106, 'Extension of file "%s" was not allowed!', array($fileName));
735 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException $e) {
736 $this->writelog(8, 1, 103, 'You are not allowed to create files!', '');
737 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
738 $this->writelog(8, 1, 102, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier()));
739 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
740 $this->writelog(8, 1, 101, 'File existed already in "%s"!', array($targetFolderObject->getIdentifier()));
741 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidFileNameException $e) {
742 $this->writelog(8, 1, 106, 'File name "%s" was not allowed!', $fileName);
743 } catch (\RuntimeException $e) {
744 $this->writelog(8, 1, 100, 'File "%s" was not created! Write-permission problem in "%s"?', array($fileName, $targetFolderObject->getIdentifier()));
745 }
746 return $resultObject;
747 }
748
749 /**
750 * Editing textfiles or folders (action=9)
751 *
752 * @param array $cmds $cmds['data'] is the new content. $cmds['target'] is the target (file or dir)
753 * @return bool Returns TRUE on success
754 */
755 public function func_edit($cmds) {
756 if (!$this->isInit) {
757 return FALSE;
758 }
759 // Example indentifier for $cmds['target'] => "4:mypath/tomyfolder/myfile.jpg"
760 // for backwards compatibility: the combined file identifier was the path+filename
761 $fileIdentifier = $cmds['target'];
762 $fileObject = $this->getFileObject($fileIdentifier);
763 // Example indentifier for $cmds['target'] => "2:targetpath/targetfolder/"
764 $content = $cmds['data'];
765 if (!$fileObject instanceof File) {
766 $this->writelog(9, 2, 123, 'Target "%s" was not a file!', array($fileIdentifier));
767 return FALSE;
768 }
769 $extList = $GLOBALS['TYPO3_CONF_VARS']['SYS']['textfile_ext'];
770 if (!GeneralUtility::inList($extList, $fileObject->getExtension())) {
771 $this->writelog(9, 1, 102, 'File extension "%s" is not a textfile format! (%s)', array($fileObject->getExtension(), $extList));
772 return FALSE;
773 }
774 try {
775 $fileObject->setContents($content);
776 clearstatcache();
777 $this->writelog(9, 0, 1, 'File saved to "%s", bytes: %s, MD5: %s ', array($fileObject->getIdentifier(), $fileObject->getSize(), md5($content)));
778 return TRUE;
779 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
780 $this->writelog(9, 1, 104, 'You are not allowed to edit files!', '');
781 return FALSE;
782 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileWritePermissionsException $e) {
783 $this->writelog(9, 1, 100, 'File "%s" was not saved! Write-permission problem?', array($fileObject->getIdentifier()));
784 return FALSE;
785 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
786 $this->writelog(9, 1, 100, 'File "%s" was not saved! File extension rejected!', array($fileObject->getIdentifier()));
787 return FALSE;
788 }
789 }
790
791 /**
792 * Upload of files (action=1)
793 * when having multiple uploads (HTML5-style), the array $_FILES looks like this:
794 * Array(
795 * [upload_1] => Array(
796 * [name] => Array(
797 * [0] => GData - Content-Elements and Media-Gallery.pdf
798 * [1] => CMS Expo 2011.txt
799 * )
800 * [type] => Array(
801 * [0] => application/pdf
802 * [1] => text/plain
803 * )
804 * [tmp_name] => Array(
805 * [0] => /Applications/MAMP/tmp/php/phpNrOB43
806 * [1] => /Applications/MAMP/tmp/php/phpD2HQAK
807 * )
808 * [size] => Array(
809 * [0] => 373079
810 * [1] => 1291
811 * )
812 * )
813 * )
814 * in HTML you'd need sth like this: <input type="file" name="upload_1[]" multiple="true" />
815 *
816 * @param array $cmds $cmds['data'] is the ID-number (points to the global var that holds the filename-ref ($_FILES['upload_' . $id]['name']) . $cmds['target'] is the target directory, $cmds['charset'] is the the character set of the file name (utf-8 is needed for JS-interaction)
817 * @return File[] | FALSE Returns an array of new file objects upon success. False otherwise
818 */
819 public function func_upload($cmds) {
820 if (!$this->isInit) {
821 return FALSE;
822 }
823 $uploadPosition = $cmds['data'];
824 $uploadedFileData = $_FILES['upload_' . $uploadPosition];
825 if (empty($uploadedFileData['name']) || is_array($uploadedFileData['name']) && empty($uploadedFileData['name'][0])) {
826 $this->writelog(1, 2, 108, 'No file was uploaded!', '');
827 return FALSE;
828 }
829 // Example indentifier for $cmds['target'] => "2:targetpath/targetfolder/"
830 $targetFolderObject = $this->getFileObject($cmds['target']);
831 // Uploading with non HTML-5-style, thus, make an array out of it, so we can loop over it
832 if (!is_array($uploadedFileData['name'])) {
833 $uploadedFileData = array(
834 'name' => array($uploadedFileData['name']),
835 'type' => array($uploadedFileData['type']),
836 'tmp_name' => array($uploadedFileData['tmp_name']),
837 'size' => array($uploadedFileData['size'])
838 );
839 }
840 $resultObjects = array();
841 $numberOfUploadedFilesForPosition = count($uploadedFileData['name']);
842 // Loop through all uploaded files
843 for ($i = 0; $i < $numberOfUploadedFilesForPosition; $i++) {
844 $fileInfo = array(
845 'name' => $uploadedFileData['name'][$i],
846 'type' => $uploadedFileData['type'][$i],
847 'tmp_name' => $uploadedFileData['tmp_name'][$i],
848 'size' => $uploadedFileData['size'][$i]
849 );
850 try {
851 // @todo can be improved towards conflict mode naming
852 if ($this->dontCheckForUnique) {
853 $conflictMode = 'replace';
854 } else {
855 $conflictMode = 'cancel';
856 }
857 /** @var $fileObject File */
858 $fileObject = $targetFolderObject->addUploadedFile($fileInfo, $conflictMode);
859 $fileObject = ResourceFactory::getInstance()->getFileObjectByStorageAndIdentifier($targetFolderObject->getStorage()->getUid(), $fileObject->getIdentifier());
860 if ($conflictMode === 'replace') {
861 $this->getIndexer($fileObject->getStorage())->updateIndexEntry($fileObject);
862 }
863 $resultObjects[] = $fileObject;
864 $this->internalUploadMap[$uploadPosition] = $fileObject->getCombinedIdentifier();
865 $this->writelog(1, 0, 1, 'Uploading file "%s" to "%s"', array($fileInfo['name'], $targetFolderObject->getIdentifier()));
866 } catch (\TYPO3\CMS\Core\Resource\Exception\UploadException $e) {
867 $this->writelog(1, 2, 106, 'The upload has failed, no uploaded file found!', '');
868 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
869 $this->writelog(1, 1, 105, 'You are not allowed to upload files!', '');
870 } catch (\TYPO3\CMS\Core\Resource\Exception\UploadSizeException $e) {
871 $this->writelog(1, 1, 104, 'The uploaded file "%s" exceeds the size-limit', array($fileInfo['name']));
872 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException $e) {
873 $this->writelog(1, 1, 103, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier()));
874 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
875 $this->writelog(1, 1, 102, 'Extension of file name "%s" is not allowed in "%s"!', array($fileInfo['name'], $targetFolderObject->getIdentifier()));
876 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
877 $this->writelog(1, 1, 101, 'No unique filename available in "%s"!', array($targetFolderObject->getIdentifier()));
878 } catch (\RuntimeException $e) {
879 $this->writelog(1, 1, 100, 'Uploaded file could not be moved! Write-permission problem in "%s"?', array($targetFolderObject->getIdentifier()));
880 }
881 }
882
883 return $resultObjects;
884 }
885
886 /**
887 * Unzipping file (action=7)
888 * This is permitted only if the user has fullAccess or if the file resides
889 *
890 * @param array $cmds $cmds['data'] is the zip-file. $cmds['target'] is the target directory. If not set we'll default to the same directory as the file is in.
891 * @return bool Returns TRUE on success
892 */
893 public function func_unzip($cmds) {
894 if (!$this->isInit || $this->dont_use_exec_commands) {
895 return FALSE;
896 }
897 $theFile = $cmds['data'];
898 if (!@is_file($theFile)) {
899 $this->writelog(7, 2, 105, 'The file "%s" did not exist!', array($theFile));
900 return FALSE;
901 }
902 $fI = GeneralUtility::split_fileref($theFile);
903 if (!isset($cmds['target'])) {
904 $cmds['target'] = $fI['path'];
905 }
906 // Clean up destination directory
907 // !!! Method has been put in the local driver, can be saftely removed
908 $theDest = $this->is_directory($cmds['target']);
909 if (!$theDest) {
910 $this->writelog(7, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
911 return FALSE;
912 }
913 if (!$this->actionPerms['unzipFile']) {
914 $this->writelog(7, 1, 103, 'You are not allowed to unzip files', '');
915 return FALSE;
916 }
917 if ($fI['fileext'] != 'zip') {
918 $this->writelog(7, 1, 102, 'File extension is not "zip"', '');
919 return FALSE;
920 }
921 if (!$this->checkIfFullAccess($theDest)) {
922 $this->writelog(7, 1, 101, 'You don\'t have full access to the destination directory "%s"!', array($theDest));
923 return FALSE;
924 }
925 // !!! Method has been put in the sotrage driver, can be saftely removed
926 if ($this->checkPathAgainstMounts($theFile) && $this->checkPathAgainstMounts($theDest . '/')) {
927 // No way to do this under windows.
928 $cmd = $this->unzipPath . 'unzip -qq ' . escapeshellarg($theFile) . ' -d ' . escapeshellarg($theDest);
929 CommandUtility::exec($cmd);
930 $this->writelog(7, 0, 1, 'Unzipping file "%s" in "%s"', array($theFile, $theDest));
931 return TRUE;
932 } else {
933 $this->writelog(7, 1, 100, 'File "%s" or destination "%s" was not within your mountpoints!', array($theFile, $theDest));
934 return FALSE;
935 }
936 }
937
938 /**
939 * Add flash message to message queue
940 *
941 * @param FlashMessage $flashMessage
942 * @return void
943 */
944 protected function addFlashMessage(FlashMessage $flashMessage) {
945 /** @var $flashMessageService FlashMessageService */
946 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
947
948 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
949 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
950 $defaultFlashMessageQueue->enqueue($flashMessage);
951 }
952
953 /**
954 * Gets Indexer
955 *
956 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
957 * @return \TYPO3\CMS\Core\Resource\Index\Indexer
958 */
959 protected function getIndexer(ResourceStorage $storage) {
960 return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Index\Indexer::class, $storage);
961 }
962
963 /**
964 * Get database connection
965 *
966 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
967 */
968 protected function getDatabaseConnection() {
969 return $GLOBALS['TYPO3_DB'];
970 }
971
972 /**
973 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
974 */
975 protected function getBackendUser() {
976 return $GLOBALS['BE_USER'];
977 }
978
979 }