/** * Saves data in the cache. * * @param string $entryIdentifier An identifier for this specific cache entry * @param string $data The data to be stored * @param array $tags Tags to associate with this cache entry. If the backend does not support tags, this option can be ignored. * @param integer $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited lifetime. * * @return void * @throws \TYPO3\CMS\Core\Cache\Exception if no cache frontend has been set. * @throws \TYPO3\CMS\Core\Cache\Exception\InvalidDataException if the data is not a string */ public function set($entryIdentifier, $data, array $tags = [], $lifetime = null) { $databaseData = ['created' => $GLOBALS['EXEC_TIME'], 'expires' => $GLOBALS['EXEC_TIME'] + $this->getRealLifetime($lifetime)]; if (in_array('explanation', $tags)) { $databaseData['explanation'] = $data; parent::set($entryIdentifier, serialize($databaseData), $tags, $lifetime); return; } // call set in front of the generation, because the set method // of the DB backend also call remove parent::set($entryIdentifier, serialize($databaseData), $tags, $lifetime); $fileName = $this->getCacheFilename($entryIdentifier); $cacheDir = PathUtility::pathinfo($fileName, PATHINFO_DIRNAME); if (!is_dir($cacheDir)) { GeneralUtility::mkdir_deep($cacheDir); } // normal GeneralUtility::writeFile($fileName, $data); // gz if ($this->configuration->get('enableStaticFileCompression')) { $contentGzip = gzencode($data, $this->getCompressionLevel()); if ($contentGzip) { GeneralUtility::writeFile($fileName . '.gz', $contentGzip); } } // htaccess $this->writeHtAccessFile($fileName, $lifetime); }
/** * Create a random directory in the virtual file system and return the path. * * @param string $prefix * @return string */ protected function getVirtualTestDir($prefix = 'root_') { $root = vfsStream::setup(); $path = $root->url() . '/typo3temp/' . $this->getUniqueId($prefix); \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($path); return $path; }
/** * Constructor */ public function __construct() { // we check for existence of our targetDirectory if (!is_dir(PATH_site . $this->targetDirectory)) { GeneralUtility::mkdir_deep(PATH_site . $this->targetDirectory); } // if enabled, we check whether we should auto-create the .htaccess file if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['generateApacheHtaccess']) { // check whether .htaccess exists $htaccessPath = PATH_site . $this->targetDirectory . '.htaccess'; if (!file_exists($htaccessPath)) { GeneralUtility::writeFile($htaccessPath, $this->htaccessTemplate); } } // decide whether we should create gzipped versions or not $compressionLevel = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['compressionLevel']; // we need zlib for gzencode() if (extension_loaded('zlib') && $compressionLevel) { $this->createGzipped = true; // $compressionLevel can also be TRUE if (MathUtility::canBeInterpretedAsInteger($compressionLevel)) { $this->gzipCompressionLevel = (int) $compressionLevel; } } $this->setInitialPaths(); }
/** * Get the cropped image by File Object * * @param FileInterface $file * @param string $ratio * * @return string The new filename */ public function getCroppedImageSrcByFile(FileInterface $file, $ratio) { $absoluteImageName = GeneralUtility::getFileAbsFileName($file->getPublicUrl()); $focusPointX = MathUtility::forceIntegerInRange((int) $file->getProperty('focus_point_x'), -100, 100, 0); $focusPointY = MathUtility::forceIntegerInRange((int) $file->getProperty('focus_point_y'), -100, 100, 0); $tempImageFolder = 'typo3temp/focuscrop/'; $tempImageName = $tempImageFolder . $file->getSha1() . '-' . str_replace(':', '-', $ratio) . '-' . $focusPointX . '-' . $focusPointY . '.' . $file->getExtension(); $absoluteTempImageName = GeneralUtility::getFileAbsFileName($tempImageName); if (is_file($absoluteTempImageName)) { return $tempImageName; } $absoluteTempImageFolder = GeneralUtility::getFileAbsFileName($tempImageFolder); if (!is_dir($absoluteTempImageFolder)) { GeneralUtility::mkdir_deep($absoluteTempImageFolder); } $this->graphicalFunctions = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Imaging\\GraphicalFunctions'); $imageSizeInformation = getimagesize($absoluteImageName); $width = $imageSizeInformation[0]; $height = $imageSizeInformation[1]; // dimensions /** @var \HDNET\Focuspoint\Service\DimensionService $service */ $dimensionService = GeneralUtility::makeInstance('HDNET\\Focuspoint\\Service\\DimensionService'); list($focusWidth, $focusHeight) = $dimensionService->getFocusWidthAndHeight($width, $height, $ratio); $cropMode = $dimensionService->getCropMode($width, $height, $ratio); list($sourceX, $sourceY) = $dimensionService->calculateSourcePosition($cropMode, $width, $height, $focusWidth, $focusHeight, $focusPointX, $focusPointY); // generate image $sourceImage = $this->graphicalFunctions->imageCreateFromFile($absoluteImageName); $destinationImage = imagecreatetruecolor($focusWidth, $focusHeight); $this->graphicalFunctions->imagecopyresized($destinationImage, $sourceImage, 0, 0, $sourceX, $sourceY, $focusWidth, $focusHeight, $focusWidth, $focusHeight); $this->graphicalFunctions->ImageWrite($destinationImage, $absoluteTempImageName, $GLOBALS['TYPO3_CONF_VARS']['GFX']['jpg_quality']); return $tempImageName; }
/** * create Font via Python with FontForge * * @param int $fontUid * @param object $currentFont * @return array */ public static function createFont($fontUid, $currentFont) { // general vars $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['fontawesomeplus']); $pathToPythonBin = escapeshellarg($extConf['pathToPython']); $pathToScript = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('fontawesomeplus') . 'Resources/Private/Python/fontawesomeplus.py'; $iconRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\FileRepository::class); $iconReferences = $iconRepository->findByRelation('tx_fontawesomeplus_domain_model_font', 'icons', $fontUid); $svgArray = array(); foreach ($iconReferences as $key => $value) { $svgArray[$key] = PATH_site . 'fileadmin' . $value->getIdentifier(); } $unicodeArray = array(); $i = hexdec(self::HEXADECIMAL); foreach ($svgArray as $key => $value) { $unicodeArray[$key] = $i . ',uni' . dechex($i); $i++; } $fontPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('fontawesomeplus') . 'Resources/Public/Contrib/' . self::FACONTRIB . '/fonts/fontawesome-webfont.svg'; $fontForgeArray = CommandUtility::escapeShellArgument(json_encode(array_combine($svgArray, $unicodeArray), JSON_UNESCAPED_SLASHES)); $fontName = strtolower(preg_replace(array('/\\s+/', '/[^a-zA-Z0-9]/'), array('-', ''), $currentFont->getTitle())); $comment = CommandUtility::escapeShellArgument(str_replace(array("\r\n", "\n", "\r"), ' ', $currentFont->getDescription())); $copyright = CommandUtility::escapeShellArgument('netweiser'); $version = CommandUtility::escapeShellArgument($currentFont->getVersion()); GeneralUtility::mkdir_deep(PATH_site . 'fileadmin/' . $currentFont->getDestination(), $fontName . '/fonts/'); $savedir = PATH_site . 'fileadmin/' . $currentFont->getDestination() . $fontName . '/fonts/'; CommandUtility::exec("{$pathToPythonBin} {$pathToScript} {$fontPath} {$fontForgeArray} {$fontName} {$comment} {$copyright} {$version} {$savedir} 2>&1", $feedback, $returnCode); if ((int) $returnCode !== 0) { return $feedback; } }
/** * @param string $packageKey * @param array $packageMethods * @return PackageManager|\PHPUnit_Framework_MockObject_MockObject */ protected function createMockPackageManagerWithMockPackage($packageKey, $packageMethods = array('getPackagePath', 'getPackageKey')) { $packagePath = PATH_site . 'typo3temp/' . $packageKey . '/'; GeneralUtility::mkdir_deep($packagePath); $this->testFilesToDelete[] = $packagePath; $package = $this->getMockBuilder(Package::class) ->disableOriginalConstructor() ->setMethods($packageMethods) ->getMock(); $packageManager = $this->getMock( PackageManager::class, array('isPackageActive', 'getPackage', 'getActivePackages') ); $package->expects($this->any()) ->method('getPackagePath') ->will($this->returnValue($packagePath)); $package->expects($this->any()) ->method('getPackageKey') ->will($this->returnValue($packageKey)); $packageManager->expects($this->any()) ->method('isPackageActive') ->will($this->returnValueMap(array( array(NULL, FALSE), array($packageKey, TRUE) ))); $packageManager->expects($this->any()) ->method('getPackage') ->with($this->equalTo($packageKey)) ->will($this->returnValue($package)); $packageManager->expects($this->any()) ->method('getActivePackages') ->will($this->returnValue(array($packageKey => $package))); return $packageManager; }
/** * Return the cache folder and check if the folder exists * * @return string */ protected function getCheckedCacheFolder() { $cacheFolder = GeneralUtility::getFileAbsFileName('typo3temp/calendarize/'); if (!is_dir($cacheFolder)) { GeneralUtility::mkdir_deep($cacheFolder); } return $cacheFolder; }
/** * Write a file and create the target folder, if the folder do not exists * * @param string $absoluteFileName * @param string $content * * @return bool * @throws Exception */ public static function writeFileAndCreateFolder($absoluteFileName, $content) { $dir = PathUtility::dirname($absoluteFileName) . '/'; if (!is_dir($dir)) { GeneralUtility::mkdir_deep($dir); } if (is_file($absoluteFileName) && !is_writable($absoluteFileName)) { throw new Exception('The autoloader try to add same content to ' . $absoluteFileName . ' but the file is not writable for the autoloader. Please fix it!', 234627835); } return GeneralUtility::writeFile($absoluteFileName, $content); }
/** * @param string $folder * * @return bool */ protected function backupFolder($folder) { GeneralUtility::mkdir_deep($this->backupPath); $compressedFileName = $folder . '_' . time() . '.tar'; $phar = new \PharData($this->backupPath . $compressedFileName); if ($phar->buildFromDirectory(PATH_site . $folder, '/^(?!_temp_|_processed_|_recycler_).*/')) { BackupUtility::generateBackupLog($folder, $compressedFileName . '.gz', $this->backupPath, $this->backupsToKeep); BackupUtility::gzCompressFile($this->backupPath . $compressedFileName); return true; } return false; }
/** * @param string $folderPath * @return boolean * @throws \Exception */ public function createFolder($folderPath) { if (TRUE === $this->dry) { return TRUE; } try { GeneralUtility::mkdir_deep($folderPath); } catch (\InvalidArgumentException $exception) { throw new \Exception('Unable to create directory "' . $folderPath . '"', 1371692697); } return TRUE; }
/** * @param string $packageKey * @param array $packageMethods * @return object */ protected function createMockPackageManagerWithMockPackage($packageKey, $packageMethods = array('getPackagePath', 'getPackageKey')) { $packagePath = PATH_site . 'typo3temp/test_ext/' . $packageKey . '/'; \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($packagePath); $package = $this->getMockBuilder('TYPO3\\CMS\\Core\\Package\\Package')->disableOriginalConstructor()->setMethods($packageMethods)->getMock(); $packageManager = $this->getMock('TYPO3\\CMS\\Core\\Package\\PackageManager', array('isPackageActive', 'getPackage', 'getActivePackages')); $package->expects($this->any())->method('getPackagePath')->will($this->returnValue($packagePath)); $package->expects($this->any())->method('getPackageKey')->will($this->returnValue($packageKey)); $packageManager->expects($this->any())->method('isPackageActive')->will($this->returnValueMap(array(array(NULL, FALSE), array($packageKey, TRUE)))); $packageManager->expects($this->any())->method('getPackage')->with($this->equalTo($packageKey))->will($this->returnValue($package)); $packageManager->expects($this->any())->method('getActivePackages')->will($this->returnValue(array($packageKey => $package))); return $packageManager; }
/** * * @return boolean */ public function execute() { $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['jh_browscap']); if (isset($extConf['cachePath']) && preg_match('/^typo3temp\\//', $extConf['cachePath'])) { $this->cachePath = rtrim($extConf['cachePath'], '/'); } if (!is_dir(PATH_site . $this->cachePath)) { GeneralUtility::mkdir_deep(PATH_site, $this->cachePath); } /** @var Browscap $browscap */ $browscap = new Browscap(PATH_site . $this->cachePath); return $browscap->updateCache(); }
/** * @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(); }
/** * getBrowser * * @param string $user_agent the user agent string * @param bool $return_array whether return an array or an object * * @return \stdClass|array the object containing the browsers details. Array if * $return_array is set to true. */ public static function getBrowser($user_agent = null, $return_array = false) { $cachePath = self::CACHE_PATH; $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['jh_browscap']); if (preg_match('/^typo3temp\\//', $extConf['cachePath'])) { $cachePath = rtrim($extConf['cachePath'], '/'); } if (!is_dir(PATH_site . $cachePath)) { GeneralUtility::mkdir_deep(PATH_site, $cachePath); } /** @var Browscap $browscap */ $browscap = new Browscap($cachePath); $browscap->doAutoUpdate = false; return $browscap->getBrowser($user_agent, $return_array); }
/** * TODO: replace the $link stuff by usage of $GLOBALS['TYPO3_DB'] * * @param string $outputFolder * @return string */ public static function backupTable($outputFolder) { GeneralUtility::mkdir_deep($outputFolder); $host = $GLOBALS['TYPO3_CONF_VARS']['DB']['host']; $user = $GLOBALS['TYPO3_CONF_VARS']['DB']['username']; $pass = $GLOBALS['TYPO3_CONF_VARS']['DB']['password']; $name = $GLOBALS['TYPO3_CONF_VARS']['DB']['database']; $link = mysqli_connect($host, $user, $pass); mysqli_select_db($link, $name); $listDbTables = array_column(mysqli_fetch_all($link->query('SHOW TABLES')), 0); $listDbTables = self::removeCacheAndLogTables($listDbTables); $return = ''; foreach ($listDbTables as $table) { $result = mysqli_query($link, 'SELECT * FROM ' . $table); $numFields = mysqli_num_fields($result); $return .= 'DROP TABLE ' . $table . ';'; $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE ' . $table)); $return .= "\n\n" . $row2[1] . ";\n\n"; for ($i = 0; $i < $numFields; $i++) { while ($row = mysqli_fetch_row($result)) { $return .= 'INSERT INTO ' . $table . ' VALUES('; for ($j = 0; $j < $numFields; $j++) { $row[$j] = addslashes($row[$j]); $row[$j] = str_replace("\n", "\\n", $row[$j]); if (isset($row[$j])) { $return .= '"' . $row[$j] . '"'; } else { $return .= '""'; } if ($j < $numFields - 1) { $return .= ','; } } $return .= ");\n"; } } $return .= "\n\n\n"; } //save file $backupFileName = 'db-backup_' . time() . '.sql'; $handle = fopen($outputFolder . $backupFileName, 'w+'); fwrite($handle, $return); fclose($handle); self::generateBackupLog($name, $backupFileName . '.gz', $outputFolder, 3); return self::gzCompressFile($outputFolder . 'db-backup_' . time() . '.sql'); }
/** * Check if the given file is already existing * * @param $path * @param $modelClass * * @return void */ protected function checkCshFile($path, $modelClass) { if (is_file($path)) { return; } $dir = PathUtility::dirname($path); if (!is_dir($dir)) { GeneralUtility::mkdir_deep($dir); } $information = SmartObjectInformationService::getInstance()->getCustomModelFieldTca($modelClass); $properties = array_keys($information); $templatePath = 'Resources/Private/Templates/ContextSensitiveHelp/LanguageDescription.xml'; $standaloneView = GeneralUtility::makeInstance('TYPO3\\CMS\\Fluid\\View\\StandaloneView'); $standaloneView->setTemplatePathAndFilename(ExtensionManagementUtility::extPath('autoloader', $templatePath)); $standaloneView->assign('properties', $properties); $content = $standaloneView->render(); FileUtility::writeFileAndCreateFolder($path, $content); }
/** * @param string $siteTitle The name of the new site, will be used for both the file mount's name and the directory created in fileadmin. * @return null|int Returns null if the file mount could not be created, or the uid of the last inserted "sys_filemounts" record. */ private function manageSysFileMounts($siteTitle) { $pathFirstPart = $this->getProcessSettings('path') ? $this->getProcessSettings('path') : self::$defaultPath; $pathFirstPart = substr($pathFirstPart, -1, 1) == '/' ? $pathFirstPart : $pathFirstPart . '/'; $folderPath = $pathFirstPart . GeneralUtility::strtolower($siteTitle); $folderPath = Core::formatAccentsInString($folderPath); $folderPath = preg_replace('/\\s+/', ' ', $folderPath); $folderPath = preg_replace('/\\s/', '_', $folderPath); $folderPath = '/' . $folderPath . '/'; // @todo: manage warning when overriding a folder? GeneralUtility::mkdir_deep(PATH_site . 'fileadmin' . $folderPath); /** @var FileMount $fileMount */ $fileMount = GeneralUtility::makeInstance(FileMount::class); $fileMount->setPath($folderPath); $fileMount->setTitle($siteTitle); $fileMount->setIsAbsolutePath(true); // @todo: seems it must be on pid=0, check? $fileMount->setPid(0); /** @var PersistenceManager $persistenceManager */ $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->add($fileMount); $persistenceManager->persistAll(); return $fileMount->getUid(); }
/** * Create directories for the session save path * and throw an exception if that fails. * * @param string $sessionSavePath The absolute path to the session files * @throws \TYPO3\CMS\Install\Exception */ private function ensureSessionSavePathExists($sessionSavePath) { if (!is_dir($sessionSavePath)) { try { GeneralUtility::mkdir_deep($sessionSavePath); } catch (\RuntimeException $exception) { throw new \TYPO3\CMS\Install\Exception('Could not create session folder in typo3temp/. Make sure it is writeable!', 1294587484); } $htaccessContent = ' # Apache < 2.3 <IfModule !mod_authz_core.c> Order allow,deny Deny from all Satisfy All </IfModule> # Apache ≥ 2.3 <IfModule mod_authz_core.c> Require all denied </IfModule> '; GeneralUtility::writeFile($sessionSavePath . '/.htaccess', $htaccessContent); $indexContent = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">'; $indexContent .= '<HTML><HEAD<TITLE></TITLE><META http-equiv=Refresh Content="0; Url=../../">'; $indexContent .= '</HEAD></HTML>'; GeneralUtility::writeFile($sessionSavePath . '/index.html', $indexContent); } }
/** * Creates the log file with correct permissions * and parent directories, if needed * * @return void */ protected function createLogFile() { if (file_exists($this->logFile)) { return; } $logFileDirectory = dirname($this->logFile); if (!@is_dir($logFileDirectory)) { GeneralUtility::mkdir_deep($logFileDirectory); // only create .htaccess, if we created the directory on our own $this->createHtaccessFile($logFileDirectory . '/.htaccess'); } // create the log file GeneralUtility::writeFile($this->logFile, ''); }
/** * Create download location in case the folder does not exist * @todo move this to folder structure * * @param string $downloadTargetPath */ protected function setDownloadTargetPath($downloadTargetPath) { if (!is_dir($downloadTargetPath)) { GeneralUtility::mkdir_deep($downloadTargetPath); } $this->downloadTargetPath = $downloadTargetPath; }
/** * @test * @expectedException \InvalidArgumentException */ public function mkdirDeepThrowsExceptionIfDeepDirectoryIsNotOfTypeString() { Utility\GeneralUtility::mkdir_deep(PATH_site . 'typo3temp/foo', array()); }
/** * Builds the path to the final upload folder depending on the current field processed * * @param string The current field name * @return string The new path **/ protected function getNewFolderPath($field) { if (is_array($this->settings['finishedUploadFolder.']) && isset($this->settings['finishedUploadFolder.'][$field])) { $newFolder = $this->utilityFuncs->getSingle($this->settings['finishedUploadFolder.'], $field); } else { $newFolder = $this->utilityFuncs->getSingle($this->settings, 'finishedUploadFolder'); } $newFolder = $this->utilityFuncs->sanitizePath($newFolder); $newFolder = $this->replaceSchemeMarkers($newFolder); $uploadPath = $this->utilityFuncs->getDocumentRoot() . $newFolder; $uploadPath = $this->utilityFuncs->sanitizePath($uploadPath); if (!file_exists($uploadPath)) { $doCreateNonExistingFolder = intval($this->utilityFuncs->getSingle($this->settings, 'createNonExistingFolder')); if (!isset($this->settings['createNonExistingFolder'])) { $doCreateNonExistingFolder = 1; } if ($doCreateNonExistingFolder === 1) { \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($this->utilityFuncs->getDocumentRoot(), $newFolder); $this->utilityFuncs->debugMessage('Creating directory "' . $newFolder . '"'); } else { $this->utilityFuncs->throwException('Directory "' . $newFolder . '" doesn\'t exist!'); } } return $uploadPath; }
/** * @test */ public function copyFolderWithinStorageCopiesFileInSingleSubFolderToNewFolderName() { list($basePath, $fixture) = $this->prepareRealTestEnvironment(); GeneralUtility::mkdir_deep($basePath, '/sourceFolder/subFolder'); GeneralUtility::mkdir_deep($basePath, '/targetFolder'); file_put_contents($basePath . '/sourceFolder/subFolder/file', uniqid()); GeneralUtility::fixPermissions($basePath . '/sourceFolder/subFolder/file'); $fixture->copyFolderWithinStorage('/sourceFolder/', '/targetFolder/', 'newFolderName'); $this->assertTrue(is_file($basePath . '/targetFolder/newFolderName/subFolder/file')); }
/** * Write a simple model class for a non aggregate root domain object * * @test */ function writeRepositoryClassFromDomainObject() { $domainObject = $this->buildDomainObject('ModelCgt6', true, true); $classFileContent = $this->fileGenerator->generateDomainRepositoryCode($domainObject, false); $repositoryClassDir = 'Classes/Domain/Repository/'; \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($this->extension->getExtensionDir(), $repositoryClassDir); $absRepositoryClassDir = $this->extension->getExtensionDir() . $repositoryClassDir; $this->assertTrue(is_dir($absRepositoryClassDir), 'Directory ' . $absRepositoryClassDir . ' was not created'); $repositoryClassPath = $absRepositoryClassDir . $domainObject->getName() . 'Repository.php'; \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($repositoryClassPath, $classFileContent); $this->assertFileExists($repositoryClassPath, 'File was not generated: ' . $repositoryClassPath); $className = $domainObject->getFullyQualifiedDomainRepositoryClassName(); if (!class_exists($className)) { include $repositoryClassPath; } $this->assertTrue(class_exists($className), 'Class was not generated:' . $className . 'in ' . $repositoryClassPath); }
/** * Unzips a document package. * * @param string $file path to zip file * @param string $path path to extract to * @throws \TYPO3\CMS\Documentation\Exception\Document * @return boolean */ protected function unzipDocumentPackage($file, $path) { $zip = zip_open($file); if (is_resource($zip)) { $result = TRUE; if (!is_dir($path)) { GeneralUtility::mkdir_deep($path); } while (($zipEntry = zip_read($zip)) !== FALSE) { $zipEntryName = zip_entry_name($zipEntry); if (strpos($zipEntryName, '/') !== FALSE) { $zipEntryPathSegments = explode('/', $zipEntryName); $fileName = array_pop($zipEntryPathSegments); // It is a folder, because the last segment is empty, let's create it if (empty($fileName)) { GeneralUtility::mkdir_deep($path, implode('/', $zipEntryPathSegments)); } else { $absoluteTargetPath = GeneralUtility::getFileAbsFileName($path . implode('/', $zipEntryPathSegments) . '/' . $fileName); if (strlen(trim($absoluteTargetPath)) > 0) { $return = GeneralUtility::writeFile($absoluteTargetPath, zip_entry_read($zipEntry, zip_entry_filesize($zipEntry))); if ($return === FALSE) { throw new \TYPO3\CMS\Documentation\Exception\Document('Could not write file ' . $zipEntryName, 1374161546); } } else { throw new \TYPO3\CMS\Documentation\Exception\Document('Could not write file ' . $zipEntryName, 1374161532); } } } else { throw new \TYPO3\CMS\Documentation\Exception\Document('Extension directory missing in zip file!', 1374161519); } } } else { throw new \TYPO3\CMS\Documentation\Exception\Document('Unable to open zip file ' . $file, 1374161508); } return $result; }
/** * Searches for upload folder settings in TypoScript setup. * If no settings is found, the default upload folder is set. * * Here is an example: * <code> * plugin.Tx_Formhandler.settings.files.tmpUploadFolder = uploads/formhandler/tmp * </code> * * The default upload folder is: '/uploads/formhandler/tmp/' * * @return string */ public function getTempUploadFolder($fieldName = '') { //set default upload folder $uploadFolder = '/uploads/formhandler/tmp/'; //if temp upload folder set in TypoScript, take that setting $settings = $this->globals->getSession()->get('settings'); if (strlen($fieldName) > 0 && $settings['files.']['uploadFolder.'][$fieldName]) { $uploadFolder = $this->getSingle($settings['files.']['uploadFolder.'], $fieldName); } elseif ($settings['files.']['uploadFolder.']['default']) { $uploadFolder = $this->getSingle($settings['files.']['uploadFolder.'], 'default'); } elseif ($settings['files.']['uploadFolder']) { $uploadFolder = $this->getSingle($settings['files.'], 'uploadFolder'); } $uploadFolder = $this->sanitizePath($uploadFolder); //if the set directory doesn't exist, print a message and try to create if (!is_dir($this->getTYPO3Root() . $uploadFolder)) { $this->debugMessage('folder_doesnt_exist', [$this->getTYPO3Root() . '/' . $uploadFolder], 2); \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($this->getTYPO3Root() . '/', $uploadFolder); } return $uploadFolder; }
/** * Unzip an extension.zip. * * @param string $file path to zip file * @param string $fileName file name * @param string $pathType path type (Local, Global, System) * @throws ExtensionManagerException * @return void */ public function unzipExtensionFromFile($file, $fileName, $pathType = 'Local') { $extensionDir = $this->makeAndClearExtensionDir($fileName, $pathType); $zip = zip_open($file); if (is_resource($zip)) { while (($zipEntry = zip_read($zip)) !== false) { if (strpos(zip_entry_name($zipEntry), '/') !== false) { $last = strrpos(zip_entry_name($zipEntry), '/'); $dir = substr(zip_entry_name($zipEntry), 0, $last); $file = substr(zip_entry_name($zipEntry), strrpos(zip_entry_name($zipEntry), '/') + 1); if (!is_dir($extensionDir . $dir)) { GeneralUtility::mkdir_deep($extensionDir . $dir); } if (trim($file) !== '') { $return = GeneralUtility::writeFile($extensionDir . $dir . '/' . $file, zip_entry_read($zipEntry, zip_entry_filesize($zipEntry))); if ($return === false) { throw new ExtensionManagerException('Could not write file ' . $this->getRelativePath($file), 1344691048); } } } else { GeneralUtility::writeFile($extensionDir . zip_entry_name($zipEntry), zip_entry_read($zipEntry, zip_entry_filesize($zipEntry))); } } } else { throw new ExtensionManagerException('Unable to open zip file ' . $this->getRelativePath($file), 1344691049); } }
/** * Ensures, that environment is valid. * * @param $fname * * @throws \Exception * * @return bool */ public function prepareEnvironment($fname) { GeneralUtility::mkdir_deep(PATH_site . 'typo3temp/', 'DynCss/'); if (!is_dir(PATH_site . $this->cachePath)) { throw new \Exception('Can´t create cache directory PATH_site/' . $this->cachePath); } if (!is_file($fname)) { return false; } return true; }
/** * Unzip an language.zip. * * @param string $file path to zip file * @param string $path path to extract to * @throws \TYPO3\CMS\Lang\Exception\Lang * @return boolean */ protected function unzipTranslationFile($file, $path) { $zip = zip_open($file); if (is_resource($zip)) { $result = TRUE; if (!is_dir($path)) { \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($path); } while (($zipEntry = zip_read($zip)) !== FALSE) { if (strpos(zip_entry_name($zipEntry), DIRECTORY_SEPARATOR) !== FALSE) { $file = substr(zip_entry_name($zipEntry), strrpos(zip_entry_name($zipEntry), DIRECTORY_SEPARATOR) + 1); if (strlen(trim($file)) > 0) { $return = \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($path . '/' . $file, zip_entry_read($zipEntry, zip_entry_filesize($zipEntry))); if ($return === FALSE) { throw new \TYPO3\CMS\Lang\Exception\Lang('Could not write file ' . $file, 1345304560); } } } else { $result = FALSE; \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($path . zip_entry_name($zipEntry), zip_entry_read($zipEntry, zip_entry_filesize($zipEntry))); } } } else { throw new \TYPO3\CMS\Lang\Exception\Lang('Unable to open zip file ' . $file, 1345304561); } return $result; }
/** * Migrates a single field. * * @param string $table * @param array $row * @param string $fieldname * @param array $fieldConfiguration * @param string $customMessages * @return array A list of performed database queries * @throws \Exception */ protected function migrateField($table, $row, $fieldname, $fieldConfiguration, &$customMessages) { $titleTextContents = []; $alternativeTextContents = []; $captionContents = []; $linkContents = []; $fieldItems = GeneralUtility::trimExplode(',', $row[$fieldname], true); if (empty($fieldItems) || is_numeric($row[$fieldname])) { return []; } if (isset($fieldConfiguration['titleTexts'])) { $titleTextField = $fieldConfiguration['titleTexts']; $titleTextContents = explode(LF, $row[$titleTextField]); } if (isset($fieldConfiguration['alternativeTexts'])) { $alternativeTextField = $fieldConfiguration['alternativeTexts']; $alternativeTextContents = explode(LF, $row[$alternativeTextField]); } if (isset($fieldConfiguration['captions'])) { $captionField = $fieldConfiguration['captions']; $captionContents = explode(LF, $row[$captionField]); } if (isset($fieldConfiguration['links'])) { $linkField = $fieldConfiguration['links']; $linkContents = explode(LF, $row[$linkField]); } $fileadminDirectory = rtrim($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/') . '/'; $queries = []; $i = 0; if (!PATH_site) { throw new \Exception('PATH_site was undefined.'); } $storageUid = (int) $this->storage->getUid(); foreach ($fieldItems as $item) { $fileUid = null; $sourcePath = PATH_site . $fieldConfiguration['sourcePath'] . $item; $targetDirectory = PATH_site . $fileadminDirectory . $fieldConfiguration['targetPath']; $targetPath = $targetDirectory . basename($item); // maybe the file was already moved, so check if the original file still exists if (file_exists($sourcePath)) { if (!is_dir($targetDirectory)) { GeneralUtility::mkdir_deep($targetDirectory); } // see if the file already exists in the storage $fileSha1 = sha1_file($sourcePath); $existingFileRecord = $this->database->exec_SELECTgetSingleRow('uid', 'sys_file', 'sha1=' . $this->database->fullQuoteStr($fileSha1, 'sys_file') . ' AND storage=' . $storageUid); // the file exists, the file does not have to be moved again if (is_array($existingFileRecord)) { $fileUid = $existingFileRecord['uid']; } else { // just move the file (no duplicate) rename($sourcePath, $targetPath); } } if ($fileUid === null) { // get the File object if it hasn't been fetched before try { // if the source file does not exist, we should just continue, but leave a message in the docs; // ideally, the user would be informed after the update as well. /** @var File $file */ $file = $this->storage->getFile($fieldConfiguration['targetPath'] . $item); $fileUid = $file->getUid(); } catch (\InvalidArgumentException $e) { // no file found, no reference can be set $this->logger->notice('File ' . $fieldConfiguration['sourcePath'] . $item . ' does not exist. Reference was not migrated.', ['table' => $table, 'record' => $row, 'field' => $fieldname]); $format = 'File \'%s\' does not exist. Referencing field: %s.%d.%s. The reference was not migrated.'; $message = sprintf($format, $fieldConfiguration['sourcePath'] . $item, $table, $row['uid'], $fieldname); $customMessages .= PHP_EOL . $message; continue; } } if ($fileUid > 0) { $fields = ['fieldname' => $fieldname, 'table_local' => 'sys_file', 'pid' => $table === 'pages' ? $row['uid'] : $row['pid'], 'uid_foreign' => $row['uid'], 'uid_local' => $fileUid, 'tablenames' => $table, 'crdate' => time(), 'tstamp' => time(), 'sorting' => $i + 256, 'sorting_foreign' => $i]; if (isset($titleTextField)) { $fields['title'] = trim($titleTextContents[$i]); } if (isset($alternativeTextField)) { $fields['alternative'] = trim($alternativeTextContents[$i]); } if (isset($captionField)) { $fields['description'] = trim($captionContents[$i]); } if (isset($linkField)) { $fields['link'] = trim($linkContents[$i]); } $this->database->exec_INSERTquery('sys_file_reference', $fields); $queries[] = str_replace(LF, ' ', $this->database->debug_lastBuiltQuery); ++$i; } } // Update referencing table's original field to now contain the count of references, // but only if all new references could be set if ($i === count($fieldItems)) { $this->database->exec_UPDATEquery($table, 'uid=' . $row['uid'], [$fieldname => $i]); $queries[] = str_replace(LF, ' ', $this->database->debug_lastBuiltQuery); } else { $this->recordOffset[$table]++; } return $queries; }