[FOLLOWUP][TASK] Remove leftover unzipping core functionality
[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\Core\Messaging\FlashMessage;
19 use TYPO3\CMS\Core\Messaging\FlashMessageService;
20 use TYPO3\CMS\Core\Resource\DuplicationBehavior;
21 use TYPO3\CMS\Core\Resource\Exception;
22 use TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException;
23 use TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException;
24 use TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException;
25 use TYPO3\CMS\Core\Resource\Exception\InsufficientFileWritePermissionsException;
26 use TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException;
27 use TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException;
28 use TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException;
29 use TYPO3\CMS\Core\Resource\Exception\InvalidFileNameException;
30 use TYPO3\CMS\Core\Resource\Exception\NotInMountPointException;
31 use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
32 use TYPO3\CMS\Core\Resource\Exception\UploadException;
33 use TYPO3\CMS\Core\Resource\Exception\UploadSizeException;
34 use TYPO3\CMS\Core\Resource\File;
35 use TYPO3\CMS\Core\Resource\Folder;
36 use TYPO3\CMS\Core\Resource\ResourceFactory;
37 use TYPO3\CMS\Core\Resource\ResourceStorage;
38 use TYPO3\CMS\Core\Type\Exception\InvalidEnumerationValueException;
39 use TYPO3\CMS\Core\Utility\CommandUtility;
40 use TYPO3\CMS\Core\Utility\GeneralUtility;
41 use TYPO3\CMS\Lang\LanguageService;
42
43 /**
44 * Contains functions for performing file operations like copying, pasting, uploading, moving,
45 * deleting etc. through the TCE
46 *
47 * See document "TYPO3 Core API" for syntax
48 *
49 * This class contains functions primarily used by tce_file.php (TYPO3 Core Engine for file manipulation)
50 * Functions include copying, moving, deleting, uploading and so on...
51 *
52 * Important internal variables:
53 *
54 * $filemounts (see basicFileFunctions)
55 * $f_ext (see basicFileFunctions)
56 *
57 * All fileoperations must be within the filemount-paths. Further the fileextension
58 * MUST validate TRUE with the f_ext array
59 *
60 * The unzip-function allows unzip only if the destination path has it's f_ext[]['allow'] set to '*'!!
61 * You are allowed to copy/move folders within the same 'space' (web/ftp).
62 * You are allowed to copy/move folders between spaces (web/ftp) IF the destination has it's f_ext[]['allow'] set to '*'!
63 *
64 * Advice:
65 * 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.
66 * 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
67 * For example this is a bad idea: you have an ftp-space that is '/www/' and a web-space that is '/www/htdocs/'
68 */
69 class ExtendedFileUtility extends BasicFileUtility
70 {
71 /**
72 * Defines behaviour when uploading files with names that already exist; possible values are
73 * the values of the \TYPO3\CMS\Core\Resource\DuplicationBehavior enumeration
74 *
75 * @var \TYPO3\CMS\Core\Resource\DuplicationBehavior
76 */
77 protected $existingFilesConflictMode;
78
79 /**
80 * This array is self-explaining (look in the class below).
81 * It grants access to the functions. This could be set from outside in order to enabled functions to users.
82 * See also the function setActionPermissions() which takes input directly from the user-record
83 *
84 * @var array
85 */
86 public $actionPerms = array(
87 // File permissions
88 'addFile' => false,
89 'readFile' => false,
90 'writeFile' => false,
91 'copyFile' => false,
92 'moveFile' => false,
93 'renameFile' => false,
94 'deleteFile' => false,
95 // Folder permissions
96 'addFolder' => false,
97 'readFolder' => false,
98 'writeFolder' => false,
99 'copyFolder' => false,
100 'moveFolder' => false,
101 'renameFolder' => false,
102 'deleteFolder' => false,
103 'recursivedeleteFolder' => false
104 );
105
106 /**
107 * This is regarded to be the recycler folder
108 *
109 * @var string
110 */
111 public $recyclerFN = '_recycler_';
112
113 /**
114 * Will contain map between upload ID and the final filename
115 *
116 * @var array
117 */
118 public $internalUploadMap = array();
119
120 /**
121 * @var string
122 */
123 public $lastError = '';
124
125 /**
126 * All error messages from the file operations of this script instance
127 *
128 * @var array
129 */
130 protected $errorMessages = array();
131
132 /**
133 * Container for FlashMessages so they can be localized
134 *
135 * @var array
136 */
137 protected $flashMessages = [];
138
139 /**
140 * @var array
141 */
142 protected $fileCmdMap;
143
144 /**
145 * The File Factory
146 *
147 * @var \TYPO3\CMS\Core\Resource\ResourceFactory
148 */
149 protected $fileFactory;
150
151 /**
152 * Get existingFilesConflictMode
153 *
154 * @return string
155 */
156 public function getExistingFilesConflictMode()
157 {
158 return (string)$this->existingFilesConflictMode;
159 }
160
161 /**
162 * Set existingFilesConflictMode
163 *
164 * @param \TYPO3\CMS\Core\Resource\DuplicationBehavior|string $existingFilesConflictMode Instance or constant of \TYPO3\CMS\Core\Resource\DuplicationBehavior
165 * @return void
166 * @throws Exception
167 */
168 public function setExistingFilesConflictMode($existingFilesConflictMode)
169 {
170 try {
171 $this->existingFilesConflictMode = DuplicationBehavior::cast($existingFilesConflictMode);
172 } catch (InvalidEnumerationValueException $e) {
173 throw new Exception(
174 sprintf(
175 'Invalid argument, received: "%s", expected a value from enumeration \TYPO3\CMS\Core\Resource\DuplicationBehavior (%s)',
176 $existingFilesConflictMode,
177 implode(', ', DuplicationBehavior::getConstants())
178 )
179 );
180 }
181 }
182
183 /**
184 * Initialization of the class
185 *
186 * @param array $fileCmds Array with the commands to execute. See "TYPO3 Core API" document
187 * @return void
188 */
189 public function start($fileCmds)
190 {
191 // Initialize Object Factory
192 $this->fileFactory = ResourceFactory::getInstance();
193 // Initializing file processing commands:
194 $this->fileCmdMap = $fileCmds;
195 }
196
197 /**
198 * Sets the file action permissions.
199 * If no argument is given, permissions of the currently logged in backend user are taken into account.
200 *
201 * @param array $permissions File Permissions.
202 * @return void
203 */
204 public function setActionPermissions(array $permissions = array())
205 {
206 if (empty($permissions)) {
207 $permissions = $this->getBackendUser()->getFilePermissions();
208 }
209 $this->actionPerms = $permissions;
210 }
211
212 /**
213 * Processing the command array in $this->fileCmdMap
214 *
215 * @return mixed FALSE, if the file functions were not initialized
216 * @throws \UnexpectedValueException
217 */
218 public function processData()
219 {
220 $result = array();
221 if (!$this->isInit) {
222 return false;
223 }
224 if (is_array($this->fileCmdMap)) {
225 // Check if there were uploads expected, but no one made
226 if ($this->fileCmdMap['upload']) {
227 $uploads = $this->fileCmdMap['upload'];
228 foreach ($uploads as $upload) {
229 if (empty($_FILES['upload_' . $upload['data']]['name'])
230 || (is_array($_FILES['upload_' . $upload['data']]['name'])
231 && empty($_FILES['upload_' . $upload['data']]['name'][0])
232 )
233 ) {
234 unset($this->fileCmdMap['upload'][$upload['data']]);
235 }
236 }
237 if (empty($this->fileCmdMap['upload'])) {
238 $this->writeLog(1, 1, 108, 'No file was uploaded!', '');
239 $this->addMessageToFlashMessageQueue('FileUtility.NoFileWasUploaded');
240 }
241 }
242
243 // Check if there were new folder names expected, but non given
244 if ($this->fileCmdMap['newfolder']) {
245 foreach ($this->fileCmdMap['newfolder'] as $key => $cmdArr) {
246 if (empty($cmdArr['data'])) {
247 unset($this->fileCmdMap['newfolder'][$key]);
248 }
249 }
250 if (empty($this->fileCmdMap['newfolder'])) {
251 $this->writeLog(6, 1, 108, 'No name for new folder given!', '');
252 $this->addMessageToFlashMessageQueue('FileUtility.NoNameForNewFolderGiven');
253 }
254 }
255
256 // Traverse each set of actions
257 foreach ($this->fileCmdMap as $action => $actionData) {
258 // Traverse all action data. More than one file might be affected at the same time.
259 if (is_array($actionData)) {
260 $result[$action] = array();
261 foreach ($actionData as $cmdArr) {
262 // Clear file stats
263 clearstatcache();
264 // Branch out based on command:
265 switch ($action) {
266 case 'delete':
267 $result[$action][] = $this->func_delete($cmdArr);
268 break;
269 case 'copy':
270 $result[$action][] = $this->func_copy($cmdArr);
271 break;
272 case 'move':
273 $result[$action][] = $this->func_move($cmdArr);
274 break;
275 case 'rename':
276 $result[$action][] = $this->func_rename($cmdArr);
277 break;
278 case 'newfolder':
279 $result[$action][] = $this->func_newfolder($cmdArr);
280 break;
281 case 'newfile':
282 $result[$action][] = $this->func_newfile($cmdArr);
283 break;
284 case 'editfile':
285 $result[$action][] = $this->func_edit($cmdArr);
286 break;
287 case 'upload':
288 $result[$action][] = $this->func_upload($cmdArr);
289 break;
290 case 'replace':
291 $result[$action][] = $this->replaceFile($cmdArr);
292 break;
293 }
294 // Hook for post-processing the action
295 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'])) {
296 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'] as $classRef) {
297 $hookObject = GeneralUtility::getUserObj($classRef);
298 if (!$hookObject instanceof ExtendedFileUtilityProcessDataHookInterface) {
299 throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\Utility\\File\\ExtendedFileUtilityProcessDataHookInterface', 1279719168);
300 }
301 $hookObject->processData_postProcessAction($action, $cmdArr, $result[$action], $this);
302 }
303 }
304 }
305 }
306 }
307 }
308 return $result;
309 }
310
311 /**
312 * Adds all log error messages from the operations of this script instance to the FlashMessageQueue
313 *
314 * @return void
315 */
316 public function pushErrorMessagesToFlashMessageQueue()
317 {
318 foreach ($this->getErrorMessages() as $msg) {
319 $flashMessage = GeneralUtility::makeInstance(
320 FlashMessage::class,
321 $msg,
322 '',
323 FlashMessage::ERROR,
324 true
325 );
326 $this->addFlashMessage($flashMessage);
327 }
328 }
329
330 /**
331 * Return all error messages from the file operations of this script instance
332 *
333 * @return array all errorMessages as a numerical array
334 */
335 public function getErrorMessages()
336 {
337 return $this->errorMessages;
338 }
339
340 /**
341 * @param int $action The action number. See the functions in the class for a hint. Eg. edit is '9', upload is '1' ...
342 * @param int $error The severity: 0 = message, 1 = error, 2 = System Error, 3 = security notice (admin)
343 * @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.
344 * @param string $details This is the default, raw error message in english
345 * @param array $data Array with special information that may go into $details by "%s" marks / sprintf() when the log is shown
346 * @return void
347 */
348 public function writeLog($action, $error, $details_nr, $details, $data)
349 {
350 // Type value for tce_file.php
351 $type = 2;
352 if (is_object($this->getBackendUser())) {
353 $this->getBackendUser()->writelog($type, $action, $error, $details_nr, $details, $data);
354 }
355 if ($error > 0) {
356 $this->lastError = vsprintf($details, $data);
357 $this->errorMessages[] = $this->lastError;
358 }
359 }
360
361 /**
362 * Adds a localized FlashMessage to the message queue
363 *
364 * @param string $localizationKey
365 * @param array $replaceMarkers
366 * @param int $severity
367 * @throws \InvalidArgumentException
368 */
369 protected function addMessageToFlashMessageQueue($localizationKey, array $replaceMarkers = [], $severity = FlashMessage::ERROR)
370 {
371 $label = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/fileMessages.xlf:' . $localizationKey);
372 $message = vsprintf($label, $replaceMarkers);
373 $flashMessage = GeneralUtility::makeInstance(
374 FlashMessage::class,
375 $message,
376 '',
377 $severity,
378 true
379 );
380 $this->addFlashMessage($flashMessage);
381 }
382
383 /*************************************
384 *
385 * File operation functions
386 *
387 **************************************/
388 /**
389 * Deleting files and folders (action=4)
390 *
391 * @param array $cmds $cmds['data'] is the file/folder to delete
392 * @return bool Returns TRUE upon success
393 */
394 public function func_delete(array $cmds)
395 {
396 $result = false;
397 if (!$this->isInit) {
398 return $result;
399 }
400 // Example indentifier for $cmds['data'] => "4:mypath/tomyfolder/myfile.jpg"
401 // for backwards compatibility: the combined file identifier was the path+filename
402 try {
403 $fileObject = $this->getFileObject($cmds['data']);
404 } catch (ResourceDoesNotExistException $e) {
405 $flashMessage = GeneralUtility::makeInstance(
406 FlashMessage::class,
407 sprintf(
408 $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.description.fileNotFound'),
409 $cmds['data']
410 ),
411 $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.header.fileNotFound'),
412 FlashMessage::ERROR,
413 true
414 );
415 $this->addFlashMessage($flashMessage);
416
417 return false;
418 }
419 // @todo implement the recycler feature which has been removed from the original implementation
420 // checks to delete the file
421 if ($fileObject instanceof File) {
422 // check if the file still has references
423 // Exclude sys_file_metadata records as these are no use references
424 $databaseConnection = $this->getDatabaseConnection();
425 $table = 'sys_refindex';
426 $refIndexRecords = $databaseConnection->exec_SELECTgetRows(
427 '*',
428 $table,
429 'deleted=0 AND ref_table=' . $databaseConnection->fullQuoteStr('sys_file', $table)
430 . ' AND ref_uid=' . (int)$fileObject->getUid()
431 . ' AND tablename != ' . $databaseConnection->fullQuoteStr('sys_file_metadata', $table)
432 );
433 $deleteFile = true;
434 if (!empty($refIndexRecords)) {
435 $shortcutContent = array();
436 $brokenReferences = array();
437
438 foreach ($refIndexRecords as $fileReferenceRow) {
439 if ($fileReferenceRow['tablename'] === 'sys_file_reference') {
440 $row = $this->transformFileReferenceToRecordReference($fileReferenceRow);
441 $shortcutRecord = BackendUtility::getRecord($row['tablename'], $row['recuid']);
442
443 if ($shortcutRecord) {
444 $shortcutContent[] = '[record:' . $row['tablename'] . ':' . $row['recuid'] . ']';
445 } else {
446 $brokenReferences[] = $fileReferenceRow['ref_uid'];
447 }
448 }
449 }
450 if (!empty($brokenReferences)) {
451 // render a message that the file has broken references
452 $flashMessage = GeneralUtility::makeInstance(
453 FlashMessage::class,
454 sprintf($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.description.fileHasBrokenReferences'), count($brokenReferences)),
455 $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.header.fileHasBrokenReferences'),
456 FlashMessage::INFO,
457 true
458 );
459 $this->addFlashMessage($flashMessage);
460 }
461 if (!empty($shortcutContent)) {
462 // render a message that the file could not be deleted
463 $flashMessage = GeneralUtility::makeInstance(
464 FlashMessage::class,
465 sprintf($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.description.fileNotDeletedHasReferences'), $fileObject->getName()) . ' ' . implode(', ', $shortcutContent),
466 $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.header.fileNotDeletedHasReferences'),
467 FlashMessage::WARNING,
468 true
469 );
470 $this->addFlashMessage($flashMessage);
471 $deleteFile = false;
472 }
473 }
474
475 if ($deleteFile) {
476 try {
477 $result = $fileObject->delete();
478
479 // show the user that the file was deleted
480 $flashMessage = GeneralUtility::makeInstance(
481 FlashMessage::class,
482 sprintf($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.description.fileDeleted'), $fileObject->getName()),
483 $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.header.fileDeleted'),
484 FlashMessage::OK,
485 true
486 );
487 $this->addFlashMessage($flashMessage);
488 // Log success
489 $this->writeLog(4, 0, 1, 'File "%s" deleted', array($fileObject->getIdentifier()));
490 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
491 $this->writeLog(4, 1, 112, 'You are not allowed to access the file', array($fileObject->getIdentifier()));
492 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToAccessTheFile', array($fileObject->getIdentifier()));
493 } catch (NotInMountPointException $e) {
494 $this->writeLog(4, 1, 111, 'Target was not within your mountpoints! T="%s"', array($fileObject->getIdentifier()));
495 $this->addMessageToFlashMessageQueue('FileUtility.TargetWasNotWithinYourMountpoints', array($fileObject->getIdentifier()));
496 } catch (\RuntimeException $e) {
497 $this->writeLog(4, 1, 110, 'Could not delete file "%s". Write-permission problem?', array($fileObject->getIdentifier()));
498 $this->addMessageToFlashMessageQueue('FileUtility.CouldNotDeleteFile', array($fileObject->getIdentifier()));
499 }
500 }
501 } else {
502 /** @var Folder $fileObject */
503 if (!$this->folderHasFilesInUse($fileObject)) {
504 try {
505 $result = $fileObject->delete(true);
506 if ($result) {
507 // notify the user that the folder was deleted
508 /** @var FlashMessage $flashMessage */
509 $flashMessage = GeneralUtility::makeInstance(
510 FlashMessage::class,
511 sprintf($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.description.folderDeleted'), $fileObject->getName()),
512 $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.header.folderDeleted'),
513 FlashMessage::OK,
514 true
515 );
516 $this->addFlashMessage($flashMessage);
517 // Log success
518 $this->writeLog(4, 0, 3, 'Directory "%s" deleted', array($fileObject->getIdentifier()));
519 }
520 } catch (InsufficientUserPermissionsException $e) {
521 $this->writeLog(4, 1, 120, 'Could not delete directory! Is directory "%s" empty? (You are not allowed to delete directories recursively).', array($fileObject->getIdentifier()));
522 $this->addMessageToFlashMessageQueue('FileUtility.CouldNotDeleteDirectory', array($fileObject->getIdentifier()));
523 } catch (InsufficientFolderAccessPermissionsException $e) {
524 $this->writeLog(4, 1, 123, 'You are not allowed to access the directory', array($fileObject->getIdentifier()));
525 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToAccessTheDirectory', array($fileObject->getIdentifier()));
526 } catch (NotInMountPointException $e) {
527 $this->writeLog(4, 1, 121, 'Target was not within your mountpoints! T="%s"', array($fileObject->getIdentifier()));
528 $this->addMessageToFlashMessageQueue('FileUtility.TargetWasNotWithinYourMountpoints', array($fileObject->getIdentifier()));
529 } catch (\TYPO3\CMS\Core\Resource\Exception\FileOperationErrorException $e) {
530 $this->writeLog(4, 1, 120, 'Could not delete directory "%s"! Write-permission problem?', array($fileObject->getIdentifier()));
531 $this->addMessageToFlashMessageQueue('FileUtility.CouldNotDeleteDirectory', array($fileObject->getIdentifier()));
532 }
533 }
534 }
535
536 return $result;
537 }
538
539 /**
540 * Checks files in given folder recursively for for existing references.
541 *
542 * Creates a flash message if there are references.
543 *
544 * @param Folder $folder
545 * @return bool TRUE if folder has files in use, FALSE otherwise
546 */
547 public function folderHasFilesInUse(Folder $folder)
548 {
549 $files = $folder->getFiles(0, 0, Folder::FILTER_MODE_USE_OWN_AND_STORAGE_FILTERS, true);
550 if (empty($files)) {
551 return false;
552 }
553
554 /** @var int[] $fileUids */
555 $fileUids = array();
556 foreach ($files as $file) {
557 $fileUids[] = $file->getUid();
558 }
559 $numberOfReferences = $this->getDatabaseConnection()->exec_SELECTcountRows(
560 '*',
561 'sys_refindex',
562 'deleted=0 AND ref_table="sys_file" AND ref_uid IN (' . implode(',', $fileUids) . ') AND tablename<>"sys_file_metadata"'
563 );
564
565 $hasReferences = $numberOfReferences > 0;
566 if ($hasReferences) {
567 /** @var FlashMessage $flashMessage */
568 $flashMessage = GeneralUtility::makeInstance(
569 FlashMessage::class,
570 $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.description.folderNotDeletedHasFilesWithReferences'),
571 $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:message.header.folderNotDeletedHasFilesWithReferences'),
572 FlashMessage::WARNING,
573 true
574 );
575 $this->addFlashMessage($flashMessage);
576 }
577
578 return $hasReferences;
579 }
580
581 /**
582 * Maps results from the fal file reference table on the
583 * structure of the normal reference index table.
584 *
585 * @param array $referenceRecord
586 * @return array
587 */
588 protected function transformFileReferenceToRecordReference(array $referenceRecord)
589 {
590 $fileReference = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
591 '*',
592 'sys_file_reference',
593 'uid=' . (int)$referenceRecord['recuid']
594 );
595 return array(
596 'recuid' => $fileReference['uid_foreign'],
597 'tablename' => $fileReference['tablenames'],
598 'field' => $fileReference['fieldname'],
599 'flexpointer' => '',
600 'softref_key' => '',
601 'sorting' => $fileReference['sorting_foreign']
602 );
603 }
604
605 /**
606 * Gets a File or a Folder object from an identifier [storage]:[fileId]
607 *
608 * @param string $identifier
609 * @return File|Folder
610 * @throws Exception\InsufficientFileAccessPermissionsException
611 * @throws Exception\InvalidFileException
612 */
613 protected function getFileObject($identifier)
614 {
615 $object = $this->fileFactory->retrieveFileOrFolderObject($identifier);
616 if (!is_object($object)) {
617 throw new \TYPO3\CMS\Core\Resource\Exception\InvalidFileException('The item ' . $identifier . ' was not a file or directory!!', 1320122453);
618 }
619 if ($object->getStorage()->getUid() === 0) {
620 throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException('You are not allowed to access files outside your storages', 1375889830);
621 }
622 return $object;
623 }
624
625 /**
626 * Copying files and folders (action=2)
627 *
628 * $cmds['data'] (string): The file/folder to copy
629 * + example "4:mypath/tomyfolder/myfile.jpg")
630 * + for backwards compatibility: the identifier was the path+filename
631 * $cmds['target'] (string): The path where to copy to.
632 * + example "2:targetpath/targetfolder/"
633 * $cmds['altName'] (string): Use an alternative name if the target already exists
634 *
635 * @param array $cmds Command details as described above
636 * @return \TYPO3\CMS\Core\Resource\File
637 */
638 protected function func_copy($cmds)
639 {
640 if (!$this->isInit) {
641 return false;
642 }
643 $sourceFileObject = $this->getFileObject($cmds['data']);
644 /** @var $targetFolderObject \TYPO3\CMS\Core\Resource\Folder */
645 $targetFolderObject = $this->getFileObject($cmds['target']);
646 // Basic check
647 if (!$targetFolderObject instanceof Folder) {
648 $this->writeLog(2, 2, 100, 'Destination "%s" was not a directory', array($cmds['target']));
649 $this->addMessageToFlashMessageQueue('FileUtility.DestinationWasNotADirectory', array($cmds['target']));
650 return false;
651 }
652 // If this is TRUE, we append _XX to the file name if
653 $appendSuffixOnConflict = (string)$cmds['altName'];
654 $resultObject = null;
655 $conflictMode = $appendSuffixOnConflict !== '' ? DuplicationBehavior::RENAME : DuplicationBehavior::CANCEL;
656 // Copying the file
657 if ($sourceFileObject instanceof File) {
658 try {
659 $resultObject = $sourceFileObject->copyTo($targetFolderObject, null, $conflictMode);
660 } catch (InsufficientUserPermissionsException $e) {
661 $this->writeLog(2, 1, 114, 'You are not allowed to copy files', '');
662 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCopyFiles');
663 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
664 $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()));
665 $this->addMessageToFlashMessageQueue('FileUtility.CouldNotAccessAllNecessaryResources', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
666 } catch (IllegalFileExtensionException $e) {
667 $this->writeLog(2, 1, 111, 'Extension of file name "%s" is not allowed in "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
668 $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameIsNotAllowedIn', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
669 } catch (ExistingTargetFileNameException $e) {
670 $this->writeLog(2, 1, 112, 'File "%s" already exists in folder "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
671 $this->addMessageToFlashMessageQueue('FileUtility.FileAlreadyExistsInFolder', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
672 } catch (\BadMethodCallException $e) {
673 $this->writeLog(3, 1, 128, 'The function to copy a file between storages is not yet implemented', array());
674 $this->addMessageToFlashMessageQueue('FileUtility.TheFunctionToCopyAFileBetweenStoragesIsNotYetImplemented');
675 } catch (\RuntimeException $e) {
676 $this->writeLog(2, 2, 109, 'File "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
677 $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotCopiedTo', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
678 }
679 if ($resultObject) {
680 $this->writeLog(2, 0, 1, 'File "%s" copied to "%s"', array($sourceFileObject->getIdentifier(), $resultObject->getIdentifier()));
681 $this->addMessageToFlashMessageQueue('FileUtility.FileCopiedTo', array($sourceFileObject->getIdentifier(), $resultObject->getIdentifier()), FlashMessage::OK);
682 }
683 } else {
684 // Else means this is a Folder
685 $sourceFolderObject = $sourceFileObject;
686 try {
687 $resultObject = $sourceFolderObject->copyTo($targetFolderObject, null, $conflictMode);
688 } catch (InsufficientUserPermissionsException $e) {
689 $this->writeLog(2, 1, 125, 'You are not allowed to copy directories', '');
690 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCopyDirectories');
691 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
692 $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()));
693 $this->addMessageToFlashMessageQueue('FileUtility.CouldNotAccessAllNecessaryResources', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
694 } catch (InsufficientFolderAccessPermissionsException $e) {
695 $this->writeLog(2, 1, 121, 'You don\'t have full access to the destination directory "%s"!', array($targetFolderObject->getIdentifier()));
696 $this->addMessageToFlashMessageQueue('FileUtility.YouDontHaveFullAccessToTheDestinationDirectory', array($targetFolderObject->getIdentifier()));
697 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException $e) {
698 $this->writeLog(2, 1, 122, 'Cannot copy folder "%s" into target folder "%s", because the target folder is already within the folder to be copied!', array($sourceFolderObject->getName(), $targetFolderObject->getName()));
699 $this->addMessageToFlashMessageQueue('FileUtility.CannotCopyFolderIntoTargetFolderBecauseTheTargetFolderIsAlreadyWithinTheFolderToBeCopied', array($sourceFolderObject->getName(), $targetFolderObject->getName()));
700 } catch (ExistingTargetFolderException $e) {
701 $this->writeLog(2, 1, 123, 'Target "%s" already exists!', array($targetFolderObject->getIdentifier()));
702 $this->addMessageToFlashMessageQueue('FileUtility.TargetAlreadyExists', array($targetFolderObject->getIdentifier()));
703 } catch (\BadMethodCallException $e) {
704 $this->writeLog(3, 1, 129, 'The function to copy a folder between storages is not yet implemented', array());
705 $this->addMessageToFlashMessageQueue('FileUtility.TheFunctionToCopyAFolderBetweenStoragesIsNotYetImplemented');
706 } catch (\RuntimeException $e) {
707 $this->writeLog(2, 2, 119, 'Directory "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
708 $this->addMessageToFlashMessageQueue('FileUtility.DirectoryWasNotCopiedTo', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
709 }
710 if ($resultObject) {
711 $this->writeLog(2, 0, 2, 'Directory "%s" copied to "%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
712 $this->addMessageToFlashMessageQueue('FileUtility.DirectoryCopiedTo', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()), FlashMessage::OK);
713 }
714 }
715 return $resultObject;
716 }
717
718 /**
719 * Moving files and folders (action=3)
720 *
721 * $cmds['data'] (string): The file/folder to move
722 * + example "4:mypath/tomyfolder/myfile.jpg")
723 * + for backwards compatibility: the identifier was the path+filename
724 * $cmds['target'] (string): The path where to move to.
725 * + example "2:targetpath/targetfolder/"
726 * $cmds['altName'] (string): Use an alternative name if the target already exists
727 *
728 * @param array $cmds Command details as described above
729 * @return \TYPO3\CMS\Core\Resource\File
730 */
731 protected function func_move($cmds)
732 {
733 if (!$this->isInit) {
734 return false;
735 }
736 $sourceFileObject = $this->getFileObject($cmds['data']);
737 $targetFolderObject = $this->getFileObject($cmds['target']);
738 // Basic check
739 if (!$targetFolderObject instanceof Folder) {
740 $this->writeLog(3, 2, 100, 'Destination "%s" was not a directory', array($cmds['target']));
741 $this->addMessageToFlashMessageQueue('FileUtility.DestinationWasNotADirectory', array($cmds['target']));
742 return false;
743 }
744 $alternativeName = (string)$cmds['altName'];
745 $resultObject = null;
746 // Moving the file
747 if ($sourceFileObject instanceof File) {
748 try {
749 if ($alternativeName !== '') {
750 // Don't allow overwriting existing files, but find a new name
751 $resultObject = $sourceFileObject->moveTo($targetFolderObject, $alternativeName, DuplicationBehavior::RENAME);
752 } else {
753 // Don't allow overwriting existing files
754 $resultObject = $sourceFileObject->moveTo($targetFolderObject, null, DuplicationBehavior::CANCEL);
755 }
756 $this->writeLog(3, 0, 1, 'File "%s" moved to "%s"', array($sourceFileObject->getIdentifier(), $resultObject->getIdentifier()));
757 $this->addMessageToFlashMessageQueue('FileUtility.FileMovedTo', array($sourceFileObject->getIdentifier(), $resultObject->getIdentifier()), FlashMessage::OK);
758 } catch (InsufficientUserPermissionsException $e) {
759 $this->writeLog(3, 1, 114, 'You are not allowed to move files', '');
760 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToMoveFiles');
761 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
762 $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()));
763 $this->addMessageToFlashMessageQueue('FileUtility.CouldNotAccessAllNecessaryResources', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
764 } catch (IllegalFileExtensionException $e) {
765 $this->writeLog(3, 1, 111, 'Extension of file name "%s" is not allowed in "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
766 $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameIsNotAllowedIn', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
767 } catch (ExistingTargetFileNameException $e) {
768 $this->writeLog(3, 1, 112, 'File "%s" already exists in folder "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
769 $this->addMessageToFlashMessageQueue('FileUtility.FileAlreadyExistsInFolder', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
770 } catch (\BadMethodCallException $e) {
771 $this->writeLog(3, 1, 126, 'The function to move a file between storages is not yet implemented', array());
772 $this->addMessageToFlashMessageQueue('FileUtility.TheFunctionToMoveAFileBetweenStoragesIsNotYetImplemented');
773 } catch (\RuntimeException $e) {
774 $this->writeLog(3, 2, 109, 'File "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
775 $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotCopiedTo', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
776 }
777 } else {
778 // Else means this is a Folder
779 $sourceFolderObject = $sourceFileObject;
780 try {
781 if ($alternativeName !== '') {
782 // Don't allow overwriting existing files, but find a new name
783 $resultObject = $sourceFolderObject->moveTo($targetFolderObject, $alternativeName, DuplicationBehavior::RENAME);
784 } else {
785 // Don't allow overwriting existing files
786 $resultObject = $sourceFolderObject->moveTo($targetFolderObject, null, DuplicationBehavior::RENAME);
787 }
788 $this->writeLog(3, 0, 2, 'Directory "%s" moved to "%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
789 $this->addMessageToFlashMessageQueue('FileUtility.DirectoryMovedTo', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()), FlashMessage::OK);
790 } catch (InsufficientUserPermissionsException $e) {
791 $this->writeLog(3, 1, 125, 'You are not allowed to move directories', '');
792 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToMoveDirectories');
793 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
794 $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()));
795 $this->addMessageToFlashMessageQueue('FileUtility.CouldNotAccessAllNecessaryResources', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
796 } catch (InsufficientFolderAccessPermissionsException $e) {
797 $this->writeLog(3, 1, 121, 'You don\'t have full access to the destination directory "%s"!', array($targetFolderObject->getIdentifier()));
798 $this->addMessageToFlashMessageQueue('FileUtility.YouDontHaveFullAccessToTheDestinationDirectory', array($targetFolderObject->getIdentifier()));
799 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException $e) {
800 $this->writeLog(3, 1, 122, 'Cannot move folder "%s" into target folder "%s", because the target folder is already within the folder to be moved!', array($sourceFolderObject->getName(), $targetFolderObject->getName()));
801 $this->addMessageToFlashMessageQueue('FileUtility.CannotMoveFolderIntoTargetFolderBecauseTheTargetFolderIsAlreadyWithinTheFolderToBeMoved', array($sourceFolderObject->getName(), $targetFolderObject->getName()));
802 } catch (ExistingTargetFolderException $e) {
803 $this->writeLog(3, 1, 123, 'Target "%s" already exists!', array($targetFolderObject->getIdentifier()));
804 $this->addMessageToFlashMessageQueue('FileUtility.TargetAlreadyExists', array($targetFolderObject->getIdentifier()));
805 } catch (\BadMethodCallException $e) {
806 $this->writeLog(3, 1, 127, 'The function to move a folder between storages is not yet implemented', array());
807 $this->addMessageToFlashMessageQueue('FileUtility.TheFunctionToMoveAFolderBetweenStoragesIsNotYetImplemented', array());
808 } catch (\RuntimeException $e) {
809 $this->writeLog(3, 2, 119, 'Directory "%s" WAS NOT moved to "%s"! Write-permission problem?', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
810 $this->addMessageToFlashMessageQueue('FileUtility.DirectoryWasNotMovedTo', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
811 }
812 }
813 return $resultObject;
814 }
815
816 /**
817 * Renaming files or foldes (action=5)
818 *
819 * $cmds['data'] (string): The file/folder to copy
820 * + example "4:mypath/tomyfolder/myfile.jpg")
821 * + for backwards compatibility: the identifier was the path+filename
822 * $cmds['target'] (string): New name of the file/folder
823 *
824 * @param array $cmds Command details as described above
825 * @return \TYPO3\CMS\Core\Resource\File Returns the new file upon success
826 */
827 public function func_rename($cmds)
828 {
829 if (!$this->isInit) {
830 return false;
831 }
832 $sourceFileObject = $this->getFileObject($cmds['data']);
833 $sourceFile = $sourceFileObject->getName();
834 $targetFile = $cmds['target'];
835 $resultObject = null;
836 if ($sourceFileObject instanceof File) {
837 try {
838 // Try to rename the File
839 $resultObject = $sourceFileObject->rename($targetFile);
840 $this->writeLog(5, 0, 1, 'File renamed from "%s" to "%s"', array($sourceFile, $targetFile));
841 $this->addMessageToFlashMessageQueue('FileUtility.FileRenamedFromTo', array($sourceFile, $targetFile), FlashMessage::OK);
842 } catch (InsufficientUserPermissionsException $e) {
843 $this->writeLog(5, 1, 102, 'You are not allowed to rename files!', '');
844 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToRenameFiles');
845 } catch (IllegalFileExtensionException $e) {
846 $this->writeLog(5, 1, 101, 'Extension of file name "%s" or "%s" was not allowed!', array($sourceFileObject->getName(), $targetFile));
847 $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameOrWasNotAllowed', array($sourceFileObject->getName(), $targetFile));
848 } catch (ExistingTargetFileNameException $e) {
849 $this->writeLog(5, 1, 120, 'Destination "%s" existed already!', array($targetFile));
850 $this->addMessageToFlashMessageQueue('FileUtility.DestinationExistedAlready', array($targetFile));
851 } catch (NotInMountPointException $e) {
852 $this->writeLog(5, 1, 121, 'Destination path "%s" was not within your mountpoints!', array($targetFile));
853 $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', array($targetFile));
854 } catch (\RuntimeException $e) {
855 $this->writeLog(5, 1, 100, 'File "%s" was not renamed! Write-permission problem in "%s"?', array($sourceFileObject->getName(), $targetFile));
856 $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotRenamed', array($sourceFileObject->getName(), $targetFile));
857 }
858 } else {
859 // Else means this is a Folder
860 try {
861 // Try to rename the Folder
862 $resultObject = $sourceFileObject->rename($targetFile);
863 $this->writeLog(5, 0, 2, 'Directory renamed from "%s" to "%s"', array($sourceFile, $targetFile));
864 $this->addMessageToFlashMessageQueue('FileUtility.DirectoryRenamedFromTo', array($sourceFile, $targetFile), FlashMessage::OK);
865 } catch (InsufficientUserPermissionsException $e) {
866 $this->writeLog(5, 1, 111, 'You are not allowed to rename directories!', '');
867 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToRenameDirectories');
868 } catch (ExistingTargetFileNameException $e) {
869 $this->writeLog(5, 1, 120, 'Destination "%s" existed already!', array($targetFile));
870 $this->addMessageToFlashMessageQueue('FileUtility.DestinationExistedAlready', array($targetFile));
871 } catch (NotInMountPointException $e) {
872 $this->writeLog(5, 1, 121, 'Destination path "%s" was not within your mountpoints!', array($targetFile));
873 $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', array($targetFile));
874 } catch (\RuntimeException $e) {
875 $this->writeLog(5, 1, 110, 'Directory "%s" was not renamed! Write-permission problem in "%s"?', array($sourceFileObject->getName(), $targetFile));
876 $this->addMessageToFlashMessageQueue('FileUtility.DirectoryWasNotRenamed', array($sourceFileObject->getName(), $targetFile));
877 }
878 }
879 return $resultObject;
880 }
881
882 /**
883 * This creates a new folder. (action=6)
884 *
885 * $cmds['data'] (string): The new folder name
886 * $cmds['target'] (string): The path where to copy to.
887 * + example "2:targetpath/targetfolder/"
888 *
889 * @param array $cmds Command details as described above
890 * @return \TYPO3\CMS\Core\Resource\Folder Returns the new foldername upon success
891 */
892 public function func_newfolder($cmds)
893 {
894 if (!$this->isInit) {
895 return false;
896 }
897 $targetFolderObject = $this->getFileObject($cmds['target']);
898 if (!$targetFolderObject instanceof Folder) {
899 $this->writeLog(6, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
900 $this->addMessageToFlashMessageQueue('FileUtility.DestinationWasNotADirectory', array($cmds['target']));
901 return false;
902 }
903 $resultObject = null;
904 try {
905 $folderName = $cmds['data'];
906 $resultObject = $targetFolderObject->createFolder($folderName);
907 $this->writeLog(6, 0, 1, 'Directory "%s" created in "%s"', array($folderName, $targetFolderObject->getIdentifier()));
908 $this->addMessageToFlashMessageQueue('FileUtility.DirectoryCreatedIn', array($folderName, $targetFolderObject->getIdentifier()), FlashMessage::OK);
909 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidFileNameException $e) {
910 $this->writeLog(6, 1, 104, 'Invalid folder name "%s"!', [$folderName]);
911 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCreateDirectories', [$folderName]);
912 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException $e) {
913 $this->writeLog(6, 1, 103, 'You are not allowed to create directories!', '');
914 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCreateDirectories');
915 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
916 $this->writeLog(6, 1, 102, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier()));
917 $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', array($targetFolderObject->getIdentifier()));
918 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException $e) {
919 $this->writeLog(6, 1, 101, 'File or directory "%s" existed already!', array($folderName));
920 $this->addMessageToFlashMessageQueue('FileUtility.FileOrDirectoryExistedAlready', array($folderName));
921 } catch (\RuntimeException $e) {
922 $this->writeLog(6, 1, 100, 'Directory "%s" not created. Write-permission problem in "%s"?', array($folderName, $targetFolderObject->getIdentifier()));
923 $this->addMessageToFlashMessageQueue('FileUtility.DirectoryNotCreated', array($folderName, $targetFolderObject->getIdentifier()));
924 }
925 return $resultObject;
926 }
927
928 /**
929 * This creates a new file. (action=8)
930 * $cmds['data'] (string): The new file name
931 * $cmds['target'] (string): The path where to create it.
932 * + example "2:targetpath/targetfolder/"
933 *
934 * @param array $cmds Command details as described above
935 * @return string Returns the new filename upon success
936 */
937 public function func_newfile($cmds)
938 {
939 if (!$this->isInit) {
940 return false;
941 }
942 $targetFolderObject = $this->getFileObject($cmds['target']);
943 if (!$targetFolderObject instanceof Folder) {
944 $this->writeLog(8, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
945 $this->addMessageToFlashMessageQueue('FileUtility.DestinationWasNotADirectory', array($cmds['target']));
946 return false;
947 }
948 $resultObject = null;
949 $fileName = $cmds['data'];
950 try {
951 $resultObject = $targetFolderObject->createFile($fileName);
952 $this->writeLog(8, 0, 1, 'File created: "%s"', array($fileName));
953 $this->addMessageToFlashMessageQueue('FileUtility.FileCreated', array($fileName), FlashMessage::OK);
954 } catch (IllegalFileExtensionException $e) {
955 $this->writeLog(8, 1, 106, 'Extension of file "%s" was not allowed!', array($fileName));
956 $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileWasNotAllowed', array($fileName));
957 } catch (InsufficientFolderWritePermissionsException $e) {
958 $this->writeLog(8, 1, 103, 'You are not allowed to create files!', '');
959 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCreateFiles');
960 } catch (NotInMountPointException $e) {
961 $this->writeLog(8, 1, 102, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier()));
962 $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', array($targetFolderObject->getIdentifier()));
963 } catch (ExistingTargetFileNameException $e) {
964 $this->writeLog(8, 1, 101, 'File existed already in "%s"!', array($targetFolderObject->getIdentifier()));
965 $this->addMessageToFlashMessageQueue('FileUtility.FileExistedAlreadyIn', array($targetFolderObject->getIdentifier()));
966 } catch (InvalidFileNameException $e) {
967 $this->writeLog(8, 1, 106, 'File name "%s" was not allowed!', $fileName);
968 $this->addMessageToFlashMessageQueue('FileUtility.FileNameWasNotAllowed', $fileName);
969 } catch (\RuntimeException $e) {
970 $this->writeLog(8, 1, 100, 'File "%s" was not created! Write-permission problem in "%s"?', array($fileName, $targetFolderObject->getIdentifier()));
971 $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotCreated', array($fileName, $targetFolderObject->getIdentifier()));
972 }
973 return $resultObject;
974 }
975
976 /**
977 * Editing textfiles or folders (action=9)
978 *
979 * @param array $cmds $cmds['data'] is the new content. $cmds['target'] is the target (file or dir)
980 * @return bool Returns TRUE on success
981 */
982 public function func_edit($cmds)
983 {
984 if (!$this->isInit) {
985 return false;
986 }
987 // Example indentifier for $cmds['target'] => "4:mypath/tomyfolder/myfile.jpg"
988 // for backwards compatibility: the combined file identifier was the path+filename
989 $fileIdentifier = $cmds['target'];
990 $fileObject = $this->getFileObject($fileIdentifier);
991 // Example indentifier for $cmds['target'] => "2:targetpath/targetfolder/"
992 $content = $cmds['data'];
993 if (!$fileObject instanceof File) {
994 $this->writeLog(9, 2, 123, 'Target "%s" was not a file!', array($fileIdentifier));
995 $this->addMessageToFlashMessageQueue('FileUtility.TargetWasNotAFile', array($fileIdentifier));
996 return false;
997 }
998 $extList = $GLOBALS['TYPO3_CONF_VARS']['SYS']['textfile_ext'];
999 if (!GeneralUtility::inList($extList, $fileObject->getExtension())) {
1000 $this->writeLog(9, 1, 102, 'File extension "%s" is not a textfile format! (%s)', array($fileObject->getExtension(), $extList));
1001 $this->addMessageToFlashMessageQueue('FileUtility.FileExtensionIsNotATextfileFormat', array($fileObject->getExtension(), $extList));
1002 return false;
1003 }
1004 try {
1005 $fileObject->setContents($content);
1006 clearstatcache();
1007 $this->writeLog(9, 0, 1, 'File saved to "%s", bytes: %s, MD5: %s ', array($fileObject->getIdentifier(), $fileObject->getSize(), md5($content)));
1008 $this->addMessageToFlashMessageQueue('FileUtility.FileSavedToBytesMd5', array($fileObject->getIdentifier(), $fileObject->getSize(), md5($content)), FlashMessage::OK);
1009 return true;
1010 } catch (InsufficientUserPermissionsException $e) {
1011 $this->writeLog(9, 1, 104, 'You are not allowed to edit files!', '');
1012 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToEditFiles');
1013 return false;
1014 } catch (InsufficientFileWritePermissionsException $e) {
1015 $this->writeLog(9, 1, 100, 'File "%s" was not saved! Write-permission problem?', array($fileObject->getIdentifier()));
1016 $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotSaved', array($fileObject->getIdentifier()));
1017 return false;
1018 } catch (IllegalFileExtensionException $e) {
1019 $this->writeLog(9, 1, 100, 'File "%s" was not saved! File extension rejected!', array($fileObject->getIdentifier()));
1020 $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotSaved', array($fileObject->getIdentifier()));
1021 return false;
1022 }
1023 }
1024
1025 /**
1026 * Upload of files (action=1)
1027 * when having multiple uploads (HTML5-style), the array $_FILES looks like this:
1028 * Array(
1029 * [upload_1] => Array(
1030 * [name] => Array(
1031 * [0] => GData - Content-Elements and Media-Gallery.pdf
1032 * [1] => CMS Expo 2011.txt
1033 * )
1034 * [type] => Array(
1035 * [0] => application/pdf
1036 * [1] => text/plain
1037 * )
1038 * [tmp_name] => Array(
1039 * [0] => /Applications/MAMP/tmp/php/phpNrOB43
1040 * [1] => /Applications/MAMP/tmp/php/phpD2HQAK
1041 * )
1042 * [size] => Array(
1043 * [0] => 373079
1044 * [1] => 1291
1045 * )
1046 * )
1047 * )
1048 * in HTML you'd need sth like this: <input type="file" name="upload_1[]" multiple="true" />
1049 *
1050 * @param array $cmds $cmds['data'] is the ID-number (points to the global var that holds the filename-ref
1051 * ($_FILES['upload_' . $id]['name']) . $cmds['target'] is the target directory, $cmds['charset']
1052 * is the the character set of the file name (utf-8 is needed for JS-interaction)
1053 * @return File[] | FALSE Returns an array of new file objects upon success. False otherwise
1054 */
1055 public function func_upload($cmds)
1056 {
1057 if (!$this->isInit) {
1058 return false;
1059 }
1060 $uploadPosition = $cmds['data'];
1061 $uploadedFileData = $_FILES['upload_' . $uploadPosition];
1062 if (empty($uploadedFileData['name']) || is_array($uploadedFileData['name']) && empty($uploadedFileData['name'][0])) {
1063 $this->writeLog(1, 2, 108, 'No file was uploaded!', '');
1064 $this->addMessageToFlashMessageQueue('FileUtility.NoFileWasUploaded');
1065 return false;
1066 }
1067 // Example indentifier for $cmds['target'] => "2:targetpath/targetfolder/"
1068 $targetFolderObject = $this->getFileObject($cmds['target']);
1069 // Uploading with non HTML-5-style, thus, make an array out of it, so we can loop over it
1070 if (!is_array($uploadedFileData['name'])) {
1071 $uploadedFileData = array(
1072 'name' => array($uploadedFileData['name']),
1073 'type' => array($uploadedFileData['type']),
1074 'tmp_name' => array($uploadedFileData['tmp_name']),
1075 'size' => array($uploadedFileData['size'])
1076 );
1077 }
1078 $resultObjects = array();
1079 $numberOfUploadedFilesForPosition = count($uploadedFileData['name']);
1080 // Loop through all uploaded files
1081 for ($i = 0; $i < $numberOfUploadedFilesForPosition; $i++) {
1082 $fileInfo = array(
1083 'name' => $uploadedFileData['name'][$i],
1084 'type' => $uploadedFileData['type'][$i],
1085 'tmp_name' => $uploadedFileData['tmp_name'][$i],
1086 'size' => $uploadedFileData['size'][$i]
1087 );
1088 try {
1089 /** @var $fileObject File */
1090 $fileObject = $targetFolderObject->addUploadedFile($fileInfo, (string)$this->existingFilesConflictMode);
1091 $fileObject = ResourceFactory::getInstance()->getFileObjectByStorageAndIdentifier($targetFolderObject->getStorage()->getUid(), $fileObject->getIdentifier());
1092 if ($this->existingFilesConflictMode->equals(DuplicationBehavior::REPLACE)) {
1093 $this->getIndexer($fileObject->getStorage())->updateIndexEntry($fileObject);
1094 }
1095 $resultObjects[] = $fileObject;
1096 $this->internalUploadMap[$uploadPosition] = $fileObject->getCombinedIdentifier();
1097 $this->writeLog(1, 0, 1, 'Uploading file "%s" to "%s"', array($fileInfo['name'], $targetFolderObject->getIdentifier()));
1098 $this->addMessageToFlashMessageQueue('FileUtility.UploadingFileTo', array($fileInfo['name'], $targetFolderObject->getIdentifier()), FlashMessage::OK);
1099 } catch (InsufficientFileWritePermissionsException $e) {
1100 $this->writeLog(1, 1, 107, 'You are not allowed to override "%s"!', array($fileInfo['name']));
1101 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToOverride', array($fileInfo['name']));
1102 } catch (UploadException $e) {
1103 $this->writeLog(1, 2, 106, 'The upload has failed, no uploaded file found!', '');
1104 $this->addMessageToFlashMessageQueue('FileUtility.TheUploadHasFailedNoUploadedFileFound');
1105 } catch (InsufficientUserPermissionsException $e) {
1106 $this->writeLog(1, 1, 105, 'You are not allowed to upload files!', '');
1107 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToUploadFiles');
1108 } catch (UploadSizeException $e) {
1109 $this->writeLog(1, 1, 104, 'The uploaded file "%s" exceeds the size-limit', array($fileInfo['name']));
1110 $this->addMessageToFlashMessageQueue('FileUtility.TheUploadedFileExceedsTheSize-limit', array($fileInfo['name']));
1111 } catch (InsufficientFolderWritePermissionsException $e) {
1112 $this->writeLog(1, 1, 103, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier()));
1113 $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', array($targetFolderObject->getIdentifier()));
1114 } catch (IllegalFileExtensionException $e) {
1115 $this->writeLog(1, 1, 102, 'Extension of file name "%s" is not allowed in "%s"!', array($fileInfo['name'], $targetFolderObject->getIdentifier()));
1116 $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameIsNotAllowedIn', array($fileInfo['name'], $targetFolderObject->getIdentifier()));
1117 } catch (ExistingTargetFileNameException $e) {
1118 $this->writeLog(1, 1, 101, 'No unique filename available in "%s"!', array($targetFolderObject->getIdentifier()));
1119 $this->addMessageToFlashMessageQueue('FileUtility.NoUniqueFilenameAvailableIn', array($targetFolderObject->getIdentifier()));
1120 } catch (\RuntimeException $e) {
1121 $this->writeLog(1, 1, 100, 'Uploaded file could not be moved! Write-permission problem in "%s"?', array($targetFolderObject->getIdentifier()));
1122 $this->addMessageToFlashMessageQueue('FileUtility.UploadedFileCouldNotBeMoved', array($targetFolderObject->getIdentifier()));
1123 }
1124 }
1125
1126 return $resultObjects;
1127 }
1128
1129 /**
1130 * Replaces a file on the filesystem and changes the identifier of the persisted file object in sys_file if
1131 * keepFilename is not checked. If keepFilename is checked, only the file content will be replaced.
1132 *
1133 * @param array $cmdArr
1134 * @return array|bool
1135 * @throws Exception\InsufficientFileAccessPermissionsException
1136 * @throws Exception\InvalidFileException
1137 * @throws \RuntimeException
1138 */
1139 protected function replaceFile(array $cmdArr)
1140 {
1141 if (!$this->isInit) {
1142 return false;
1143 }
1144
1145 $uploadPosition = $cmdArr['data'];
1146 $fileInfo = $_FILES['replace_' . $uploadPosition];
1147 if (empty($fileInfo['name'])) {
1148 $this->writeLog(1, 2, 108, 'No file was uploaded for replacing!', '');
1149 $this->addMessageToFlashMessageQueue('FileUtility.NoFileWasUploadedForReplacing');
1150 return false;
1151 }
1152
1153 $keepFileName = ($cmdArr['keepFilename'] == 1) ? true : false;
1154 $resultObjects = array();
1155
1156 try {
1157 $fileObjectToReplace = $this->getFileObject($cmdArr['uid']);
1158 $folder = $fileObjectToReplace->getParentFolder();
1159 $resourceStorage = $fileObjectToReplace->getStorage();
1160
1161 $fileObject = $resourceStorage->addUploadedFile($fileInfo, $folder, $fileObjectToReplace->getName(), DuplicationBehavior::REPLACE);
1162
1163 // Check if there is a file that is going to be uploaded that has a different name as the replacing one
1164 // but exists in that folder as well.
1165 // rename to another name, but check if the name is already given
1166 if ($keepFileName === false) {
1167 // if a file with the same name already exists, we need to change it to _01 etc.
1168 // if the file does not exist, we can do a simple rename
1169 $resourceStorage->moveFile($fileObject, $folder, $fileInfo['name'], DuplicationBehavior::RENAME);
1170 }
1171
1172 $resultObjects[] = $fileObject;
1173 $this->internalUploadMap[$uploadPosition] = $fileObject->getCombinedIdentifier();
1174
1175 $this->writeLog(1, 0, 1, 'Replacing file "%s" to "%s"', array($fileInfo['name'], $fileObjectToReplace->getIdentifier()));
1176 $this->addMessageToFlashMessageQueue('FileUtility.ReplacingFileTo', array($fileInfo['name'], $fileObjectToReplace->getIdentifier()), FlashMessage::OK);
1177 } catch (InsufficientFileWritePermissionsException $e) {
1178 $this->writeLog(1, 1, 107, 'You are not allowed to override "%s"!', array($fileInfo['name']));
1179 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToOverride', array($fileInfo['name']));
1180 } catch (UploadException $e) {
1181 $this->writeLog(1, 2, 106, 'The upload has failed, no uploaded file found!', '');
1182 $this->addMessageToFlashMessageQueue('FileUtility.TheUploadHasFailedNoUploadedFileFound');
1183 } catch (InsufficientUserPermissionsException $e) {
1184 $this->writeLog(1, 1, 105, 'You are not allowed to upload files!', '');
1185 $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToUploadFiles');
1186 } catch (UploadSizeException $e) {
1187 $this->writeLog(1, 1, 104, 'The uploaded file "%s" exceeds the size-limit', array($fileInfo['name']));
1188 $this->addMessageToFlashMessageQueue('FileUtility.TheUploadedFileExceedsTheSize-limit', array($fileInfo['name']));
1189 } catch (InsufficientFolderWritePermissionsException $e) {
1190 $this->writeLog(1, 1, 103, 'Destination path "%s" was not within your mountpoints!', array($fileObjectToReplace->getIdentifier()));
1191 $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', array($fileObjectToReplace->getIdentifier()));
1192 } catch (IllegalFileExtensionException $e) {
1193 $this->writeLog(1, 1, 102, 'Extension of file name "%s" is not allowed in "%s"!', array($fileInfo['name'], $fileObjectToReplace->getIdentifier()));
1194 $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameIsNotAllowedIn', array($fileInfo['name'], $fileObjectToReplace->getIdentifier()));
1195 } catch (ExistingTargetFileNameException $e) {
1196 $this->writeLog(1, 1, 101, 'No unique filename available in "%s"!', array($fileObjectToReplace->getIdentifier()));
1197 $this->addMessageToFlashMessageQueue('FileUtility.NoUniqueFilenameAvailableIn', array($fileObjectToReplace->getIdentifier()));
1198 } catch (\RuntimeException $e) {
1199 throw $e;
1200 }
1201 return $resultObjects;
1202 }
1203
1204 /**
1205 * Add flash message to message queue
1206 *
1207 * @param FlashMessage $flashMessage
1208 * @return void
1209 */
1210 protected function addFlashMessage(FlashMessage $flashMessage)
1211 {
1212 /** @var $flashMessageService FlashMessageService */
1213 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1214
1215 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
1216 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1217 $defaultFlashMessageQueue->enqueue($flashMessage);
1218 }
1219
1220 /**
1221 * Gets Indexer
1222 *
1223 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
1224 * @return \TYPO3\CMS\Core\Resource\Index\Indexer
1225 */
1226 protected function getIndexer(ResourceStorage $storage)
1227 {
1228 return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Index\Indexer::class, $storage);
1229 }
1230
1231 /**
1232 * Get database connection
1233 *
1234 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
1235 */
1236 protected function getDatabaseConnection()
1237 {
1238 return $GLOBALS['TYPO3_DB'];
1239 }
1240
1241 /**
1242 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1243 */
1244 protected function getBackendUser()
1245 {
1246 return $GLOBALS['BE_USER'];
1247 }
1248
1249 /**
1250 * Returns LanguageService
1251 *
1252 * @return LanguageService
1253 */
1254 protected function getLanguageService()
1255 {
1256 return $GLOBALS['LANG'];
1257 }
1258 }