Example #1
0
 /**
  * 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;
 }
Example #2
0
 /**
  * Public Key Encryption Used by Encrypted Website Payments
  *
  * Encrypted Website Payments uses public key encryption, or asymmetric cryptography, which provides security and convenience
  * by allowing senders and receivers of encrypted communication to exchange public keys to unlock each others messages.
  * The fundamental aspects of public key encryption are:
  *
  * Public keys
  * They are created by receivers and are given to senders before they encrypt and send information. Public certificates
  * comprise a public key and identity information, such as the originator of the key and an expiry date.
  * Public certificates can be signed by certificate authorities, who guarantee that public certificates and their
  * public keys belong to the named entities. You and PayPal exchange each others' public certificates.
  *
  * Private keys
  * They are created by receivers are kept to themselves. You create a private key and keep it in your system.
  * PayPal keeps its private key on its system.
  *
  * The encryption process
  * Senders use their private keys and receivers' public keys to encrypt information before sending it.
  * Receivers use their private keys and senders' public keys to decrypt information after receiving it.
  * This encryption process also uses digital signatures in public certificates to verify the sender of the information.
  * You use your private key and PayPal's public key to encrypt your HTML button code.
  * PayPal uses its private key and your public key to decrypt button code after people click your payment buttons.
  *
  * @param array $data
  * @return string
  * @throws \Exception
  */
 public function encrypt(array $data)
 {
     $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['paypal']);
     $openSSL = $extensionConfiguration['opensslPath'];
     $certificationDir = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($this->settings['certification']['dir']);
     if ($this->settings['context']['sandbox']) {
         $certificationDir .= 'Sandbox/';
     }
     $files = array();
     foreach ($this->settings['certification']['file'] as $type => $file) {
         $files[$type] = $certificationDir . $file;
         if (!file_exists($files[$type])) {
             throw new \Exception('Certification "' . $files[$type] . '" does not exist!', 1392135405);
         }
     }
     $data['cert_id'] = $this->settings['seller']['cert_id'];
     $data['bn'] = 'ShoppingCart_WPS';
     $hash = '';
     foreach ($data as $key => $value) {
         if ($value != '') {
             $hash .= $key . '=' . $value . "\n";
         }
     }
     $openssl_cmd = "({$openSSL} smime -sign -signer " . $files['public'] . " -inkey " . $files['private'] . " " . "-outform der -nodetach -binary <<_EOF_\n{$hash}\n_EOF_\n) | " . "{$openSSL} smime -encrypt -des3 -binary -outform pem " . $files['public_paypal'] . "";
     exec($openssl_cmd, $output, $error);
     if (!$error) {
         return implode("\n", $output);
     } else {
         throw new \Exception('Paypal Request Encryption failed!', 1392135967);
     }
 }
Example #3
0
 /**
  * Render method
  *
  * @throws Exception
  * @return string
  */
 public function render()
 {
     $sources = $this->getSourcesFromArgument();
     if (0 === count($sources)) {
         throw new Exception('No audio sources provided.', 1359382189);
     }
     foreach ($sources as $source) {
         if (TRUE === is_string($source)) {
             if (FALSE !== strpos($source, '//')) {
                 $src = $source;
                 $type = substr($source, strrpos($source, '.') + 1);
             } else {
                 $src = substr(GeneralUtility::getFileAbsFileName($source), strlen(PATH_site));
                 $type = pathinfo($src, PATHINFO_EXTENSION);
             }
         } elseif (TRUE === is_array($source)) {
             if (FALSE === isset($source['src'])) {
                 throw new Exception('Missing value for "src" in sources array.', 1359381250);
             }
             $src = $source['src'];
             if (FALSE === isset($source['type'])) {
                 throw new Exception('Missing value for "type" in sources array.', 1359381255);
             }
             $type = $source['type'];
         } else {
             // skip invalid source
             continue;
         }
         if (FALSE === in_array(strtolower($type), $this->validTypes)) {
             throw new Exception('Invalid audio type "' . $type . '".', 1359381260);
         }
         $type = $this->mimeTypesMap[$type];
         $src = $this->preprocessSourceUri($src);
         $this->renderChildTag('source', array('src' => $src, 'type' => $type), FALSE, 'append');
     }
     $tagAttributes = array('width' => $this->arguments['width'], 'height' => $this->arguments['height'], 'preload' => 'auto');
     if (TRUE === (bool) $this->arguments['autoplay']) {
         $tagAttributes['autoplay'] = 'autoplay';
     }
     if (TRUE === (bool) $this->arguments['controls']) {
         $tagAttributes['controls'] = 'controls';
     }
     if (TRUE === (bool) $this->arguments['loop']) {
         $tagAttributes['loop'] = 'loop';
     }
     if (TRUE === (bool) $this->arguments['muted']) {
         $tagAttributes['muted'] = 'muted';
     }
     if (TRUE === in_array($this->validPreloadModes, $this->arguments['preload'])) {
         $tagAttributes['preload'] = 'preload';
     }
     if (NULL !== $this->arguments['poster']) {
         $tagAttributes['poster'] = $this->arguments['poster'];
     }
     $this->tag->addAttributes($tagAttributes);
     if (NULL !== $this->arguments['unsupported']) {
         $this->tag->setContent($this->tag->getContent() . LF . $this->arguments['unsupported']);
     }
     return $this->tag->render();
 }
