TYPO3 CMS  TYPO3_8-7
ExtendedFileUtility.php
Go to the documentation of this file.
1 <?php
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 
45 
63 {
71 
79  public $actionPerms = [
80  // File permissions
81  'addFile' => false,
82  'readFile' => false,
83  'writeFile' => false,
84  'copyFile' => false,
85  'moveFile' => false,
86  'renameFile' => false,
87  'deleteFile' => false,
88  // Folder permissions
89  'addFolder' => false,
90  'readFolder' => false,
91  'writeFolder' => false,
92  'copyFolder' => false,
93  'moveFolder' => false,
94  'renameFolder' => false,
95  'deleteFolder' => false,
96  'recursivedeleteFolder' => false
97  ];
98 
104  public $internalUploadMap = [];
105 
111  protected $errorMessages = [];
112 
118  protected $flashMessages = [];
119 
123  protected $fileCmdMap;
124 
130  protected $fileFactory;
131 
138  {
139  return (string)$this->existingFilesConflictMode;
140  }
141 
149  {
150  try {
151  $this->existingFilesConflictMode = DuplicationBehavior::cast($existingFilesConflictMode);
152  } catch (InvalidEnumerationValueException $e) {
153  throw new Exception(
154  sprintf(
155  'Invalid argument, received: "%s", expected a value from enumeration \TYPO3\CMS\Core\Resource\DuplicationBehavior (%s)',
157  implode(', ', DuplicationBehavior::getConstants())
158  ),
159  1476046229
160  );
161  }
162  }
163 
169  public function start($fileCmds)
170  {
171  // Initialize Object Factory
172  $this->fileFactory = ResourceFactory::getInstance();
173  // Initializing file processing commands:
174  $this->fileCmdMap = $fileCmds;
175  }
176 
183  public function setActionPermissions(array $permissions = [])
184  {
185  if (empty($permissions)) {
186  $permissions = $this->getBackendUser()->getFilePermissions();
187  }
188  $this->actionPerms = $permissions;
189  }
190 
197  public function processData()
198  {
199  $result = [];
200  if (is_array($this->fileCmdMap)) {
201  // Check if there were uploads expected, but no one made
202  if ($this->fileCmdMap['upload']) {
203  $uploads = $this->fileCmdMap['upload'];
204  foreach ($uploads as $upload) {
205  if (empty($_FILES['upload_' . $upload['data']]['name'])
206  || (
207  is_array($_FILES['upload_' . $upload['data']]['name'])
208  && empty($_FILES['upload_' . $upload['data']]['name'][0])
209  )
210  ) {
211  unset($this->fileCmdMap['upload'][$upload['data']]);
212  }
213  }
214  if (empty($this->fileCmdMap['upload'])) {
215  $this->writeLog(1, 1, 108, 'No file was uploaded!', []);
216  $this->addMessageToFlashMessageQueue('FileUtility.NoFileWasUploaded');
217  }
218  }
219 
220  // Check if there were new folder names expected, but non given
221  if ($this->fileCmdMap['newfolder']) {
222  foreach ($this->fileCmdMap['newfolder'] as $key => $cmdArr) {
223  if (empty($cmdArr['data'])) {
224  unset($this->fileCmdMap['newfolder'][$key]);
225  }
226  }
227  if (empty($this->fileCmdMap['newfolder'])) {
228  $this->writeLog(6, 1, 108, 'No name for new folder given!', []);
229  $this->addMessageToFlashMessageQueue('FileUtility.NoNameForNewFolderGiven');
230  }
231  }
232 
233  // Traverse each set of actions
234  foreach ($this->fileCmdMap as $action => $actionData) {
235  // Traverse all action data. More than one file might be affected at the same time.
236  if (is_array($actionData)) {
237  $result[$action] = [];
238  foreach ($actionData as $cmdArr) {
239  // Clear file stats
240  clearstatcache();
241  // Branch out based on command:
242  switch ($action) {
243  case 'delete':
244  $result[$action][] = $this->func_delete($cmdArr);
245  break;
246  case 'copy':
247  $result[$action][] = $this->func_copy($cmdArr);
248  break;
249  case 'move':
250  $result[$action][] = $this->func_move($cmdArr);
251  break;
252  case 'rename':
253  $result[$action][] = $this->func_rename($cmdArr);
254  break;
255  case 'newfolder':
256  $result[$action][] = $this->func_newfolder($cmdArr);
257  break;
258  case 'newfile':
259  $result[$action][] = $this->func_newfile($cmdArr);
260  break;
261  case 'editfile':
262  $result[$action][] = $this->func_edit($cmdArr);
263  break;
264  case 'upload':
265  $result[$action][] = $this->func_upload($cmdArr);
266  break;
267  case 'replace':
268  $result[$action][] = $this->replaceFile($cmdArr);
269  break;
270  }
271  // Hook for post-processing the action
272  if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'])) {
273  foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'] as $classRef) {
274  $hookObject = GeneralUtility::getUserObj($classRef);
275  if (!$hookObject instanceof ExtendedFileUtilityProcessDataHookInterface) {
276  throw new \UnexpectedValueException($classRef . ' must implement interface ' . ExtendedFileUtilityProcessDataHookInterface::class, 1279719168);
277  }
278  $hookObject->processData_postProcessAction($action, $cmdArr, $result[$action], $this);
279  }
280  }
281  }
282  }
283  }
284  }
285  return $result;
286  }
287 
294  {
296  foreach ($this->getErrorMessages() as $msg) {
297  $flashMessage = GeneralUtility::makeInstance(
298  FlashMessage::class,
299  $msg,
300  '',
302  true
303  );
304  $this->addFlashMessage($flashMessage);
305  }
306  }
307 
313  public function getErrorMessages()
314  {
315  return $this->errorMessages;
316  }
317 
325  public function writeLog($action, $error, $details_nr, $details, $data)
326  {
327  // Type value for tce_file.php
328  $type = 2;
329  if (is_object($this->getBackendUser())) {
330  $this->getBackendUser()->writelog($type, $action, $error, $details_nr, $details, $data);
331  }
332  if ($error > 0) {
333  $this->errorMessages[] = vsprintf($details, $data);
334  }
335  }
336 
345  protected function addMessageToFlashMessageQueue($localizationKey, array $replaceMarkers = [], $severity = FlashMessage::ERROR)
346  {
347  if (TYPO3_MODE !== 'BE') {
348  return;
349  }
350  $label = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/fileMessages.xlf:' . $localizationKey);
351  $message = vsprintf($label, $replaceMarkers);
352  $flashMessage = GeneralUtility::makeInstance(
353  FlashMessage::class,
354  $message,
355  '',
356  $severity,
357  true
358  );
359  $this->addFlashMessage($flashMessage);
360  }
361 
362  /*************************************
363  *
364  * File operation functions
365  *
366  **************************************/
373  public function func_delete(array $cmds)
374  {
375  $result = false;
376  // Example identifier for $cmds['data'] => "4:mypath/tomyfolder/myfile.jpg"
377  // for backwards compatibility: the combined file identifier was the path+filename
378  try {
379  $fileObject = $this->getFileObject($cmds['data']);
380  } catch (ResourceDoesNotExistException $e) {
381  $flashMessage = GeneralUtility::makeInstance(
382  FlashMessage::class,
383  sprintf(
384  $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.description.fileNotFound'),
385  $cmds['data']
386  ),
387  $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.header.fileNotFound'),
389  true
390  );
391  $this->addFlashMessage($flashMessage);
392 
393  return false;
394  }
395  // checks to delete the file
396  if ($fileObject instanceof File) {
397  // check if the file still has references
398  // Exclude sys_file_metadata records as these are no use references
399  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
400  $queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
401  $refIndexRecords = $queryBuilder
402  ->select('tablename', 'recuid', 'ref_uid')
403  ->from('sys_refindex')
404  ->where(
405  $queryBuilder->expr()->eq(
406  'ref_table',
407  $queryBuilder->createNamedParameter('sys_file', \PDO::PARAM_STR)
408  ),
409  $queryBuilder->expr()->eq(
410  'ref_uid',
411  $queryBuilder->createNamedParameter($fileObject->getUid(), \PDO::PARAM_INT)
412  ),
413  $queryBuilder->expr()->neq(
414  'tablename',
415  $queryBuilder->createNamedParameter('sys_file_metadata', \PDO::PARAM_STR)
416  ),
417  $queryBuilder->expr()->eq(
418  'deleted',
419  $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
420  )
421  )
422  ->execute()
423  ->fetchAll();
424  $deleteFile = true;
425  if (!empty($refIndexRecords)) {
426  $shortcutContent = [];
427  $brokenReferences = [];
428 
429  foreach ($refIndexRecords as $fileReferenceRow) {
430  if ($fileReferenceRow['tablename'] === 'sys_file_reference') {
431  $row = $this->transformFileReferenceToRecordReference($fileReferenceRow);
432  $shortcutRecord = BackendUtility::getRecord($row['tablename'], $row['recuid']);
433 
434  if ($shortcutRecord) {
435  $shortcutContent[] = '[record:' . $row['tablename'] . ':' . $row['recuid'] . ']';
436  } else {
437  $brokenReferences[] = $fileReferenceRow['ref_uid'];
438  }
439  } else {
440  $shortcutContent[] = '[record:' . $fileReferenceRow['tablename'] . ':' . $fileReferenceRow['recuid'] . ']';
441  }
442  }
443  if (!empty($brokenReferences)) {
444  // render a message that the file has broken references
445  $flashMessage = GeneralUtility::makeInstance(
446  FlashMessage::class,
447  sprintf($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.description.fileHasBrokenReferences'), count($brokenReferences)),
448  $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.header.fileHasBrokenReferences'),
450  true
451  );
452  $this->addFlashMessage($flashMessage);
453  }
454  if (!empty($shortcutContent)) {
455  // render a message that the file could not be deleted
456  $flashMessage = GeneralUtility::makeInstance(
457  FlashMessage::class,
458  sprintf($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.description.fileNotDeletedHasReferences'), $fileObject->getName()) . ' ' . implode(', ', $shortcutContent),
459  $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.header.fileNotDeletedHasReferences'),
461  true
462  );
463  $this->addFlashMessage($flashMessage);
464  $deleteFile = false;
465  }
466  }
467 
468  if ($deleteFile) {
469  try {
470  $result = $fileObject->delete();
471 
472  // show the user that the file was deleted
473  $flashMessage = GeneralUtility::makeInstance(
474  FlashMessage::class,
475  sprintf($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.description.fileDeleted'), $fileObject->getName()),
476  $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.header.fileDeleted'),
478  true
479  );
480  $this->addFlashMessage($flashMessage);
481  // Log success
482  $this->writeLog(4, 0, 1, 'File "%s" deleted', [$fileObject->getIdentifier()]);
483  } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
484  $this->writeLog(4, 1, 112, 'You are not allowed to access the file', [$fileObject->getIdentifier()]);
485  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToAccessTheFile', [$fileObject->getIdentifier()]);
486  } catch (NotInMountPointException $e) {
487  $this->writeLog(4, 1, 111, 'Target was not within your mountpoints! T="%s"', [$fileObject->getIdentifier()]);
488  $this->addMessageToFlashMessageQueue('FileUtility.TargetWasNotWithinYourMountpoints', [$fileObject->getIdentifier()]);
489  } catch (\RuntimeException $e) {
490  $this->writeLog(4, 1, 110, 'Could not delete file "%s". Write-permission problem?', [$fileObject->getIdentifier()]);
491  $this->addMessageToFlashMessageQueue('FileUtility.CouldNotDeleteFile', [$fileObject->getIdentifier()]);
492  }
493  }
494  } else {
496  if (!$this->folderHasFilesInUse($fileObject)) {
497  try {
498  $result = $fileObject->delete(true);
499  if ($result) {
500  // notify the user that the folder was deleted
502  $flashMessage = GeneralUtility::makeInstance(
503  FlashMessage::class,
504  sprintf($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.description.folderDeleted'), $fileObject->getName()),
505  $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.header.folderDeleted'),
507  true
508  );
509  $this->addFlashMessage($flashMessage);
510  // Log success
511  $this->writeLog(4, 0, 3, 'Directory "%s" deleted', [$fileObject->getIdentifier()]);
512  }
514  $this->writeLog(4, 1, 120, 'Could not delete directory! Is directory "%s" empty? (You are not allowed to delete directories recursively).', [$fileObject->getIdentifier()]);
515  $this->addMessageToFlashMessageQueue('FileUtility.CouldNotDeleteDirectory', [$fileObject->getIdentifier()]);
517  $this->writeLog(4, 1, 123, 'You are not allowed to access the directory', [$fileObject->getIdentifier()]);
518  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToAccessTheDirectory', [$fileObject->getIdentifier()]);
519  } catch (NotInMountPointException $e) {
520  $this->writeLog(4, 1, 121, 'Target was not within your mountpoints! T="%s"', [$fileObject->getIdentifier()]);
521  $this->addMessageToFlashMessageQueue('FileUtility.TargetWasNotWithinYourMountpoints', [$fileObject->getIdentifier()]);
522  } catch (\TYPO3\CMS\Core\Resource\Exception\FileOperationErrorException $e) {
523  $this->writeLog(4, 1, 120, 'Could not delete directory "%s"! Write-permission problem?', [$fileObject->getIdentifier()]);
524  $this->addMessageToFlashMessageQueue('FileUtility.CouldNotDeleteDirectory', [$fileObject->getIdentifier()]);
525  }
526  }
527  }
528 
529  return $result;
530  }
531 
540  public function folderHasFilesInUse(Folder $folder)
541  {
542  $files = $folder->getFiles(0, 0, Folder::FILTER_MODE_USE_OWN_AND_STORAGE_FILTERS, true);
543  if (empty($files)) {
544  return false;
545  }
546 
548  $fileUids = [];
549  foreach ($files as $file) {
550  $fileUids[] = $file->getUid();
551  }
552 
553  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
554  $queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
555  $numberOfReferences = $queryBuilder
556  ->count('hash')
557  ->from('sys_refindex')
558  ->where(
559  $queryBuilder->expr()->eq(
560  'ref_table',
561  $queryBuilder->createNamedParameter('sys_file', \PDO::PARAM_STR)
562  ),
563  $queryBuilder->expr()->in(
564  'ref_uid',
565  $queryBuilder->createNamedParameter($fileUids, Connection::PARAM_INT_ARRAY)
566  ),
567  $queryBuilder->expr()->neq(
568  'tablename',
569  $queryBuilder->createNamedParameter('sys_file_metadata', \PDO::PARAM_STR)
570  ),
571  $queryBuilder->expr()->eq(
572  'deleted',
573  $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
574  )
575  )->execute()->fetchColumn(0);
576 
577  $hasReferences = $numberOfReferences > 0;
578  if ($hasReferences) {
580  $flashMessage = GeneralUtility::makeInstance(
581  FlashMessage::class,
582  $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.description.folderNotDeletedHasFilesWithReferences'),
583  $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:message.header.folderNotDeletedHasFilesWithReferences'),
585  true
586  );
587  $this->addFlashMessage($flashMessage);
588  }
589 
590  return $hasReferences;
591  }
592 
600  protected function transformFileReferenceToRecordReference(array $referenceRecord)
601  {
602  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
603  $queryBuilder->getRestrictions()->removeAll();
604  $fileReference = $queryBuilder
605  ->select('uid_foreign', 'tablenames', 'fieldname', 'sorting_foreign')
606  ->from('sys_file_reference')
607  ->where(
608  $queryBuilder->expr()->eq(
609  'uid',
610  $queryBuilder->createNamedParameter($referenceRecord['recuid'], \PDO::PARAM_INT)
611  )
612  )
613  ->execute()
614  ->fetch();
615 
616  return [
617  'recuid' => $fileReference['uid_foreign'],
618  'tablename' => $fileReference['tablenames'],
619  'field' => $fileReference['fieldname'],
620  'flexpointer' => '',
621  'softref_key' => '',
622  'sorting' => $fileReference['sorting_foreign']
623  ];
624  }
625 
634  protected function getFileObject($identifier)
635  {
636  $object = $this->fileFactory->retrieveFileOrFolderObject($identifier);
637  if (!is_object($object)) {
638  throw new \TYPO3\CMS\Core\Resource\Exception\InvalidFileException('The item ' . $identifier . ' was not a file or directory!!', 1320122453);
639  }
640  if ($object->getStorage()->getUid() === 0) {
641  throw new \TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException('You are not allowed to access files outside your storages', 1375889830);
642  }
643  return $object;
644  }
645 
659  protected function func_copy($cmds)
660  {
661  $sourceFileObject = $this->getFileObject($cmds['data']);
663  $targetFolderObject = $this->getFileObject($cmds['target']);
664  // Basic check
665  if (!$targetFolderObject instanceof Folder) {
666  $this->writeLog(2, 2, 100, 'Destination "%s" was not a directory', [$cmds['target']]);
667  $this->addMessageToFlashMessageQueue('FileUtility.DestinationWasNotADirectory', [$cmds['target']]);
668  return false;
669  }
670  // If this is TRUE, we append _XX to the file name if
671  $appendSuffixOnConflict = (string)$cmds['altName'];
672  $resultObject = null;
673  $conflictMode = $appendSuffixOnConflict !== '' ? DuplicationBehavior::RENAME : DuplicationBehavior::CANCEL;
674  // Copying the file
675  if ($sourceFileObject instanceof File) {
676  try {
677  $resultObject = $sourceFileObject->copyTo($targetFolderObject, null, $conflictMode);
679  $this->writeLog(2, 1, 114, 'You are not allowed to copy files', []);
680  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCopyFiles');
681  } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
682  $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"', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
683  $this->addMessageToFlashMessageQueue('FileUtility.CouldNotAccessAllNecessaryResources', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
684  } catch (IllegalFileExtensionException $e) {
685  $this->writeLog(2, 1, 111, 'Extension of file name "%s" is not allowed in "%s"!', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
686  $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameIsNotAllowedIn', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
687  } catch (ExistingTargetFileNameException $e) {
688  $this->writeLog(2, 1, 112, 'File "%s" already exists in folder "%s"!', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
689  $this->addMessageToFlashMessageQueue('FileUtility.FileAlreadyExistsInFolder', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
690  } catch (NotImplementedMethodException $e) {
691  $this->writeLog(3, 1, 128, 'The function to copy a file between storages is not yet implemented', []);
692  $this->addMessageToFlashMessageQueue('FileUtility.TheFunctionToCopyAFileBetweenStoragesIsNotYetImplemented');
693  } catch (\RuntimeException $e) {
694  $this->writeLog(2, 2, 109, 'File "%s" WAS NOT copied to "%s"! Write-permission problem?', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
695  $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotCopiedTo', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
696  }
697  if ($resultObject) {
698  $this->writeLog(2, 0, 1, 'File "%s" copied to "%s"', [$sourceFileObject->getIdentifier(), $resultObject->getIdentifier()]);
699  $this->addMessageToFlashMessageQueue('FileUtility.FileCopiedTo', [$sourceFileObject->getIdentifier(), $resultObject->getIdentifier()], FlashMessage::OK);
700  }
701  } else {
702  // Else means this is a Folder
703  $sourceFolderObject = $sourceFileObject;
704  try {
705  $resultObject = $sourceFolderObject->copyTo($targetFolderObject, null, $conflictMode);
707  $this->writeLog(2, 1, 125, 'You are not allowed to copy directories', []);
708  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCopyDirectories');
709  } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
710  $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"', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
711  $this->addMessageToFlashMessageQueue('FileUtility.CouldNotAccessAllNecessaryResources', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
713  $this->writeLog(2, 1, 121, 'You don\'t have full access to the destination directory "%s"!', [$targetFolderObject->getIdentifier()]);
714  $this->addMessageToFlashMessageQueue('FileUtility.YouDontHaveFullAccessToTheDestinationDirectory', [$targetFolderObject->getIdentifier()]);
715  } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException $e) {
716  $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!', [$sourceFolderObject->getName(), $targetFolderObject->getName()]);
717  $this->addMessageToFlashMessageQueue('FileUtility.CannotCopyFolderIntoTargetFolderBecauseTheTargetFolderIsAlreadyWithinTheFolderToBeCopied', [$sourceFolderObject->getName(), $targetFolderObject->getName()]);
718  } catch (ExistingTargetFolderException $e) {
719  $this->writeLog(2, 1, 123, 'Target "%s" already exists!', [$targetFolderObject->getIdentifier()]);
720  $this->addMessageToFlashMessageQueue('FileUtility.TargetAlreadyExists', [$targetFolderObject->getIdentifier()]);
721  } catch (NotImplementedMethodException $e) {
722  $this->writeLog(3, 1, 129, 'The function to copy a folder between storages is not yet implemented', []);
723  $this->addMessageToFlashMessageQueue('FileUtility.TheFunctionToCopyAFolderBetweenStoragesIsNotYetImplemented');
724  } catch (\RuntimeException $e) {
725  $this->writeLog(2, 2, 119, 'Directory "%s" WAS NOT copied to "%s"! Write-permission problem?', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
726  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryWasNotCopiedTo', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
727  }
728  if ($resultObject) {
729  $this->writeLog(2, 0, 2, 'Directory "%s" copied to "%s"', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
730  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryCopiedTo', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()], FlashMessage::OK);
731  }
732  }
733  return $resultObject;
734  }
735 
749  protected function func_move($cmds)
750  {
751  $sourceFileObject = $this->getFileObject($cmds['data']);
752  $targetFolderObject = $this->getFileObject($cmds['target']);
753  // Basic check
754  if (!$targetFolderObject instanceof Folder) {
755  $this->writeLog(3, 2, 100, 'Destination "%s" was not a directory', [$cmds['target']]);
756  $this->addMessageToFlashMessageQueue('FileUtility.DestinationWasNotADirectory', [$cmds['target']]);
757  return false;
758  }
759  $alternativeName = (string)$cmds['altName'];
760  $resultObject = null;
761  // Moving the file
762  if ($sourceFileObject instanceof File) {
763  try {
764  if ($alternativeName !== '') {
765  // Don't allow overwriting existing files, but find a new name
766  $resultObject = $sourceFileObject->moveTo($targetFolderObject, $alternativeName, DuplicationBehavior::RENAME);
767  } else {
768  // Don't allow overwriting existing files
769  $resultObject = $sourceFileObject->moveTo($targetFolderObject, null, DuplicationBehavior::CANCEL);
770  }
771  $this->writeLog(3, 0, 1, 'File "%s" moved to "%s"', [$sourceFileObject->getIdentifier(), $resultObject->getIdentifier()]);
772  $this->addMessageToFlashMessageQueue('FileUtility.FileMovedTo', [$sourceFileObject->getIdentifier(), $resultObject->getIdentifier()], FlashMessage::OK);
774  $this->writeLog(3, 1, 114, 'You are not allowed to move files', []);
775  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToMoveFiles');
776  } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
777  $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"', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
778  $this->addMessageToFlashMessageQueue('FileUtility.CouldNotAccessAllNecessaryResources', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
779  } catch (IllegalFileExtensionException $e) {
780  $this->writeLog(3, 1, 111, 'Extension of file name "%s" is not allowed in "%s"!', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
781  $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameIsNotAllowedIn', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
782  } catch (ExistingTargetFileNameException $e) {
783  $this->writeLog(3, 1, 112, 'File "%s" already exists in folder "%s"!', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
784  $this->addMessageToFlashMessageQueue('FileUtility.FileAlreadyExistsInFolder', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
785  } catch (NotImplementedMethodException $e) {
786  $this->writeLog(3, 1, 126, 'The function to move a file between storages is not yet implemented', []);
787  $this->addMessageToFlashMessageQueue('FileUtility.TheFunctionToMoveAFileBetweenStoragesIsNotYetImplemented');
788  } catch (\RuntimeException $e) {
789  $this->writeLog(3, 2, 109, 'File "%s" WAS NOT copied to "%s"! Write-permission problem?', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
790  $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotCopiedTo', [$sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
791  }
792  } else {
793  // Else means this is a Folder
794  $sourceFolderObject = $sourceFileObject;
795  try {
796  if ($alternativeName !== '') {
797  // Don't allow overwriting existing files, but find a new name
798  $resultObject = $sourceFolderObject->moveTo($targetFolderObject, $alternativeName, DuplicationBehavior::RENAME);
799  } else {
800  // Don't allow overwriting existing files
801  $resultObject = $sourceFolderObject->moveTo($targetFolderObject, null, DuplicationBehavior::RENAME);
802  }
803  $this->writeLog(3, 0, 2, 'Directory "%s" moved to "%s"', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
804  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryMovedTo', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()], FlashMessage::OK);
806  $this->writeLog(3, 1, 125, 'You are not allowed to move directories', []);
807  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToMoveDirectories');
808  } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
809  $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"', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
810  $this->addMessageToFlashMessageQueue('FileUtility.CouldNotAccessAllNecessaryResources', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
812  $this->writeLog(3, 1, 121, 'You don\'t have full access to the destination directory "%s"!', [$targetFolderObject->getIdentifier()]);
813  $this->addMessageToFlashMessageQueue('FileUtility.YouDontHaveFullAccessToTheDestinationDirectory', [$targetFolderObject->getIdentifier()]);
814  } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException $e) {
815  $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!', [$sourceFolderObject->getName(), $targetFolderObject->getName()]);
816  $this->addMessageToFlashMessageQueue('FileUtility.CannotMoveFolderIntoTargetFolderBecauseTheTargetFolderIsAlreadyWithinTheFolderToBeMoved', [$sourceFolderObject->getName(), $targetFolderObject->getName()]);
817  } catch (ExistingTargetFolderException $e) {
818  $this->writeLog(3, 1, 123, 'Target "%s" already exists!', [$targetFolderObject->getIdentifier()]);
819  $this->addMessageToFlashMessageQueue('FileUtility.TargetAlreadyExists', [$targetFolderObject->getIdentifier()]);
820  } catch (NotImplementedMethodException $e) {
821  $this->writeLog(3, 1, 127, 'The function to move a folder between storages is not yet implemented', []);
822  $this->addMessageToFlashMessageQueue('FileUtility.TheFunctionToMoveAFolderBetweenStoragesIsNotYetImplemented', []);
823  } catch (\RuntimeException $e) {
824  $this->writeLog(3, 2, 119, 'Directory "%s" WAS NOT moved to "%s"! Write-permission problem?', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
825  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryWasNotMovedTo', [$sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()]);
826  }
827  }
828  return $resultObject;
829  }
830 
842  public function func_rename($cmds)
843  {
844  $sourceFileObject = $this->getFileObject($cmds['data']);
845  $sourceFile = $sourceFileObject->getName();
846  $targetFile = $cmds['target'];
847  $resultObject = null;
848  if ($sourceFileObject instanceof File) {
849  try {
850  // Try to rename the File
851  $resultObject = $sourceFileObject->rename($targetFile, $this->existingFilesConflictMode);
852  if ($resultObject->getName() !== $targetFile) {
853  $this->writeLog(5, 1, 1, 'File renamed from "%s" to "%s". Filename had to be sanitized!', [$sourceFile, $targetFile]);
854  $this->addMessageToFlashMessageQueue('FileUtility.FileNameSanitized', [$targetFile, $resultObject->getName()], FlashMessage::WARNING);
855  } else {
856  $this->writeLog(5, 0, 1, 'File renamed from "%s" to "%s"', [$sourceFile, $targetFile]);
857  }
858  if ($sourceFile === $resultObject->getName()) {
859  $this->addMessageToFlashMessageQueue('FileUtility.FileRenamedSameName', [$sourceFile], FlashMessage::INFO);
860  } else {
861  $this->addMessageToFlashMessageQueue('FileUtility.FileRenamedFromTo', [$sourceFile, $resultObject->getName()], FlashMessage::OK);
862  }
864  $this->writeLog(5, 1, 102, 'You are not allowed to rename files!', []);
865  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToRenameFiles');
866  } catch (IllegalFileExtensionException $e) {
867  $this->writeLog(5, 1, 101, 'Extension of file name "%s" or "%s" was not allowed!', [$sourceFileObject->getName(), $targetFile]);
868  $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameOrWasNotAllowed', [$sourceFileObject->getName(), $targetFile]);
869  } catch (ExistingTargetFileNameException $e) {
870  $this->writeLog(5, 1, 120, 'Destination "%s" existed already!', [$targetFile]);
871  $this->addMessageToFlashMessageQueue('FileUtility.DestinationExistedAlready', [$targetFile]);
872  } catch (NotInMountPointException $e) {
873  $this->writeLog(5, 1, 121, 'Destination path "%s" was not within your mountpoints!', [$targetFile]);
874  $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', [$targetFile]);
875  } catch (\RuntimeException $e) {
876  $this->writeLog(5, 1, 100, 'File "%s" was not renamed! Write-permission problem in "%s"?', [$sourceFileObject->getName(), $targetFile]);
877  $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotRenamed', [$sourceFileObject->getName(), $targetFile]);
878  }
879  } else {
880  // Else means this is a Folder
881  try {
882  // Try to rename the Folder
883  $resultObject = $sourceFileObject->rename($targetFile);
884  $this->writeLog(5, 0, 2, 'Directory renamed from "%s" to "%s"', [$sourceFile, $targetFile]);
885  if ($sourceFile === $targetFile) {
886  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryRenamedSameName', [$sourceFile], FlashMessage::INFO);
887  } else {
888  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryRenamedFromTo', [$sourceFile, $targetFile], FlashMessage::OK);
889  }
891  $this->writeLog(5, 1, 111, 'You are not allowed to rename directories!', []);
892  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToRenameDirectories');
893  } catch (ExistingTargetFileNameException $e) {
894  $this->writeLog(5, 1, 120, 'Destination "%s" existed already!', [$targetFile]);
895  $this->addMessageToFlashMessageQueue('FileUtility.DestinationExistedAlready', [$targetFile]);
896  } catch (NotInMountPointException $e) {
897  $this->writeLog(5, 1, 121, 'Destination path "%s" was not within your mountpoints!', [$targetFile]);
898  $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', [$targetFile]);
899  } catch (\RuntimeException $e) {
900  $this->writeLog(5, 1, 110, 'Directory "%s" was not renamed! Write-permission problem in "%s"?', [$sourceFileObject->getName(), $targetFile]);
901  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryWasNotRenamed', [$sourceFileObject->getName(), $targetFile]);
902  }
903  }
904  return $resultObject;
905  }
906 
917  public function func_newfolder($cmds)
918  {
919  $targetFolderObject = $this->getFileObject($cmds['target']);
920  if (!$targetFolderObject instanceof Folder) {
921  $this->writeLog(6, 2, 104, 'Destination "%s" was not a directory', [$cmds['target']]);
922  $this->addMessageToFlashMessageQueue('FileUtility.DestinationWasNotADirectory', [$cmds['target']]);
923  return false;
924  }
925  $resultObject = null;
926  $folderName = $cmds['data'];
927  try {
928  $resultObject = $targetFolderObject->createFolder($folderName);
929  $this->writeLog(6, 0, 1, 'Directory "%s" created in "%s"', [$folderName, $targetFolderObject->getIdentifier()]);
930  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryCreatedIn', [$folderName, $targetFolderObject->getIdentifier()], FlashMessage::OK);
931  } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidFileNameException $e) {
932  $this->writeLog(6, 1, 104, 'Invalid folder name "%s"!', [$folderName]);
933  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCreateDirectories', [$folderName]);
934  } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException $e) {
935  $this->writeLog(6, 1, 103, 'You are not allowed to create directories!', []);
936  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCreateDirectories');
937  } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
938  $this->writeLog(6, 1, 102, 'Destination path "%s" was not within your mountpoints!', [$targetFolderObject->getIdentifier()]);
939  $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', [$targetFolderObject->getIdentifier()]);
940  } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException $e) {
941  $this->writeLog(6, 1, 101, 'File or directory "%s" existed already!', [$folderName]);
942  $this->addMessageToFlashMessageQueue('FileUtility.FileOrDirectoryExistedAlready', [$folderName]);
943  } catch (\RuntimeException $e) {
944  $this->writeLog(6, 1, 100, 'Directory "%s" not created. Write-permission problem in "%s"?', [$folderName, $targetFolderObject->getIdentifier()]);
945  $this->addMessageToFlashMessageQueue('FileUtility.DirectoryNotCreated', [$folderName, $targetFolderObject->getIdentifier()]);
946  }
947  return $resultObject;
948  }
949 
959  public function func_newfile($cmds)
960  {
961  $targetFolderObject = $this->getFileObject($cmds['target']);
962  if (!$targetFolderObject instanceof Folder) {
963  $this->writeLog(8, 2, 104, 'Destination "%s" was not a directory', [$cmds['target']]);
964  $this->addMessageToFlashMessageQueue('FileUtility.DestinationWasNotADirectory', [$cmds['target']]);
965  return false;
966  }
967  $resultObject = null;
968  $fileName = $cmds['data'];
969  try {
970  $resultObject = $targetFolderObject->createFile($fileName);
971  $this->writeLog(8, 0, 1, 'File created: "%s"', [$fileName]);
972  if ($resultObject->getName() !== $fileName) {
973  $this->addMessageToFlashMessageQueue('FileUtility.FileNameSanitized', [$fileName, $resultObject->getName()], FlashMessage::WARNING);
974  }
975  $this->addMessageToFlashMessageQueue('FileUtility.FileCreated', [$resultObject->getName()], FlashMessage::OK);
976  } catch (IllegalFileExtensionException $e) {
977  $this->writeLog(8, 1, 106, 'Extension of file "%s" was not allowed!', [$fileName]);
978  $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileWasNotAllowed', [$fileName]);
980  $this->writeLog(8, 1, 103, 'You are not allowed to create files!', []);
981  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToCreateFiles');
982  } catch (NotInMountPointException $e) {
983  $this->writeLog(8, 1, 102, 'Destination path "%s" was not within your mountpoints!', [$targetFolderObject->getIdentifier()]);
984  $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', [$targetFolderObject->getIdentifier()]);
985  } catch (ExistingTargetFileNameException $e) {
986  $this->writeLog(8, 1, 101, 'File existed already in "%s"!', [$targetFolderObject->getIdentifier()]);
987  $this->addMessageToFlashMessageQueue('FileUtility.FileExistedAlreadyIn', [$targetFolderObject->getIdentifier()]);
988  } catch (InvalidFileNameException $e) {
989  $this->writeLog(8, 1, 106, 'File name "%s" was not allowed!', [$fileName]);
990  $this->addMessageToFlashMessageQueue('FileUtility.FileNameWasNotAllowed', [$fileName]);
991  } catch (\RuntimeException $e) {
992  $this->writeLog(8, 1, 100, 'File "%s" was not created! Write-permission problem in "%s"?', [$fileName, $targetFolderObject->getIdentifier()]);
993  $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotCreated', [$fileName, $targetFolderObject->getIdentifier()]);
994  }
995  return $resultObject;
996  }
997 
1004  public function func_edit($cmds)
1005  {
1006  // Example identifier for $cmds['target'] => "4:mypath/tomyfolder/myfile.jpg"
1007  // for backwards compatibility: the combined file identifier was the path+filename
1008  $fileIdentifier = $cmds['target'];
1009  $fileObject = $this->getFileObject($fileIdentifier);
1010  // Example identifier for $cmds['target'] => "2:targetpath/targetfolder/"
1011  $content = $cmds['data'];
1012  if (!$fileObject instanceof File) {
1013  $this->writeLog(9, 2, 123, 'Target "%s" was not a file!', [$fileIdentifier]);
1014  $this->addMessageToFlashMessageQueue('FileUtility.TargetWasNotAFile', [$fileIdentifier]);
1015  return false;
1016  }
1017  $extList = $GLOBALS['TYPO3_CONF_VARS']['SYS']['textfile_ext'];
1018  if (!GeneralUtility::inList($extList, $fileObject->getExtension())) {
1019  $this->writeLog(9, 1, 102, 'File extension "%s" is not a textfile format! (%s)', [$fileObject->getExtension(), $extList]);
1020  $this->addMessageToFlashMessageQueue('FileUtility.FileExtensionIsNotATextfileFormat', [$fileObject->getExtension(), $extList]);
1021  return false;
1022  }
1023  try {
1024  $fileObject->setContents($content);
1025  clearstatcache();
1026  $this->writeLog(9, 0, 1, 'File saved to "%s", bytes: %s, MD5: %s ', [$fileObject->getIdentifier(), $fileObject->getSize(), md5($content)]);
1027  $this->addMessageToFlashMessageQueue('FileUtility.FileSavedToBytesMd5', [$fileObject->getIdentifier(), $fileObject->getSize(), md5($content)], FlashMessage::OK);
1028  return true;
1030  $this->writeLog(9, 1, 104, 'You are not allowed to edit files!', []);
1031  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToEditFiles');
1032  return false;
1034  $this->writeLog(9, 1, 100, 'File "%s" was not saved! Write-permission problem?', [$fileObject->getIdentifier()]);
1035  $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotSaved', [$fileObject->getIdentifier()]);
1036  return false;
1037  } catch (IllegalFileExtensionException $e) {
1038  $this->writeLog(9, 1, 100, 'File "%s" was not saved! File extension rejected!', [$fileObject->getIdentifier()]);
1039  $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotSaved', [$fileObject->getIdentifier()]);
1040  return false;
1041  } catch (\RuntimeException $e) {
1042  $this->writeLog(9, 1, 100, 'File "%s" was not saved! File extension rejected!', [$fileObject->getIdentifier()]);
1043  $this->addMessageToFlashMessageQueue('FileUtility.FileWasNotSaved', [$fileObject->getIdentifier()]);
1044  return false;
1045  }
1046  }
1047 
1078  public function func_upload($cmds)
1079  {
1080  $uploadPosition = $cmds['data'];
1081  $uploadedFileData = $_FILES['upload_' . $uploadPosition];
1082  if (empty($uploadedFileData['name']) || is_array($uploadedFileData['name']) && empty($uploadedFileData['name'][0])) {
1083  $this->writeLog(1, 2, 108, 'No file was uploaded!', []);
1084  $this->addMessageToFlashMessageQueue('FileUtility.NoFileWasUploaded');
1085  return false;
1086  }
1087  // Example identifier for $cmds['target'] => "2:targetpath/targetfolder/"
1088  $targetFolderObject = $this->getFileObject($cmds['target']);
1089  // Uploading with non HTML-5-style, thus, make an array out of it, so we can loop over it
1090  if (!is_array($uploadedFileData['name'])) {
1091  $uploadedFileData = [
1092  'name' => [$uploadedFileData['name']],
1093  'type' => [$uploadedFileData['type']],
1094  'tmp_name' => [$uploadedFileData['tmp_name']],
1095  'size' => [$uploadedFileData['size']]
1096  ];
1097  }
1098  $resultObjects = [];
1099  $numberOfUploadedFilesForPosition = count($uploadedFileData['name']);
1100  // Loop through all uploaded files
1101  for ($i = 0; $i < $numberOfUploadedFilesForPosition; $i++) {
1102  $fileInfo = [
1103  'name' => $uploadedFileData['name'][$i],
1104  'type' => $uploadedFileData['type'][$i],
1105  'tmp_name' => $uploadedFileData['tmp_name'][$i],
1106  'size' => $uploadedFileData['size'][$i]
1107  ];
1108  try {
1110  $fileObject = $targetFolderObject->addUploadedFile($fileInfo, (string)$this->existingFilesConflictMode);
1111  $fileObject = ResourceFactory::getInstance()->getFileObjectByStorageAndIdentifier($targetFolderObject->getStorage()->getUid(), $fileObject->getIdentifier());
1112  if ($this->existingFilesConflictMode->equals(DuplicationBehavior::REPLACE)) {
1113  $this->getIndexer($fileObject->getStorage())->updateIndexEntry($fileObject);
1114  }
1115  $resultObjects[] = $fileObject;
1116  $this->internalUploadMap[$uploadPosition] = $fileObject->getCombinedIdentifier();
1117  if ($fileObject->getName() !== $fileInfo['name']) {
1118  $this->addMessageToFlashMessageQueue('FileUtility.FileNameSanitized', [$fileInfo['name'], $fileObject->getName()], FlashMessage::WARNING);
1119  }
1120  $this->writeLog(1, 0, 1, 'Uploading file "%s" to "%s"', [$fileInfo['name'], $targetFolderObject->getIdentifier()]);
1121  $this->addMessageToFlashMessageQueue('FileUtility.UploadingFileTo', [$fileInfo['name'], $targetFolderObject->getIdentifier()], FlashMessage::OK);
1123  $this->writeLog(1, 1, 107, 'You are not allowed to override "%s"!', [$fileInfo['name']]);
1124  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToOverride', [$fileInfo['name']]);
1125  } catch (UploadException $e) {
1126  $this->writeLog(1, 2, 106, 'The upload has failed, no uploaded file found!', []);
1127  $this->addMessageToFlashMessageQueue('FileUtility.TheUploadHasFailedNoUploadedFileFound');
1129  $this->writeLog(1, 1, 105, 'You are not allowed to upload files!', []);
1130  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToUploadFiles');
1131  } catch (UploadSizeException $e) {
1132  $this->writeLog(1, 1, 104, 'The uploaded file "%s" exceeds the size-limit', [$fileInfo['name']]);
1133  $this->addMessageToFlashMessageQueue('FileUtility.TheUploadedFileExceedsTheSize-limit', [$fileInfo['name']]);
1135  $this->writeLog(1, 1, 103, 'Destination path "%s" was not within your mountpoints!', [$targetFolderObject->getIdentifier()]);
1136  $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', [$targetFolderObject->getIdentifier()]);
1137  } catch (IllegalFileExtensionException $e) {
1138  $this->writeLog(1, 1, 102, 'Extension of file name "%s" is not allowed in "%s"!', [$fileInfo['name'], $targetFolderObject->getIdentifier()]);
1139  $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameIsNotAllowedIn', [$fileInfo['name'], $targetFolderObject->getIdentifier()]);
1140  } catch (ExistingTargetFileNameException $e) {
1141  $this->writeLog(1, 1, 101, 'No unique filename available in "%s"!', [$targetFolderObject->getIdentifier()]);
1142  $this->addMessageToFlashMessageQueue('FileUtility.NoUniqueFilenameAvailableIn', [$targetFolderObject->getIdentifier()]);
1143  } catch (\RuntimeException $e) {
1144  $this->writeLog(1, 1, 100, 'Uploaded file could not be moved! Write-permission problem in "%s"?', [$targetFolderObject->getIdentifier()]);
1145  $this->addMessageToFlashMessageQueue('FileUtility.UploadedFileCouldNotBeMoved', [$targetFolderObject->getIdentifier()]);
1146  }
1147  }
1148 
1149  return $resultObjects;
1150  }
1151 
1162  protected function replaceFile(array $cmdArr)
1163  {
1164  $uploadPosition = $cmdArr['data'];
1165  $fileInfo = $_FILES['replace_' . $uploadPosition];
1166  if (empty($fileInfo['name'])) {
1167  $this->writeLog(1, 2, 108, 'No file was uploaded for replacing!', []);
1168  $this->addMessageToFlashMessageQueue('FileUtility.NoFileWasUploadedForReplacing');
1169  return false;
1170  }
1171 
1172  $keepFileName = ($cmdArr['keepFilename'] == 1) ? true : false;
1173  $resultObjects = [];
1174 
1175  try {
1176  $fileObjectToReplace = $this->getFileObject($cmdArr['uid']);
1177  $folder = $fileObjectToReplace->getParentFolder();
1178  $resourceStorage = $fileObjectToReplace->getStorage();
1179 
1180  $fileObject = $resourceStorage->addUploadedFile($fileInfo, $folder, $fileObjectToReplace->getName(), DuplicationBehavior::REPLACE);
1181 
1182  // Check if there is a file that is going to be uploaded that has a different name as the replacing one
1183  // but exists in that folder as well.
1184  // rename to another name, but check if the name is already given
1185  if ($keepFileName === false) {
1186  // if a file with the same name already exists, we need to change it to _01 etc.
1187  // if the file does not exist, we can do a simple rename
1188  $resourceStorage->moveFile($fileObject, $folder, $fileInfo['name'], DuplicationBehavior::RENAME);
1189  }
1190 
1191  $resultObjects[] = $fileObject;
1192  $this->internalUploadMap[$uploadPosition] = $fileObject->getCombinedIdentifier();
1193 
1194  $this->writeLog(1, 0, 1, 'Replacing file "%s" to "%s"', [$fileInfo['name'], $fileObjectToReplace->getIdentifier()]);
1195  $this->addMessageToFlashMessageQueue('FileUtility.ReplacingFileTo', [$fileInfo['name'], $fileObjectToReplace->getIdentifier()], FlashMessage::OK);
1197  $this->writeLog(1, 1, 107, 'You are not allowed to override "%s"!', [$fileInfo['name']]);
1198  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToOverride', [$fileInfo['name']]);
1199  } catch (UploadException $e) {
1200  $this->writeLog(1, 2, 106, 'The upload has failed, no uploaded file found!', []);
1201  $this->addMessageToFlashMessageQueue('FileUtility.TheUploadHasFailedNoUploadedFileFound');
1203  $this->writeLog(1, 1, 105, 'You are not allowed to upload files!', []);
1204  $this->addMessageToFlashMessageQueue('FileUtility.YouAreNotAllowedToUploadFiles');
1205  } catch (UploadSizeException $e) {
1206  $this->writeLog(1, 1, 104, 'The uploaded file "%s" exceeds the size-limit', [$fileInfo['name']]);
1207  $this->addMessageToFlashMessageQueue('FileUtility.TheUploadedFileExceedsTheSize-limit', [$fileInfo['name']]);
1209  $this->writeLog(1, 1, 103, 'Destination path "%s" was not within your mountpoints!', [$fileObjectToReplace->getIdentifier()]);
1210  $this->addMessageToFlashMessageQueue('FileUtility.DestinationPathWasNotWithinYourMountpoints', [$fileObjectToReplace->getIdentifier()]);
1211  } catch (IllegalFileExtensionException $e) {
1212  $this->writeLog(1, 1, 102, 'Extension of file name "%s" is not allowed in "%s"!', [$fileInfo['name'], $fileObjectToReplace->getIdentifier()]);
1213  $this->addMessageToFlashMessageQueue('FileUtility.ExtensionOfFileNameIsNotAllowedIn', [$fileInfo['name'], $fileObjectToReplace->getIdentifier()]);
1214  } catch (ExistingTargetFileNameException $e) {
1215  $this->writeLog(1, 1, 101, 'No unique filename available in "%s"!', [$fileObjectToReplace->getIdentifier()]);
1216  $this->addMessageToFlashMessageQueue('FileUtility.NoUniqueFilenameAvailableIn', [$fileObjectToReplace->getIdentifier()]);
1217  } catch (\RuntimeException $e) {
1218  throw $e;
1219  }
1220  return $resultObjects;
1221  }
1222 
1228  protected function addFlashMessage(FlashMessage $flashMessage)
1229  {
1231  $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1232 
1234  $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1235  $defaultFlashMessageQueue->enqueue($flashMessage);
1236  }
1237 
1244  protected function getIndexer(ResourceStorage $storage)
1245  {
1246  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Index\Indexer::class, $storage);
1247  }
1248 
1252  protected function getBackendUser()
1253  {
1254  return $GLOBALS['BE_USER'];
1255  }
1256 
1262  protected function getLanguageService()
1263  {
1264  return $GLOBALS['LANG'];
1265  }
1266 }
writeLog($action, $error, $details_nr, $details, $data)
addMessageToFlashMessageQueue($localizationKey, array $replaceMarkers=[], $severity=FlashMessage::ERROR)
static makeInstance($className,... $constructorArguments)
static getConstants($include_default=false)
getFiles($start=0, $numberOfItems=0, $filterMode=self::FILTER_MODE_USE_OWN_AND_STORAGE_FILTERS, $recursive=false, $sort='', $sortRev=false)
Definition: Folder.php:217
const FILTER_MODE_USE_OWN_AND_STORAGE_FILTERS
Definition: Folder.php:68
static getRecord($table, $uid, $fields=' *', $where='', $useDeleteClause=true)
if(TYPO3_MODE==='BE') $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsfebeuserauth.php']['frontendEditingController']['default']