/** * @test */ public function getParsedDataHandlesLocallangXMLOverride() { /** @var $subject LocalizationFactory */ $subject = new LocalizationFactory(); $unique = 'locallangXMLOverrideTest' . substr($this->getUniqueId(), 0, 10); $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?> <T3locallang> <data type="array"> <languageKey index="default" type="array"> <label index="buttons.logout">EXIT</label> </languageKey> </data> </T3locallang>'; $file = PATH_site . 'typo3temp/' . $unique . '.xml'; GeneralUtility::writeFileToTypo3tempDir($file, $xml); // Make sure there is no cached version of the label GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('l10n')->flush(); // Get default value $defaultLL = $subject->getParsedData('EXT:lang/locallang_core.xlf', 'default', 'utf-8', 0); // Clear language cache again GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('l10n')->flush(); // Set override file $GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride']['EXT:lang/locallang_core.xlf'][$unique] = $file; /** @var $store \TYPO3\CMS\Core\Localization\LanguageStore */ $store = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Localization\\LanguageStore'); $store->flushData('EXT:lang/locallang_core.xlf'); // Get override value $overrideLL = $subject->getParsedData('EXT:lang/locallang_core.xlf', 'default', 'utf-8', 0); // Clean up again unlink($file); $this->assertNotEquals($overrideLL['default']['buttons.logout'][0]['target'], ''); $this->assertNotEquals($defaultLL['default']['buttons.logout'][0]['target'], $overrideLL['default']['buttons.logout'][0]['target']); $this->assertEquals($overrideLL['default']['buttons.logout'][0]['target'], 'EXIT'); }
/** * Return JS configuration of the htmlArea plugins registered by the extension * * @return string JS configuration for registered plugins */ public function buildJavascriptConfiguration() { $registerRTEinJavascriptString = ''; if (!file_exists(PATH_site . $this->jsonFileName)) { $schema = array('types' => array(), 'properties' => array()); $fileName = 'EXT:rte_schema/Resources/Public/RDF/schema.rdfa'; $fileName = GeneralUtility::getFileAbsFileName($fileName); $rdf = GeneralUtility::getUrl($fileName); if ($rdf) { $this->parseSchema($rdf, $schema); } uasort($schema['types'], array($this, 'compareLabels')); uasort($schema['properties'], array($this, 'compareLabels')); // Insert no type and no property entries if ($this->isFrontend()) { $noSchema = $GLOBALS['TSFE']->getLLL('No type', $this->LOCAL_LANG); $noProperty = $GLOBALS['TSFE']->getLLL('No property', $this->LOCAL_LANG); } else { $noSchema = $GLOBALS['LANG']->getLL('No type'); $noProperty = $GLOBALS['LANG']->getLL('No property'); } array_unshift($schema['types'], array('name' => 'none', 'domain' => $noSchema, 'comment' => '')); array_unshift($schema['properties'], array('name' => 'none', 'domain' => $noProperty, 'comment' => '')); GeneralUtility::writeFileToTypo3tempDir(PATH_site . $this->jsonFileName, json_encode($schema)); } $output = ($this->isFrontend() && $GLOBALS['TSFE']->absRefPrefix ? $GLOBALS['TSFE']->absRefPrefix : '../') . $this->jsonFileName; $registerRTEinJavascriptString = 'RTEarea[editornumber].schemaUrl = "' . ($this->isFrontend() && $GLOBALS['TSFE']->absRefPrefix ? $GLOBALS['TSFE']->absRefPrefix : '') . $output . '";'; return $registerRTEinJavascriptString; }
/** * @param array|NULL $backendUser * @param int $size * @param bool $showIcon * @return string */ public function render(array $backendUser = NULL, $size = 32, $showIcon = FALSE) { $size = (int) $size; if (!is_array($backendUser)) { $backendUser = $this->getBackendUser()->user; } $image = parent::render($backendUser, $size, $showIcon); if (!StringUtility::beginsWith($image, '<span class="avatar"><span class="avatar-image"></span>') || empty($backendUser['email'])) { return $image; } $cachedFilePath = PATH_site . 'typo3temp/t3gravatar/'; $cachedFileName = sha1($backendUser['email'] . $size) . '.jpg'; if (!file_exists($cachedFilePath . $cachedFileName)) { $gravatar = 'https://www.gravatar.com/avatar/' . md5(strtolower($backendUser['email'])) . '?s=' . $size . '&d=404'; $gravatarImage = GeneralUtility::getUrl($gravatar); if (empty($gravatarImage)) { return $image; } GeneralUtility::writeFileToTypo3tempDir($cachedFileName, $gravatarImage); } // Icon $icon = ''; if ($showIcon) { $icon = '<span class="avatar-icon">' . IconUtility::getSpriteIconForRecord('be_users', $backendUser) . '</span>'; } $relativeFilePath = PathUtility::getRelativePath(PATH_typo3, $cachedFilePath); return '<span class="avatar"><span class="avatar-image">' . '<img src="' . $relativeFilePath . $cachedFileName . '" width="' . $size . '" height="' . $size . '" /></span>' . $icon . '</span>'; }
/** * This function initializes the to-ASCII conversion table for a charset other than UTF-8. * This function is automatically called by the ASCII transliteration functions. * * @param string $charset Charset for which to initialize conversion. * @return int Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached). * @access private */ public function initToASCII($charset) { // Only process if the case table is not yet loaded: if (is_array($this->toASCII[$charset])) { return 1; } // Use cached version if possible $cacheFile = GeneralUtility::getFileAbsFileName('typo3temp/cs/csascii_' . $charset . '.tbl'); if ($cacheFile && @is_file($cacheFile)) { $this->toASCII[$charset] = unserialize(GeneralUtility::getUrl($cacheFile)); return 2; } // Init UTF-8 conversion for this charset if (!$this->initCharset($charset)) { return FALSE; } // UTF-8/ASCII transliteration is used as the base conversion table if (!$this->initUnicodeData('ascii')) { return FALSE; } foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8) { // Reconvert to charset (don't use chr() of numeric value, might be muli-byte) $c = $this->utf8_decode($utf8, $charset); if (isset($this->toASCII['utf-8'][$utf8])) { $this->toASCII[$charset][$c] = $this->toASCII['utf-8'][$utf8]; } } if ($cacheFile) { GeneralUtility::writeFileToTypo3tempDir($cacheFile, serialize($this->toASCII[$charset])); } return 3; }
/** * @test */ public function templateWithErrorReturnsFormWithErrorReporter() { $badSource = '<f:layout invalid="TRUE" />'; $temp = GeneralUtility::tempnam('badtemplate') . '.html'; GeneralUtility::writeFileToTypo3tempDir($temp, $badSource); $form = $this->createFluxServiceInstance()->getFormFromTemplateFile($temp); $this->assertInstanceOf('FluidTYPO3\\Flux\\Form', $form); $this->assertInstanceOf('FluidTYPO3\\Flux\\Form\\Field\\UserFunction', reset($form->getFields())); $this->assertEquals('FluidTYPO3\\Flux\\UserFunction\\ErrorReporter->renderField', reset($form->getFields())->getFunction()); }
/** * Generates the cache file. * * @param string $sourcePath * @param string $languageKey * @return array * @throws \RuntimeException */ protected function generateCacheFile($sourcePath, $languageKey) { $LOCAL_LANG = array(); // Get PHP data include $sourcePath; if (!is_array($LOCAL_LANG)) { $fileName = substr($sourcePath, strlen(PATH_site)); throw new \RuntimeException('TYPO3 Fatal Error: "' . $fileName . '" is no TYPO3 language file!', 1308898491); } // Converting the default language (English) // This needs to be done for a few accented loan words and extension names if (is_array($LOCAL_LANG['default']) && $this->targetCharset !== 'utf-8') { foreach ($LOCAL_LANG['default'] as &$labelValue) { $labelValue = $this->csConvObj->conv($labelValue, 'utf-8', $this->targetCharset); } unset($labelValue); } if ($languageKey !== 'default' && is_array($LOCAL_LANG[$languageKey]) && $this->sourceCharset != $this->targetCharset) { foreach ($LOCAL_LANG[$languageKey] as &$labelValue) { $labelValue = $this->csConvObj->conv($labelValue, $this->sourceCharset, $this->targetCharset); } unset($labelValue); } // Cache the content now: if (isset($LOCAL_LANG[$languageKey])) { $serContent = array('origFile' => $this->hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $languageKey => $LOCAL_LANG[$languageKey])); } else { $serContent = array('origFile' => $this->hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'])); } $res = \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($this->cacheFileName, serialize($serContent)); if ($res) { throw new \RuntimeException('TYPO3 Fatal Error: "' . $res, 1308898501); } return $LOCAL_LANG; }
/** * Returns the file name to the LLL JavaScript, containing the localized labels, * which can be used in JavaScript code. * * @return string File name of the JS file, relative to TYPO3_mainDir * @throws \RuntimeException */ protected function getLocalLangFileName() { $code = $this->generateLocalLang(); $filePath = 'typo3temp/Language/Backend-' . sha1($code) . '.js'; if (!file_exists(PATH_site . $filePath)) { // writeFileToTypo3tempDir() returns NULL on success (please double-read!) $error = GeneralUtility::writeFileToTypo3tempDir(PATH_site . $filePath, $code); if ($error !== null) { throw new \RuntimeException('Locallang JS file could not be written to ' . $filePath . '. Reason: ' . $error, 1295193026); } } return '../' . $filePath; }
/** * Download data of an extension as sql statements * * @param string $extension * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException */ protected function downloadExtensionDataAction($extension) { $error = NULL; $sqlData = $this->installUtility->getExtensionSqlDataDump($extension); $dump = $sqlData['extTables'] . $sqlData['staticSql']; $fileName = $extension . '_sqlDump.sql'; $filePath = PATH_site . 'typo3temp/' . $fileName; $error = \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($filePath, $dump); if (is_string($error)) { throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException($error, 1343048718); } $this->fileHandlingUtility->sendSqlDumpFileToBrowserAndDelete($filePath, $fileName); }
/** * Determine the real class name to use * * @param string $extensionKey * @return string Returns the final class name if an update script is present, otherwise empty string * @throws ExtensionManagerException If an update script is present but no ext_update class can be loaded */ protected function determineUpdateClassName($extensionKey) { $updateScript = GeneralUtility::getFileAbsFileName('EXT:' . $extensionKey . '/class.ext_update.php', false); if (!file_exists($updateScript)) { return ''; } // get script contents $scriptSourceCode = GeneralUtility::getUrl($updateScript); // check if it has a namespace if (!preg_match('/<\\?php.*namespace\\s+([^;]+);.*class/is', $scriptSourceCode, $matches)) { // if no, rename the class with a unique name $className = 'ext_update' . md5($extensionKey . $scriptSourceCode); $temporaryFileName = PATH_site . 'typo3temp/ExtensionManager/UpdateScripts/' . $className . '.php'; if (!file_exists(GeneralUtility::getFileAbsFileName($temporaryFileName))) { $scriptSourceCode = preg_replace('/^\\s*class\\s+ext_update\\s+/m', 'class ' . $className . ' ', $scriptSourceCode); GeneralUtility::writeFileToTypo3tempDir($temporaryFileName, $scriptSourceCode); } $updateScript = $temporaryFileName; } else { $className = $matches[1] . '\\ext_update'; } @(include_once $updateScript); if (!class_exists($className, false)) { throw new ExtensionManagerException(sprintf('class.ext_update.php of extension "%s" did not declare ext_update class', $extensionKey), 1428176468); } return $className; }
/** * Loads php files containing classes or interfaces found in the classes directory of * a package and specifically registered classes. * * @param string $className: Name of the class/interface to load * @return void * @author Jochen Rau <*****@*****.**> */ private function loadClass($className) { $classNameParts = explode('_', $className, 3); if ($classNameParts[0] === self::PACKAGE_PREFIX) { // Caches the $classFiles if (!is_array($this->classFiles[$classNameParts[1]]) || empty($this->classFiles[$classNameParts[1]])) { $this->classFiles[$classNameParts[1]] = $this->buildArrayOfClassFiles($classNameParts[1]); if (is_array($this->additionalIncludePaths)) { foreach ($this->additionalIncludePaths as $idx => $dir) { $temp = $this->buildArrayOfClassFiles($dir); $this->classFiles[$classNameParts[1]] = array_merge($temp, $this->classFiles[$classNameParts[1]]); } } \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($this->cacheFilePath, serialize($this->classFiles)); //If the package exists in the cache, but the class does not, look in the additionalIncludePaths again. } elseif (!array_key_exists($className, $this->classFiles[$classNameParts[1]])) { if (is_array($this->additionalIncludePaths)) { foreach ($this->additionalIncludePaths as $idx => $dir) { $temp = array(); $temp = $this->buildArrayOfClassFiles($dir); $this->classFiles[$classNameParts[1]] = array_merge($temp, $this->classFiles[$classNameParts[1]]); } } \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($this->cacheFilePath, serialize($this->classFiles)); } $classFilePathAndName = NULL; if (isset($this->classFiles[$classNameParts[1]][$className])) { $classFilePathAndName = PATH_site . $this->classFiles[$classNameParts[1]][$className]; } if (isset($classFilePathAndName) && file_exists($classFilePathAndName)) { require_once $classFilePathAndName; } } }
/** * Create new OnlineMedia item container file. * This is created inside typo3temp/ and then moved from FAL to the proper storage. * * @param Folder $targetFolder * @param string $fileName * @param string $onlineMediaId * @return File */ protected function createNewFile(Folder $targetFolder, $fileName, $onlineMediaId) { $temporaryFile = PATH_site . 'typo3temp/assets/transient/' . GeneralUtility::tempnam('online_media'); GeneralUtility::writeFileToTypo3tempDir($temporaryFile, $onlineMediaId); return $targetFolder->addFile($temporaryFile, $fileName, 'changeName'); }
/** * Writes contents in a file in typo3temp and returns the file name * * @param string $label: A label to insert at the beginning of the name of the file * @param string $fileExtension: The file extension of the file, defaulting to 'js' * @param string $contents: The contents to write into the file * @return string The name of the file written to typo3temp * @throws \RuntimeException If writing to file failed */ protected function writeTemporaryFile($label, $fileExtension = 'js', $contents = '') { $relativeFilename = 'typo3temp/assets/js/rte_' . str_replace('-', '_', $label) . '_' . GeneralUtility::shortMD5($contents, 20) . '.' . $fileExtension; $destination = PATH_site . $relativeFilename; if (!file_exists($destination)) { $minifiedJavaScript = ''; if ($fileExtension === 'js' && $contents !== '') { $minifiedJavaScript = GeneralUtility::minifyJavaScript($contents); } $failure = GeneralUtility::writeFileToTypo3tempDir($destination, $minifiedJavaScript ? $minifiedJavaScript : $contents); if ($failure) { throw new \RuntimeException($failure, 1294585668); } } return PathUtility::getAbsoluteWebPath($destination); }
/** * @param string $src * @param string $type * @param boolean $compress * @param boolean $forceOnTop * @param string $allWrap * @param boolean $excludeFromConcatenation * @param string $section * @param boolean $preventMarkupUpdateOnAjaxLoad * @param boolean $moveToExternalFile * @param boolean $noCache * @param string $name * * @return string */ public function render($src = "", $type = 'text/javascript', $compress = TRUE, $forceOnTop = FALSE, $allWrap = '', $excludeFromConcatenation = FALSE, $section = 'footer', $preventMarkupUpdateOnAjaxLoad = false, $moveToExternalFile = false, $noCache = false, $name = '') { $content = $this->renderChildren(); if ($this->ajaxDispatcher->getIsActive()) { if ($preventMarkupUpdateOnAjaxLoad) { $this->ajaxDispatcher->setPreventMarkupUpdateOnAjaxLoad(true); } // need to just echo the code in ajax call if (!$src) { if ($compress) { $content = $this->compressScript($content); } return \TYPO3\CMS\Core\Utility\GeneralUtility::wrapJS($content); } else { return '<script type="' . htmlspecialchars($type) . '" src="' . htmlspecialchars($src) . '"></script>'; } } else { if ($this->isCached()) { if ($noCache) { if ($src) { $content = '<script type="' . htmlspecialchars($type) . '" src="' . htmlspecialchars($src) . '"></script>'; } else { if ($compress) { $content = $this->compressScript($content); } $content = \TYPO3\CMS\Core\Utility\GeneralUtility::wrapJS($content); } $tslibFE = GeneralUtility::makeInstance('EssentialDots\\ExtbaseHijax\\Tslib\\FE\\Hook'); /* @var $tslibFE \EssentialDots\ExtbaseHijax\Tslib\FE\Hook */ if ($section == 'footer') { $tslibFE->addNonCacheableFooterCode($name ? $name : md5($content), $content); } else { $tslibFE->addNonCacheableHeaderCode($name ? $name : md5($content), $content); } return ''; } else { if (!$src && $moveToExternalFile) { $src = 'typo3temp' . DIRECTORY_SEPARATOR . 'extbase_hijax' . DIRECTORY_SEPARATOR . md5($content) . '.js'; \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir(PATH_site . $src, $content); if ($GLOBALS['TSFE']) { if ($GLOBALS['TSFE']->baseUrl) { $src = $GLOBALS['TSFE']->baseUrl . $src; } elseif ($GLOBALS['TSFE']->absRefPrefix) { $src = $GLOBALS['TSFE']->absRefPrefix . $src; } } } if (!$src) { if ($section == 'footer') { $this->pageRenderer->addJsFooterInlineCode($name ? $name : md5($content), $content, $compress, $forceOnTop); } else { $this->pageRenderer->addJsInlineCode($name ? $name : md5($content), $content, $compress, $forceOnTop); } } else { if ($section == 'footer') { $this->pageRenderer->addJsFooterFile($src, $type, $compress, $forceOnTop, $allWrap, $excludeFromConcatenation); } else { $this->pageRenderer->addJsFile($src, $type, $compress, $forceOnTop, $allWrap, $excludeFromConcatenation); } } } } else { // additionalFooterData not possible in USER_INT if (!$src) { $GLOBALS['TSFE']->additionalHeaderData[$name ? $name : md5($content)] = \TYPO3\CMS\Core\Utility\GeneralUtility::wrapJS($content); } else { $GLOBALS['TSFE']->additionalHeaderData[$name ? $name : md5($content)] = '<script type="' . htmlspecialchars($type) . '" src="' . htmlspecialchars($src) . '"></script>'; } } } return ''; }
private function safeRSSData($fileName, $rssArray) { if (file_exists($fileName)) { unlink($fileName); } \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($fileName, serialize($rssArray)); }
/** * @test */ public function retrieveFileOrFolderObjectReturnsFileIfPathIsGiven() { $this->subject = $this->getAccessibleMock(\TYPO3\CMS\Core\Resource\ResourceFactory::class, array('getFileObjectFromCombinedIdentifier'), array(), '', false); $filename = 'typo3temp/4711.txt'; $this->subject->expects($this->once())->method('getFileObjectFromCombinedIdentifier')->with($filename); // Create and prepare test file \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir(PATH_site . $filename, '42'); $this->filesCreated[] = PATH_site . $filename; $this->subject->retrieveFileOrFolderObject($filename); }
/** * Initialize the normal module operation * * @return void */ public function init() { $beUser = $this->getBackendUser(); // Setting more GPvars: $this->popViewId = GeneralUtility::_GP('popViewId'); $this->popViewId_addParams = GeneralUtility::_GP('popViewId_addParams'); $this->viewUrl = GeneralUtility::_GP('viewUrl'); $this->editRegularContentFromId = GeneralUtility::_GP('editRegularContentFromId'); $this->recTitle = GeneralUtility::_GP('recTitle'); $this->noView = GeneralUtility::_GP('noView'); $this->perms_clause = $beUser->getPagePermsClause(1); // Set other internal variables: $this->R_URL_getvars['returnUrl'] = $this->retUrl; $this->R_URI = $this->R_URL_parts['path'] . '?' . ltrim(GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars), '&'); // Setting virtual document name $this->MCONF['name'] = 'xMOD_alt_doc.php'; // Create an instance of the document template object $this->doc = $GLOBALS['TBE_TEMPLATE']; $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class); $pageRenderer->addInlineLanguageLabelFile('EXT:lang/locallang_alt_doc.xlf'); // override the default jumpToUrl $this->moduleTemplate->addJavaScriptCode('jumpToUrl', ' function jumpToUrl(URL,formEl) { if (!TBE_EDITOR.isFormChanged()) { window.location.href = URL; } else if (formEl && formEl.type=="checkbox") { formEl.checked = formEl.checked ? 0 : 1; } } '); // define the window size of the element browser $popupWindowWidth = 700; $popupWindowHeight = 750; $popupWindowSize = trim($beUser->getTSConfigVal('options.popupWindowSize')); if (!empty($popupWindowSize)) { list($popupWindowWidth, $popupWindowHeight) = GeneralUtility::intExplode('x', $popupWindowSize); } $t3Configuration = array('PopupWindow' => array('width' => $popupWindowWidth, 'height' => $popupWindowHeight)); if (ExtensionManagementUtility::isLoaded('feedit') && (int) GeneralUtility::_GP('feEdit') === 1) { // We have to load some locallang strings and push them into TYPO3.LLL if this request was // triggered by feedit. Originally, this object is fed by BackendController which is not // called here. This block of code is intended to be removed at a later point again. $lang = $this->getLanguageService(); $coreLabels = array('csh_tooltip_loading' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:csh_tooltip_loading')); $generatedLabels = array(); $generatedLabels['core'] = $coreLabels; $code = 'TYPO3.LLL = ' . json_encode($generatedLabels) . ';'; $filePath = 'typo3temp/Language/Backend-' . sha1($code) . '.js'; if (!file_exists(PATH_site . $filePath)) { // writeFileToTypo3tempDir() returns NULL on success (please double-read!) $error = GeneralUtility::writeFileToTypo3tempDir(PATH_site . $filePath, $code); if ($error !== null) { throw new \RuntimeException('Locallang JS file could not be written to ' . $filePath . '. Reason: ' . $error, 1446118286); } } $pageRenderer->addJsFile('../' . $filePath); // define the window size of the popups within the RTE $rtePopupWindowSize = trim($beUser->getTSConfigVal('options.rte.popupWindowSize')); if (!empty($rtePopupWindowSize)) { list($rtePopupWindowWidth, $rtePopupWindowHeight) = GeneralUtility::trimExplode('x', $rtePopupWindowSize); } $rtePopupWindowWidth = !empty($rtePopupWindowWidth) ? (int) $rtePopupWindowWidth : $popupWindowWidth - 200; $rtePopupWindowHeight = !empty($rtePopupWindowHeight) ? (int) $rtePopupWindowHeight : $popupWindowHeight - 250; $t3Configuration['RTEPopupWindow'] = ['width' => $rtePopupWindowWidth, 'height' => $rtePopupWindowHeight]; } $javascript = ' TYPO3.configuration = ' . json_encode($t3Configuration) . '; // Object: TS: // passwordDummy and decimalSign are used by tbe_editor.js and have to be declared here as // TS object overwrites the object declared in tbe_editor.js function typoSetup() { // this.uniqueID = ""; this.passwordDummy = "********"; this.PATH_typo3 = ""; this.decimalSign = "."; } var TS = new typoSetup(); // Info view: function launchView(table,uid,bP) { // var backPath= bP ? bP : ""; var thePreviewWindow = window.open( backPath+' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('show_item') . '&table=') . ' + encodeURIComponent(table) + "&uid=" + encodeURIComponent(uid), "ShowItem" + TS.uniqueID, "height=300,width=410,status=0,menubar=0,resizable=0,location=0,directories=0,scrollbars=1,toolbar=0" ); if (thePreviewWindow && thePreviewWindow.focus) { thePreviewWindow.focus(); } } function deleteRecord(table,id,url) { // window.location.href = ' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('tce_db') . '&cmd[') . '+table+"]["+id+"][delete]=1&redirect="+escape(url)+"&vC=' . $beUser->veriCode() . '&prErr=1&uPT=1"; } '; $previewCode = isset($_POST['_savedokview']) && $this->popViewId ? $this->generatePreviewCode() : ''; $this->moduleTemplate->addJavaScriptCode('PreviewCode', $javascript . $previewCode); // Setting up the context sensitive menu: $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu'); $this->emitFunctionAfterSignal(__FUNCTION__); }
/** * Writes contents in a file in typo3temp and returns the file name * * @param string $label: A label to insert at the beginning of the name of the file * @param string $fileExtension: The file extension of the file, defaulting to 'js' * @param string $contents: The contents to write into the file * @return string The name of the file written to typo3temp * @throws \RuntimeException If writing to file failed */ protected function writeTemporaryFile($label, $fileExtension = 'js', $contents = '') { $relativeFilename = 'typo3temp/assets/js/rte_' . str_replace('-', '_', $label) . '_' . GeneralUtility::shortMD5($contents, 20) . '.' . $fileExtension; $destination = PATH_site . $relativeFilename; if (!file_exists($destination)) { $minifiedJavaScript = ''; if ($fileExtension === 'js' && $contents !== '') { $minifiedJavaScript = GeneralUtility::minifyJavaScript($contents); } $failure = GeneralUtility::writeFileToTypo3tempDir($destination, $minifiedJavaScript ? $minifiedJavaScript : $contents); if ($failure) { throw new \RuntimeException($failure, 1460975840); } } if (isset($GLOBALS['TSFE'])) { $fileName = $relativeFilename; } else { $fileName = '../' . $relativeFilename; } return GeneralUtility::resolveBackPath($fileName); }
/** * Method fetches contents from remote server and * writes them into a file in the local file system. * * @param string $remoteResource remote resource to read contents from * @param string $localResource local resource (absolute file path) to store retrieved contents to (must be within typo3temp/) * @return void * @see \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl(), \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile() * @throws ExtensionManagerException */ protected function fetchFile($remoteResource, $localResource) { if ($this->configurationUtility->getCurrentConfiguration('extensionmanager')['offlineMode']['value']) { throw new ExtensionManagerException('Extension Manager is in offline mode. No TER connection available.', 1437078780); } if (is_string($remoteResource) && is_string($localResource) && !empty($remoteResource) && !empty($localResource)) { $fileContent = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($remoteResource); if ($fileContent !== false) { if (\TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($localResource, $fileContent) !== null) { throw new ExtensionManagerException(sprintf('Could not write to file %s.', $localResource), 1342635378); } } else { throw new ExtensionManagerException(sprintf('Could not access remote resource %s.', $remoteResource), 1342635425); } } }
/** * Writes contents in a file in typo3temp/rtehtmlarea directory and returns the file name * * @param string $sourceFileName: The name of the file from which the contents should be extracted * @param string $label: A label to insert at the beginning of the name of the file * @param string $fileExtension: The file extension of the file, defaulting to 'js' * @param string $contents: The contents to write into the file if no $sourceFileName is provided * @param boolean $concatenate Not used anymore * @return string The name of the file writtten to typo3temp/rtehtmlarea */ public function writeTemporaryFile($sourceFileName = '', $label, $fileExtension = 'js', $contents = '', $concatenate = FALSE) { if ($sourceFileName) { $output = ''; $source = GeneralUtility::getFileAbsFileName($sourceFileName); $output = file_get_contents($source); } else { $output = $contents; } $relativeFilename = 'typo3temp/' . $this->ID . '_' . str_replace('-', '_', $label) . '_' . GeneralUtility::shortMD5(TYPO3_version . $TYPO3_CONF_VARS['EXTCONF'][$this->ID]['version'] . ($sourceFileName ? $sourceFileName : $output), 20) . '.' . $fileExtension; $destination = PATH_site . $relativeFilename; if (!file_exists($destination)) { $minifiedJavaScript = ''; if ($fileExtension == 'js' && $output != '') { $minifiedJavaScript = GeneralUtility::minifyJavaScript($output); } $failure = GeneralUtility::writeFileToTypo3tempDir($destination, $minifiedJavaScript ? $minifiedJavaScript : $output); if ($failure) { throw new \RuntimeException($failure, 1294585668); } } if ($this->is_FE()) { $filename = $relativeFilename; } else { $filename = ($this->isFrontendEditActive() ? '' : $this->backPath . '../') . $relativeFilename; } return GeneralUtility::resolveBackPath($filename); }
/** * Writes string to a temporary file named after the md5-hash of the string * * @param string $str CSS styles / JavaScript to write to file. * @param string $ext Extension: "css" or "js * @return string <script> or <link> tag for the file. */ public static function inline2TempFile($str, $ext) { // Create filename / tags: $script = ''; switch ($ext) { case 'js': $script = 'typo3temp/assets/js/' . GeneralUtility::shortMD5($str) . '.js'; break; case 'css': $script = 'typo3temp/assets/css/' . GeneralUtility::shortMD5($str) . '.css'; break; } // Write file: if ($script) { if (!@is_file(PATH_site . $script)) { GeneralUtility::writeFileToTypo3tempDir(PATH_site . $script, $str); } } return $script; }
/** * @return string * @throws Exception */ private function downloadLatestPiwik() { // tell installer where to grab piwik $settings = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['piwikintegration']); if (array_key_exists('piwikDownloadSource', $settings) && $settings['piwikDownloadSource'] != '') { $downloadSource = $settings['piwikDownloadSource']; } else { $downloadSource = 'http://builds.piwik.org/latest.zip'; } //download piwik into typo3temp $zipArchivePath = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('typo3temp/piwiklatest.zip'); \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($zipArchivePath, \TYPO3\CMS\Core\Utility\GeneralUtility::getURL($downloadSource)); if (@filesize($zipArchivePath) === FALSE) { throw new \Exception('Installation invalid, typo3temp ' . $zipArchivePath . ' can´t be created for some reason'); } if (@filesize($zipArchivePath) < 10) { throw new \Exception('Installation invalid, typo3temp' . $zipArchivePath . ' is smaller than 10 bytes, download definitly failed'); } return $zipArchivePath; }
/** * @test */ public function copyDirectoryCopiesFilesAndDirectoriesWithAbsolutePaths() { $sourceDirectory = 'typo3temp/' . $this->getUniqueId('test_') . '/'; $absoluteSourceDirectory = PATH_site . $sourceDirectory; $this->testFilesToDelete[] = $absoluteSourceDirectory; GeneralUtility::mkdir($absoluteSourceDirectory); $targetDirectory = 'typo3temp/' . $this->getUniqueId('test_') . '/'; $absoluteTargetDirectory = PATH_site . $targetDirectory; $this->testFilesToDelete[] = $absoluteTargetDirectory; GeneralUtility::mkdir($absoluteTargetDirectory); GeneralUtility::writeFileToTypo3tempDir($absoluteSourceDirectory . 'file', '42'); GeneralUtility::mkdir($absoluteSourceDirectory . 'foo'); GeneralUtility::writeFileToTypo3tempDir($absoluteSourceDirectory . 'foo/file', '42'); GeneralUtility::copyDirectory($absoluteSourceDirectory, $absoluteTargetDirectory); $this->assertFileExists($absoluteTargetDirectory . 'file'); $this->assertFileExists($absoluteTargetDirectory . 'foo/file'); }
/** * Fetches a document from docs.typo3.org. * * @param string $url * @param string $key * @param string $version * @param string $language * @return bool TRUE if fetch succeeded, otherwise FALSE */ public function fetchDocument($url, $key, $version = 'latest', $language = 'default') { $result = false; $url = rtrim($url, '/') . '/'; $packagePrefix = substr($key, strrpos($key, '.') + 1); $languageSegment = str_replace('_', '-', strtolower($language)); $packageName = sprintf('%s-%s-%s.zip', $packagePrefix, $version, $languageSegment); $packageUrl = $url . 'packages/' . $packageName; $absolutePathToZipFile = GeneralUtility::getFileAbsFileName('typo3temp/var/transient/' . $packageName); $packages = $this->getAvailablePackages($url); if (empty($packages) || !isset($packages[$version][$language])) { return false; } // Check if a local version of the package is already present $hasArchive = false; if (is_file($absolutePathToZipFile)) { $localMd5 = md5_file($absolutePathToZipFile); $remoteMd5 = $packages[$version][$language]; $hasArchive = $localMd5 === $remoteMd5; } if (!$hasArchive) { /** @var $http \TYPO3\CMS\Core\Http\HttpRequest */ $http = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Http\HttpRequest::class, $packageUrl); $response = $http->send(); if ($response->getStatus() == 200) { GeneralUtility::writeFileToTypo3tempDir($absolutePathToZipFile, $response->getBody()); } } if (is_file($absolutePathToZipFile)) { $absoluteDocumentPath = GeneralUtility::getFileAbsFileName('typo3conf/Documentation/'); $result = $this->unzipDocumentPackage($absolutePathToZipFile, $absoluteDocumentPath); // Create a composer.json file $absoluteCacheFilename = GeneralUtility::getFileAbsFileName('typo3temp/var/transient/documents.json'); $documents = json_decode(file_get_contents($absoluteCacheFilename), true); foreach ($documents as $document) { if ($document['key'] === $key) { $composerData = array('name' => $document['title'], 'type' => 'documentation', 'description' => 'TYPO3 ' . $document['type']); $relativeComposerFilename = $key . '/' . $language . '/composer.json'; $absoluteComposerFilename = GeneralUtility::getFileAbsFileName('typo3conf/Documentation/' . $relativeComposerFilename); GeneralUtility::writeFile($absoluteComposerFilename, json_encode($composerData)); break; } } } return $result; }
/** * Swapping versions of a record * Version from archive (future/past, called "swap version") will get the uid of the "t3ver_oid", the official element with uid = "t3ver_oid" will get the new versions old uid. PIDs are swapped also * * @param string $table Table name * @param int $id UID of the online record to swap * @param int $swapWith UID of the archived version to swap with! * @param bool $swapIntoWS If set, swaps online into workspace instead of publishing out of workspace. * @param DataHandler $tcemainObj TCEmain object * @param string $comment Notification comment * @param bool $notificationEmailInfo Accumulate state changes in memory for compiled notification email? * @param array $notificationAlternativeRecipients comma separated list of recipients to notificate instead of normal be_users * @return void */ protected function version_swap($table, $id, $swapWith, $swapIntoWS = 0, DataHandler $tcemainObj, $comment = '', $notificationEmailInfo = FALSE, $notificationAlternativeRecipients = array()) { // Check prerequisites before start swapping // First, check if we may actually edit the online record if (!$tcemainObj->checkRecordUpdateAccess($table, $id)) { $tcemainObj->newlog('Error: You cannot swap versions for a record you do not have access to edit!', 1); return; } // Select the two versions: $curVersion = BackendUtility::getRecord($table, $id, '*'); $swapVersion = BackendUtility::getRecord($table, $swapWith, '*'); $movePlh = array(); $movePlhID = 0; if (!(is_array($curVersion) && is_array($swapVersion))) { $tcemainObj->newlog('Error: Either online or swap version could not be selected!', 2); return; } if (!$tcemainObj->BE_USER->workspacePublishAccess($swapVersion['t3ver_wsid'])) { $tcemainObj->newlog('User could not publish records from workspace #' . $swapVersion['t3ver_wsid'], 1); return; } $wsAccess = $tcemainObj->BE_USER->checkWorkspace($swapVersion['t3ver_wsid']); if (!($swapVersion['t3ver_wsid'] <= 0 || !($wsAccess['publish_access'] & 1) || (int) $swapVersion['t3ver_stage'] === -10)) { $tcemainObj->newlog('Records in workspace #' . $swapVersion['t3ver_wsid'] . ' can only be published when in "Publish" stage.', 1); return; } if (!($tcemainObj->doesRecordExist($table, $swapWith, 'show') && $tcemainObj->checkRecordUpdateAccess($table, $swapWith))) { $tcemainObj->newlog('You cannot publish a record you do not have edit and show permissions for', 1); return; } if ($swapIntoWS && !$tcemainObj->BE_USER->workspaceSwapAccess()) { $tcemainObj->newlog('Workspace #' . $swapVersion['t3ver_wsid'] . ' does not support swapping.', 1); return; } // Check if the swapWith record really IS a version of the original! if (!((int) $swapVersion['pid'] == -1 && (int) $curVersion['pid'] >= 0 && (int) $swapVersion['t3ver_oid'] === (int) $id)) { $tcemainObj->newlog('In swap version, either pid was not -1 or the t3ver_oid didn\'t match the id of the online version as it must!', 2); return; } // Lock file name: $lockFileName = PATH_site . 'typo3temp/swap_locking/' . $table . ':' . $id . '.ser'; if (@is_file($lockFileName)) { $tcemainObj->newlog('A swapping lock file was present. Either another swap process is already running or a previous swap process failed. Ask your administrator to handle the situation.', 2); return; } // Now start to swap records by first creating the lock file // Write lock-file: GeneralUtility::writeFileToTypo3tempDir($lockFileName, serialize(array('tstamp' => $GLOBALS['EXEC_TIME'], 'user' => $tcemainObj->BE_USER->user['username'], 'curVersion' => $curVersion, 'swapVersion' => $swapVersion))); // Find fields to keep $keepFields = $this->getUniqueFields($table); if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) { $keepFields[] = $GLOBALS['TCA'][$table]['ctrl']['sortby']; } // l10n-fields must be kept otherwise the localization // will be lost during the publishing if (!isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) { $keepFields[] = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']; } // Swap "keepfields" foreach ($keepFields as $fN) { $tmp = $swapVersion[$fN]; $swapVersion[$fN] = $curVersion[$fN]; $curVersion[$fN] = $tmp; } // Preserve states: $t3ver_state = array(); $t3ver_state['swapVersion'] = $swapVersion['t3ver_state']; $t3ver_state['curVersion'] = $curVersion['t3ver_state']; // Modify offline version to become online: $tmp_wsid = $swapVersion['t3ver_wsid']; // Set pid for ONLINE $swapVersion['pid'] = (int) $curVersion['pid']; // We clear this because t3ver_oid only make sense for offline versions // and we want to prevent unintentional misuse of this // value for online records. $swapVersion['t3ver_oid'] = 0; // In case of swapping and the offline record has a state // (like 2 or 4 for deleting or move-pointer) we set the // current workspace ID so the record is not deselected // in the interface by BackendUtility::versioningPlaceholderClause() $swapVersion['t3ver_wsid'] = 0; if ($swapIntoWS) { if ($t3ver_state['swapVersion'] > 0) { $swapVersion['t3ver_wsid'] = $tcemainObj->BE_USER->workspace; } else { $swapVersion['t3ver_wsid'] = (int) $curVersion['t3ver_wsid']; } } $swapVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME']; $swapVersion['t3ver_stage'] = 0; if (!$swapIntoWS) { $swapVersion['t3ver_state'] = (string) new VersionState(VersionState::DEFAULT_STATE); } // Moving element. if ((int) $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) { // && $t3ver_state['swapVersion']==4 // Maybe we don't need this? if ($plhRec = BackendUtility::getMovePlaceholder($table, $id, 't3ver_state,pid,uid' . ($GLOBALS['TCA'][$table]['ctrl']['sortby'] ? ',' . $GLOBALS['TCA'][$table]['ctrl']['sortby'] : ''))) { $movePlhID = $plhRec['uid']; $movePlh['pid'] = $swapVersion['pid']; $swapVersion['pid'] = (int) $plhRec['pid']; $curVersion['t3ver_state'] = (int) $swapVersion['t3ver_state']; $swapVersion['t3ver_state'] = (string) new VersionState(VersionState::DEFAULT_STATE); if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) { // sortby is a "keepFields" which is why this will work... $movePlh[$GLOBALS['TCA'][$table]['ctrl']['sortby']] = $swapVersion[$GLOBALS['TCA'][$table]['ctrl']['sortby']]; $swapVersion[$GLOBALS['TCA'][$table]['ctrl']['sortby']] = $plhRec[$GLOBALS['TCA'][$table]['ctrl']['sortby']]; } } } unset($swapVersion['uid']); // Modify online version to become offline: unset($curVersion['uid']); // Set pid for OFFLINE $curVersion['pid'] = -1; $curVersion['t3ver_oid'] = (int) $id; $curVersion['t3ver_wsid'] = $swapIntoWS ? (int) $tmp_wsid : 0; $curVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME']; $curVersion['t3ver_count'] = $curVersion['t3ver_count'] + 1; // Increment lifecycle counter $curVersion['t3ver_stage'] = 0; if (!$swapIntoWS) { $curVersion['t3ver_state'] = (string) new VersionState(VersionState::DEFAULT_STATE); } // Registering and swapping MM relations in current and swap records: $tcemainObj->version_remapMMForVersionSwap($table, $id, $swapWith); // Generating proper history data to prepare logging $tcemainObj->compareFieldArrayWithCurrentAndUnset($table, $id, $swapVersion); $tcemainObj->compareFieldArrayWithCurrentAndUnset($table, $swapWith, $curVersion); // Execute swapping: $sqlErrors = array(); $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int) $id, $swapVersion); if ($GLOBALS['TYPO3_DB']->sql_error()) { $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error(); } else { $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int) $swapWith, $curVersion); if ($GLOBALS['TYPO3_DB']->sql_error()) { $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error(); } else { unlink($lockFileName); } } if (!count($sqlErrors)) { // Register swapped ids for later remapping: $this->remappedIds[$table][$id] = $swapWith; $this->remappedIds[$table][$swapWith] = $id; // If a moving operation took place...: if ($movePlhID) { // Remove, if normal publishing: if (!$swapIntoWS) { // For delete + completely delete! $tcemainObj->deleteEl($table, $movePlhID, TRUE, TRUE); } else { // Otherwise update the movePlaceholder: $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int) $movePlhID, $movePlh); $tcemainObj->addRemapStackRefIndex($table, $movePlhID); } } // Checking for delete: // Delete only if new/deleted placeholders are there. if (!$swapIntoWS && ((int) $t3ver_state['swapVersion'] === 1 || (int) $t3ver_state['swapVersion'] === 2)) { // Force delete $tcemainObj->deleteEl($table, $id, TRUE); } $tcemainObj->newlog2(($swapIntoWS ? 'Swapping' : 'Publishing') . ' successful for table "' . $table . '" uid ' . $id . '=>' . $swapWith, $table, $id, $swapVersion['pid']); // Update reference index of the live record: $tcemainObj->addRemapStackRefIndex($table, $id); // Set log entry for live record: $propArr = $tcemainObj->getRecordPropertiesFromRow($table, $swapVersion); if ($propArr['_ORIG_pid'] == -1) { $label = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tcemain.xlf:version_swap.offline_record_updated'); } else { $label = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tcemain.xlf:version_swap.online_record_updated'); } $theLogId = $tcemainObj->log($table, $id, 2, $propArr['pid'], 0, $label, 10, array($propArr['header'], $table . ':' . $id), $propArr['event_pid']); $tcemainObj->setHistory($table, $id, $theLogId); // Update reference index of the offline record: $tcemainObj->addRemapStackRefIndex($table, $swapWith); // Set log entry for offline record: $propArr = $tcemainObj->getRecordPropertiesFromRow($table, $curVersion); if ($propArr['_ORIG_pid'] == -1) { $label = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tcemain.xlf:version_swap.offline_record_updated'); } else { $label = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tcemain.xlf:version_swap.online_record_updated'); } $theLogId = $tcemainObj->log($table, $swapWith, 2, $propArr['pid'], 0, $label, 10, array($propArr['header'], $table . ':' . $swapWith), $propArr['event_pid']); $tcemainObj->setHistory($table, $swapWith, $theLogId); $stageId = -20; // \TYPO3\CMS\Workspaces\Service\StagesService::STAGE_PUBLISH_EXECUTE_ID; if ($notificationEmailInfo) { $notificationEmailInfoKey = $wsAccess['uid'] . ':' . $stageId . ':' . $comment; $this->notificationEmailInfo[$notificationEmailInfoKey]['shared'] = array($wsAccess, $stageId, $comment); $this->notificationEmailInfo[$notificationEmailInfoKey]['elements'][] = $table . ':' . $id; $this->notificationEmailInfo[$notificationEmailInfoKey]['alternativeRecipients'] = $notificationAlternativeRecipients; } else { $this->notifyStageChange($wsAccess, $stageId, $table, $id, $comment, $tcemainObj, $notificationAlternativeRecipients); } // Write to log with stageId -20 $tcemainObj->newlog2('Stage for record was changed to ' . $stageId . '. Comment was: "' . substr($comment, 0, 100) . '"', $table, $id); $tcemainObj->log($table, $id, 6, 0, 0, 'Published', 30, array('comment' => $comment, 'stage' => $stageId)); // Clear cache: $tcemainObj->registerRecordIdForPageCacheClearing($table, $id); // Checking for "new-placeholder" and if found, delete it (BUT FIRST after swapping!): if (!$swapIntoWS && $t3ver_state['curVersion'] > 0) { // For delete + completely delete! $tcemainObj->deleteEl($table, $swapWith, TRUE, TRUE); } //Update reference index for live workspace too: /** @var $refIndexObj \TYPO3\CMS\Core\Database\ReferenceIndex */ $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class); $refIndexObj->setWorkspaceId(0); $refIndexObj->updateRefIndexTable($table, $id); $refIndexObj->updateRefIndexTable($table, $swapWith); } else { $tcemainObj->newlog('During Swapping: SQL errors happened: ' . implode('; ', $sqlErrors), 2); } }
/** * Install translations for all selected languages for an extension * * @param string $extensionKey The extension key to install the translations for * @param string $language Language code of translation to fetch * @param string $mirrorUrl Mirror URL to fetch data from * @return bool TRUE on success, error string on failure */ public function updateTranslation($extensionKey, $language, $mirrorUrl) { $result = false; try { $l10n = $this->fetchTranslation($extensionKey, $language, $mirrorUrl); if (is_array($l10n)) { $absolutePathToZipFile = GeneralUtility::getFileAbsFileName('typo3temp/Language/' . $extensionKey . '-l10n-' . $language . '.zip'); $relativeLanguagePath = 'l10n' . '/' . $language . '/'; $absoluteLanguagePath = GeneralUtility::getFileAbsFileName(PATH_typo3conf . $relativeLanguagePath); $absoluteExtensionLanguagePath = GeneralUtility::getFileAbsFileName(PATH_typo3conf . $relativeLanguagePath . $extensionKey . '/'); if (empty($absolutePathToZipFile) || empty($absoluteLanguagePath) || empty($absoluteExtensionLanguagePath)) { throw new \TYPO3\CMS\Lang\Exception\Language('Given path is invalid.', 1352565336); } if (!is_dir($absoluteLanguagePath)) { GeneralUtility::mkdir_deep(PATH_typo3conf, $relativeLanguagePath); } GeneralUtility::writeFileToTypo3tempDir($absolutePathToZipFile, $l10n[0]); if (is_dir($absoluteExtensionLanguagePath)) { GeneralUtility::rmdir($absoluteExtensionLanguagePath, true); } if ($this->unzipTranslationFile($absolutePathToZipFile, $absoluteLanguagePath)) { $result = true; } } } catch (\TYPO3\CMS\Core\Exception $exception) { // @todo logging } return $result; }
/** * Writes contents in a file in typo3temp and returns the file name * * @param string $label: A label to insert at the beginning of the name of the file * @param string $fileExtension: The file extension of the file, defaulting to 'js' * @param string $contents: The contents to write into the file * @return string The name of the file written to typo3temp * @throws \RuntimeException If writing to file failed */ protected function writeTemporaryFile($label, $fileExtension = 'js', $contents = '') { $relativeFilename = 'typo3temp/RteHtmlArea/' . str_replace('-', '_', $label) . '_' . GeneralUtility::shortMD5($contents, 20) . '.' . $fileExtension; $destination = PATH_site . $relativeFilename; if (!file_exists($destination)) { $minifiedJavaScript = ''; if ($fileExtension === 'js' && $contents !== '') { $minifiedJavaScript = GeneralUtility::minifyJavaScript($contents); } $failure = GeneralUtility::writeFileToTypo3tempDir($destination, $minifiedJavaScript ? $minifiedJavaScript : $contents); if ($failure) { throw new \RuntimeException($failure, 1294585668); } } if ($this->isFrontend() || $this->isFrontendEditActive()) { $fileName = $relativeFilename; } else { $fileName = '../' . $relativeFilename; } return GeneralUtility::resolveBackPath($fileName); }
/** * Returns the file name to the LLL JavaScript, containing the localized labels, * which can be used in JavaScript code. * * @return string File name of the JS file, relative to TYPO3_mainDir */ protected function getLocalLangFileName() { $code = $this->generateLocalLang(); $filePath = 'typo3temp/locallang-BE-' . sha1($code) . '.js'; if (!file_exists(PATH_site . $filePath)) { // writeFileToTypo3tempDir() returns NULL on success (please double-read!) if (\TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir(PATH_site . $filePath, $code) !== NULL) { throw new \RuntimeException('LocalLangFile could not be written to ' . $filePath, 1295193026); } } return '../' . $filePath; }
/** * @test */ public function fixPermissionsSetsPermissionsWithRelativeFileReference() { if (TYPO3_OS == 'WIN') { $this->markTestSkipped('fixPermissions() tests not available on Windows'); } $filename = 'typo3temp/' . uniqid('test_'); Utility\GeneralUtility::writeFileToTypo3tempDir(PATH_site . $filename, '42'); chmod(PATH_site . $filename, 482); // Set target permissions and run method $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660'; $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($filename); // Get actual permissions and clean up clearstatcache(); $resultFilePermissions = substr(decoct(fileperms(PATH_site . $filename)), 2); unlink(PATH_site . $filename); // Test if everything was ok $this->assertTrue($fixPermissionsResult); $this->assertEquals($resultFilePermissions, '0660'); }
/** * Create new OnlineMedia item container file. * This is created inside typo3temp/ and then moved from FAL to the proper storage. * * @param Folder $targetFolder * @param string $fileName * @param string $onlineMediaId * @return File */ protected function createNewFile(Folder $targetFolder, $fileName, $onlineMediaId) { $temporaryFile = GeneralUtility::tempnam('online_media'); GeneralUtility::writeFileToTypo3tempDir($temporaryFile, $onlineMediaId); $file = $targetFolder->addFile($temporaryFile, $fileName, DuplicationBehavior::RENAME); GeneralUtility::unlink_tempfile($temporaryFile); return $file; }