Example #4
0
 /**
  * @test
  */
 public function canCreateAssetInstanceFromStaticFileFactoryWithRelativeFileAndTranslatesRelativeToAbsolutePath()
 {
     $file = $this->getRelativeAssetFixturePath();
     $asset = Asset::createFromFile($file);
     $this->assertInstanceOf('FluidTYPO3\\Vhs\\Asset', $asset);
     $this->assertEquals(GeneralUtility::getFileAbsFileName($file), $asset->getPath());
 }
 /**
  * Gets a list of all files in a directory recursively and removes
  * old ones.
  *
  * @throws \RuntimeException If folders are not found or files can not be deleted
  * @param string $directory Path to the directory
  * @param int $timestamp Timestamp of the last file modification
  * @return bool TRUE if success
  */
 protected function cleanupRecycledFiles($directory, $timestamp)
 {
     $directory = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($directory);
     $timestamp = (int) $timestamp;
     // Check if given directory exists
     if (!@is_dir($directory)) {
         throw new \RuntimeException('Given directory "' . $directory . '" does not exist', 1301614535);
     }
     // Find all _recycler_ directories
     $directoryContent = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory));
     foreach ($directoryContent as $fileName => $file) {
         // Skip directories and files without recycler directory in absolute path
         $filePath = $file->getPath();
         if (substr($filePath, strrpos($filePath, '/') + 1) !== $this->recyclerDirectory) {
             continue;
         }
         // Remove files from _recycler_ that where moved to this folder for more than 'number of days'
         if ($file->isFile() && $timestamp > $file->getCTime()) {
             if (!@unlink($fileName)) {
                 throw new \RuntimeException('Could not remove file "' . $fileName . '"', 1301614537);
             }
         }
     }
     return true;
 }
 /**
  * Resolve path
  *
  * @param string $resourcePath
  * @return NULL|string
  */
 protected function resolvePath($resourcePath)
 {
     $absoluteFilePath = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($resourcePath);
     $absolutePath = dirname($absoluteFilePath);
     $fileName = basename($absoluteFilePath);
     return \TYPO3\CMS\Core\Utility\PathUtility::getRelativePathTo($absolutePath) . $fileName;
 }
