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