/** * Processes the actual transformation from CSV to sys_file_references * * @param array $record * @return void */ protected function migrateRecord(array $record) { $collections = array(); $files = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $record['image'], TRUE); $descriptions = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $record['imagecaption']); $titleText = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $record['imagetitletext']); $i = 0; foreach ($files as $file) { if (file_exists(PATH_site . 'uploads/tx_cal/pics/' . $file)) { \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . 'uploads/tx_cal/pics/' . $file, $this->targetDirectory . $file); $fileObject = $this->storage->getFile(self::FOLDER_ContentUploads . '/' . $file); //TYPO3 >= 6.2.0 if (\TYPO3\CMS\Core\Utility\VersionNumberUtility::convertVersionNumberToInteger(TYPO3_version) >= 6002000) { $this->fileIndexRepository->add($fileObject); } else { //TYPO3 6.1.0 $this->fileRepository->addToIndex($fileObject); } $dataArray = array('uid_local' => $fileObject->getUid(), 'tablenames' => $this->getRecordTableName(), 'uid_foreign' => $record['uid'], 'pid' => $record['pid'], 'fieldname' => 'image', 'sorting_foreign' => $i); if (isset($descriptions[$i])) { $dataArray['description'] = $descriptions[$i]; } if (isset($titleText[$i])) { $dataArray['alternative'] = $titleText[$i]; } $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_file_reference', $dataArray); unlink(PATH_site . 'uploads/tx_cal/pics/' . $file); } $i++; } $this->cleanRecord($record, $i, $collections); }
/** * Converts HTML-array to an object * @param array $attachments * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage */ public function initAttachments(array $attachments) { /* @var \Mittwald\Typo3Forum\Domain\Model\Forum\Attachment */ $objAttachments = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); foreach ($attachments as $attachmentID => $attachment) { if ($attachment['name'] == '') { continue; } $attachmentObj = $this->objectManager->get('Mittwald\\Typo3Forum\\Domain\\Model\\Forum\\Attachment'); $tmp_name = $_FILES['tx_typo3forum_pi1']['tmp_name']['attachments'][$attachmentID]; $mime_type = mime_content_type($tmp_name); //Save in ObjectStorage and in file system $attachmentObj->setFilename($attachment['name']); $attachmentObj->setRealFilename(sha1($attachment['name'] . time())); $attachmentObj->setMimeType($mime_type); //Create dir if not exists $tca = $attachmentObj->getTCAConfig(); $path = $tca['columns']['real_filename']['config']['uploadfolder']; if (!file_exists($path)) { mkdir($path, '0777', true); } //upload file and put in object storage $res = \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($tmp_name, $attachmentObj->getAbsoluteFilename()); if ($res === true) { $objAttachments->attach($attachmentObj); } } return $objAttachments; }
/** * @return FlashMessage */ public function execute() { $this->controller->headerMessage(LocalizationUtility::translate('moveDamRecordsToStorageCommand', 'dam_falmigration', array($this->storageObject->getName()))); if (!$this->isTableAvailable('tx_dam')) { return $this->getResultMessage('damTableNotFound'); } $this->fileIndexRepository = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Index\\FileIndexRepository'); $result = $this->execSelectNotMigratedDamRecordsQuery(); $counter = 0; $total = $this->database->sql_num_rows($result); $this->controller->infoMessage('Found ' . $total . ' DAM records without a connection to a sys_file storage'); $relativeTargetFolderBasePath = $this->storageBasePath . $this->targetFolderBasePath; while ($damRecord = $this->database->sql_fetch_assoc($result)) { $counter++; try { $relativeSourceFilePath = GeneralUtility::fixWindowsFilePath($this->getFullFileName($damRecord)); $absoluteSourceFilePath = PATH_site . $relativeSourceFilePath; if (!file_exists($absoluteSourceFilePath)) { throw new \RuntimeException('No file found for DAM record. DAM uid: ' . $damRecord['uid'] . ': "' . $relativeSourceFilePath . '"', 1441110613); } list($_, $directory) = explode('/', dirname($relativeSourceFilePath), 2); $relativeTargetFolder = $relativeTargetFolderBasePath . rtrim($directory, '/') . '/'; $absoluteTargetFolder = PATH_site . $relativeTargetFolder; if (!is_dir($absoluteTargetFolder)) { GeneralUtility::mkdir_deep($absoluteTargetFolder); } $basename = basename($relativeSourceFilePath); $absoluteTargetFilePath = $absoluteTargetFolder . $basename; if (!file_exists($absoluteTargetFilePath)) { GeneralUtility::upload_copy_move($absoluteSourceFilePath, $absoluteTargetFilePath); } elseif (filesize($absoluteSourceFilePath) !== filesize($absoluteTargetFilePath)) { throw new \RuntimeException('File already exists. DAM uid: ' . $damRecord['uid'] . ': "' . $relativeSourceFilePath . '"', 1441112138); } $fileIdentifier = substr($relativeTargetFolder, strlen($this->storageBasePath)) . $basename; $fileObject = $this->storageObject->getFile($fileIdentifier); $this->fileIndexRepository->add($fileObject); $this->updateDamFilePath($damRecord['uid'], $relativeTargetFolder); $this->amountOfMigratedRecords++; } catch (\Exception $e) { $this->setDamFileMissingByUid($damRecord['uid']); $this->controller->warningMessage($e->getMessage()); $this->amountOfFilesNotFound++; continue; } } $this->database->sql_free_result($result); $this->controller->message('Not migrated dam records at start of task: ' . $total . '. Migrated files after task: ' . $this->amountOfMigratedRecords . '. Files not found: ' . $this->amountOfFilesNotFound . '.'); return $this->getResultMessage(); }
/** * Upload file from $_FILES['qqfile'] * * @return string|bool false or filename like "file.png" */ public static function uploadFile() { $files = self::getFilesArray(); if (!is_array($files['qqfile'])) { return false; } if (empty($files['qqfile']['name']) || !self::checkExtension($files['qqfile']['name'])) { return false; } // create new filename and upload it $basicFileFunctions = self::getObjectManager()->get(BasicFileUtility::class); $filename = StringUtility::cleanString($files['qqfile']['name']); $newFile = $basicFileFunctions->getUniqueName($filename, GeneralUtility::getFileAbsFileName(self::getUploadFolderFromTca())); if (GeneralUtility::upload_copy_move($files['qqfile']['tmp_name'], $newFile)) { $fileInfo = pathinfo($newFile); return $fileInfo['basename']; } return false; }
function map($data, $settings) { $data = $this->mapToTCA($data, $settings); $media = $settings['media']; foreach ($media as $k => $path) { if ($data[$k]) { $basefile = basename($data[$k]); $unique_filename = $this->basicFileFunctions->getUniqueName(trim($basefile), $path); \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move('uploads/tx_nnfesubmit/' . $basefile, $unique_filename); if (file_exists($unique_filename)) { //$this->anyHelper->addFlashMessage ( 'Media kopiert', 'Die Datei '.$data[$k].' wurde erfolgreich verschoben.', 'OK'); unlink('uploads/tx_nnfesubmit/' . $basefile); $data[$k] = basename($unique_filename); } else { $this->anyHelper->addFlashMessage('Datei nicht kopiert', 'Die Datei ' . $data[$k] . ' konnte nicht kopiert werden.', 'WARNING'); unset($data[$k]); } } } return $data; }
/** * File Upload * * @param string $destinationPath * @param Mail $mail * @param string $fileExtensions allowed file extensions * @return bool */ public static function fileUpload($destinationPath, Mail $mail, $fileExtensions = '') { $result = false; $files = self::getFilesArray(); if (isset($files['tx_powermail_pi1']['tmp_name']['field']) && self::hasFormAnUploadField($mail->getForm())) { foreach (array_keys($files['tx_powermail_pi1']['tmp_name']['field']) as $marker) { foreach ($files['tx_powermail_pi1']['tmp_name']['field'][$marker] as $key => $tmpName) { if (!empty($files['tx_powermail_pi1']['name']['field'][$marker][$key])) { $uniqueFileName = self::getUniqueName($files['tx_powermail_pi1']['name']['field'][$marker][$key], $destinationPath); if (self::checkExtension($uniqueFileName, $fileExtensions) && self::checkFolder($uniqueFileName)) { $result = GeneralUtility::upload_copy_move($tmpName, $uniqueFileName); } } } } } return $result; }
/** * Migrate files to sys_file_references * * @param array $record * @param string $field * @return void */ protected function migrateFiles(array $record, $field) { $filesList = $record['tx_jhopengraphprotocol_ogimage']; $files = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $filesList, TRUE); if ($files) { foreach ($files as $file) { if (file_exists(PATH_site . 'uploads/tx_jhopengraphprotocol/' . $file)) { \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . 'uploads/tx_jhopengraphprotocol/' . $file, $this->targetDirectory . $file); $fileObject = $this->storage->getFile(self::FOLDER_ContentUploads . '/' . $file); $this->fileRepository->add($fileObject); $dataArray = array('uid_local' => $fileObject->getUid(), 'tablenames' => 'pages', 'fieldname' => $field, 'uid_foreign' => $record['uid'], 'table_local' => 'sys_file', 'cruser_id' => self::CruserId, 'pid' => $record['pid'], 'sorting_foreign' => $record['sorting'], 'title' => $record['title']); $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_file_reference', $dataArray); } } } }
/** * Show Form action step 3 * * @param \Winkel\WinkelProducts\Domain\Model\Bearing $bearing * @param string $firstName * @param string $lastName * @param string $companyName * @param string $email * @param string $address * @param string $cadFormat * @param string $cadDownloadUrl * @return void * @see http://forge.typo3.org/projects/typo3v45-projects/wiki/SwiftMailer * @todo $cadFormat / $cadDownloadUrl prüfen */ public function showFormStep3Action(\Winkel\WinkelProducts\Domain\Model\Bearing $bearing = NULL, $firstName, $lastName, $companyName, $email, $phone, $cadFormat = NULL, $cadDownloadUrl = NULL) { $error = FALSE; $textProfile = ''; $textFlangePlate = ''; $request = $this->request->getArguments(); // echo '<pre>'; // var_dump($request); // echo '</pre>'; if (array_key_exists('firstName', $request)) { $firstName = $this->request->getArgument('firstName'); } if (array_key_exists('lastName', $request)) { $lastName = $this->request->getArgument('lastName'); } if (array_key_exists('companyName', $request)) { $companyName = $this->request->getArgument('companyName'); } if (array_key_exists('address', $request)) { $address = $this->request->getArgument('address'); } if (array_key_exists('zip', $request)) { $zip = $this->request->getArgument('zip'); } if (array_key_exists('city', $request)) { $city = $this->request->getArgument('city'); } if (array_key_exists('country', $request)) { $country = $this->request->getArgument('country'); } if (array_key_exists('email', $request)) { // todo validEmail if (\TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($this->request->getArgument('email')) === TRUE) { $textContact = 'E-Mail: ' . $this->request->getArgument('email') . "\n"; $email = $this->request->getArgument('email'); } else { $error = TRUE; $this->flashMessageContainer->add('Fehlerhafte E-Mail'); } } else { $error = TRUE; $this->flashMessageContainer->add('Keine E-Mail'); } if (array_key_exists('phone', $request)) { $phone = $this->request->getArgument('phone'); } foreach ($request as $key => $singleRequest) { // Flangeplate if (substr($key, -8) == '-count-f') { $anfang = substr($key, 0, -8); $flangeplate[$this->request->getArgument($anfang . '-name-f')] = array('count' => $this->request->getArgument($anfang . '-count-f'), 'uid' => $this->request->getArgument($anfang . '-uid-f'), 'name' => $this->request->getArgument($anfang . '-name-f')); $textFlangePlate .= 'Flangeplate: ' . $this->request->getArgument($anfang . '-count-f') . ' Stück ' . $this->request->getArgument($anfang . '-name-f') . "\n\n"; } // Profile // lenght ist nur bei profilen vorhanden! if (substr($key, -7) == '-length') { $anfang = substr($key, 0, -7); $profile[$this->request->getArgument($anfang . '-name')] = array('count' => $this->request->getArgument($anfang . '-count'), 'lenght' => $this->request->getArgument($anfang . '-length'), 'uid' => $this->request->getArgument($anfang . '-uid'), 'name' => $this->request->getArgument($anfang . '-name')); $profile[$this->request->getArgument($anfang . '-name')]['fine-straightened'] = ''; if (array_key_exists($anfang . '-fine-straightened', $request)) { if ($this->request->getArgument($anfang . '-fine-straightened') == '1') { $profile[$this->request->getArgument($anfang . '-name')]['fine-straightened'] = ' Feingerichtet'; } } $textProfile .= 'Profil: ' . $this->request->getArgument($anfang . '-count') . ' Stück ' . "\n" . $this->request->getArgument($anfang . '-name') . "\n" . ' Länge: ' . $this->request->getArgument($anfang . '-length') . ' mm' . "\n" . $profile[$this->request->getArgument($anfang . '-name')]['fine-straightened'] . "\n\n"; } } if ($textFlangePlate != '') { $textFlangePlate = 'Gewählte Anschraubplatten:' . "\n" . '==========================' . "\n" . $textFlangePlate; } if ($textProfile != '') { $textProfile = 'Gewählte Profile:' . "\n" . '==========================' . "\n" . $textProfile; } #echo '<pre>'; #var_dump($profile); #echo '</pre>'; /* if(array_key_exists('profile', $request)) { $profileUid = intval($this->request->getArgument('profile')); $profile = $this->profileRepository->findByUid($profileUid); $textProfile = 'Profile: ' . $this->request->getArgument('profile-count') . ' Stück ' . $profile->getTitle() . ' Länge: ' . $this->request->getArgument('profile-length') . ' Meter'. "\n". ' Feingerichtet: ' . $this->request->getArgument('profile-fine-straightened'); $this->view->assign('currentProfile', $profile); } else { $textProfile = ''; } if(array_key_exists('flangeplate', $request)) { $flangePlateUid = intval($this->request->getArgument('flangeplate')); #var_dump($flangePlateUid); $flangePlate = $this->flangePlateRepository->findByUid($flangePlateUid); $textFlangePlate = 'FlangePlate: ' . $this->request->getArgument('flangeplate-count') . ' Stück ' . $flangePlate->getType() . "\n"; $this->view->assign('currentFlangePlate', $flangePlate); } else { $textFlangePlate = ''; } */ $moredetails = ''; if ($this->request->hasArgument('moredetails')) { if ($this->request->getArgument('moredetails') != '') { $comment = $this->request->getArgument('moredetails'); $moredetails = 'Weitere Informationen: ' . "\n" . $comment . "\n"; } } $angebot = 0; $angebotMessage = ''; if ($this->request->hasArgument('angebot')) { if ($this->request->getArgument('angebot') == '1') { $angebotMessage = 'Kunde wünscht ein Angebot'; } } if ($_FILES['tx_winkelproducts_pi1']['name']['flangeplate-pdf'] != '') { $flangeplatePdf = 'Anhang vorhanden' . "\n"; #var_dump($_FILES); $basicFileFunctions = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('t3lib_basicFileFunctions'); $fileName = $basicFileFunctions->getUniqueName($_FILES['tx_winkelproducts_pi1']['name']['flangeplate-pdf'], \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('uploads/tx_winkelproducts/')); $mimeType = $_FILES['tx_winkelproducts_pi1']['type']['flangeplate-pdf']; \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($_FILES['tx_winkelproducts_pi1']['tmp_name']['flangeplate-pdf'], $fileName); $pdf = basename($fileName); #var_dump($fileName); } else { $flangeplatePdf = 'Kein Anhang' . "\n"; } # $error = TRUE; $this->view->assign('bearing', $bearing); $this->view->assign('error', $error); if ($error === TRUE) { // @todo Errormeldungen setzen $request['firstName'] = $this->request->getArgument('firstName'); $request['lastName'] = $this->request->getArgument('lastName'); $request['cadFormat'] = $this->request->getArgument('cadFormat'); $request['angebot'] = $this->request->getArgument('angebot'); $request['bearing-count'] = $this->request->getArgument('bearing-count'); $request['flangeplate-count'] = $this->request->getArgument('flangeplate-count'); $request['cadDownloadUrl'] = $this->request->getArgument('cadDownloadUrl'); if ($this->request->getArgument('newsletter') == '1') { $request['newsletterChecked'] = TRUE; } else { $request['newsletterChecked'] = FALSE; } if ($this->request->getArgument('angebot') == '1') { $request['angebotChecked'] = TRUE; } else { $request['angebotChecked'] = FALSE; } $this->view->assign('request', $request); } else { // DebuggerUtility::var_dump($bearing, 'Bearing'); /** @var \Winkel\WinkelCustomerlog\Domain\Model\CustomerData */ $customerData = $this->objectManager->get('\\Winkel\\WinkelCustomerlog\\Domain\\Model\\CustomerData'); $xIP = (string) getenv('HTTP_X_FORWARDED_FOR'); $ip = (string) getenv('REMOTE_ADDR'); if ($xIP != '') { $ip = $xIP; } $customerData->setIp($ip); $language = $GLOBALS['TSFE']->config['config']['language']; $customerData->setLanguage($language); $customerData->setPid('2057'); $requestType = $this->requestTypeRepository->findByUid(2); $customerData->setRequestType($requestType); $customerData->setFirstName($firstName); $customerData->setLastName($lastName); $customerData->setCompany($companyName); $customerData->setComment($moredetails); $customerData->setEmail($email); $customerData->setTelephone($phone); $customerData->setArticleNumber($bearing->getArticleNumber()); $customerData->setArticleTitle($bearing->getTitleShow()); $customerData->setArticleCadFormat($cadFormat); $customerData->setCadDownloadUrl($cadDownloadUrl); #DebuggerUtility::var_dump($customerData); $message = 'WINKEL-Rolle: ' . $bearing->getTitleShow() . "\n" . '==========================' . "\n" . $this->request->getArgument('bearing-count') . ' Stück ' . "\n\n" . $textProfile . $textFlangePlate . $flangeplatePdf . '-------------------------------------' . "\n" . $moredetails . "\n" . '-------------------------------------' . "\n" . \Winkel\UserWebsite\Utilities\BuildAddressTextFromRequestObject::plainText($this->request) . 'Download-URL: ' . $cadDownloadUrl . "\n" . $angebotMessage; $customerData->setRaw($message); $subject = '[Produktanfrage Rolle] von ' . $companyName . ' (' . $firstName . ' ' . $lastName . ')'; \Winkel\UserWebsite\Utilities\SendMail::sendMailToAdmin($subject, $message); \Winkel\UserWebsite\Utilities\SendMail::sendMailToWinkel($subject, $message); // Daten in der Extension CustomerLog speichern $this->customerDataRepository->add($customerData); $this->persistenceManager->persistAll(); } }
/** * Sets the image * * @param \array $image * @return void */ public function setImage(array $image) { if (!empty($image['name'])) { // image name $imageName = $image['name']; // temporary name (incl. path) in upload directory $imageTempName = $image['tmp_name']; $basicFileUtility = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Utility\\File\\BasicFileUtility'); // determining a unique namens (incl. path) in // uploads/tx_simpleblog/ and copy file $imageNameNew = $basicFileUtility->getUniqueName($imageName, \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('uploads/tx_simpleblog/')); \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($imageTempName, $imageNameNew); // set name without path $this->image = basename($imageNameNew); } }
/** * @param string $fieldName * @return NULL|string * @throws FileTooLargeException * @throws FilePartiallyUploadedException * @throws NoFileUploadedException * @throws InvalidExtensionException */ public function processUploadedFile($fieldName) { if (!array_key_exists($fieldName, $this->files)) { return NULL; } $file = $this->files[$fieldName]; switch ($file['error']) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: new FileTooLargeException(); case UPLOAD_ERR_PARTIAL: new FilePartiallyUploadedException(); case UPLOAD_ERR_NO_FILE: new NoFileUploadedException(); } if (!$this->isAllowed($file['name'])) { throw new InvalidExtensionException('invalid file extension', 0, NULL, $this->allowedExtensions); } $basicFileFunctions = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Utility\\File\\BasicFileUtility'); $fileName = $basicFileFunctions->getUniqueName($file['name'], $this->uploadFolder); GeneralUtility::upload_copy_move($file['tmp_name'], $fileName); return 'uploads/tx_t3chimp/' . basename($fileName); }
/** * The actual sprite generator, renders the command for IM/GM and executes * * @return void */ protected function generateHighDensityGraphic() { $tempSprite = GeneralUtility::tempnam($this->spriteName . '@x2', '.png'); $filePath = PATH_site . $this->spriteFolder . $this->spriteName . '@x2.png'; // Create black true color image with given size $newSprite = imagecreatetruecolor($this->spriteWidth * 2, $this->spriteHeight * 2); imagesavealpha($newSprite, TRUE); // Make it transparent imagefill($newSprite, 0, 0, imagecolorallocatealpha($newSprite, 0, 255, 255, 127)); foreach ($this->iconsData as $icon) { $function = 'imagecreatefrom' . strtolower($icon['fileExtension']); if (function_exists($function)) { if ($icon['fileNameHighDensity'] !== FALSE) { // copy HighDensity file $currentIcon = $function($icon['fileNameHighDensity']); imagecopy($newSprite, $currentIcon, $icon['left'] * 2, $icon['top'] * 2, 0, 0, $icon['width'] * 2, $icon['height'] * 2); } else { // scale up normal file $currentIcon = $function($icon['fileName']); imagecopyresized($newSprite, $currentIcon, $icon['left'] * 2, $icon['top'] * 2, 0, 0, $icon['width'] * 2, $icon['height'] * 2, $icon['width'], $icon['height']); } } } imagepng($newSprite, $tempSprite); GeneralUtility::upload_copy_move($tempSprite, $filePath); GeneralUtility::unlink_tempfile($tempSprite); }
/** * wrapper for GeneralUtility::writeFile * checks for overwrite settings * * @param string $targetFile the path and filename of the targetFile * @param string $fileContents */ protected function upload_copy_move($sourceFile, $targetFile) { $overWriteMode = RoundTrip::getOverWriteSettingForPath($targetFile, $this->extension); if ($overWriteMode === -1) { // skip creation return; } if (!file_exists($targetFile) || $this->roundTripEnabled && $overWriteMode < 2) { GeneralUtility::upload_copy_move($sourceFile, $targetFile); } }
/** * Processes the actual transformation from CSV to sys_file_references * * @param array $source * @param array $destination * @param array $configuration * * @return void */ protected function migrateFilesToFal(array $source, array $destination, array $configuration) { $path = PATH_site . $configuration['sourcePath']; $files = GeneralUtility::trimExplode(',', $source[$configuration['sourceField']], true); $i = 1; foreach ($files as $file) { if (file_exists($path . $file)) { GeneralUtility::upload_copy_move($path . $file, $this->targetDirectory . $file); /** @var \TYPO3\CMS\Core\Resource\File $fileObject */ $fileObject = $this->storage->getFile(self::FILE_MIGRATION_FOLDER . $file); $this->fileIndexRepository->add($fileObject); $count = $this->database->exec_SELECTcountRows('*', 'sys_file_reference', 'tablenames = ' . $this->database->fullQuoteStr($configuration['destinationTable'], 'sys_file_reference') . ' AND fieldname = ' . $this->database->fullQuoteStr($configuration['destinationField'], 'sys_file_reference') . ' AND uid_local = ' . $fileObject->getUid() . ' AND uid_foreign = ' . $destination['uid']); if (!$count) { $dataArray = array('uid_local' => $fileObject->getUid(), 'tablenames' => $configuration['destinationTable'], 'uid_foreign' => $destination['uid'], 'pid' => $source['pid'], 'fieldname' => $configuration['destinationField'], 'sorting_foreign' => $i, 'table_local' => 'sys_file'); $this->database->exec_INSERTquery('sys_file_reference', $dataArray); } } $i++; } }
/** * action feeditAction * Bearbeiten eines bestehenden Datensatzes aus fremder Tabelle starten. * Dazu Kopie in tx_nnfesubmit_domain_model_entry anlegen und zum Formular weiterleiten * * @return array */ public function feeditAction($params) { $this->settings = $this->settingsUtility->getSettings(); $uid = intval($params['uid']); $type = $params['type']; $settings = $this->settings[$type]; $extName = $settings['extension']; // Prüfen, ob Datensatz in fremder Tabelle exisitert if (!($data = $this->tableService->getEntry($settings, $uid))) { return $this->anyHelper->addFlashMessage('Kein Eintrag gefunden', "In der Tabelle {$settings['tablename']} wurde kein Datensatz mit der uid={$uid} gefunden.", 'ERROR'); } // Datensatz zum Bearbeiten anlegen if (!($entry = $this->entryRepository->getEntryForExt($uid, $type))) { $entry = $this->objectManager->get('\\Nng\\Nnfesubmit\\Domain\\Model\\Entry'); $this->entryRepository->add($entry); $this->persistenceManager->persistAll(); //$unique_filename = $this->basicFileFunctions->getUniqueName($file, 'uploads/tx_nnfesubmit/'); //if (\TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($files['tmp_name'][$k], $unique_filename)) { } // Media zurück in den Ordner uploads/tx_nnfesubmit kopieren $media = $settings['media']; foreach ($media as $k => $path) { if ($data[$k]) { $unique_filename = $this->basicFileFunctions->getUniqueName(trim(basename($data[$k])), 'uploads/tx_nnfesubmit/'); \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($path . $data[$k], $unique_filename); if (!file_exists($unique_filename)) { $this->anyHelper->addFlashMessage('Datei nicht kopiert', 'Die Datei ' . $data[$k] . ' konnte nicht kopiert werden.', 'WARNING'); } } } //$entry->setFeUser( $GLOBALS['TSFE']->fe_user->user['uid'] ); $entry->setCruserId($GLOBALS['TSFE']->fe_user->user['uid']); $entry->setSrcuid($uid); $entry->setExt($type); $entry->setData(json_encode($data)); $this->entryRepository->update($entry); $this->persistenceManager->persistAll(); $entryUid = $entry->getUid(); $newAdminKey = ''; if ($params['adminKey'] && $this->anyHelper->validateKeyForUid($uid, $params['adminKey'], 'admin')) { $newAdminKey = $this->anyHelper->createKeyForUid($entryUid, 'admin'); } //http://adhok.99grad.de/index.php?id=17&id=17&nnf%5B193%5D%5Buid%5D=3&cHash=f14da214fc18a7f53b4da7342f3abe64&eID=nnfesubmit&action=feedit&type=nnfilearchive&uid=21&key=02bc7442 $this->anyHelper->httpRedirect($settings['editPid'], array('nnf' => $params['nnf'], 'tx_nnfesubmit_nnfesubmit[key]' => $this->anyHelper->createKeyForUid($entryUid), 'tx_nnfesubmit_nnfesubmit[adminKey]' => $newAdminKey, 'tx_nnfesubmit_nnfesubmit[entry]' => $entryUid, 'tx_nnfesubmit_nnfesubmit[pluginUid]' => intval($params['pluginUid']), 'tx_nnfesubmit_nnfesubmit[returnUrl]' => $params['returnUrl'])); // \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($entry); // $this->editAction( $entry->getUid() ); die; }
/** * Upload file from $_FILES['qqfile'] * * @return mixed false or filename like "file.png" */ public function uploadFile() { if (!is_array($_FILES['qqfile'])) { return FALSE; } if (empty($_FILES['qqfile']['name']) || !self::checkExtension($_FILES['qqfile']['name'])) { return FALSE; } // create new filename and upload it $basicFileFunctions = $this->objectManager->get('TYPO3\\CMS\\Core\\Utility\\File\\BasicFileUtility'); $filename = $this->cleanFileName($_FILES['qqfile']['name']); $newFile = $basicFileFunctions->getUniqueName($filename, GeneralUtility::getFileAbsFileName(self::getUploadFolderFromTca())); if (GeneralUtility::upload_copy_move($_FILES['qqfile']['tmp_name'], $newFile)) { $fileInfo = pathinfo($newFile); return $fileInfo['basename']; } return FALSE; }
/** * Check and validate field of type "group" * * @param string $field * @param array $val * @return string */ public function checkFieldFromTcaGroup($field, $val) { $config = $this->getFieldConfig($field); if ($config['internal_type'] == 'file') { $existingFiles = array(); // delete files if (!empty($val)) { foreach ($val as $file) { if (!empty($this->piVars[$field . 'del']) && in_array($file, $this->piVars[$field . 'del'])) { @unlink(PATH_site . $config['uploadfolder'] . '/' . $file); } else { $existingFiles[] = $file; } } } $uploadedFilenames = array_filter($_FILES[$this->prefixId]['name'][$field]); $uploadedTmpFilenames = array_filter($_FILES[$this->prefixId]['tmp_name'][$field]); // upload new file if (!empty($uploadedFilenames)) { if (!empty($config['maxitems'])) { if (count($existingFiles) == $config['maxitems']) { $this->validation->setError(sprintf($this->getLabel('uploadlimit'), $config['maxitems'])); } } foreach ($uploadedFilenames as $keyFilename => $filename) { $file = $uploadedTmpFilenames[$keyFilename]; $fileFunc = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Utility\\File\\BasicFileUtility'); $name = $fileFunc->getUniqueName($filename, PATH_site . $config['uploadfolder']); $fileName = substr($name, strlen(PATH_site . $config['uploadfolder']) + 1); $ext = pathinfo($fileName, PATHINFO_EXTENSION); if (!empty($config['allowed'])) { if ($this->validation->isInList($ext, $config['allowed'], sprintf($this->getLabel('errors.fileextension'), $this->getFieldLabel($field), $config['allowed'])) === true) { \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($file, $name); $existingFiles[] = $fileName; } } else { \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($file, $name); $existingFiles[] = $fileName; } } } return implode(',', $existingFiles); } if (empty($val)) { return $val; } if ($config['internal_type'] == 'db') { return implode(',', $val); } return $val; }
/** * Copies files which are referenced multiple times and updates the reference index so they are only used once * * @param array $multipleReferencesToFiles Contains files which have been referenced multiple times * @param bool $dryRun if set, the info is just displayed, but no files are copied nor reference index updated * @param SymfonyStyle $io the IO object for output * @return void */ protected function copyMultipleReferencedFiles(array $multipleReferencesToFiles, bool $dryRun, SymfonyStyle $io) { $fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class); $referenceIndex = GeneralUtility::makeInstance(ReferenceIndex::class); foreach ($multipleReferencesToFiles as $fileName => $usages) { $absoluteFileName = GeneralUtility::getFileAbsFileName($fileName); if ($absoluteFileName && @is_file($absoluteFileName)) { if ($io->isVeryVerbose()) { $io->writeln('Processing file "' . $absoluteFileName . '"'); } $counter = 0; foreach ($usages as $hash => $recReference) { if ($counter++ === 0) { $io->writeln('Keeping "' . $fileName . '" for record "' . $recReference . '"'); } else { // Create unique name for file $newName = $fileFunc->getUniqueName(basename($fileName), dirname($absoluteFileName)); $io->writeln('Copying "' . $fileName . '" to "' . PathUtility::stripPathSitePrefix($newName) . '" for record "' . $recReference . '"'); if (!$dryRun) { GeneralUtility::upload_copy_move($absoluteFileName, $newName); clearstatcache(); if (@is_file($newName)) { $error = $referenceIndex->setReferenceValue($hash, basename($newName)); if ($error) { $io->error('ReferenceIndex::setReferenceValue() reported "' . $error . '"'); } } else { $io->error('File "' . $newName . '" could not be created.'); } } } } } else { $io->error('File "' . $absoluteFileName . '" was not found.'); } } }
/** * Processes the actual transformation from CSV to sys_file_references * * @param array $record * @return void */ protected function migrateRecord(array $record) { $collections = array(); if (trim($record['select_key'])) { $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_file_collection', array('pid' => $record['pid'], 'title' => $record['select_key'], 'storage' => $this->storage->getUid(), 'folder' => ltrim('fileadmin/', $record['select_key']))); $collections[] = $GLOBALS['TYPO3_DB']->sql_insert_id(); } $files = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $record['media'], TRUE); $descriptions = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $record['imagecaption']); $titleText = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $record['titleText']); $i = 0; foreach ($files as $file) { if (file_exists(PATH_site . 'uploads/media/' . $file)) { \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . 'uploads/media/' . $file, $this->targetDirectory . $file); $fileObject = $this->storage->getFile(self::FOLDER_ContentUploads . '/' . $file); $this->fileRepository->addToIndex($fileObject); $dataArray = array('uid_local' => $fileObject->getUid(), 'tablenames' => 'tt_content', 'uid_foreign' => $record['uid'], 'fieldname' => 'media', 'sorting_foreign' => $i); if (isset($descriptions[$i])) { $dataArray['description'] = $descriptions[$i]; } if (isset($titleText[$i])) { $dataArray['alternative'] = $titleText[$i]; } $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_file_reference', $dataArray); unlink(PATH_site . 'uploads/media/' . $file); } $i++; } $this->cleanRecord($record, $i, $collections); }
/** * Copies any "RTEmagic" image files found in record with table/id to new names. * Usage: After copying a record this function should be called to search for "RTEmagic"-images inside the record. If such are found they should be duplicated to new names so all records have a 1-1 relation to them. * Reason for copying RTEmagic files: a) if you remove an RTEmagic image from a record it will remove the file - any other record using it will have a lost reference! b) RTEmagic images keeps an original and a copy. The copy always is re-calculated to have the correct physical measures as the HTML tag inserting it defines. This is calculated from the original. Two records using the same image could have difference HTML-width/heights for the image and the copy could only comply with one of them. If you don't want a 1-1 relation you should NOT use RTEmagic files but just insert it as a normal file reference to a file inside fileadmin/ folder * * @param string $table Table name * @param integer $theNewSQLID Record UID * @return void * @todo Define visibility */ public function copyRecord_fixRTEmagicImages($table, $theNewSQLID) { // Creating fileFunc object. if (!$this->fileFunc) { $this->fileFunc = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Utility\\File\\BasicFileUtility'); $this->include_filefunctions = 1; } // Select all RTEmagic files in the reference table from the table/ID $recs = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_refindex', 'ref_table=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('_FILE', 'sys_refindex') . ' AND ref_string LIKE ' . $GLOBALS['TYPO3_DB']->fullQuoteStr('%/RTEmagic%', 'sys_refindex') . ' AND softref_key=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('images', 'sys_refindex') . ' AND tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_refindex') . ' AND recuid=' . intval($theNewSQLID), '', 'sorting DESC'); // Traverse the files found and copy them: if (is_array($recs)) { foreach ($recs as $rec) { $filename = basename($rec['ref_string']); $fileInfo = array(); if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($filename, 'RTEmagicC_')) { $fileInfo['exists'] = @is_file(PATH_site . $rec['ref_string']); $fileInfo['original'] = substr($rec['ref_string'], 0, -strlen($filename)) . 'RTEmagicP_' . preg_replace('/\\.[[:alnum:]]+$/', '', substr($filename, 10)); $fileInfo['original_exists'] = @is_file(PATH_site . $fileInfo['original']); // CODE from tx_impexp and class.rte_images.php adapted for use here: if ($fileInfo['exists'] && $fileInfo['original_exists']) { // Initialize; Get directory prefix for file and set the original name: $dirPrefix = dirname($rec['ref_string']) . '/'; $rteOrigName = basename($fileInfo['original']); // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file! if ($rteOrigName && \TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/') && @is_dir(PATH_site . $dirPrefix)) { // RTE: // From the "original" RTE filename, produce a new "original" destination filename which is unused. $origDestName = $this->fileFunc->getUniqueName($rteOrigName, PATH_site . $dirPrefix); // Create copy file name: $pI = pathinfo($rec['ref_string']); $copyDestName = dirname($origDestName) . '/RTEmagicC_' . substr(basename($origDestName), 10) . '.' . $pI['extension']; if (!@is_file($copyDestName) && !@is_file($origDestName) && $origDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($origDestName) && $copyDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($copyDestName)) { // Making copies: \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileInfo['original'], $origDestName); \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $rec['ref_string'], $copyDestName); clearstatcache(); // Register this: $this->RTEmagic_copyIndex[$rec['tablename']][$rec['recuid']][$rec['field']][$rec['ref_string']] = substr($copyDestName, strlen(PATH_site)); // Check and update the record using the t3lib_refindex class: if (@is_file($copyDestName)) { $sysRefObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\ReferenceIndex'); $error = $sysRefObj->setReferenceValue($rec['hash'], substr($copyDestName, strlen(PATH_site)), FALSE, TRUE); if ($error) { echo $this->newlog('TYPO3\\CMS\\Core\\Database\\ReferenceIndex::setReferenceValue(): ' . $error, 1); } } else { $this->newlog('File "' . $copyDestName . '" was not created!', 1); } } else { $this->newlog('Could not construct new unique names for file!', 1); } } else { $this->newlog('Maybe directory of file was not within "uploads/"?', 1); } } else { $this->newlog('Trying to copy RTEmagic files (' . $rec['ref_string'] . ' / ' . $fileInfo['original'] . ') but one or both were missing', 1); } } } } }
protected function getFileMarker($marker, &$template, &$sims, &$rems) { if (!$this->isAllowed($marker)) { return; } $max = $GLOBALS['TCA']['tx_cal_' . $this->objectString]['columns'][$marker]['config']['maxitems']; $sims['###' . strtoupper($marker) . '###'] = ''; $sims['###' . strtoupper($marker) . '_VALUE###'] = ''; $sims['###' . strtoupper($marker) . '_CAPTION###'] = ''; $sims['###' . strtoupper($marker) . '_CAPTION_VALUE###'] = ''; if ($this->isConfirm) { $sims['###' . strtoupper($marker) . '###'] = ''; $fileFunc = new \TYPO3\CMS\Core\Utility\File\BasicFileUtility(); $all_files = array(); $all_files['webspace']['allow'] = '*'; $all_files['webspace']['deny'] = ''; $fileFunc->init('', $all_files); $allowedExt = array(); $denyExt = array(); if ($marker == 'image') { $allowedExt = explode(',', $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']); } else { if ($marker == 'attachment') { $allowedExt = explode(',', $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace']['allow']); $denyExt = explode(',', $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace']['deny']); } } $i = 0; // new files if (is_array($_FILES[$this->prefixId]['name'])) { foreach ($_FILES[$this->prefixId]['name'][$marker] as $id => $filename) { $theDestFile = ''; $iConf = $this->conf['view.'][$this->conf['view'] . '.'][strtolower($marker) . '_stdWrap.']; if ($_FILES[$this->prefixId]['error'][$marker][$id]) { continue; } else { $theFile = GeneralUtility::upload_to_tempfile($_FILES[$this->prefixId]['tmp_name'][$marker][$id]); $fI = GeneralUtility::split_fileref($filename); if (in_array($fI['fileext'], $denyExt)) { continue; } else { if ($marker == 'image' && !in_array($fI['fileext'], $allowedExt)) { continue; } } $theDestFile = $fileFunc->getUniqueName($fileFunc->cleanFileName($fI['file']), 'typo3temp'); GeneralUtility::upload_copy_move($theFile, $theDestFile); $iConf['file'] = $theDestFile; $return = '__NEW__' . basename($theDestFile); } $temp_sims = array(); $temp_sims['###INDEX###'] = $id; $temp_sims['###' . strtoupper($marker) . '_VALUE###'] = $return; $temp = ''; if ($marker == 'image') { $temp = $this->renderImage($iConf['file'], $this->controller->piVars[$marker . '_caption'][$id], $this->controller->piVars[$marker . '_title'][$id], $marker, true); } else { if ($marker == 'attachment' || $marker == 'ics_file') { $temp = $this->renderFile($iConf['file'], $this->controller->piVars[$marker . '_caption'][$id], $this->controller->piVars[$marker . '_title'][$id], $marker, true); } } if ($this->isAllowed($marker . '_caption')) { $temp .= $this->applyStdWrap($this->controller->piVars[$marker . '_caption'][$id], $marker . '_caption_stdWrap'); } if ($this->isAllowed($marker . '_title')) { $temp .= $this->applyStdWrap($this->controller->piVars[$marker . '_title'][$id], $marker . '_title_stdWrap'); } $sims['###' . strtoupper($marker) . '###'] .= \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($temp, $temp_sims, array(), array()); $i++; } } $removeFiles = $this->controller->piVars['remove_' . $marker] ? $this->controller->piVars['remove_' . $marker] : array(); $where = 'uid_foreign = ' . $this->conf['uid'] . ' AND tablenames=\'tx_cal_' . $this->objectString . '\' AND fieldname=\'' . $marker . '\' AND deleted=0'; if (!empty($removeFiles)) { $where .= ' AND uid not in (' . implode(',', array_values($removeFiles)) . ')'; } $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_file_reference', $where); while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) { if ($marker == 'image') { $temp = $this->renderImage($row, $row['description'], $row['title'], $marker, false); } else { if ($marker == 'attachment' || $marker == 'ics_file') { $temp = $this->renderFile($row, $row['description'], $row['title'], $marker, false); } } $temp_sims = array(); $temp_sims['###' . strtoupper($marker) . '_VALUE###'] = $row['uid']; foreach ($this->controller->piVars[$marker] as $index => $image) { if ($image == $row['uid']) { if (isset($this->controller->piVars[$marker . '_caption'][$index])) { $row['description'] = $this->controller->piVars[$marker . '_caption'][$index]; } if (isset($this->controller->piVars[$marker . '_title'][$index])) { $row['title'] = $this->controller->piVars[$marker . '_title'][$index]; } $temp_sims['###INDEX###'] = $index; break; } } if ($this->isAllowed($marker . '_caption')) { $temp .= $this->applyStdWrap($row['description'], $marker . '_caption_stdWrap'); } if ($this->isAllowed($marker . '_title')) { $temp .= $this->applyStdWrap($row['title'], $marker . '_title_stdWrap'); } $sims['###' . strtoupper($marker) . '###'] .= \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($temp, $temp_sims, array(), array()); } $GLOBALS['TYPO3_DB']->sql_free_result($result); foreach ($removeFiles as $removeFile) { $sims['###' . strtoupper($marker) . '###'] .= '<input type="hidden" name="tx_cal_controller[remove_' . $marker . '][]" value="' . $removeFile . '">'; } } else { if ($this->isEditMode && $this->rightsObj->isAllowedTo('edit', $this->objectString, $marker)) { $sims['###' . strtoupper($marker) . '###'] = ''; $i = 0; $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_file_reference', 'uid_foreign = ' . $this->conf['uid'] . ' AND tablenames=\'tx_cal_' . $this->objectString . '\' AND fieldname=\'' . $marker . '\' AND deleted=0'); while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) { $temp_sims = array(); $temp_sims['###' . strtoupper($marker) . '_VALUE###'] = $row['uid']; $temp = $this->cObj->stdWrap('', $this->conf['view.'][$this->conf['view'] . '.'][strtolower($marker) . '_stdWrap.']); if ($marker == 'image') { $temp_sims['###' . strtoupper($marker) . '_PREVIEW###'] = $this->renderImage($row, $row['description'], $row['title'], $marker, false); } else { if ($marker == 'attachment' || $marker == 'ics_file') { $temp_sims['###' . strtoupper($marker) . '_PREVIEW###'] = $this->renderFile($row, $row['description'], $row['title'], $marker, false); } } $temp = \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($temp, $temp_sims, array(), array()); if ($this->isAllowed($marker . '_caption')) { $temp .= $this->applyStdWrap($row['description'], $marker . '_caption_stdWrap'); } if ($this->isAllowed($marker . '_title')) { $temp .= $this->applyStdWrap($row['title'], $marker . '_title_stdWrap'); } $temp_sims['###INDEX###'] = $i; $sims['###' . strtoupper($marker) . '###'] .= \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($temp, $temp_sims, array(), array()); $i++; } $GLOBALS['TYPO3_DB']->sql_free_result($result); $upload = ''; for (; $i < $max; $i++) { $temp_sims = array(); $upload .= $this->cObj->stdWrap('', $this->conf['view.'][$this->conf['view'] . '.'][$marker . 'Upload_stdWrap.']); if ($this->isAllowed($marker . '_caption')) { $upload .= $this->applyStdWrap('', $marker . '_caption_stdWrap'); } if ($this->isAllowed($marker . '_title')) { $upload .= $this->applyStdWrap('', $marker . '_title_stdWrap'); } $temp_sims['###INDEX###'] = $i; $upload = \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($upload, $temp_sims, array(), array()); } $sims['###' . strtoupper($marker) . '###'] .= $upload; } else { if (!$this->isEditMode && $this->rightsObj->isAllowedTo('create', $this->objectString, $marker)) { for ($i = 0; $i < $max; $i++) { $value = ''; $upload = $this->cObj->stdWrap($value, $this->conf['view.'][$this->conf['view'] . '.'][$marker . 'Upload_stdWrap.']); $value = ''; if ($this->isAllowed($marker . '_caption')) { $upload .= $this->applyStdWrap('', $marker . '_caption_stdWrap'); } if ($this->isAllowed($marker . '_title')) { $upload .= $this->applyStdWrap('', $marker . '_title_stdWrap'); } $temp_sims['###INDEX###'] = $i; $sims['###' . strtoupper($marker) . '###'] .= \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($upload, $temp_sims, array(), array()); } } } } }
/** * Move an temporary uploaded file to the upload folder * * @return string */ public function moveTempFileToTempFolder() { $result = ''; $fileData = $this->getUploadedFileInfo(); if (count($fileData)) { /** @var $basicFileFunctions \TYPO3\CMS\Core\Utility\File\BasicFileUtility */ $basicFileFunctions = $this->objectManager->get(\TYPO3\CMS\Core\Utility\File\BasicFileUtility::Class); $filename = $basicFileFunctions->cleanFileName($fileData['filename']); $uploadFolder = \TYPO3\CMS\Core\Utility\PathUtility::getCanonicalPath(PATH_site . $this->tempFolder); $this->createUploadFolderIfNotExist($uploadFolder); $uniqueFilename = $basicFileFunctions->getUniqueName($filename, $uploadFolder); if (GeneralUtility::upload_copy_move($fileData['tmp_name'], $uniqueFilename)) { $result = basename($uniqueFilename); } } return $result; }
/** * Move the uploaded file to a new location. * * Use this method as an alternative to move_uploaded_file(). This method is * guaranteed to work in both SAPI and non-SAPI environments. * Implementations must determine which environment they are in, and use the * appropriate method (move_uploaded_file(), rename(), or a stream * operation) to perform the operation. * * $targetPath may be an absolute path, or a relative path. If it is a * relative path, resolution should be the same as used by PHP's rename() * function. * * The original file or stream MUST be removed on completion. * * If this method is called more than once, any subsequent calls MUST raise * an exception. * * When used in an SAPI environment where $_FILES is populated, when writing * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be * used to ensure permissions and upload status are verified correctly. * * If you wish to move to a stream, use getStream(), as SAPI operations * cannot guarantee writing to stream destinations. * * @see http://php.net/is_uploaded_file * @see http://php.net/move_uploaded_file * @param string $targetPath Path to which to move the uploaded file. * @throws \InvalidArgumentException if the $path specified is invalid. * @throws \RuntimeException on any error during the move operation, or on the second or subsequent call to the method. */ public function moveTo($targetPath) { if (!is_string($targetPath) || empty($targetPath)) { throw new \InvalidArgumentException('Invalid path while moving an uploaded file.', 1436717307); } if ($this->moved) { throw new \RuntimeException('Cannot move uploaded file, as it was already moved.', 1436717308); } // Check if the target path is inside the allowed paths of TYPO3, and make it absolute. $targetPath = GeneralUtility::getFileAbsFileName($targetPath); if (empty($targetPath)) { throw new \RuntimeException('Cannot move uploaded file, as it was already moved.', 1436717309); } if (!empty($this->file) && is_uploaded_file($this->file)) { if (GeneralUtility::upload_copy_move($this->file, $targetPath . basename($this->file)) === false) { throw new \RuntimeException('An error occurred while moving uploaded file', 1436717310); } } elseif ($this->stream) { $handle = fopen($targetPath, 'wb+'); if ($handle === false) { throw new \RuntimeException('Unable to write to target path.', 1436717311); } $this->stream->rewind(); while (!$this->stream->eof()) { fwrite($handle, $this->stream->read(4096)); } fclose($handle); } $this->moved = true; }
/** * Copies any "RTEmagic" image files found in record with table/id to new names. * Usage: After copying a record this function should be called to search for "RTEmagic"-images inside the record. If such are found they should be duplicated to new names so all records have a 1-1 relation to them. * Reason for copying RTEmagic files: a) if you remove an RTEmagic image from a record it will remove the file - any other record using it will have a lost reference! b) RTEmagic images keeps an original and a copy. The copy always is re-calculated to have the correct physical measures as the HTML tag inserting it defines. This is calculated from the original. Two records using the same image could have difference HTML-width/heights for the image and the copy could only comply with one of them. If you don't want a 1-1 relation you should NOT use RTEmagic files but just insert it as a normal file reference to a file inside fileadmin/ folder * * @param string $table Table name * @param int $theNewSQLID Record UID * @return void */ public function copyRecord_fixRTEmagicImages($table, $theNewSQLID) { // Creating fileFunc object. if (!$this->fileFunc) { $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class); $this->include_filefunctions = 1; } // Select all RTEmagic files in the reference table from the table/ID $where = join(' AND ', array('ref_table=' . $this->databaseConnection->fullQuoteStr('_FILE', 'sys_refindex'), 'ref_string LIKE ' . $this->databaseConnection->fullQuoteStr('%/RTEmagic%', 'sys_refindex'), 'softref_key=' . $this->databaseConnection->fullQuoteStr('images', 'sys_refindex'), 'tablename=' . $this->databaseConnection->fullQuoteStr($table, 'sys_refindex'), 'recuid=' . (int) $theNewSQLID)); $rteFileRecords = $this->databaseConnection->exec_SELECTgetRows('*', 'sys_refindex', $where, '', 'sorting DESC'); // Traverse the files found and copy them: if (!is_array($rteFileRecords)) { return; } foreach ($rteFileRecords as $rteFileRecord) { $filename = basename($rteFileRecord['ref_string']); if (!GeneralUtility::isFirstPartOfStr($filename, 'RTEmagicC_')) { continue; } $fileInfo = array(); $fileInfo['exists'] = @is_file(PATH_site . $rteFileRecord['ref_string']); $fileInfo['original'] = substr($rteFileRecord['ref_string'], 0, -strlen($filename)) . 'RTEmagicP_' . preg_replace('/\\.[[:alnum:]]+$/', '', substr($filename, 10)); $fileInfo['original_exists'] = @is_file(PATH_site . $fileInfo['original']); // CODE from tx_impexp and class.rte_images.php adapted for use here: if (!$fileInfo['exists'] || !$fileInfo['original_exists']) { if ($this->enableLogging) { $this->newlog('Trying to copy RTEmagic files (' . $rteFileRecord['ref_string'] . ' / ' . $fileInfo['original'] . ') but one or both were missing', 1); } continue; } // Initialize; Get directory prefix for file and set the original name: $dirPrefix = dirname($rteFileRecord['ref_string']) . '/'; $rteOrigName = basename($fileInfo['original']); // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file! if ($rteOrigName && GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/') && @is_dir(PATH_site . $dirPrefix)) { // RTE: // From the "original" RTE filename, produce a new "original" destination filename which is unused. $origDestName = $this->fileFunc->getUniqueName($rteOrigName, PATH_site . $dirPrefix); // Create copy file name: $pI = pathinfo($rteFileRecord['ref_string']); $copyDestName = dirname($origDestName) . '/RTEmagicC_' . substr(basename($origDestName), 10) . '.' . $pI['extension']; if (!@is_file($copyDestName) && !@is_file($origDestName) && $origDestName === GeneralUtility::getFileAbsFileName($origDestName) && $copyDestName === GeneralUtility::getFileAbsFileName($copyDestName)) { // Making copies: GeneralUtility::upload_copy_move(PATH_site . $fileInfo['original'], $origDestName); GeneralUtility::upload_copy_move(PATH_site . $rteFileRecord['ref_string'], $copyDestName); clearstatcache(); // Register this: $this->RTEmagic_copyIndex[$rteFileRecord['tablename']][$rteFileRecord['recuid']][$rteFileRecord['field']][$rteFileRecord['ref_string']] = PathUtility::stripPathSitePrefix($copyDestName); // Check and update the record using \TYPO3\CMS\Core\Database\ReferenceIndex if (@is_file($copyDestName)) { /** @var ReferenceIndex $sysRefObj */ $sysRefObj = GeneralUtility::makeInstance(ReferenceIndex::class); $error = $sysRefObj->setReferenceValue($rteFileRecord['hash'], PathUtility::stripPathSitePrefix($copyDestName), false, true); if ($this->enableLogging && $error) { echo $this->newlog(ReferenceIndex::class . '::setReferenceValue(): ' . $error, 1); } } elseif ($this->enableLogging) { $this->newlog('File "' . $copyDestName . '" was not created!', 1); } } elseif ($this->enableLogging) { $this->newlog('Could not construct new unique names for file!', 1); } } elseif ($this->enableLogging) { $this->newlog('Maybe directory of file was not within "uploads/"?', 1); } } }
/** * Adds a files content to the export memory * * @param array $fI File information with three keys: "filename" = filename without path, "ID_absFile" = absolute filepath to the file (including the filename), "ID" = md5 hash of "ID_absFile". "relFileName" is optional for files attached to records, but mandatory for soft referenced files (since the relFileName determines where such a file should be stored!) * @param string $recordRef If the file is related to a record, this is the id on the form [table]:[id]. Information purposes only. * @param string $fieldname If the file is related to a record, this is the field name it was related to. Information purposes only. * @return void */ public function export_addFile($fI, $recordRef = '', $fieldname = '') { if (!@is_file($fI['ID_absFile'])) { $this->error($fI['ID_absFile'] . ' was not a file! Skipping.'); return; } if (filesize($fI['ID_absFile']) >= $this->maxFileSize) { $this->error($fI['ID_absFile'] . ' was larger (' . GeneralUtility::formatSize(filesize($fI['ID_absFile'])) . ') than the maxFileSize (' . GeneralUtility::formatSize($this->maxFileSize) . ')! Skipping.'); return; } $fileInfo = stat($fI['ID_absFile']); $fileRec = array(); $fileRec['filesize'] = $fileInfo['size']; $fileRec['filename'] = PathUtility::basename($fI['ID_absFile']); $fileRec['filemtime'] = $fileInfo['mtime']; //for internal type file_reference $fileRec['relFileRef'] = PathUtility::stripPathSitePrefix($fI['ID_absFile']); if ($recordRef) { $fileRec['record_ref'] = $recordRef . '/' . $fieldname; } if ($fI['relFileName']) { $fileRec['relFileName'] = $fI['relFileName']; } // Setting this data in the header $this->dat['header']['files'][$fI['ID']] = $fileRec; // ... and for the recordlisting, why not let us know WHICH relations there was... if ($recordRef && $recordRef !== '_SOFTREF_') { $refParts = explode(':', $recordRef, 2); if (!is_array($this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'])) { $this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'] = array(); } $this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'][] = $fI['ID']; } $fileMd5 = md5_file($fI['ID_absFile']); if (!$this->saveFilesOutsideExportFile) { // ... and finally add the heavy stuff: $fileRec['content'] = GeneralUtility::getUrl($fI['ID_absFile']); } else { GeneralUtility::upload_copy_move($fI['ID_absFile'], $this->getTemporaryFilesPathForExport() . $fileMd5); } $fileRec['content_md5'] = $fileMd5; $this->dat['files'][$fI['ID']] = $fileRec; // For soft references, do further processing: if ($recordRef === '_SOFTREF_') { // RTE files? if ($RTEoriginal = $this->getRTEoriginalFilename(PathUtility::basename($fI['ID_absFile']))) { $RTEoriginal_absPath = PathUtility::dirname($fI['ID_absFile']) . '/' . $RTEoriginal; if (@is_file($RTEoriginal_absPath)) { $RTEoriginal_ID = md5($RTEoriginal_absPath); $fileInfo = stat($RTEoriginal_absPath); $fileRec = array(); $fileRec['filesize'] = $fileInfo['size']; $fileRec['filename'] = PathUtility::basename($RTEoriginal_absPath); $fileRec['filemtime'] = $fileInfo['mtime']; $fileRec['record_ref'] = '_RTE_COPY_ID:' . $fI['ID']; $this->dat['header']['files'][$fI['ID']]['RTE_ORIG_ID'] = $RTEoriginal_ID; // Setting this data in the header $this->dat['header']['files'][$RTEoriginal_ID] = $fileRec; $fileMd5 = md5_file($RTEoriginal_absPath); if (!$this->saveFilesOutsideExportFile) { // ... and finally add the heavy stuff: $fileRec['content'] = GeneralUtility::getUrl($RTEoriginal_absPath); } else { GeneralUtility::upload_copy_move($RTEoriginal_absPath, $this->getTemporaryFilesPathForExport() . $fileMd5); } $fileRec['content_md5'] = $fileMd5; $this->dat['files'][$RTEoriginal_ID] = $fileRec; } else { $this->error('RTE original file "' . PathUtility::stripPathSitePrefix($RTEoriginal_absPath) . '" was not found!'); } } // Files with external media? // This is only done with files grabbed by a softreference parser since it is deemed improbable that hard-referenced files should undergo this treatment. $html_fI = pathinfo(PathUtility::basename($fI['ID_absFile'])); if ($this->includeExtFileResources && GeneralUtility::inList($this->extFileResourceExtensions, strtolower($html_fI['extension']))) { $uniquePrefix = '###' . md5($GLOBALS['EXEC_TIME']) . '###'; if (strtolower($html_fI['extension']) === 'css') { $prefixedMedias = explode($uniquePrefix, preg_replace('/(url[[:space:]]*\\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\\))/i', '\\1' . $uniquePrefix . '\\2' . $uniquePrefix . '\\3', $fileRec['content'])); } else { // html, htm: $htmlParser = GeneralUtility::makeInstance(HtmlParser::class); $prefixedMedias = explode($uniquePrefix, $htmlParser->prefixResourcePath($uniquePrefix, $fileRec['content'], array(), $uniquePrefix)); } $htmlResourceCaptured = false; foreach ($prefixedMedias as $k => $v) { if ($k % 2) { $EXTres_absPath = GeneralUtility::resolveBackPath(PathUtility::dirname($fI['ID_absFile']) . '/' . $v); $EXTres_absPath = GeneralUtility::getFileAbsFileName($EXTres_absPath); if ($EXTres_absPath && GeneralUtility::isFirstPartOfStr($EXTres_absPath, PATH_site . $this->fileadminFolderName . '/') && @is_file($EXTres_absPath)) { $htmlResourceCaptured = true; $EXTres_ID = md5($EXTres_absPath); $this->dat['header']['files'][$fI['ID']]['EXT_RES_ID'][] = $EXTres_ID; $prefixedMedias[$k] = '{EXT_RES_ID:' . $EXTres_ID . '}'; // Add file to memory if it is not set already: if (!isset($this->dat['header']['files'][$EXTres_ID])) { $fileInfo = stat($EXTres_absPath); $fileRec = array(); $fileRec['filesize'] = $fileInfo['size']; $fileRec['filename'] = PathUtility::basename($EXTres_absPath); $fileRec['filemtime'] = $fileInfo['mtime']; $fileRec['record_ref'] = '_EXT_PARENT_:' . $fI['ID']; // Media relative to the HTML file. $fileRec['parentRelFileName'] = $v; // Setting this data in the header $this->dat['header']['files'][$EXTres_ID] = $fileRec; // ... and finally add the heavy stuff: $fileRec['content'] = GeneralUtility::getUrl($EXTres_absPath); $fileRec['content_md5'] = md5($fileRec['content']); $this->dat['files'][$EXTres_ID] = $fileRec; } } } } if ($htmlResourceCaptured) { $this->dat['files'][$fI['ID']]['tokenizedContent'] = implode('', $prefixedMedias); } } } }
/** * The actual sprite generator, renders the command for Im/GM and executes * * @return void */ protected function generateGraphic() { $tempSprite = \TYPO3\CMS\Core\Utility\GeneralUtility::tempnam($this->spriteName); $filePath = array('mainFile' => PATH_site . $this->spriteFolder . $this->spriteName . '.png'); // Create black true color image with given size $newSprite = imagecreatetruecolor($this->spriteWidth, $this->spriteHeight); imagesavealpha($newSprite, TRUE); // Make it transparent imagefill($newSprite, 0, 0, imagecolorallocatealpha($newSprite, 0, 255, 255, 127)); foreach ($this->iconsData as $icon) { $function = 'imagecreatefrom' . strtolower($icon['fileExtension']); if (function_exists($function)) { $currentIcon = $function($icon['fileName']); imagecopy($newSprite, $currentIcon, $icon['left'], $icon['top'], 0, 0, $icon['width'], $icon['height']); } } imagepng($newSprite, $tempSprite . '.png'); \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($tempSprite . '.png', $filePath['mainFile']); \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($tempSprite . '.png'); }
/** * Uploads a new avatar to the server. * @author Martin Helmich <*****@*****.**> * @author Georg Ringer <*****@*****.**> * @version 2007-10-03 * @param string $content The plugin content * @return string The content */ function uploadAvatar($content) { $avatarFile = $_FILES[$this->prefixId]; if (isset($this->piVars['del_avatar'])) { $this->user->removeAvatar($this->conf['path_avatar']); $this->user->updateDatabase(); return $content; } $fI = GeneralUtility::split_fileref($avatarFile['name']['file']); $fileExt = $fI['fileext']; if (!GeneralUtility::verifyFilenameAgainstDenyPattern($avatarFile['name']['file']) || !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExt)) { return ''; } if (isset($this->piVars['upload'])) { $uploaddir = $this->conf['path_avatar']; /* * Load the allowed file size for avatar image from the TCA and * check against the size of the uploaded image. */ if (filesize($avatarFile['tmp_name']['file']) > $GLOBALS['TCA']['fe_users']['columns']['tx_mmforum_avatar']['config']['max_size'] * 1024) { return ''; } $file = $this->user->getUid() . '_' . $GLOBALS['EXEC_TIME'] . '.' . $fileExt; $uploadfile = $uploaddir . $file; if (GeneralUtility::upload_copy_move($avatarFile['tmp_name']['file'], $uploadfile)) { $this->user->setAvatar($file); $this->user->updateDatabase(); } } return $content; }
/** * Processes the actual transformation from CSV to sys_file_references * * @param array $record * @param string $field * @return void */ protected function migrateRecord(array $record, $field) { if ($field === 'fal_related_files') { $file = $record['file']; } else { $file = $record['image']; } if (!empty($file) && file_exists(PATH_site . 'uploads/tx_news/' . $file)) { GeneralUtility::upload_copy_move(PATH_site . 'uploads/tx_news/' . $file, $this->targetDirectory . $file); $fileObject = $this->storage->getFile(self::FOLDER_ContentUploads . '/' . $file); $this->fileRepository->add($fileObject); $dataArray = ['uid_local' => $fileObject->getUid(), 'tablenames' => 'tx_news_domain_model_news', 'fieldname' => $field, 'uid_foreign' => $record['newsUid'], 'table_local' => 'sys_file', 'cruser_id' => 999, 'pid' => $record['newsPid'], 'sorting_foreign' => $record['sorting'], 'title' => $record['title'], 'hidden' => $record['hidden']]; if ($field === 'fal_media') { $description = []; if (!empty($record['caption'])) { $description[] = $record['caption']; } if (!empty($record['description'])) { $description[] = $record['description']; } $additionalData = ['description' => implode(LF . LF, $description), 'alternative' => $record['alt'], 'showinpreview' => $record['showinpreview']]; } else { $additionalData = ['description' => $record['description']]; } $dataArray += $additionalData; $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_file_reference', $dataArray); } }
/** * File Upload * * @param string $destinationPath * @param string $allowedFileExtensions * @param \In2code\Powermail\Domain\Model\Mail $mail * @return bool */ public static function fileUpload($destinationPath, $allowedFileExtensions = '', \In2code\Powermail\Domain\Model\Mail $mail) { $result = FALSE; if (isset($_FILES['tx_powermail_pi1']['tmp_name']['field']) && self::hasFormAnUploadField($mail->getForm())) { foreach (array_keys($_FILES['tx_powermail_pi1']['tmp_name']['field']) as $marker) { foreach ($_FILES['tx_powermail_pi1']['tmp_name']['field'][$marker] as $key => $tmpName) { $uniqueFileName = self::getUniqueName($_FILES['tx_powermail_pi1']['name']['field'][$marker][$key], $destinationPath); if (!self::checkExtension($uniqueFileName, $allowedFileExtensions)) { continue; } $result = GeneralUtility::upload_copy_move($tmpName, $uniqueFileName); } } } return $result; }
/** * Mandatory autofix function * Will run auto-fix on the result array. Echos status during processing. * * @param array $resultArray Result array from main() function * @return void */ public function main_autoFix($resultArray) { foreach ($resultArray['multipleReferencesList'] as $key => $value) { $absFileName = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($key); if ($absFileName && @is_file($absFileName)) { echo 'Processing file: ' . $key . LF; $c = 0; foreach ($value as $hash => $recReference) { if ($c == 0) { echo ' Keeping ' . $key . ' for record "' . $recReference . '"' . LF; } else { // Create unique name for file: $fileFunc = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Utility\File\BasicFileUtility::class); $newName = $fileFunc->getUniqueName(basename($key), dirname($absFileName)); echo ' Copying ' . $key . ' to ' . \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($newName) . ' for record "' . $recReference . '": '; if ($bypass = $this->cli_noExecutionCheck($recReference)) { echo $bypass; } else { \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($absFileName, $newName); clearstatcache(); if (@is_file($newName)) { $sysRefObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ReferenceIndex::class); $error = $sysRefObj->setReferenceValue($hash, basename($newName)); if ($error) { echo ' ERROR: TYPO3\\CMS\\Core\\Database\\ReferenceIndex::setReferenceValue(): ' . $error . LF; die; } else { echo 'DONE'; } } else { echo ' ERROR: File "' . $newName . '" was not created!'; } } echo LF; } $c++; } } else { echo ' ERROR: File "' . $absFileName . '" was not found!'; } } }
/** * Mandatory autofix function * Will run auto-fix on the result array. Echos status during processing. * * @param array $resultArray Result array from main() function * @return void */ public function main_autoFix($resultArray) { $limitTo = $this->cli_args['--AUTOFIX'][0]; if (is_array($resultArray['doubleFiles'])) { if (!$limitTo || $limitTo === 'doubleFiles') { echo 'FIXING double-usages of RTE files in uploads/: ' . LF; foreach ($resultArray['RTEmagicFilePairs'] as $fileName => $fileInfo) { // Only fix something if there is a usage count of more than 1 plus if both original and copy exists: if ($fileInfo['count'] > 1 && $fileInfo['exists'] && $fileInfo['original_exists']) { // Traverse all records using the file: $c = 0; foreach ($fileInfo['usedIn'] as $hash => $recordID) { if ($c == 0) { echo ' Keeping file ' . $fileName . ' for record ' . $recordID . LF; } else { // CODE below is adapted from \TYPO3\CMS\Impexp\ImportExport where there is support for duplication of RTE images: echo ' Copying file ' . basename($fileName) . ' for record ' . $recordID . ' '; // Initialize; Get directory prefix for file and set the original name: $dirPrefix = dirname($fileName) . '/'; $rteOrigName = basename($fileInfo['original']); // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file! if ($rteOrigName && \TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/') && @is_dir(PATH_site . $dirPrefix)) { // RTE: // From the "original" RTE filename, produce a new "original" destination filename which is unused. $fileProcObj = $this->getFileProcObj(); $origDestName = $fileProcObj->getUniqueName($rteOrigName, PATH_site . $dirPrefix); // Create copy file name: $pI = pathinfo($fileName); $copyDestName = dirname($origDestName) . '/RTEmagicC_' . substr(basename($origDestName), 10) . '.' . $pI['extension']; if (!@is_file($copyDestName) && !@is_file($origDestName) && $origDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($origDestName) && $copyDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($copyDestName)) { echo ' to ' . basename($copyDestName); if ($bypass = $this->cli_noExecutionCheck($fileName)) { echo $bypass; } else { // Making copies: \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileInfo['original'], $origDestName); \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileName, $copyDestName); clearstatcache(); if (@is_file($copyDestName)) { $sysRefObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ReferenceIndex::class); $error = $sysRefObj->setReferenceValue($hash, \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($copyDestName)); if ($error) { echo ' - ERROR: TYPO3\\CMS\\Core\\Database\\ReferenceIndex::setReferenceValue(): ' . $error . LF; die; } else { echo ' - DONE'; } } else { echo ' - ERROR: File "' . $copyDestName . '" was not created!'; } } } else { echo ' - ERROR: Could not construct new unique names for file!'; } } else { echo ' - ERROR: Maybe directory of file was not within "uploads/"?'; } echo LF; } $c++; } } } } else { echo 'Bypassing fixing of double-usages since --AUTOFIX was not "doubleFiles"' . LF; } } if (is_array($resultArray['lostFiles'])) { if ($limitTo === 'lostFiles') { echo 'Removing lost RTEmagic files from folders inside uploads/: ' . LF; foreach ($resultArray['lostFiles'] as $key => $value) { $absFileName = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($value); echo 'Deleting file: "' . $absFileName . '": '; if ($bypass = $this->cli_noExecutionCheck($absFileName)) { echo $bypass; } else { if ($absFileName && @is_file($absFileName)) { unlink($absFileName); echo 'DONE'; } else { echo ' ERROR: File "' . $absFileName . '" was not found!'; } } echo LF; } } } else { echo 'Bypassing fixing of double-usages since --AUTOFIX was not "lostFiles"' . LF; } }