Example #7
0
 /**
  * @param string $file
  * @return bool|string
  * @throws \Exception
  */
 public static function getCompiledFile($file)
 {
     $file = GeneralUtility::getFileAbsFileName($file);
     $pathParts = pathinfo($file);
     if ($pathParts['extension'] === 'less') {
         try {
             $options = array('cache_dir' => GeneralUtility::getFileAbsFileName('typo3temp/mooxcore'));
             $settings = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_mooxcore.']['settings.'] ?: array();
             if ($settings['cssSourceMapping']) {
                 // enable source mapping
                 $optionsForSourceMap = array('sourceMap' => true, 'sourceMapWriteTo' => GeneralUtility::getFileAbsFileName('typo3temp/mooxcore') . '/mooxcore.map', 'sourceMapURL' => '/typo3temp/mooxcore/mooxcore.map', 'sourceMapBasepath' => PATH_site, 'sourceMapRootpath' => '/');
                 $options += $optionsForSourceMap;
                 // disable CSS compression
                 /** @var $pageRenderer \TYPO3\CMS\Core\Page\PageRenderer */
                 $pageRenderer = $GLOBALS['TSFE']->getPageRenderer();
                 $pageRenderer->disableCompressCss();
             }
             if ($settings['overrideLessVariables']) {
                 $variables = self::getVariablesFromConstants();
             } else {
                 $variables = array();
             }
             $files = array();
             $files[$file] = '../../' . str_replace(PATH_site, '', dirname($file)) . '/';
             $compiledFile = \Less_Cache::Get($files, $options, $variables);
             $file = "typo3temp/mooxcore/" . $compiledFile;
             return $file;
         } catch (\Exception $e) {
             throw new \Exception($e->getMessage());
         }
     }
     return false;
 }
    /**
     * Add as content_designer item to the element wizard
     *
     * @param $newElementKey
     * @param $newElementConfig
     * @return void
     */
    public static function addItemToWizard(&$newElementKey, &$newElementConfig)
    {
        // Get the icon if its an file register new icon
        if (strlen($newElementConfig['icon']) > 0) {
            $icon = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($newElementConfig['icon']);
            if (file_exists($icon)) {
                if (self::$iconRegistry == NULL) {
                    self::$iconRegistry = GeneralUtility::makeInstance(\KERN23\ContentDesigner\Helper\IconRegistryHelper::class);
                }
                self::$iconRegistry->registerNewIcon($newElementKey . '-icon', $icon);
                $newElementConfig['icon'] = $newElementKey . '-icon';
            }
        } else {
            $newElementConfig['icon'] = 'contentdesigner-default';
        }
        // Generate the tsconfig
        ExtensionManagementUtility::addPageTsConfig('
            mod.wizards.newContentElement.wizardItems.' . self::$sheetName . '.show := addToList(' . $newElementKey . ')
            mod.wizards.newContentElement.wizardItems.' . self::$sheetName . '.elements {
                ' . $newElementKey . ' {
                    iconIdentifier = ' . $newElementConfig['icon'] . '
                    title          = ' . $newElementConfig['title'] . '
                    description    = ' . $newElementConfig['description'] . '
                    tt_content_defValues.CType = ' . $newElementKey . '
                }
            }
		');
    }
Example #9
0
 /**
  *
  */
 public function parseResource()
 {
     $configuration = $this->getConfiguration();
     if (!ExtensionManagementUtility::isLoaded('phpexcel_library')) {
         throw new \Exception('phpexcel_library is not loaded', 12367812368);
     }
     $filename = GeneralUtility::getFileAbsFileName($this->filepath);
     GeneralUtility::makeInstanceService('phpexcel');
     $objReader = \PHPExcel_IOFactory::createReaderForFile($filename);
     $objReader->setReadDataOnly(true);
     $objPHPExcel = $objReader->load($filename);
     if ($configuration['sheet'] >= 0) {
         $objWorksheet = $objPHPExcel->getSheet($configuration['sheet']);
     } else {
         $objWorksheet = $objPHPExcel->getActiveSheet();
     }
     $highestRow = $objWorksheet->getHighestRow();
     $highestColumn = $objWorksheet->getHighestColumn();
     $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
     for ($row = 1 + $configuration['skipRows']; $row <= $highestRow; ++$row) {
         $rowRecord = [];
         for ($col = 0; $col <= $highestColumnIndex; ++$col) {
             $rowRecord[] = trim($objWorksheet->getCellByColumnAndRow($col, $row)->getValue());
         }
         $this->content[] = $rowRecord;
     }
 }
 /**
  * Get Upload Path
  *
  * @param string $fileName like picture.jpg
  * @param string $path like fileadmin/powermail/uploads/
  * @return string
  */
 public function render($fileName, $path)
 {
     if (file_exists(GeneralUtility::getFileAbsFileName($path . $fileName))) {
         return $path . $fileName;
     }
     return $this->uploadPathFallback . $fileName;
 }
Example #11
0
 /**
  * Rebuild the class cache
  *
  * @param array $parameters
  *
  * @throws \Evoweb\Extender\Exception\FileNotFoundException
  * @throws \TYPO3\CMS\Core\Cache\Exception\InvalidDataException
  * @return void
  */
 public function reBuild(array $parameters = array())
 {
     if (empty($parameters) || !empty($parameters['cacheCmd']) && GeneralUtility::inList('all,system', $parameters['cacheCmd']) && isset($GLOBALS['BE_USER'])) {
         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'] as $extensionKey => $extensionConfiguration) {
             if (!isset($extensionConfiguration['extender']) || !is_array($extensionConfiguration['extender'])) {
                 continue;
             }
             foreach ($extensionConfiguration['extender'] as $entity => $entityConfiguration) {
                 $key = 'Domain/Model/' . $entity;
                 // Get the file to extend, this needs to be loaded as first
                 $path = ExtensionManagementUtility::extPath($extensionKey) . 'Classes/' . $key . '.php';
                 if (!is_file($path)) {
                     throw new \Evoweb\Extender\Exception\FileNotFoundException('given file "' . $path . '" does not exist');
                 }
                 $code = $this->parseSingleFile($path, false);
                 // Get the files from all other extensions that are extending this domain model
                 if (is_array($entityConfiguration)) {
                     foreach ($entityConfiguration as $extendingExtension => $extendingFilepath) {
                         $path = GeneralUtility::getFileAbsFileName($extendingFilepath, false);
                         if (!is_file($path) && !is_numeric($extendingExtension)) {
                             $path = ExtensionManagementUtility::extPath($extendingExtension) . 'Classes/' . $key . '.php';
                         }
                         $code .= $this->parseSingleFile($path);
                     }
                 }
                 // Close the class definition
                 $code = $this->closeClassDefinition($code);
                 // Add the new file to the class cache
                 $cacheEntryIdentifier = GeneralUtility::underscoredToLowerCamelCase($extensionKey) . '_' . str_replace('/', '', $key);
                 $this->cacheInstance->set($cacheEntryIdentifier, $code);
             }
         }
     }
 }
 /**
  * getColorForCaptcha Test
  *
  * @param string $hexColorString
  * @param string $expectedResult
  * @dataProvider getColorForCaptchaReturnIntDataProvider
  * @return void
  * @test
  */
 public function getColorForCaptchaReturnInt($hexColorString, $expectedResult)
 {
     $imageResource = ImageCreateFromPNG(GeneralUtility::getFileAbsFileName('typo3conf/ext/powermail/Resources/Private/Image/captcha_bg.png'));
     $this->generalValidatorMock->_set('configuration', array('captcha.' => array('default.' => array('textColor' => $hexColorString))));
     $result = $this->generalValidatorMock->_call('getColorForCaptcha', $imageResource);
     $this->assertSame($expectedResult, $result);
 }
 /**
  * Initializes the DrawItem
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->view = $this->objectManager->get(StandaloneView::class);
     $this->view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:vantomas/Resources/Private/Templates/DrawItem/SiteLastUpdatedPages.html'));
     $this->pageRepository = $this->objectManager->get(PageRepository::class);
 }
 /**
  * @return string
  * @throws \TYPO3\CMS\Core\Exception
  */
 public function render()
 {
     $out = '';
     $filePath = GeneralUtility::getFileAbsFileName($this->arguments['includeFile'], TRUE);
     if (!$filePath || !file_exists($filePath)) {
         throw new \Exception('Could not get include file for js inclusion');
     }
     try {
         $fileContents = file_get_contents($filePath);
     } catch (\Exception $e) {
         throw new \Exception('Could not read include file for js inclusion');
     }
     $lines = array();
     $pathInfo = pathinfo($filePath);
     $basePath = $this->getRelativeFromAbsolutePath($pathInfo['dirname']);
     foreach (GeneralUtility::trimExplode(chr(10), $fileContents) as $line) {
         $file = "{$basePath}/{$line}";
         if (file_exists($file)) {
             $lines[] = "<script src=\"{$file}\"></script>";
         }
     }
     if (count($lines)) {
         $out = implode("\n", $lines);
     }
     return $out;
 }
