/** * Get all the complex data for the loader. * This return value will be cached and stored in the database * There is no file monitoring for this cache * * @param Loader $autoLoader * @param int $type * * @return array */ public function prepareLoader(Loader $autoLoader, $type) { $languageOverride = []; if ($type === LoaderInterface::EXT_TABLES) { return $languageOverride; } $languageOverridePath = ExtensionManagementUtility::extPath($autoLoader->getExtensionKey()) . 'Resources/Private/Language/Overrides/'; if (!is_dir($languageOverridePath)) { return $languageOverride; } $files = GeneralUtility::getAllFilesAndFoldersInPath([], $languageOverridePath, 'xlf,php,xml', false, 99); foreach ($files as $file) { $file = str_replace($languageOverridePath, '', $file); $parts = GeneralUtility::trimExplode('/', $file, true); $extension = GeneralUtility::camelCaseToLowerCaseUnderscored($parts[0]); unset($parts[0]); $parts = array_values($parts); // language $language = 'default'; $fileParts = GeneralUtility::trimExplode('.', PathUtility::basename($file), true); if (strlen($fileParts[0]) === 2) { $language = $fileParts[0]; unset($fileParts[0]); $parts[sizeof($parts) - 1] = implode('.', $fileParts); } $languageOverride[] = ['language' => $language, 'original' => 'EXT:' . $extension . '/' . implode('/', $parts), 'override' => 'EXT:' . $autoLoader->getExtensionKey() . '/Resources/Private/Language/Overrides/' . $file]; } return $languageOverride; }
/** * Unset all additional properties of test classes to help PHP * garbage collection. This reduces memory footprint with lots * of tests. * * If owerwriting tearDown() in test classes, please call * parent::tearDown() at the end. Unsetting of own properties * is not needed this way. * * @throws \RuntimeException * @return void */ protected function tearDown() { // Unset properties of test classes to safe memory $reflection = new \ReflectionObject($this); foreach ($reflection->getProperties() as $property) { $declaringClass = $property->getDeclaringClass()->getName(); if (!$property->isStatic() && $declaringClass !== \TYPO3\CMS\Core\Tests\UnitTestCase::class && $declaringClass !== \TYPO3\CMS\Core\Tests\BaseTestCase::class && strpos($property->getDeclaringClass()->getName(), 'PHPUnit_') !== 0) { $propertyName = $property->getName(); unset($this->{$propertyName}); } } unset($reflection); // Delete registered test files and directories foreach ($this->testFilesToDelete as $absoluteFileName) { $absoluteFileName = GeneralUtility::fixWindowsFilePath(PathUtility::getCanonicalPath($absoluteFileName)); if (!GeneralUtility::validPathStr($absoluteFileName)) { throw new \RuntimeException('tearDown() cleanup: Filename contains illegal characters', 1410633087); } if (!StringUtility::beginsWith($absoluteFileName, PATH_site . 'typo3temp/')) { throw new \RuntimeException('tearDown() cleanup: Files to delete must be within typo3temp/', 1410633412); } // file_exists returns false for links pointing to not existing targets, so handle links before next check. if (@is_link($absoluteFileName) || @is_file($absoluteFileName)) { unlink($absoluteFileName); } elseif (@is_dir($absoluteFileName)) { GeneralUtility::rmdir($absoluteFileName, true); } else { throw new \RuntimeException('tearDown() cleanup: File, link or directory does not exist', 1410633510); } } $this->testFilesToDelete = array(); }
/** * Initialize new row with default values from various sources * * @param array $result * @return array * @todo: Should not implode valid values with | again, container & elements should work * @todo: with the array as it was done for select items * @throws \UnexpectedValueException */ public function addData(array $result) { foreach ($result['processedTca']['columns'] as $fieldName => $fieldConfig) { if (empty($fieldConfig['config']['type']) || $fieldConfig['config']['type'] !== 'group' || empty($fieldConfig['config']['internal_type'])) { continue; } $databaseRowFieldContent = ''; if (!empty($result['databaseRow'][$fieldName])) { $databaseRowFieldContent = (string) $result['databaseRow'][$fieldName]; } $internalType = $fieldConfig['config']['internal_type']; if ($internalType === 'file_reference' || $internalType === 'file') { $files = array(); // Simple list of files $fileList = GeneralUtility::trimExplode(',', $databaseRowFieldContent, true); foreach ($fileList as $file) { if ($file) { $files[] = rawurlencode($file) . '|' . rawurlencode(PathUtility::basename($file)); } } $result['databaseRow'][$fieldName] = implode(',', $files); } elseif ($internalType === 'db') { /** @var $relationHandler RelationHandler */ $relationHandler = GeneralUtility::makeInstance(RelationHandler::class); $relationHandler->start($databaseRowFieldContent, $fieldConfig['config']['allowed'], $fieldConfig['config']['MM'], $result['databaseRow']['uid'], $result['tableName'], $fieldConfig['config']); $relationHandler->getFromDB(); $result['databaseRow'][$fieldName] = $relationHandler->readyForInterface(); } else { // @todo: "folder" is a valid internal_type, too. throw new \UnexpectedValueException('TCA internal_type of field "' . $fieldName . '" in table ' . $result['tableName'] . ' must be set to either "db", "file" or "file_reference"', 1438780511); } } return $result; }
/** * Compresses and minifies a javascript file * * @param string $filename Source filename, relative to requested page * @return string Filename of the compressed file, relative to requested page */ public function compressJsFile($filename) { // generate the unique name of the file $filenameAbsolute = GeneralUtility::resolveBackPath($this->rootPath . $this->getFilenameFromMainDir($filename)); if (@file_exists($filenameAbsolute)) { $fileStatus = stat($filenameAbsolute); $unique = $filenameAbsolute . $fileStatus['mtime'] . $fileStatus['size']; } else { $unique = $filenameAbsolute; } $pathinfo = PathUtility::pathinfo($filename); $targetFile = $this->targetDirectory . $pathinfo['filename'] . '-' . md5($unique) . '.js'; // only create it, if it doesn't exist, yet if (!file_exists(PATH_site . $targetFile) || $this->createGzipped && !file_exists(PATH_site . $targetFile . '.gzip')) { $contents = file_get_contents($filenameAbsolute); try { $minifiedContents = Minifier::minify($contents); } catch (\Exception $e) { // Log error and use un-minified content as fallback /** @var $logger Logger */ $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); $logger->error($e->getMessage(), ['filename' => $filename]); $minifiedContents = $contents; } $this->writeFileAndCompressed($targetFile, $minifiedContents); } return $this->relativePath . $this->returnFileReference($targetFile); }
/** * Get all the complex data for the loader. * This return value will be cached and stored in the database * There is no file monitoring for this cache * * @param Loader $loader * @param int $type * * @return array */ public function prepareLoader(Loader $loader, $type) { $icons = []; if (!class_exists('TYPO3\\CMS\\Core\\Imaging\\IconRegistry')) { return $icons; } $iconFolder = 'Resources/Public/Icon/'; $folder = ExtensionManagementUtility::extPath($loader->getExtensionKey()) . $iconFolder; $extensionPath = ExtensionManagementUtility::extPath($loader->getExtensionKey()); $files = GeneralUtility::getAllFilesAndFoldersInPath([], $folder, '', false, true); if (!sizeof($files)) { return $icons; } foreach ($files as $path) { $provider = 'TYPO3\\CMS\\Core\\Imaging\\IconProvider\\BitmapIconProvider'; if (substr(strtolower($path), -3) === 'svg') { $provider = 'TYPO3\\CMS\\Core\\Imaging\\IconProvider\\SvgIconProvider'; } $relativePath = str_replace($extensionPath, '', $path); $iconPath = str_replace($iconFolder, '', $relativePath); $pathElements = PathUtility::pathinfo(strtolower(str_replace('/', '-', $iconPath))); $icons[] = ['provider' => $provider, 'path' => 'EXT:' . $loader->getExtensionKey() . '/' . $relativePath, 'identifier' => str_replace('_', '-', $loader->getExtensionKey()) . '-' . $pathElements['filename']]; } return $icons; }
/** * Get all the complex data for the loader. * This return value will be cached and stored in the database * There is no file monitoring for this cache * * @param Loader $loader * @param int $type * * @return array */ public function prepareLoader(Loader $loader, $type) { $grids = []; if (!ExtensionManagementUtility::isLoaded('gridelements')) { return $grids; } $commandPath = ExtensionManagementUtility::extPath($loader->getExtensionKey()) . 'Resources/Private/Grids/'; $files = FileUtility::getBaseFilesWithExtensionInDir($commandPath, 'ts,txt'); foreach ($files as $file) { $pathInfo = PathUtility::pathinfo($file); $iconPath = 'EXT:' . $loader->getExtensionKey() . '/Resources/Public/Icons/Grids/' . $pathInfo['filename'] . '.'; $extension = IconUtility::getIconFileExtension(GeneralUtility::getFileAbsFileName($iconPath)); $translationKey = 'grid.' . $pathInfo['filename']; if ($type === LoaderInterface::EXT_TABLES) { TranslateUtility::assureLabel($translationKey, $loader->getExtensionKey(), $pathInfo['filename']); } $path = 'EXT:' . $loader->getExtensionKey() . '/Resources/Private/Grids/' . $file; $icon = $extension ? $iconPath . $extension : false; $label = TranslateUtility::getLllString($translationKey, $loader->getExtensionKey()); $content = GeneralUtility::getUrl(GeneralUtility::getFileAbsFileName($path)); $flexForm = 'EXT:' . $loader->getExtensionKey() . '/Configuration/FlexForms/Grids/' . $pathInfo['filename'] . '.xml'; $flexFormFile = GeneralUtility::getFileAbsFileName($flexForm); $flexFormContent = is_file($flexFormFile) ? GeneralUtility::getUrl($flexFormFile) : false; $grids[] = $this->getPageTsConfig($pathInfo['filename'], $label, $content, $icon, $flexFormContent); } return $grids; }
/** * collect all fileinformations of given file and * save them to the global fileinformation array * * @param string $file * @return boolean is valid file? */ protected function setFileInformations($file) { $this->fileInfo = array(); // reset previously information to have a cleaned object $this->file = $file instanceof \TYPO3\CMS\Core\Resource\File ? $file : NULL; if (is_string($file) && !empty($file)) { $this->fileInfo = TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($file); $this->fileInfo['mtime'] = filemtime($file); $this->fileInfo['atime'] = fileatime($file); $this->fileInfo['owner'] = fileowner($file); $this->fileInfo['group'] = filegroup($file); $this->fileInfo['size'] = filesize($file); $this->fileInfo['type'] = filetype($file); $this->fileInfo['perms'] = fileperms($file); $this->fileInfo['is_dir'] = is_dir($file); $this->fileInfo['is_file'] = is_file($file); $this->fileInfo['is_link'] = is_link($file); $this->fileInfo['is_readable'] = is_readable($file); $this->fileInfo['is_uploaded'] = is_uploaded_file($file); $this->fileInfo['is_writeable'] = is_writeable($file); } if ($file instanceof \TYPO3\CMS\Core\Resource\File) { $pathInfo = \TYPO3\CMS\Core\Utility\PathUtility::pathinfo($file->getName()); $this->fileInfo = array('file' => $file->getName(), 'filebody' => $file->getNameWithoutExtension(), 'fileext' => $file->getExtension(), 'realFileext' => $pathInfo['extension'], 'atime' => $file->getCreationTime(), 'mtime' => $file->getModificationTime(), 'owner' => '', 'group' => '', 'size' => $file->getSize(), 'type' => 'file', 'perms' => '', 'is_dir' => FALSE, 'is_file' => $file->getStorage()->getDriverType() === 'Local' ? is_file($file->getForLocalProcessing(FALSE)) : TRUE, 'is_link' => $file->getStorage()->getDriverType() === 'Local' ? is_link($file->getForLocalProcessing(FALSE)) : FALSE, 'is_readable' => TRUE, 'is_uploaded' => FALSE, 'is_writeable' => FALSE); } return $this->fileInfo !== array(); }
/** * @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>'; }
/** * Index action shows install tool / step installer or redirect to action to enable install tool * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function index(ServerRequestInterface $request, ResponseInterface $response) { /** @var EnableFileService $enableFileService */ $enableFileService = GeneralUtility::makeInstance(EnableFileService::class); /** @var AbstractFormProtection $formProtection */ $formProtection = FormProtectionFactory::get(); if ($enableFileService->checkInstallToolEnableFile()) { // Install tool is open and valid, redirect to it $response = $response->withStatus(303)->withHeader('Location', 'sysext/install/Start/Install.php?install[context]=backend'); } elseif ($request->getMethod() === 'POST' && $request->getParsedBody()['action'] === 'enableInstallTool') { // Request to open the install tool $installToolEnableToken = $request->getParsedBody()['installToolEnableToken']; if (!$formProtection->validateToken($installToolEnableToken, 'installTool')) { throw new \RuntimeException('Given form token was not valid', 1369161225); } $enableFileService->createInstallToolEnableFile(); // Install tool is open and valid, redirect to it $response = $response->withStatus(303)->withHeader('Location', 'sysext/install/Start/Install.php?install[context]=backend'); } else { // Show the "create enable install tool" button /** @var StandaloneView $view */ $view = GeneralUtility::makeInstance(StandaloneView::class); $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:install/Resources/Private/Templates/BackendModule/ShowEnableInstallToolButton.html')); $token = $formProtection->generateToken('installTool'); $view->assign('installToolEnableToken', $token); /** @var ModuleTemplate $moduleTemplate */ $moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class); $cssFile = 'EXT:install/Resources/Public/Css/BackendModule/ShowEnableInstallToolButton.css'; $cssFile = GeneralUtility::getFileAbsFileName($cssFile); $moduleTemplate->getPageRenderer()->addCssFile(PathUtility::getAbsoluteWebPath($cssFile)); $moduleTemplate->setContent($view->render()); $response->getBody()->write($moduleTemplate->renderContent()); } return $response; }
/** * @param string $identifier * * @return string */ public function render($identifier = '') { $basePath = 'sysext/t3skin/images/icons/'; $nameParts = GeneralUtility::trimExplode('-', $identifier); $folder = array_shift($nameParts); $basePath .= $folder . '/' . implode('-', $nameParts) . '.png'; return '<img src="' . PathUtility::getAbsoluteWebPath($basePath) . '" />'; }
/** * Return a public path pointing to a resource. * * @param string $resource * @return string */ public static function getRelativePath($resource) { // If file is not found, resolve the path if (!is_file(PATH_site . $resource)) { $resource = substr(self::resolvePath($resource), strlen(PATH_site)); } return PathUtility::getRelativePathTo(PathUtility::dirname(PATH_site . $resource)) . PathUtility::basename($resource); }
/** * Check if the given path or extension is valid for the focuspoint * * @param $pathOrExtension * @return bool */ public static function isValidFileExtension($pathOrExtension) { $pathOrExtension = strtolower($pathOrExtension); $validExtensions = self::getAllowedFileExtensions(); if (in_array($pathOrExtension, $validExtensions)) { return true; } return in_array(PathUtility::pathinfo($pathOrExtension, PATHINFO_EXTENSION), $validExtensions); }
/** * Get url * * @param bool $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all. * @return string */ public function getUrl($relativeToCurrentScript = false) { $url = $this->url; if ($relativeToCurrentScript && !GeneralUtility::isValidUrl($url)) { $absolutePathToContainingFolder = PathUtility::dirname(PATH_site . $url); $pathPart = PathUtility::getRelativePathTo($absolutePathToContainingFolder); $filePart = substr(PATH_site . $url, strlen($absolutePathToContainingFolder) + 1); $url = $pathPart . $filePart; } return $url; }
/** * @param array $asset * @return void */ protected function loadByCorePageRender(array $asset) { $file = $this->resolveFileForApplicationContext($asset); $fileNameAndPath = GeneralUtility::getFileAbsFileName($file); $fileNameAndPath = PathUtility::stripPathSitePrefix($fileNameAndPath); if ($asset['type'] === 'js') { $this->getPageRenderer()->addJsFooterFile($fileNameAndPath); } elseif ($asset['type'] === 'css') { $this->getPageRenderer()->addCssFile($fileNameAndPath); } }
/** * @param Icon $icon * @param array $options * @return string * @throws \InvalidArgumentException */ protected function generateMarkup(Icon $icon, array $options) { if (empty($options['source'])) { throw new \InvalidArgumentException('[' . $icon->getIdentifier() . '] The option "source" is required and must not be empty', 1440754980); } $source = $options['source']; if (StringUtility::beginsWith($source, 'EXT:') || !StringUtility::beginsWith($source, '/')) { $source = GeneralUtility::getFileAbsFileName($source); } $source = PathUtility::getAbsoluteWebPath($source); return '<img src="' . htmlspecialchars($source) . '" width="' . $icon->getDimension()->getWidth() . '" height="' . $icon->getDimension()->getHeight() . '" />'; }
/** * Rendering the "data-htmlarea-clickenlarge" custom attribute, called from TypoScript * * @param string Content input. Not used, ignore. * @param array TypoScript configuration * @return string HTML output. * @access private * @todo Define visibility */ public function render_clickenlarge($content, $conf) { $clickenlarge = isset($this->cObj->parameters['data-htmlarea-clickenlarge']) ? $this->cObj->parameters['data-htmlarea-clickenlarge'] : 0; if (!$clickenlarge) { // Backward compatibility $clickenlarge = isset($this->cObj->parameters['clickenlarge']) ? $this->cObj->parameters['clickenlarge'] : 0; } $fileFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance(); $fileTable = $this->cObj->parameters['data-htmlarea-file-table']; $fileUid = $this->cObj->parameters['data-htmlarea-file-uid']; if ($fileUid) { $fileObject = $fileFactory->getFileObject($fileUid); $filePath = $fileObject->getForLocalProcessing(FALSE); $file = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($filePath); } else { // Pre-FAL backward compatibility $path = $this->cObj->parameters['src']; $magicFolder = $fileFactory->getFolderObjectFromCombinedIdentifier($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_imageStorageDir']); if ($magicFolder instanceof \TYPO3\CMS\Core\Resource\Folder) { $magicFolderPath = $magicFolder->getPublicUrl(); $pathPre = $magicFolderPath . 'RTEmagicC_'; if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($path, $pathPre)) { // Find original file: $pI = pathinfo(substr($path, strlen($pathPre))); $filename = substr($pI['basename'], 0, -strlen('.' . $pI['extension'])); $file = $magicFolderPath . 'RTEmagicP_' . $filename; } else { $file = $this->cObj->parameters['src']; } } } // Unset clickenlarge custom attribute unset($this->cObj->parameters['data-htmlarea-clickenlarge']); // Backward compatibility unset($this->cObj->parameters['clickenlarge']); unset($this->cObj->parameters['allParams']); $content = '<img ' . \TYPO3\CMS\Core\Utility\GeneralUtility::implodeAttributes($this->cObj->parameters, TRUE, TRUE) . ' />'; if ($clickenlarge && is_array($conf['imageLinkWrap.'])) { $theImage = $file ? $GLOBALS['TSFE']->tmpl->getFileName($file) : ''; if ($theImage) { $this->cObj->parameters['origFile'] = $theImage; if ($this->cObj->parameters['title']) { $conf['imageLinkWrap.']['title'] = $this->cObj->parameters['title']; } if ($this->cObj->parameters['alt']) { $conf['imageLinkWrap.']['alt'] = $this->cObj->parameters['alt']; } $content = $this->cObj->imageLinkWrap($content, $theImage, $conf['imageLinkWrap.']); $content = $this->cObj->stdWrap($content, $conf['stdWrap.']); } } return $content; }
/** * Convert arrays with EXT: resource paths to web paths * * Input: * [ * 100 => 'EXT:form/Resources/Public/Css/form.css' * ] * * Output: * * [ * 0 => 'typo3/sysext/form/Resources/Public/Css/form.css' * ] * * @param array $resourcePaths * @return array */ protected function resolveResourcePaths(array $resourcePaths) : array { $return = []; foreach ($resourcePaths as $resourcePath) { $fullResourcePath = GeneralUtility::getFileAbsFileName($resourcePath); $resourcePath = PathUtility::getAbsoluteWebPath($fullResourcePath); if (empty($resourcePath)) { continue; } $return[] = $resourcePath; } return $return; }
/** * The actual text extraction. * * @param FileInterface $file * @return string */ public function extractText(FileInterface $file) { $localTempFile = $file->getForLocalProcessing(false); // extract text $content = file_get_contents($localTempFile); // In case of remote storage, the temporary copy of the // original file in typo3temp must be removed // Simply compare the filenames, because the filename is so unique that // it is nearly impossible to have a file with this name in a storage if (PathUtility::basename($localTempFile) !== $file->getName()) { unlink($localTempFile); } return $content; }
/** * Sets the path to the log file. * * @param string $relativeLogFile path to the log file, relative to PATH_site * @return WriterInterface * @throws InvalidLogWriterConfigurationException */ public function setLogFile($relativeLogFile) { $logFile = $relativeLogFile; // Skip handling if logFile is a stream resource. This is used by unit tests with vfs:// directories if (false === strpos($logFile, '://') && !PathUtility::isAbsolutePath($logFile)) { $logFile = GeneralUtility::getFileAbsFileName($logFile); if ($logFile === NULL) { throw new InvalidLogWriterConfigurationException('Log file path "' . $relativeLogFile . '" is not valid!', 1444374805); } } $this->logFile = $logFile; $this->openLogFile(); return $this; }
/** * Renders the view and returns the content * * @param string $title The title to be shown * @param string $message The message to be shown * @param int $severity The severity of the error, see AbstractMessage constants * @param int $errorCode The error code to be referenced * @return string the output of the view */ public function errorAction(string $title, string $message, int $severity = AbstractMessage::ERROR, int $errorCode = 0) : string { $this->severity = $severity; $classes = [AbstractMessage::NOTICE => 'notice', AbstractMessage::INFO => 'information', AbstractMessage::OK => 'ok', AbstractMessage::WARNING => 'warning', AbstractMessage::ERROR => 'error']; $this->view->assign('severityCssClass', $classes[$this->severity]); $this->view->assign('severity', $this->severity); $this->view->assign('message', $message); $this->view->assign('title', $title); $this->view->assign('errorCodeUrlPrefix', TYPO3_URL_EXCEPTION); $this->view->assign('errorCode', $errorCode); $this->view->assign('logo', PathUtility::getAbsoluteWebPath(ExtensionManagementUtility::extPath('backend', 'Resources/Public/Images/typo3_orange.svg'))); $this->view->assign('cssFile', PathUtility::getAbsoluteWebPath(ExtensionManagementUtility::extPath('core', 'Resources/Public/Css/errorpage.css'))); $this->view->assign('copyrightYear', TYPO3_copyright_year); return $this->view->render('Error'); }
/** * Handles the existing files of a Fine Uploader form. * The values are stored in the GET/POST var at the index "fieldValue". * * @return string */ public function getExistingFiles() { $files = array(); $fieldValue = GeneralUtility::_GP('fieldValue'); if ($fieldValue != '') { $imagePath = GeneralUtility::getFileAbsFileName($fieldValue); $imageName = PathUtility::basename($imagePath); $imageDirectoryPath = PathUtility::dirname($imagePath); $imageDirectoryPath = PathUtility::getRelativePath(PATH_site, $imageDirectoryPath); $imageUrl = GeneralUtility::locationHeaderUrl('/' . $imageDirectoryPath . $imageName); if (file_exists($imagePath)) { $files[] = array('name' => $imageName, 'uuid' => $imageUrl, 'thumbnailUrl' => $imageUrl); } } return json_encode($files); }
/** * Render the URI to the resource. The filename is used from child content. * * @param string $path The path and filename of the resource (relative to Public resource directory of the extension). * @param string $extensionName Target extension name. If not set, the current extension name will be used * @param boolean $absolute If set, an absolute URI is rendered * @return string The URI to the resource * @api */ public function render($path, $extensionName = NULL, $absolute = FALSE) { if ($extensionName === NULL) { $extensionName = $this->controllerContext->getRequest()->getControllerExtensionName(); } $uri = 'EXT:' . \TYPO3\CMS\Core\Utility\GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName) . '/Resources/Public/' . $path; $uri = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($uri); $uri = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($uri); if (TYPO3_MODE === 'BE' && $absolute === FALSE && $uri !== FALSE) { $uri = '../' . $uri; } if ($absolute === TRUE) { $uri = $this->controllerContext->getRequest()->getBaseURI() . $uri; } return $uri; }
/** * @param ResourceStorage $storage * @param AbstractDriver $driver * @param ResourceInterface $resource * @param boolean $relativeToCurrentScript * @param array $urlData */ public function getPublicUrl(ResourceStorage $storage, AbstractDriver $driver, ResourceInterface $resource, $relativeToCurrentScript, array $urlData) { if (!$driver instanceof LocalDriver) { // We cannot handle other files than local files yet return; } $publicUrl = $this->resourcePublisher->getResourceWebUri($resource); if ($publicUrl !== FALSE) { // If requested, make the path relative to the current script in order to make it possible // to use the relative file if ($relativeToCurrentScript) { $publicUrl = PathUtility::getRelativePathTo(PathUtility::dirname(PATH_site . $publicUrl)) . PathUtility::basename($publicUrl); } // $urlData['publicUrl'] is passed by reference, so we can change that here and the value will be taken into account $urlData['publicUrl'] = $publicUrl; } }
/** * Handles the existing files of a Fine Uploader form. * The values are stored in the GET/POST var at the index "fieldValue". * * @return string */ public function getExistingFiles() { $files = []; $fieldValue = GeneralUtility::_GP('fieldValue'); if ($fieldValue != '') { // $imagePath = GeneralUtility::getFileAbsFileName($fieldValue); $imagePath = str_replace('new:', '', $fieldValue); $imageName = PathUtility::basename($imagePath); $imageDirectoryPath = PathUtility::dirname($imagePath); $imageDirectoryPath = PathUtility::getRelativePath(PATH_site, $imageDirectoryPath); $imageUrl = GeneralUtility::locationHeaderUrl('/' . $imageDirectoryPath . $imageName); if (file_exists($imagePath)) { $files[] = ['name' => $imageName, 'uuid' => $imageUrl, 'thumbnailUrl' => $imageUrl]; } } return $files; }
/** * Get all the complex data and information for the loader. * This return value will be cached and stored in the core_cache of TYPO3. * There is no file monitoring for this cache. * * @param Loader $loader * @param int $type * * @return array */ public function prepareLoader(Loader $loader, $type) { $backendLayouts = array(); $commandPath = ExtensionManagementUtility::extPath($loader->getExtensionKey()) . 'Resources/Private/BackendLayouts/'; $backendLayoutFiles = FileUtility::getBaseFilesWithExtensionInDir($commandPath, 'ts,txt'); foreach ($backendLayoutFiles as $file) { $pathInfo = PathUtility::pathinfo($file); $iconPath = 'EXT:' . $loader->getExtensionKey() . '/Resources/Public/Icons/BackendLayouts/' . $pathInfo['filename'] . '.'; $extension = IconUtility::getIconFileExtension(GeneralUtility::getFileAbsFileName($iconPath)); $translationKey = 'backendLayout.' . $pathInfo['basename']; if ($type === LoaderInterface::EXT_TABLES) { TranslateUtility::assureLabel($translationKey, $loader->getExtensionKey(), $pathInfo['filename']); } $backendLayouts[] = array('path' => 'EXT:' . $loader->getExtensionKey() . '/Resources/Private/BackendLayouts/' . $file, 'filename' => $pathInfo['filename'], 'icon' => $extension ? $iconPath . $extension : FALSE, 'label' => TranslateUtility::getLllString($translationKey, $loader->getExtensionKey()), 'extension' => $loader->getExtensionKey()); } return $backendLayouts; }
/** * Initializes the controller before invoking an action method. * * @return void */ protected function initializeAction() { $this->pageRenderer = $this->getPageRenderer(); // @todo Evaluate how the intval() call can be used with Extbase validators/filters $this->pageId = (int) GeneralUtility::_GP('id'); $iconFactory = GeneralUtility::makeInstance(IconFactory::class); $icons = array('language' => $iconFactory->getIcon('flags-multiple', Icon::SIZE_SMALL)->render(), 'integrity' => $iconFactory->getIcon('status-dialog-information', Icon::SIZE_SMALL)->render(), 'success' => $iconFactory->getIcon('status-dialog-ok', Icon::SIZE_SMALL)->render(), 'info' => $iconFactory->getIcon('status-dialog-information', Icon::SIZE_SMALL)->render(), 'warning' => $iconFactory->getIcon('status-dialog-warning', Icon::SIZE_SMALL)->render(), 'error' => $iconFactory->getIcon('status-dialog-error', Icon::SIZE_SMALL)->render()); $this->pageRenderer->addInlineSetting('Workspaces', 'icons', $icons); $this->pageRenderer->addInlineSetting('Workspaces', 'id', $this->pageId); $this->pageRenderer->addInlineSetting('Workspaces', 'depth', $this->pageId === 0 ? 999 : 1); $this->pageRenderer->addInlineSetting('Workspaces', 'language', $this->getLanguageSelection()); $cssFile = 'EXT:workspaces/Resources/Public/Css/module.css'; $cssFile = GeneralUtility::getFileAbsFileName($cssFile); $this->pageRenderer->addCssFile(PathUtility::getAbsoluteWebPath($cssFile)); $this->pageRenderer->addInlineLanguageLabelArray(array('title' => $GLOBALS['LANG']->getLL('title'), 'path' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.path'), 'table' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.table'), 'depth' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_perm.xlf:Depth'), 'depth_0' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_0'), 'depth_1' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_1'), 'depth_2' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_2'), 'depth_3' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_3'), 'depth_4' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_4'), 'depth_infi' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_infi'))); $this->pageRenderer->addInlineLanguageLabelFile('EXT:workspaces/Resources/Private/Language/locallang.xlf'); $this->assignExtensionSettings(); }
/** * 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); }
/** * Add the given icon to the TCA table type * * @param string $table * @param string $type * @param string $icon */ public static function addTcaTypeIcon($table, $type, $icon) { if (GeneralUtility::compat_version('7.0')) { $fullIconPath = substr(PathUtility::getAbsoluteWebPath($icon), 1); if (StringUtility::endsWith(strtolower($fullIconPath), 'svg')) { $iconProviderClass = 'TYPO3\\CMS\\Core\\Imaging\\IconProvider\\SvgIconProvider'; } else { $iconProviderClass = 'TYPO3\\CMS\\Core\\Imaging\\IconProvider\\BitmapIconProvider'; } /** @var IconRegistry $iconRegistry */ $iconRegistry = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Imaging\\IconRegistry'); $iconIdentifier = 'tcarecords-' . $table . '-' . $type; $iconRegistry->registerIcon($iconIdentifier, $iconProviderClass, ['source' => $fullIconPath]); $GLOBALS['TCA']['tt_content']['ctrl']['typeicon_classes'][$type] = $iconIdentifier; } else { $fullIconPath = str_replace('../typo3/', '', $icon); SpriteManager::addTcaTypeIcon('tt_content', $type, $fullIconPath); } }
/** * @param array $arguments * @param callable $renderChildrenClosure * @param RenderingContextInterface $renderingContext * @return string */ public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) { $path = $arguments['path']; $extensionName = $arguments['extensionName']; $absolute = $arguments['absolute']; if ($extensionName === NULL) { $extensionName = $renderingContext->getControllerContext()->getRequest()->getControllerExtensionName(); } $uri = 'EXT:' . GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName) . '/Resources/Public/' . $path; $uri = GeneralUtility::getFileAbsFileName($uri); $uri = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($uri); if (TYPO3_MODE === 'BE' && $absolute === FALSE && $uri !== FALSE) { $uri = '../' . $uri; } if ($absolute === TRUE) { $uri = $renderingContext->getControllerContext()->getRequest()->getBaseUri() . $uri; } return $uri; }
/** * Set a class loader cache content * * @TODO: Rename method * @param string $entryIdentifier * @param string $filePath * @throws \InvalidArgumentException * @internal This is not an API method */ public function setLinkToPhpFile($entryIdentifier, $filePath) { if ($entryIdentifier === '') { throw new \InvalidArgumentException('The specified entry identifier must not be empty.', 1364205170); } if (!PathUtility::isAbsolutePath($filePath)) { throw new \InvalidArgumentException('Only absolute paths are allowed for the class loader, given path was: ' . $filePath, 1381923089); } if (!@file_exists($filePath)) { throw new \InvalidArgumentException('The specified file path (' . $filePath . ') must exist.', 1364205235); } if (strtolower(substr($filePath, -4)) !== '.php') { throw new \InvalidArgumentException('The specified file (' . $filePath . ') must be a php file.', 1364205377); } if ($entryIdentifier !== basename($entryIdentifier)) { throw new \InvalidArgumentException('The specified entry identifier (' . $entryIdentifier . ') must not contain a path segment.', 1364205166); } $this->set($entryIdentifier, sprintf($this->requireFileTemplate, $filePath)); }