/** * 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; } }
/** * Search for GraphicsMagick executables in given paths. * * @param array $searchPaths List of paths to search for * @return bool TRUE if graphics magick was found in path */ protected function findImageMagick6InPaths(array $searchPaths) { $result = FALSE; foreach ($searchPaths as $path) { if (TYPO3_OS === 'WIN') { $executable = 'identify.exe'; } else { $executable = 'identify'; } if (@is_file($path . $executable)) { $command = escapeshellarg($path . $executable) . ' -version'; $executingResult = FALSE; \TYPO3\CMS\Core\Utility\CommandUtility::exec($command, $executingResult); // First line of exec command should contain string GraphicsMagick $firstResultLine = array_shift($executingResult); // Example: "Version: ImageMagick 6.6.0-4 2012-05-02 Q16 http://www.imagemagick.org" if (strpos($firstResultLine, 'ImageMagick') !== FALSE) { list(, $version) = explode('ImageMagick', $firstResultLine); // Example: "6.6.0-4" list($version) = explode(' ', trim($version)); if (version_compare($version, '6.0.0') >= 0) { $this->foundPath = $path; $result = TRUE; break; } } } } return $result; }
/** * This method actually does the processing of files locally * * takes the original file (on remote storages this will be fetched from the remote server) * does the IM magic on the local server by creating a temporary typo3temp/ file * copies the typo3temp/ file to the processing folder of the target storage * removes the typo3temp/ file * * @param TaskInterface $task * @return array */ public function process(TaskInterface $task) { $targetFile = $task->getTargetFile(); // Merge custom configuration with default configuration $configuration = array_merge(array('width' => 64, 'height' => 64), $task->getConfiguration()); $configuration['width'] = Utility\MathUtility::forceIntegerInRange($configuration['width'], 1, 1000); $configuration['height'] = Utility\MathUtility::forceIntegerInRange($configuration['height'], 1, 1000); $originalFileName = $targetFile->getOriginalFile()->getForLocalProcessing(FALSE); // Create a temporary file in typo3temp/ if ($targetFile->getOriginalFile()->getExtension() === 'jpg') { $targetFileExtension = '.jpg'; } else { $targetFileExtension = '.png'; } // Create the thumb filename in typo3temp/preview_....jpg $temporaryFileName = Utility\GeneralUtility::tempnam('preview_') . $targetFileExtension; // Check file extension if ($targetFile->getOriginalFile()->getType() != Resource\File::FILETYPE_IMAGE && !Utility\GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $targetFile->getOriginalFile()->getExtension())) { // Create a default image $this->processor->getTemporaryImageWithText($temporaryFileName, 'Not imagefile!', 'No ext!', $targetFile->getOriginalFile()->getName()); } else { // Create the temporary file if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) { $parameters = '-sample ' . $configuration['width'] . 'x' . $configuration['height'] . ' ' . $this->processor->wrapFileName($originalFileName) . '[0] ' . $this->processor->wrapFileName($temporaryFileName); $cmd = Utility\GeneralUtility::imageMagickCommand('convert', $parameters) . ' 2>&1'; Utility\CommandUtility::exec($cmd); if (!file_exists($temporaryFileName)) { // Create a error gif $this->processor->getTemporaryImageWithText($temporaryFileName, 'No thumb', 'generated!', $targetFile->getOriginalFile()->getName()); } } } return array('filePath' => $temporaryFileName); }
/** * Helper function to check for a working diff tool on a system. * * Tests same file to be sure there is not any error message. * * @return bool TRUE if a diff tool was found, FALSE otherwise */ protected function isDiffToolAvailable() { $filePath = ExtensionManagementUtility::extPath('phpunit') . 'Tests/Unit/Backend/Fixtures/LoadMe.php'; // Makes sure everything is sent to the stdOutput. $executeCommand = $GLOBALS['TYPO3_CONF_VARS']['BE']['diff_path'] . ' 2>&1 ' . $filePath . ' ' . $filePath; $result = array(); CommandUtility::exec($executeCommand, $result); return empty($result); }
/** * @param $filePath * @return array */ public function parseCoreData($filePath) { $imageMagicCommand = \TYPO3\CMS\Core\Utility\GeneralUtility::imageMagickCommand('identify', '-verbose'); $imageMagicCommand .= ' ' . $filePath; \TYPO3\CMS\Core\Utility\CommandUtility::exec($imageMagicCommand, $result); $data = array(); foreach ($result as $resultLine) { $chunks = explode(':', $resultLine); $data[trim($chunks[0])] = trim($chunks[1]); } return array('colorSpace' => $this->parseColorSpace($data), 'dpi' => $this->parseDPI($data)); }
/** * @return string */ public function render() { $path = GeneralUtility::getFileAbsFileName($this->arguments['path']); if (FALSE === file_exists($path)) { return NULL; } $density = $this->arguments['density']; $rotate = $this->arguments['rotate']; $page = intval($this->arguments['page']); $background = $this->arguments['background']; $forceOverwrite = (bool) $this->arguments['forceOverwrite']; $width = $this->arguments['width']; $height = $this->arguments['height']; $minWidth = $this->arguments['minWidth']; $minHeight = $this->arguments['minHeight']; $maxWidth = $this->arguments['maxWidth']; $maxHeight = $this->arguments['maxHeight']; $filename = basename($path); $pageArgument = $page > 0 ? $page - 1 : 0; $colorspace = TRUE === isset($GLOBALS['TYPO3_CONF_VARS']['GFX']['colorspace']) ? $GLOBALS['TYPO3_CONF_VARS']['GFX']['colorspace'] : 'RGB'; $destination = GeneralUtility::getFileAbsFileName('typo3temp/vhs-pdf-' . $filename . '-page' . $page . '.png'); if (FALSE === file_exists($destination) || TRUE === $forceOverwrite) { $arguments = '-colorspace ' . $colorspace; if (0 < intval($density)) { $arguments .= ' -density ' . $density; } if (0 !== intval($rotate)) { $arguments .= ' -rotate ' . $rotate; } $arguments .= ' "' . $path . '"[' . $pageArgument . ']'; if (NULL !== $background) { $arguments .= ' -background "' . $background . '" -flatten'; } $arguments .= ' "' . $destination . '"'; $command = CommandUtility::imageMagickCommand('convert', $arguments); CommandUtility::exec($command); } $image = substr($destination, strlen(PATH_site)); return parent::render($image, $width, $height, $minWidth, $minHeight, $maxWidth, $maxHeight); }
/** * @return string */ public function render() { $src = GeneralUtility::getFileAbsFileName($this->arguments['src']); if (false === file_exists($src)) { return null; } $density = $this->arguments['density']; $rotate = $this->arguments['rotate']; $page = (int) $this->arguments['page']; $background = $this->arguments['background']; $forceOverwrite = (bool) $this->arguments['forceOverwrite']; $filename = basename($src); $pageArgument = $page > 0 ? $page - 1 : 0; if (isset($GLOBALS['TYPO3_CONF_VARS']['GFX']['colorspace'])) { $colorspace = $GLOBALS['TYPO3_CONF_VARS']['GFX']['colorspace']; } else { $colorspace = 'RGB'; } $path = GeneralUtility::getFileAbsFileName('typo3temp/vhs-pdf-' . $filename . '-page' . $page . '.png'); if (false === file_exists($path) || true === $forceOverwrite) { $arguments = '-colorspace ' . $colorspace; if (0 < (int) $density) { $arguments .= ' -density ' . $density; } if (0 !== (int) $rotate) { $arguments .= ' -rotate ' . $rotate; } $arguments .= ' "' . $src . '"[' . $pageArgument . ']'; if (null !== $background) { $arguments .= ' -background "' . $background . '" -flatten'; } $arguments .= ' "' . $path . '"'; $command = CommandUtility::imageMagickCommand('convert', $arguments); CommandUtility::exec($command); } $this->preprocessImage($path); return $this->renderTag(); }
/** * get Content of DOC file * @param string $file * @return string The extracted content of the file */ public function getContent($file) { // create the tempfile which will contain the content $tempFileName = GeneralUtility::tempnam('xls_files-Indexer'); // Delete if exists, just to be safe. @unlink($tempFileName); // generate and execute the pdftotext commandline tool $fileEscaped = CommandUtility::escapeShellArgument($file); $cmd = "{$this->app['xls2csv']} -c ' ' -q 0 -s8859-1 -dutf-8 {$fileEscaped} > {$tempFileName}"; CommandUtility::exec($cmd); // check if the tempFile was successfully created if (@is_file($tempFileName)) { $content = GeneralUtility::getUrl($tempFileName); unlink($tempFileName); } else { return false; } // check if content was found if (strlen($content)) { return $content; } else { return false; } }
/** * Search for GraphicsMagick executables in given paths. * * @param array $searchPaths List of pathes to search for * @return boolean TRUE if graphics magick was found in path */ protected function findGraphicsMagickInPaths(array $searchPaths) { $result = FALSE; foreach ($searchPaths as $path) { if (TYPO3_OS === 'WIN') { $executable = 'gm.exe'; } else { $executable = 'gm'; } if (@is_file($path . $executable)) { $command = escapeshellarg($path . $executable) . ' -version'; $executingResult = FALSE; \TYPO3\CMS\Core\Utility\CommandUtility::exec($command, $executingResult); // First line of exec command should contain string GraphicsMagick $firstResultLine = array_shift($executingResult); if (strpos($firstResultLine, 'GraphicsMagick') !== FALSE) { $this->foundPath = $path; $result = TRUE; break; } } } return $result; }
/** * Extracts the version number for ImageMagick * * @param string $file The program name to execute in order to find out the version number * @param string $path Path for the above program * @return string Version number of the found ImageMagick instance * @todo Define visibility */ public function _checkImageMagick_getVersion($file, $path) { // Temporarily override some settings $im_version = $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5']; $combine_filename = $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_combine_filename']; if ($file == 'gm') { $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5'] = 'gm'; // Work-around, preventing execution of "gm gm" $file = 'identify'; // Work-around - GM doesn't like to be executed without any arguments $parameters = '-version'; } else { $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5'] = 'im5'; // Override the combine_filename setting if ($file == 'combine' || $file == 'composite') { $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_combine_filename'] = $file; } } $cmd = \TYPO3\CMS\Core\Utility\GeneralUtility::imageMagickCommand($file, $parameters, $path); $retVal = FALSE; \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd, $retVal); $string = $retVal[0]; list(, $ver) = explode('Magick', $string); list($ver) = explode(' ', trim($ver)); // Restore the values $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5'] = $im_version; $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_combine_filename'] = $combine_filename; return trim($ver); }
/** * Unzipping file (action=7) * This is permitted only if the user has fullAccess or if the file resides * * @param array $cmds $cmds['data'] is the zip-file. $cmds['target'] is the target directory. If not set we'll default to the same directory as the file is in. * @return bool Returns TRUE on success */ public function func_unzip($cmds) { if (!$this->isInit || $this->dont_use_exec_commands) { return FALSE; } $theFile = $cmds['data']; if (!@is_file($theFile)) { $this->writelog(7, 2, 105, 'The file "%s" did not exist!', array($theFile)); return FALSE; } $fI = GeneralUtility::split_fileref($theFile); if (!isset($cmds['target'])) { $cmds['target'] = $fI['path']; } // Clean up destination directory // !!! Method has been put in the local driver, can be saftely removed $theDest = $this->is_directory($cmds['target']); if (!$theDest) { $this->writelog(7, 2, 104, 'Destination "%s" was not a directory', array($cmds['target'])); return FALSE; } if (!$this->actionPerms['unzipFile']) { $this->writelog(7, 1, 103, 'You are not allowed to unzip files', ''); return FALSE; } if ($fI['fileext'] != 'zip') { $this->writelog(7, 1, 102, 'File extension is not "zip"', ''); return FALSE; } if (!$this->checkIfFullAccess($theDest)) { $this->writelog(7, 1, 101, 'You don\'t have full access to the destination directory "%s"!', array($theDest)); return FALSE; } // !!! Method has been put in the sotrage driver, can be saftely removed if ($this->checkPathAgainstMounts($theFile) && $this->checkPathAgainstMounts($theDest . '/')) { // No way to do this under windows. $cmd = $this->unzipPath . 'unzip -qq ' . escapeshellarg($theFile) . ' -d ' . escapeshellarg($theDest); CommandUtility::exec($cmd); $this->writelog(7, 0, 1, 'Unzipping file "%s" in "%s"', array($theFile, $theDest)); return TRUE; } else { $this->writelog(7, 1, 100, 'File "%s" or destination "%s" was not within your mountpoints!', array($theFile, $theDest)); return FALSE; } }
/** * Create the thumbnail * Will exit before return if all is well. * * @return void * @todo Define visibility */ public function main() { // Clean output buffer to ensure no extraneous output exists ob_clean(); // If file exists, we make a thumbnail of the file. if (is_object($this->image)) { // Check file extension: if ($this->image->getExtension() == 'ttf') { // Make font preview... (will not return) $this->fontGif($this->image); } elseif ($this->image->getType() != File::FILETYPE_IMAGE && !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $this->image->getExtension())) { $this->errorGif('Not imagefile!', 'No ext!', $this->image->getName()); } // ... so we passed the extension test meaning that we are going to make a thumbnail here: // default if (!$this->size) { $this->size = $this->sizeDefault; } // I added extra check, so that the size input option could not be fooled to pass other values. // That means the value is exploded, evaluated to an integer and the imploded to [value]x[value]. // Furthermore you can specify: size=340 and it'll be translated to 340x340. // explodes the input size (and if no "x" is found this will add size again so it is the same for both dimensions) $sizeParts = explode('x', $this->size . 'x' . $this->size); // Cleaning it up, only two parameters now. $sizeParts = array(MathUtility::forceIntegerInRange($sizeParts[0], 1, 1000), MathUtility::forceIntegerInRange($sizeParts[1], 1, 1000)); // Imploding the cleaned size-value back to the internal variable $this->size = implode('x', $sizeParts); // Getting max value $sizeMax = max($sizeParts); // Init $outpath = PATH_site . $this->outdir; // Should be - ? 'png' : 'gif' - , but doesn't work (ImageMagick prob.?) // René: png work for me $thmMode = MathUtility::forceIntegerInRange($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails_png'], 0); $outext = $this->image->getExtension() != 'jpg' || $thmMode & 2 ? $thmMode & 1 ? 'png' : 'gif' : 'jpg'; $outfile = 'tmb_' . substr(md5($this->image->getName() . $this->mtime . $this->size), 0, 10) . '.' . $outext; $this->output = $outpath . $outfile; if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) { // If thumbnail does not exist, we generate it if (!file_exists($this->output)) { $parameters = '-sample ' . $this->size . ' ' . $this->wrapFileName($this->image->getForLocalProcessing(FALSE)) . '[0] ' . $this->wrapFileName($this->output); $cmd = GeneralUtility::imageMagickCommand('convert', $parameters); \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd); if (!file_exists($this->output)) { $this->errorGif('No thumb', 'generated!', $this->image->getName()); } else { GeneralUtility::fixPermissions($this->output); } } // The thumbnail is read and output to the browser if ($fd = @fopen($this->output, 'rb')) { $fileModificationTime = filemtime($this->output); header('Content-Type: image/' . ($outext === 'jpg' ? 'jpeg' : $outext)); header('Last-Modified: ' . date('r', $fileModificationTime)); header('ETag: ' . md5($this->output) . '-' . $fileModificationTime); // Expiration time is chosen arbitrary to 1 month header('Expires: ' . date('r', $fileModificationTime + 30 * 24 * 60 * 60)); fpassthru($fd); fclose($fd); } else { $this->errorGif('Read problem!', '', $this->output); } } else { die; } } else { $this->errorGif('No valid', 'inputfile!', basename($this->image)); } }
/** * This method actually does the processing of files locally * * takes the original file (on remote storages this will be fetched from the remote server) * does the IM magic on the local server by creating a temporary typo3temp/ file * copies the typo3temp/ file to the processingfolder of the target storage * removes the typo3temp/ file * * @param \TYPO3\CMS\Core\Resource\ProcessedFile $processedFile * @param \TYPO3\CMS\Core\Resource\FileInterface $file * @param array $configuration * @return void */ protected function processImagePreview(\TYPO3\CMS\Core\Resource\ProcessedFile $processedFile, \TYPO3\CMS\Core\Resource\FileInterface $file, array $configuration) { // Merge custom configuration with default configuration $configuration = array_merge(array('width' => 64, 'height' => 64), $configuration); $configuration['width'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($configuration['width'], 1, 1000); $configuration['height'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($configuration['height'], 1, 1000); $originalFileName = $file->getForLocalProcessing(FALSE); // Create a temporary file in typo3temp/ if ($file->getExtension() === 'jpg') { $targetFileExtension = '.jpg'; } else { $targetFileExtension = '.png'; } $targetFolder = $this->storage->getProcessingFolder(); $targetFileName = 'preview_' . $processedFile->calculateChecksum() . $targetFileExtension; // Do the actual processing if (!$targetFolder->hasFile($targetFileName)) { // Create the thumb filename in typo3temp/preview_....jpg $temporaryFileName = \TYPO3\CMS\Core\Utility\GeneralUtility::tempnam('preview_') . $targetFileExtension; // Check file extension if ($file->getType() != $file::FILETYPE_IMAGE && !\TYPO3\CMS\Core\Utility\GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $file->getExtension())) { // Create a default image $this->getTemporaryImageWithText($temporaryFileName, 'Not imagefile!', 'No ext!', $file->getName()); } else { // Create the temporary file if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) { $parameters = '-sample ' . $configuration['width'] . 'x' . $configuration['height'] . ' ' . $this->wrapFileName($originalFileName) . '[0] ' . $this->wrapFileName($temporaryFileName); $cmd = \TYPO3\CMS\Core\Utility\GeneralUtility::imageMagickCommand('convert', $parameters); \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd); if (!file_exists($temporaryFileName)) { // Create a error gif $this->getTemporaryImageWithText($temporaryFileName, 'No thumb', 'generated!', $file->getName()); } } } // Temporary image could have been created if (file_exists($temporaryFileName)) { \TYPO3\CMS\Core\Utility\GeneralUtility::fixPermissions($temporaryFileName); // Copy the temporary file to the processedFolder // this is done here, as the driver can do this without worrying // about existing ProcessedFile objects // or permissions in the storage // for "remote" storages this means "uploading" the file to the storage again // for the virtual storage, it is merely a thing of "copying a file from typo3temp/ to typo3temp/_processed_" $this->driver->addFile($temporaryFileName, $targetFolder, $targetFileName, $processedFile); // Remove the temporary file as it's not needed anymore \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($temporaryFileName); $processedFile->setProcessed(TRUE); } } else { // the file already exists, nothing to do locally, but still mark the file as processed and save the data // and update the fields, as they might have not been set if ($processedFile->getProperty('identifier') == '') { $identifier = $targetFolder->getIdentifier() . $targetFileName; $processedFile->updateProperties(array('name' => $targetFileName, 'identifier' => $identifier)); } $processedFile->setProcessed(TRUE); } }
/** * Creates an array with pointers to divisions of document. * * ONLY for PDF files at this point. All other types will have an array with a single element with the value "0" (zero) * coming back. * * @param string $ext File extension * @param string $absFile Absolute filename (must exist and be validated OK before calling function) * @return array Array of pointers to sections that the document should be divided into */ public function fileContentParts($ext, $absFile) { $cParts = array(0); switch ($ext) { case 'pdf': $this->setLocaleForServerFileSystem(); // Getting pdf-info: $cmd = $this->app['pdfinfo'] . ' ' . escapeshellarg($absFile); \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd, $res); $pdfInfo = $this->splitPdfInfo($res); unset($res); if ((int) $pdfInfo['pages']) { $cParts = array(); // Calculate mode if ($this->pdf_mode > 0) { $iter = ceil($pdfInfo['pages'] / $this->pdf_mode); } else { $iter = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(abs($this->pdf_mode), 1, $pdfInfo['pages']); } // Traverse and create intervals. for ($a = 0; $a < $iter; $a++) { $low = floor($a * ($pdfInfo['pages'] / $iter)) + 1; $high = floor(($a + 1) * ($pdfInfo['pages'] / $iter)); $cParts[] = $low . '-' . $high; } } $this->setLocaleForServerFileSystem(TRUE); break; default: } return $cParts; }
/** * @param string $originalFileName * @param string $temporaryFileName * @param array $configuration */ protected function resizeImage($originalFileName, $temporaryFileName, $configuration) { // Create the temporary file if (empty($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'])) { return; } if (file_exists($originalFileName)) { $arguments = CommandUtility::escapeShellArguments(array('width' => $configuration['width'], 'height' => $configuration['height'], 'originalFileName' => $originalFileName, 'temporaryFileName' => $temporaryFileName)); $parameters = '-sample ' . $arguments['width'] . 'x' . $arguments['height'] . ' ' . $arguments['originalFileName'] . '[0] ' . $arguments['temporaryFileName']; $cmd = GeneralUtility::imageMagickCommand('convert', $parameters) . ' 2>&1'; CommandUtility::exec($cmd); } if (!file_exists($temporaryFileName)) { // Create a error image $graphicalFunctions = $this->getGraphicalFunctionsObject(); $graphicalFunctions->getTemporaryImageWithText($temporaryFileName, 'No thumb', 'generated!', basename($originalFileName)); } }
/** * Determine ImageMagick / GraphicsMagick version * * @return string Version */ protected function determineImageMagickVersion() { $command = \TYPO3\CMS\Core\Utility\CommandUtility::imageMagickCommand('identify', '-version'); \TYPO3\CMS\Core\Utility\CommandUtility::exec($command, $result); $string = $result[0]; list(, $version) = explode('Magick', $string); list($version) = explode(' ', trim($version)); return trim($version); }
/** * Test if all necessary Modules in Python are available * * @return void */ public function testPythonModulesAction() { // Extension Configuration $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['fontawesomeplus']); $pathToPythonBin = escapeshellarg($extConf['pathToPython']); $pathToScript = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('fontawesomeplus') . 'Resources/Private/Python/test_environment.py'; CommandUtility::exec("{$pathToPythonBin} {$pathToScript} 2>&1", $pythonReturnArray, $returnCode); $countAnswer = count($pythonReturnArray); if ($countAnswer < 3) { $this->addFlashMessage(LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:error.pythonVersion.body', 'fontawesomeplus'), LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:message.pythonVersion.title', 'fontawesomeplus'), FlashMessage::ERROR); } else { $fontforgeModule = (int) $pythonReturnArray[0]; $jsonModule = (int) $pythonReturnArray[1]; $pythonVersion = $pythonReturnArray[2]; $this->addFlashMessage($pythonVersion . ' ' . $pythonReturnArray[1], LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:message.pythonVersion.title', 'fontawesomeplus'), FlashMessage::OK); if (!empty($fontforgeModule)) { $this->addFlashMessage(LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:ok.pythonModuleFontforge.body', 'fontawesomeplus'), LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:message.pythonModuleFontforge.title', 'fontawesomeplus'), FlashMessage::OK); } else { $this->addFlashMessage(LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:error.pythonModuleFontforge.body', 'fontawesomeplus'), LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:message.pythonModuleFontforge.title', 'fontawesomeplus'), FlashMessage::ERROR); } if (!empty($jsonModule)) { $this->addFlashMessage(LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:ok.pythonModuleJson.body', 'fontawesomeplus'), LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:message.pythonModuleJson.title', 'fontawesomeplus'), FlashMessage::OK); } else { $this->addFlashMessage(LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:error.pythonModuleJson.body', 'fontawesomeplus'), LocalizationUtility::translate('LLL:EXT:fontawesomeplus/Resources/Private/Language/locallang_be_module.xlf:message.pythonModuleJson.title', 'fontawesomeplus'), FlashMessage::ERROR); } } $this->forward('index'); }
/** * Generates a preview for a file * * @param File $file The source file * @param array $configuration Processing configuration * @param string $targetFilePath Output file path * @return array|NULL */ protected function generatePreviewFromFile(File $file, array $configuration, $targetFilePath) { $originalFileName = $file->getForLocalProcessing(FALSE); // Check file extension if ($file->getType() != File::FILETYPE_IMAGE && !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $file->getExtension())) { // Create a default image $this->processor->getTemporaryImageWithText($targetFilePath, 'Not imagefile!', 'No ext!', $file->getName()); } else { // Create the temporary file if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) { $parameters = '-sample ' . $configuration['width'] . 'x' . $configuration['height'] . ' ' . $this->processor->wrapFileName($originalFileName) . '[0] ' . $this->processor->wrapFileName($targetFilePath); $cmd = GeneralUtility::imageMagickCommand('convert', $parameters) . ' 2>&1'; CommandUtility::exec($cmd); if (!file_exists($targetFilePath)) { // Create a error gif $this->processor->getTemporaryImageWithText($targetFilePath, 'No thumb', 'generated!', $file->getName()); } } } return array('filePath' => $targetFilePath); }
/** * Generates a preview for a file * * @param File $file The source file * @param array $configuration Processing configuration * @param string $targetFilePath Output file path * @return array|NULL */ protected function generatePreviewFromFile(File $file, array $configuration, $targetFilePath) { $originalFileName = $file->getForLocalProcessing(FALSE); // Check file extension if ($file->getType() != File::FILETYPE_IMAGE && !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $file->getExtension())) { // Create a default image $graphicalFunctions = GeneralUtility::makeInstance(GraphicalFunctions::class); $graphicalFunctions->getTemporaryImageWithText($targetFilePath, 'Not imagefile!', 'No ext!', $file->getName()); $result = array('filePath' => $targetFilePath); } elseif ($file->getExtension() === 'svg') { /** @var $gifBuilder \TYPO3\CMS\Frontend\Imaging\GifBuilder */ $gifBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Imaging\GifBuilder::class); $gifBuilder->init(); $gifBuilder->absPrefix = PATH_site; $info = $gifBuilder->getImageDimensions($originalFileName); $newInfo = $gifBuilder->getImageScale($info, $configuration['width'], $configuration['height'], array()); $result = array('width' => $newInfo[0], 'height' => $newInfo[1], 'filePath' => ''); } else { // Create the temporary file if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) { $parameters = '-sample ' . $configuration['width'] . 'x' . $configuration['height'] . ' ' . CommandUtility::escapeShellArgument($originalFileName) . '[0] ' . CommandUtility::escapeShellArgument($targetFilePath); $cmd = GeneralUtility::imageMagickCommand('convert', $parameters) . ' 2>&1'; CommandUtility::exec($cmd); if (!file_exists($targetFilePath)) { // Create a error gif $graphicalFunctions = GeneralUtility::makeInstance(GraphicalFunctions::class); $graphicalFunctions->getTemporaryImageWithText($targetFilePath, 'No thumb', 'generated!', $file->getName()); } } $result = array('filePath' => $targetFilePath); } return $result; }
/** * execute commandline tool pdfinfo to extract pdf informations from file * @param string $file * @return array The pdf informations as array */ public function getPdfInfo($file) { if ($this->fileInfo->getIsFile() && $this->fileInfo->getExtension() == 'pdf' && $this->isAppArraySet) { $fileEscaped = CommandUtility::escapeShellArgument($file); $cmd = "{$this->app['pdfinfo']} {$fileEscaped}"; CommandUtility::exec($cmd, $pdfInfoArray); $pdfInfo = $this->splitPdfInfo($pdfInfoArray); return $pdfInfo; } return false; }
/** * @param $zipPathAndFileName string * @param $tempDir string * @return bool * @throws Exception */ protected function unzipArchive($zipPathAndFileName, $tempDir) { // check if the PHP module ZipArchive is loaded and use it if (extension_loaded('zip')) { $zip = new ZipArchive(); if ($zip->open($zipPathAndFileName) === TRUE) { $zip->extractTo($tempDir); $zip->close(); } else { throw new Exception('Error while trying to extract a zip archive using the PHP module ZipArchive', 1294159795); } } // call the unzip executable if set if ($this->unzipExecutable && is_executable($this->unzipExecutable)) { $cmd = $this->unzipExecutable . ' -qq "' . $zipPathAndFileName . '" -d "' . $tempDir . '"'; \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd); } }
/** * Checks if command line version of the OpenSSL is available and can be * executed successfully. * * @return bool * @see \TYPO3\CMS\Rsaauth\Backend\AbstractBackend::isAvailable() */ public function isAvailable() { $result = FALSE; if ($this->opensslPath) { // If path exists, test that command runs and can produce output $test = CommandUtility::exec($this->opensslPath . ' version'); $result = substr($test, 0, 8) === 'OpenSSL '; } return $result; }
/** * Returns filename of the png/gif version of the input file (which can be png or gif). * If input file type does not match the wanted output type a conversion is made and temp-filename returned. * * @param string $theFile Filepath of image file * @param bool $output_png If TRUE, then input file is converted to PNG, otherwise to GIF * @return string|NULL If the new image file exists, its filepath is returned */ public static function readPngGif($theFile, $output_png = false) { if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['processor_enabled'] || !@is_file($theFile)) { return null; } $ext = strtolower(substr($theFile, -4, 4)); if ((string) $ext == '.png' && $output_png || (string) $ext == '.gif' && !$output_png) { return $theFile; } if (!@is_dir(PATH_site . 'typo3temp/assets/images/')) { GeneralUtility::mkdir_deep(PATH_site . 'typo3temp/assets/images/'); } $newFile = PATH_site . 'typo3temp/assets/images/' . md5($theFile . '|' . filemtime($theFile)) . ($output_png ? '.png' : '.gif'); $cmd = GeneralUtility::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['processor_path']); CommandUtility::exec($cmd); if (@is_file($newFile)) { GeneralUtility::fixPermissions($newFile); return $newFile; } return null; }
file_put_contents($packingslip_path, $packingslip_data); $attachments[] = $packingslip_path; } if (count($attachments)) { $combinedPdfFile = $this->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . time() . '_' . uniqid() . '.pdf'; $prog = \TYPO3\CMS\Core\Utility\CommandUtility::exec('which gs'); //hook to let other plugins further manipulate the settings if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/multishop/pi1/classes/class.mslib_befe.php']['overrideGhostScripPath'])) { $params = array('prog' => &$prog); foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/multishop/pi1/classes/class.mslib_befe.php']['overrideGhostScripPath'] as $funcRef) { \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($funcRef, $params, $this); } } if ($prog && is_file($prog)) { $cmd = $prog . ' -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=' . $combinedPdfFile . ' ' . implode(' ', $attachments); \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd); if (file_exists($combinedPdfFile)) { header("Content-type:application/pdf"); readfile($combinedPdfFile); // delete temporary invoice from disk unlink($combinedPdfFile); foreach ($attachments as $attachment) { unlink($attachment); } exit; } } else { echo 'gs binary cannot be found. This is needed for merging multiple PDF files as one file.'; exit; } }
/** * Gets the current GIT revision and branch * * @return void */ protected function getGitRevision() { if (!StringUtility::endsWith(TYPO3_version, '-dev') || \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::isFunctionDisabled('exec')) { return; } // check if git exists CommandUtility::exec('git --version', $_, $returnCode); if ((int) $returnCode !== 0) { // git is not available return; } $revision = trim(CommandUtility::exec('git rev-parse --short HEAD')); $branch = trim(CommandUtility::exec('git rev-parse --abbrev-ref HEAD')); if (!empty($revision) && !empty($branch)) { $this->systemInformation[] = array('title' => htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:toolbarItems.sysinfo.gitrevision')), 'value' => sprintf('%s [%s]', $revision, $branch), 'icon' => $this->iconFactory->getIcon('sysinfo-git', Icon::SIZE_SMALL)->render()); } }
/** * Convert PNG image using pngquant command. * * @param AbstractFile $file */ public function convertPngImage(AbstractFile $file) { try { if (self::EXTENSION_PNG !== $file->getExtension()) { return; } // Ignore processed file which uses original file if ($file instanceof ProcessedFile && $file->usesOriginalFile()) { $this->logger->debug('Do not convert processed file identical with its original file', array('file' => $inputFilePath)); return; } // Set input/output files for pngquant command // Input file is the the specified file we want to quantize // Output file is a temporary file in typo3temp directory $inputFilePath = PATH_site . $file->getPublicUrl(); $outputFilePath = GeneralUtility::tempnam('sg_pngquant_', '.' . self::EXTENSION_PNG); // Build command line $cmd = $this->buildCommand($inputFilePath, $outputFilePath); $result = CommandUtility::exec($cmd, $output, $returnValue); if (0 === $returnValue) { // Replace content if ($file instanceof ProcessedFile) { // For processed file, only convert real processed file (i.e. different than their original file) // Temporary file is automatically removed when updating a processed file $this->logger->debug('Update processed file', array('cmd' => $cmd)); $file->updateWithLocalFile($outputFilePath); } elseif (!$this->confArray['keepOriginal']) { // Convert original files according to extension configuration // After conversion the temporary file is removed $this->logger->debug('Update original file', array('cmd' => $cmd)); $contents = @file_get_contents($outputFilePath); $file->setContents($contents); } } else { $this->logger->error('Convert image', array('cmd' => $cmd, 'result' => $result, 'output' => $output, 'returnValue' => $returnValue)); } } catch (\RuntimeException $e) { $this->logger->error($e->getMessage()); } // Remove temporary file, if exists if (file_exists($outputFilePath)) { $this->removeTemporaryFile($outputFilePath); } }
/** * Returns the contents of a specific file within the ZIP * * @return string Contents * @todo Define visibility */ public function getZIPFileContents($ZIPfile, $filename) { if (file_exists($ZIPfile)) { // Unzipping SXW file, getting filelist: $tempPath = PATH_site . 'typo3temp/tx_tsconfighelp_ziptemp/'; \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir($tempPath); $this->unzip($ZIPfile, $tempPath); $output = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($tempPath . $filename); $cmd = 'rm -r "' . $tempPath . '"'; \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd); return $output; } }
/** * execute commandline tool pdfinfo to extract pdf informations from file * * @param string $file * @return array The pdf informations as array */ public function getPdfInfo($file) { if ($this->fileInfo->getIsFile()) { if ($this->fileInfo->getExtension() == 'pdf' && $this->isAppArraySet) { $cmd = $this->app['pdfinfo'] . ' ' . escapeshellarg($file); \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd, $pdfInfoArray); $pdfInfo = $this->splitPdfInfo($pdfInfoArray); unset($pdfInfoArray); return $pdfInfo; } else { return false; } } else { return false; } }
/** * Returns filename of the png/gif version of the input file (which can be png or gif). * If input file type does not match the wanted output type a conversion is made and temp-filename returned. * * @param string $theFile Filepath of image file * @param boolean $output_png If set, then input file is converted to PNG, otherwise to GIF * @return string If the new image file exists, its filepath is returned */ public static function read_png_gif($theFile, $output_png = FALSE) { if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) { $ext = strtolower(substr($theFile, -4, 4)); if ((string) $ext == '.png' && $output_png || (string) $ext == '.gif' && !$output_png) { return $theFile; } else { $newFile = PATH_site . 'typo3temp/readPG_' . md5($theFile . '|' . filemtime($theFile)) . ($output_png ? '.png' : '.gif'); $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']); \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd); if (@is_file($newFile)) { self::fixPermissions($newFile); return $newFile; } } } }
/** * Executes a ImageMagick "combine" (or composite in newer times) on four filenames - $input, $overlay and $mask as input files and $output as the output filename (written to) * Can be used for many things, mostly scaling and effects. * * @param string $input The relative (to PATH_site) image filepath, bottom file * @param string $overlay The relative (to PATH_site) image filepath, overlay file (top) * @param string $mask The relative (to PATH_site) image filepath, the mask file (grayscale) * @param string $output The relative (to PATH_site) image filepath, output filename (written to) * @param boolean $handleNegation * @return void * @todo Define visibility */ public function combineExec($input, $overlay, $mask, $output, $handleNegation = FALSE) { if (!$this->NO_IMAGE_MAGICK) { $params = '-colorspace GRAY +matte'; if ($handleNegation) { if ($this->maskNegate) { $params .= ' ' . $this->maskNegate; } } $theMask = $this->randomName() . '.' . $this->gifExtension; $this->imageMagickExec($mask, $theMask, $params); $cmd = \TYPO3\CMS\Core\Utility\GeneralUtility::imageMagickCommand('combine', '-compose over +matte ' . $this->wrapFileName($input) . ' ' . $this->wrapFileName($overlay) . ' ' . $this->wrapFileName($theMask) . ' ' . $this->wrapFileName($output)); // +matte = no alpha layer in output $this->IM_commands[] = array($output, $cmd); $ret = \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd); // Change the permissions of the file \TYPO3\CMS\Core\Utility\GeneralUtility::fixPermissions($output); if (is_file($theMask)) { @unlink($theMask); } return $ret; } }