Example #15
0
 /**
  * Preprocesses the preview rendering of a content element.
  *
  * @param \TYPO3\CMS\Backend\View\PageLayoutView $parentObject Calling parent object
  * @param boolean $drawItem Whether to draw the item using the default functionalities
  * @param string $headerContent Header content
  * @param string $itemContent Item content
  * @param array $row Record row of tt_content
  * @return void
  */
 public function preProcess(\TYPO3\CMS\Backend\View\PageLayoutView &$parentObject, &$drawItem, &$headerContent, &$itemContent, array &$row)
 {
     // only render special backend preview if it is a mask element
     if (substr($row['CType'], 0, 4) === "mask") {
         $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['mask']);
         $elementKey = substr($row['CType'], 5);
         $templateRootPath = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($extConf["backend"]);
         $templatePathAndFilename = $templateRootPath . $elementKey . '.html';
         if (file_exists($templatePathAndFilename)) {
             // initialize some things we need
             $this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
             $this->utility = $this->objectManager->get("MASK\\Mask\\Utility\\MaskUtility");
             $this->storageRepository = $this->objectManager->get("MASK\\Mask\\Domain\\Repository\\StorageRepository");
             $view = $this->objectManager->get('TYPO3\\CMS\\Fluid\\View\\StandaloneView');
             // Load the backend template
             $view->setTemplatePathAndFilename($templatePathAndFilename);
             // Fetch and assign some useful variables
             $data = $this->getContentObject($row["uid"]);
             $element = $this->storageRepository->loadElement("tt_content", $elementKey);
             $view->assign("row", $row);
             $view->assign("data", $data);
             // Render everything
             $content = $view->render();
             $headerContent = '<strong>' . $element["label"] . '</strong><br>';
             $itemContent .= '<div style="display:block; padding: 10px 0 4px 0px;border-top: 1px solid #CACACA;margin-top: 6px;" class="content_preview_' . $elementKey . '">';
             $itemContent .= $content;
             $itemContent .= '</div>';
             $drawItem = FALSE;
         }
     }
 }
Example #16
0
 public function main()
 {
     $result = $error = $url = NULL;
     $this->view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($this->templatePath . 'Main.html'));
     if ($this->configuration->isValid()) {
         try {
             $this->checkPageId();
             $url = $this->urlService->getFullUrl($this->pageId, $this->pObj->MOD_SETTINGS);
             if (GeneralUtility::_GET('clear')) {
                 $this->pageSpeedRepository->clearByIdentifier($url);
                 $this->view->assign('cacheCleared', TRUE);
             }
             $result = $this->pageSpeedRepository->findByIdentifier($url);
         } catch (\HTTP_Request2_ConnectionException $e) {
             $error = 'error.http_request.connection';
             // todo add log
         } catch (\RuntimeException $e) {
             $error = $e->getMessage();
         }
     } else {
         $error = 'error.invalid.key';
     }
     $this->view->assignMultiple(array('lll' => 'LLL:EXT:page_speed/Resources/Private/Language/locallang.xlf:', 'menu' => $this->modifyFuncMenu(BackendUtility::getFuncMenu($this->pObj->id, 'SET[language]', $this->pObj->MOD_SETTINGS['language'], $this->pObj->MOD_MENU['language']), 'language'), 'configuration' => $this->configuration, 'result' => $result, 'url' => $url, 'error' => $error, 'pageId' => $this->pageId));
     return $this->view->render();
 }
 /**
  * @param null|string $file
  * @return bool
  */
 public function render($file = null)
 {
     if ($file === null) {
         $file = $this->renderChildren();
     }
     return file_exists(\TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($file));
 }
Example #18
0
 /**
  * Extends the getData()-Method of ContentObjectRenderer to process more/other commands
  *
  * @param string                $getDataString Full content of getData-request e.g. "TSFE:id // field:title // field:uid
  * @param array                 $fields        Current field-array
  * @param string                $sectionValue  Currently examined section value of the getData request e.g. "field:title
  * @param string                $returnValue   Current returnValue that was processed so far by getData
  * @param ContentObjectRenderer $parentObject  Parent content object
  *
  * @return string Get data result
  */
 public function getDataExtension($getDataString, array $fields, $sectionValue, $returnValue, ContentObjectRenderer &$parentObject)
 {
     $parts = explode(':', $getDataString);
     if (isset($parts[0]) && isset($parts[1]) && $parts[0] === 'fp') {
         $fileObject = $parentObject->getCurrentFile();
         if (!$fileObject instanceof FileReference) {
             return $returnValue;
         }
         $originalFile = $fileObject->getOriginalFile();
         switch ($parts[1]) {
             case 'x':
             case 'y':
                 $metaData = $originalFile->_getMetaData();
                 return $metaData['focus_point_' . $parts[1]] / 100;
             case 'xp':
             case 'yp':
                 $metaData = $originalFile->_getMetaData();
                 return (double) $metaData['focus_point_' . substr($parts[1], 0, 1)];
             case 'xp_positive':
             case 'yp_positive':
                 $metaData = $originalFile->_getMetaData();
                 return ((double) $metaData['focus_point_' . substr($parts[1], 0, 1)] + 100) / 2;
             case 'w':
             case 'h':
                 $fileName = GeneralUtility::getFileAbsFileName($fileObject->getPublicUrl(true));
                 if (file_exists($fileName)) {
                     $sizes = getimagesize($fileName);
                     return $sizes[$parts[1] == 'w' ? 0 : 1];
                 }
                 break;
         }
     }
     return $returnValue;
 }
Example #19
0
 /**
  * Renders Lorem Ipsum paragraphs. If $lipsum is provided it
  * will be used as source text. If not provided as an argument
  * or as inline argument, $lipsum is fetched from TypoScript settings.
  *
  * @param string $lipsum String of paragraphs file path or EXT:myext/path/to/file
  * @return string
  */
 public function render($lipsum = null)
 {
     if (strlen($lipsum) === 0) {
         $lipsum = $this->lipsum;
     }
     if (strlen($lipsum) < 255 && !preg_match('/[^a-z0-9_\\.\\:\\/]/i', $lipsum) || 0 === strpos($lipsum, 'EXT:')) {
         // argument is most likely a file reference.
         $sourceFile = GeneralUtility::getFileAbsFileName($lipsum);
         if (file_exists($sourceFile)) {
             $lipsum = file_get_contents($sourceFile);
         } else {
             GeneralUtility::sysLog('Vhs LipsumViewHelper was asked to load Lorem Ipsum from a file which does not exist. ' . 'The file was: ' . $sourceFile, 'vhs', GeneralUtility::SYSLOG_SEVERITY_WARNING);
             $lipsum = $this->lipsum;
         }
     }
     $lipsum = preg_replace('/[\\r\\n]{1,}/i', "\n", $lipsum);
     $paragraphs = explode("\n", $lipsum);
     $paragraphs = array_slice($paragraphs, 0, intval($this->arguments['paragraphs']));
     foreach ($paragraphs as $index => $paragraph) {
         $length = $this->arguments['wordsPerParagraph'] + rand(0 - intval($this->arguments['skew']), intval($this->arguments['skew']));
         $words = explode(' ', $paragraph);
         $paragraphs[$index] = implode(' ', array_slice($words, 0, $length));
     }
     $lipsum = implode("\n", $paragraphs);
     if ($this->arguments['html']) {
         $tsParserPath = $this->arguments['parseFuncTSPath'] ? '< ' . $this->arguments['parseFuncTSPath'] : null;
         $lipsum = $this->contentObject->parseFunc($lipsum, [], $tsParserPath);
     }
     return $lipsum;
 }
 /**
  * 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;
 }
Example #21
0
 /**
  * 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;
 }
Example #22
0
 /**
  * Get the cropped image by File Object
  *
  * @param FileInterface $file
  * @param string        $ratio
  *
  * @return string The new filename
  */
 public function getCroppedImageSrcByFile(FileInterface $file, $ratio)
 {
     $absoluteImageName = GeneralUtility::getFileAbsFileName($file->getPublicUrl());
     $focusPointX = MathUtility::forceIntegerInRange((int) $file->getProperty('focus_point_x'), -100, 100, 0);
     $focusPointY = MathUtility::forceIntegerInRange((int) $file->getProperty('focus_point_y'), -100, 100, 0);
     $tempImageFolder = 'typo3temp/focuscrop/';
     $tempImageName = $tempImageFolder . $file->getSha1() . '-' . str_replace(':', '-', $ratio) . '-' . $focusPointX . '-' . $focusPointY . '.' . $file->getExtension();
     $absoluteTempImageName = GeneralUtility::getFileAbsFileName($tempImageName);
     if (is_file($absoluteTempImageName)) {
         return $tempImageName;
     }
     $absoluteTempImageFolder = GeneralUtility::getFileAbsFileName($tempImageFolder);
     if (!is_dir($absoluteTempImageFolder)) {
         GeneralUtility::mkdir_deep($absoluteTempImageFolder);
     }
     $this->graphicalFunctions = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Imaging\\GraphicalFunctions');
     $imageSizeInformation = getimagesize($absoluteImageName);
     $width = $imageSizeInformation[0];
     $height = $imageSizeInformation[1];
     // dimensions
     /** @var \HDNET\Focuspoint\Service\DimensionService $service */
     $dimensionService = GeneralUtility::makeInstance('HDNET\\Focuspoint\\Service\\DimensionService');
     list($focusWidth, $focusHeight) = $dimensionService->getFocusWidthAndHeight($width, $height, $ratio);
     $cropMode = $dimensionService->getCropMode($width, $height, $ratio);
     list($sourceX, $sourceY) = $dimensionService->calculateSourcePosition($cropMode, $width, $height, $focusWidth, $focusHeight, $focusPointX, $focusPointY);
     // generate image
     $sourceImage = $this->graphicalFunctions->imageCreateFromFile($absoluteImageName);
     $destinationImage = imagecreatetruecolor($focusWidth, $focusHeight);
     $this->graphicalFunctions->imagecopyresized($destinationImage, $sourceImage, 0, 0, $sourceX, $sourceY, $focusWidth, $focusHeight, $focusWidth, $focusHeight);
     $this->graphicalFunctions->ImageWrite($destinationImage, $absoluteTempImageName, $GLOBALS['TYPO3_CONF_VARS']['GFX']['jpg_quality']);
     return $tempImageName;
 }
 /**
  * @throws Exception
  * @return array
  */
 public function getInfo()
 {
     $src = $this->arguments['src'];
     $treatIdAsUid = (bool) $this->arguments['treatIdAsUid'];
     $treatIdAsReference = (bool) $this->arguments['treatIdAsReference'];
     if (NULL === $src) {
         $src = $this->renderChildren();
         if (NULL === $src) {
             return array();
         }
     }
     if (TRUE === $treatIdAsUid || TRUE === $treatIdAsReference) {
         $id = (int) $src;
         $info = array();
         if (TRUE === $treatIdAsUid) {
             $info = $this->getInfoByUid($id);
         } elseif (TRUE === $treatIdAsReference) {
             $info = $this->getInfoByReference($id);
         }
     } else {
         $file = GeneralUtility::getFileAbsFileName($src);
         if (FALSE === file_exists($file) || TRUE === is_dir($file)) {
             throw new Exception('Cannot determine info for "' . $file . '". File does not exist or is a directory.', 1357066532);
         }
         $imageSize = getimagesize($file);
         $info = array('width' => $imageSize[0], 'height' => $imageSize[1], 'type' => $imageSize['mime']);
     }
     return $info;
 }
 /**
  * Import command
  *
  * @param string $icsCalendarUri
  * @param int    $pid
  */
 public function importCommand($icsCalendarUri = null, $pid = null)
 {
     if ($icsCalendarUri === null || !filter_var($icsCalendarUri, FILTER_VALIDATE_URL)) {
         $this->enqueueMessage('You have to enter a valid URL to the iCalendar ICS', 'Error', FlashMessage::ERROR);
         return;
     }
     if (!MathUtility::canBeInterpretedAsInteger($pid)) {
         $this->enqueueMessage('You have to enter a valid PID for the new created elements', 'Error', FlashMessage::ERROR);
         return;
     }
     // fetch external URI and write to file
     $this->enqueueMessage('Start to checkout the calendar: ' . $icsCalendarUri, 'Calendar', FlashMessage::INFO);
     $relativeIcalFile = 'typo3temp/ical.' . GeneralUtility::shortMD5($icsCalendarUri) . '.ical';
     $absoluteIcalFile = GeneralUtility::getFileAbsFileName($relativeIcalFile);
     $content = GeneralUtility::getUrl($icsCalendarUri);
     GeneralUtility::writeFile($absoluteIcalFile, $content);
     // get Events from file
     $icalEvents = $this->getIcalEvents($absoluteIcalFile);
     $this->enqueueMessage('Found ' . sizeof($icalEvents) . ' events in the given calendar', 'Items', FlashMessage::INFO);
     $events = $this->prepareEvents($icalEvents);
     $this->enqueueMessage('Found ' . sizeof($events) . ' events in ' . $icsCalendarUri, 'Items', FlashMessage::INFO);
     /** @var Dispatcher $signalSlotDispatcher */
     $signalSlotDispatcher = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
     $this->enqueueMessage('Send the ' . __CLASS__ . '::importCommand signal for each event.', 'Signal', FlashMessage::INFO);
     foreach ($events as $event) {
         $arguments = ['event' => $event, 'commandController' => $this, 'pid' => $pid, 'handled' => false];
         $signalSlotDispatcher->dispatch(__CLASS__, 'importCommand', $arguments);
     }
 }
Example #25
0
    /**
     * Check and define cli parameters.
     * First argument is a key that points to the script configuration.
     * If it is not set or not valid, the script exits with an error message.
     *
     * @return void
     */
    public static function initializeCliKeyOrDie()
    {
        if (!isset($_SERVER['argv'][1]) || !is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys'][$_SERVER['argv'][1]])) {
            if (!isset($_SERVER['argv'][1])) {
                $message = 'This script must have a \'cliKey\' as first argument.';
            } else {
                $message = 'The supplied \'cliKey\' is not valid.';
            }
            $message .= ' Valid keys are:

';
            $cliKeys = array_keys($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys']);
            asort($cliKeys);
            foreach ($cliKeys as $key => $value) {
                $message .= '  ' . $value . LF;
            }
            fwrite(STDERR, $message . LF);
            die(1);
        }
        define('TYPO3_cliKey', $_SERVER['argv'][1]);
        define('TYPO3_cliInclude', \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys'][TYPO3_cliKey][0]));
        $GLOBALS['MCONF']['name'] = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys'][TYPO3_cliKey][1];
        // This is a compatibility layer: Some cli scripts rely on this, like ext:phpunit cli
        $GLOBALS['temp_cliScriptPath'] = array_shift($_SERVER['argv']);
        $GLOBALS['temp_cliKey'] = array_shift($_SERVER['argv']);
        array_unshift($_SERVER['argv'], $GLOBALS['temp_cliScriptPath']);
    }
 /**
  * Setup
  */
 public function setup()
 {
     $tempFiles = (array) glob(GeneralUtility::getFileAbsFileName('typo3temp/flux-preview-*.tmp'));
     foreach ($tempFiles as $tempFile) {
         unlink($tempFile);
     }
 }
 /**
  * Import command
  *
  * @param string $icsCalendarUri
  * @param int    $pid
  */
 public function importCommand($icsCalendarUri = NULL, $pid = NULL)
 {
     if ($icsCalendarUri === NULL || !filter_var($icsCalendarUri, FILTER_VALIDATE_URL)) {
         $this->enqueueMessage('You have to enter a valid URL to the iCalendar ICS', 'Error', FlashMessage::ERROR);
     }
     if (!MathUtility::canBeInterpretedAsInteger($pid)) {
         $this->enqueueMessage('You have to enter a valid PID for the new created elements', 'Error', FlashMessage::ERROR);
     }
     // fetch external URI and write to file
     $this->enqueueMessage('Start to checkout the calendar: ' . $icsCalendarUri, 'Calendar', FlashMessage::INFO);
     $relativeIcalFile = 'typo3temp/ical.' . GeneralUtility::shortMD5($icsCalendarUri) . '.ical';
     $absoluteIcalFile = GeneralUtility::getFileAbsFileName($relativeIcalFile);
     $content = GeneralUtility::getUrl($icsCalendarUri);
     GeneralUtility::writeFile($absoluteIcalFile, $content);
     // get Events from file
     $icalEvents = $this->getIcalEvents($absoluteIcalFile);
     $this->enqueueMessage('Found ' . sizeof($icalEvents) . ' events in the given calendar', 'Items', FlashMessage::INFO);
     $events = $this->prepareEvents($icalEvents);
     $this->enqueueMessage('This is just a first draft. There are same missing fields. Will be part of the next release', 'Items', FlashMessage::ERROR);
     return;
     foreach ($events as $event) {
         $eventObject = $this->eventRepository->findOneByImportId($event['uid']);
         if ($eventObject instanceof Event) {
             // update
             $eventObject->setTitle($event['title']);
             $eventObject->setDescription($this->nl2br($event['description']));
             $this->eventRepository->update($eventObject);
             $this->enqueueMessage('Update Event Meta data: ' . $eventObject->getTitle(), 'Update');
         } else {
             // create
             $eventObject = new Event();
             $eventObject->setPid($pid);
             $eventObject->setImportId($event['uid']);
             $eventObject->setTitle($event['title']);
             $eventObject->setDescription($this->nl2br($event['description']));
             $configuration = new Configuration();
             $configuration->setType(Configuration::TYPE_TIME);
             $configuration->setFrequency(Configuration::FREQUENCY_NONE);
             /** @var \DateTime $startDate */
             $startDate = clone $event['start'];
             $startDate->setTime(0, 0, 0);
             $configuration->setStartDate($startDate);
             /** @var \DateTime $endDate */
             $endDate = clone $event['end'];
             $endDate->setTime(0, 0, 0);
             $configuration->setEndDate($endDate);
             $startTime = $this->dateTimeToDaySeconds($event['start']);
             if ($startTime > 0) {
                 $configuration->setStartTime($startTime);
                 $configuration->setEndTime($this->dateTimeToDaySeconds($event['end']));
                 $configuration->setAllDay(FALSE);
             } else {
                 $configuration->setAllDay(TRUE);
             }
             $eventObject->addCalendarize($configuration);
             $this->eventRepository->add($eventObject);
             $this->enqueueMessage('Add Event: ' . $eventObject->getTitle(), 'Add');
         }
     }
 }
Example #28
0
 /**
  * Gets the location of the words list based on configured language
  *
  * @param string $defaultWordsList: location of the default words list
  * @return string the location of the words list to be used
  */
 public static function getWordsListLocation($defaultWordsList = '')
 {
     self::setLanguageKeys();
     $initialWordsList = $defaultWordsList;
     if (!trim($initialWordsList)) {
         $initialWordsList = 'EXT:' . self::$extensionKey . '/Resources/Private/Captcha/Words/default_freecap_words';
     }
     $path = dirname(GeneralUtility::getFileAbsFileName($initialWordsList)) . '/';
     $wordsListLocation = $path . self::$languageKey . '_freecap_words';
     if (!is_file($wordsListLocation)) {
         foreach (self::$alternativeLanguageKeys as $language) {
             $wordsListLocation = $path . $language . '_freecap_words';
             if (is_file($wordsListLocation)) {
                 break;
             }
         }
     }
     if (!is_file($wordsListLocation)) {
         $wordsListLocation = $path . 'default_freecap_words';
         if (!is_file($wordsListLocation)) {
             $wordsListLocation = '';
         }
     }
     return $wordsListLocation;
 }
 /**
  * Return JS configuration of the htmlArea plugins registered by the extension
  *
  * @return string JS configuration for registered plugins
  */
 public function buildJavascriptConfiguration()
 {
     $schema = array('types' => array(), 'properties' => array());
     // Parse configured schemas
     if (is_array($this->configuration['thisConfig']['schema.']) && is_array($this->configuration['thisConfig']['schema.']['sources.'])) {
         foreach ($this->configuration['thisConfig']['schema.']['sources.'] as $source) {
             $fileName = trim($source);
             $absolutePath = GeneralUtility::getFileAbsFileName($fileName);
             // Fallback to default schema file if configured file does not exists or is of zero size
             if (!$fileName || !file_exists($absolutePath) || !filesize($absolutePath)) {
                 $fileName = 'EXT:' . $this->extensionKey . '/Resources/Public/Rdf/MicrodataSchema/SchemaOrgAll.rdf';
             }
             $fileName = $this->getFullFileName($fileName);
             $rdf = file_get_contents($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
     $languageService = $this->getLanguageService();
     $noSchema = $languageService->sL('LLL:EXT:rtehtmlarea/Resources/Private/Language/Plugins/MicrodataSchema/locallang.xlf:No type');
     $noProperty = $languageService->sL('LLL:EXT:rtehtmlarea/Resources/Private/Language/Plugins/MicrodataSchema/locallang.xlf:No property');
     array_unshift($schema['types'], array('name' => 'none', 'label' => $noSchema));
     array_unshift($schema['properties'], array('name' => 'none', 'label' => $noProperty));
     // Store json encoded array in temporary file
     return 'RTEarea[editornumber].schemaUrl = "' . $this->writeTemporaryFile('schema_' . $this->configuration['language'], 'js', json_encode($schema)) . '";';
 }
 /**
  * @throws Exception
  * @return array
  */
 public function getInfo()
 {
     $src = $this->arguments['src'];
     $treatIdAsUid = (bool) $this->arguments['treatIdAsUid'];
     $treatIdAsReference = (bool) $this->arguments['treatIdAsReference'];
     if (null === $src) {
         $src = $this->renderChildren();
         if (null === $src) {
             return [];
         }
     }
     if (is_object($src) && $src instanceof FileReference) {
         $src = $src->getUid();
         $treatIdAsUid = true;
         $treatIdAsReference = true;
     }
     if (true === $treatIdAsUid || true === $treatIdAsReference) {
         $id = (int) $src;
         $info = [];
         if (true === $treatIdAsUid) {
             $info = $this->getInfoByUid($id);
         } elseif (true === $treatIdAsReference) {
             $info = $this->getInfoByReference($id);
         }
     } else {
         $file = GeneralUtility::getFileAbsFileName($src);
         if (false === file_exists($file) || true === is_dir($file)) {
             throw new Exception('Cannot determine info for "' . $file . '". File does not exist or is a directory.', 1357066532);
         }
         $imageSize = getimagesize($file);
         $info = ['width' => $imageSize[0], 'height' => $imageSize[1], 'type' => $imageSize['mime']];
     }
     return $info;
 }