Ejemplo n.º 1
1
 /**
  * Render the captcha image html
  *
  * @param string suffix to be appended to the extenstion key when forming css class names
  * @return string The html used to render the captcha image
  */
 public function render($suffix = '')
 {
     $value = '';
     // Include the required JavaScript
     $GLOBALS['TSFE']->additionalHeaderData[$this->extensionKey . '_freeCap'] = '<script type="text/javascript" src="' . GeneralUtility::createVersionNumberedFilename(ExtensionManagementUtility::siteRelPath($this->extensionKey) . 'Resources/Public/JavaScript/freeCap.js') . '"></script>';
     // Disable caching
     $GLOBALS['TSFE']->no_cache = 1;
     // Get the plugin configuration
     $settings = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS, $this->extensionName);
     // Get the translation view helper
     $objectManager = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
     $translator = $objectManager->get('SJBR\\SrFreecap\\ViewHelpers\\TranslateViewHelper');
     $translator->injectConfigurationManager($this->configurationManager);
     // Generate the image url
     $fakeId = GeneralUtility::shortMD5(uniqid(rand()), 5);
     $siteURL = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
     $L = GeneralUtility::_GP('L');
     $urlParams = array('eID' => 'sr_freecap_EidDispatcher', 'id' => $GLOBALS['TSFE']->id, 'vendorName' => 'SJBR', 'extensionName' => 'SrFreecap', 'pluginName' => 'ImageGenerator', 'controllerName' => 'ImageGenerator', 'actionName' => 'show', 'formatName' => 'png', 'L' => $GLOBALS['TSFE']->sys_language_uid);
     if ($GLOBALS['TSFE']->MP) {
         $urlParams['MP'] = $GLOBALS['TSFE']->MP;
     }
     $urlParams['set'] = $fakeId;
     $imageUrl = $siteURL . 'index.php?' . ltrim(GeneralUtility::implodeArrayForUrl('', $urlParams), '&');
     // Generate the html text
     $value = '<img' . $this->getClassAttribute('image', $suffix) . ' id="tx_srfreecap_captcha_image_' . $fakeId . '"' . ' src="' . htmlspecialchars($imageUrl) . '"' . ' alt="' . $translator->render('altText') . ' "/>' . '<span' . $this->getClassAttribute('cant-read', $suffix) . '>' . $translator->render('cant_read1') . ' <a href="#" onclick="this.blur();' . $this->extensionName . '.newImage(\'' . $fakeId . '\', \'' . $translator->render('noImageMessage') . '\');return false;">' . $translator->render('click_here') . '</a>' . $translator->render('cant_read2') . '</span>';
     return $value;
 }
Ejemplo n.º 2
0
 /**
  * Create Hash from String and TYPO3 Encryption Key
  *
  * @param string $string Any String
  * @return string Hashed String
  */
 protected static function createHash($string)
 {
     if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) {
         $string .= $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
     }
     return GeneralUtility::shortMD5($string);
 }
 /**
  * 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');
         }
     }
 }
 /**
  * Call back function for page tree traversal!
  *
  * @param string $tableName Table name
  * @param int $uid UID of record in processing
  * @param int $echoLevel Echo level  (see calling function
  * @param string $versionSwapmode Version swap mode on that level (see calling function
  * @param int $rootIsVersion Is root version (see calling function
  * @return void
  */
 public function main_parseTreeCallBack($tableName, $uid, $echoLevel, $versionSwapmode, $rootIsVersion)
 {
     foreach ($GLOBALS['TCA'][$tableName]['columns'] as $colName => $config) {
         if ($config['config']['type'] == 'flex') {
             if ($echoLevel > 2) {
                 echo LF . '			[cleanflexform:] Field "' . $colName . '" in ' . $tableName . ':' . $uid . ' was a flexform and...';
             }
             $recRow = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordRaw($tableName, 'uid=' . (int) $uid);
             $flexObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
             if ($recRow[$colName]) {
                 // Clean XML:
                 $newXML = $flexObj->cleanFlexFormXML($tableName, $colName, $recRow);
                 if (md5($recRow[$colName]) != md5($newXML)) {
                     if ($echoLevel > 2) {
                         echo ' was DIRTY, needs cleanup!';
                     }
                     $this->cleanFlexForm_dirtyFields[\TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($tableName . ':' . $uid . ':' . $colName)] = $tableName . ':' . $uid . ':' . $colName;
                 } else {
                     if ($echoLevel > 2) {
                         echo ' was CLEAN';
                     }
                 }
             } elseif ($echoLevel > 2) {
                 echo ' was EMPTY';
             }
         }
     }
 }
Ejemplo n.º 5
0
 /**
  * Creates a "real" directory for doing tests. This is neccessary because some file system properties (e.g. permissions)
  * cannot be reflected by vfsStream, and some methods (like touch()) don't work there either.
  *
  * Created directories are automatically destroyed by the tearDownAfterClass() method.
  *
  * @return string
  */
 protected function createRealTestdir()
 {
     $basedir = PATH_site . 'typo3temp/fal-test-' . \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5(microtime(TRUE));
     mkdir($basedir);
     self::$testDirs[] = $basedir;
     return $basedir;
 }
 /**
  * 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);
     }
 }
Ejemplo n.º 7
0
 /**
  * Writes the GD font file
  *
  * @param \SJBR\SrFreecap\Domain\Model\Font the object to be stored
  * @return \SJBR\SrFreecap\Domain\Repository\FontRepository $this
  */
 public function writeFontFile(\SJBR\SrFreecap\Domain\Model\Font $font)
 {
     $relativeFileName = 'uploads/' . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getCN($this->extensionKey) . '/' . $font->getGdFontFilePrefix() . '_' . \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($font->getGdFontData()) . '.gdf';
     if (\TYPO3\CMS\Core\Utility\GeneralUtility::writeFile(PATH_site . $relativeFileName, $font->getGdFontData())) {
         $font->setGdFontFileName($relativeFileName);
     }
     return $this;
 }
Ejemplo n.º 8
0
 /**
  * @test
  */
 public function extractHyperLinksReturnsCorrectFileUsingT3Vars()
 {
     $this->temporaryFileName = tempnam(sys_get_temp_dir(), 't3unit-');
     $html = 'test <a href="testfile">test</a> test';
     $GLOBALS['T3_VAR']['ext']['indexed_search']['indexLocalFiles'] = array(\TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5('testfile') => $this->temporaryFileName);
     $result = $this->fixture->extractHyperLinks($html);
     $this->assertEquals(1, count($result));
     $this->assertEquals($this->temporaryFileName, $result[0]['localPath']);
 }
 /**
  * @param $str
  * @param $table
  * @param string $uid
  * @return string
  */
 private function wrapClickMenuOnIcon($str, $table, $uid = '')
 {
     $listFr = 1;
     $addParams = '';
     $enDisItems = '';
     $returnOnClick = FALSE;
     $backPath = rawurlencode($GLOBALS['BACK_PATH']) . '|' . \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($GLOBALS['BACK_PATH'] . '|' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']);
     $onClick = 'showClickmenu("' . $table . '","' . $uid . '","' . $listFr . '","' . str_replace('+', '%2B', $enDisItems) . '","' . str_replace('&', '&amp;', addcslashes($backPath, '"')) . '","' . str_replace('&', '&amp;', addcslashes($addParams, '"')) . '");return false;';
     return $returnOnClick ? $onClick : '<a href="#" onclick="' . htmlspecialchars($onClick) . '" oncontextmenu="' . htmlspecialchars($onClick) . '">' . $str . '</a>';
 }
Ejemplo n.º 10
0
 /**
  * @test
  */
 public function extractHyperLinksReturnsCorrectFileUsingT3Vars()
 {
     $temporaryFileName = tempnam(PATH_site . 'typo3temp/var/tests/', 't3unit-');
     $this->testFilesToDelete[] = $temporaryFileName;
     $html = 'test <a href="testfile">test</a> test';
     $GLOBALS['T3_VAR']['ext']['indexed_search']['indexLocalFiles'] = array(\TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5('testfile') => $temporaryFileName);
     $result = $this->subject->extractHyperLinks($html);
     $this->assertEquals(1, count($result));
     $this->assertEquals($temporaryFileName, $result[0]['localPath']);
 }
Ejemplo n.º 11
0
 /**
  * Find lost files in uploads/ folder
  * FIX METHOD: Simply delete the file...
  *
  * @todo Add parameter to exclude filepath
  * @todo Add parameter to list more file names/patterns to ignore
  * @todo Add parameter to include RTEmagic images
  *
  * @return array
  */
 public function main()
 {
     // Initialize result array:
     $resultArray = array('message' => $this->cli_help['name'] . LF . LF . $this->cli_help['description'], 'headers' => array('managedFiles' => array('Files related to TYPO3 records and managed by TCEmain', 'These files you definitely want to keep.', 0), 'ignoredFiles' => array('Ignored files (index.html, .htaccess etc.)', 'These files are allowed in uploads/ folder', 0), 'RTEmagicFiles' => array('RTE magic images - those found (and ignored)', 'These files are also allowed in some uploads/ folders as RTEmagic images.', 0), 'lostFiles' => array('Lost files - those you can delete', 'You can delete these files!', 3), 'warnings' => array('Warnings picked up', '', 2)), 'managedFiles' => array(), 'ignoredFiles' => array(), 'RTEmagicFiles' => array(), 'lostFiles' => array(), 'warnings' => array());
     // Get all files:
     $fileArr = array();
     $fileArr = \TYPO3\CMS\Core\Utility\GeneralUtility::getAllFilesAndFoldersInPath($fileArr, PATH_site . 'uploads/');
     $fileArr = \TYPO3\CMS\Core\Utility\GeneralUtility::removePrefixPathFromList($fileArr, PATH_site);
     $excludePaths = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this->cli_argValue('--excludePath', 0), true);
     // Traverse files and for each, look up if its found in the reference index.
     foreach ($fileArr as $key => $value) {
         $include = true;
         foreach ($excludePaths as $exclPath) {
             if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($value, $exclPath)) {
                 $include = false;
             }
         }
         $shortKey = \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($value);
         if ($include) {
             // First, allow "index.html", ".htaccess" files since they are often used for good reasons
             if (substr($value, -11) == '/index.html' || substr($value, -10) == '/.htaccess') {
                 unset($fileArr[$key]);
                 $resultArray['ignoredFiles'][$shortKey] = $value;
             } else {
                 // Looking for a reference from a field which is NOT a soft reference (thus, only fields with a proper TCA/Flexform configuration)
                 $recs = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_refindex', 'ref_table=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('_FILE', 'sys_refindex') . ' AND ref_string=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, 'sys_refindex') . ' AND softref_key=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('', 'sys_refindex'), '', 'sorting DESC');
                 // If found, unset entry:
                 if (count($recs)) {
                     unset($fileArr[$key]);
                     $resultArray['managedFiles'][$shortKey] = $value;
                     if (count($recs) > 1) {
                         $resultArray['warnings'][$shortKey] = 'Warning: File "' . $value . '" had ' . count($recs) . ' references from group-fields, should have only one!';
                     }
                 } else {
                     // When here it means the file was not found. So we test if it has a RTEmagic-image name and if so, we allow it:
                     if (preg_match('/^RTEmagic[P|C]_/', basename($value))) {
                         unset($fileArr[$key]);
                         $resultArray['RTEmagicFiles'][$shortKey] = $value;
                     } else {
                         // We conclude that the file is lost...:
                         unset($fileArr[$key]);
                         $resultArray['lostFiles'][$shortKey] = $value;
                     }
                 }
             }
         }
     }
     asort($resultArray['ignoredFiles']);
     asort($resultArray['managedFiles']);
     asort($resultArray['RTEmagicFiles']);
     asort($resultArray['lostFiles']);
     asort($resultArray['warnings']);
     // $fileArr variable should now be empty with all contents transferred to the result array keys.
     return $resultArray;
 }
Ejemplo n.º 12
0
 /**
  * Checks that using t3vars returns correct file
  *
  * @return void
  */
 public function testLocalPathWithT3Vars()
 {
     $this->temporaryFileName = tempnam(sys_get_temp_dir(), 't3unit-');
     $html = 'test <a href="testfile">test</a> test';
     $savedValue = $GLOBALS['T3_VAR']['ext']['indexed_search']['indexLocalFiles'];
     $GLOBALS['T3_VAR']['ext']['indexed_search']['indexLocalFiles'] = array(\TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5('testfile') => $this->temporaryFileName);
     $result = $this->indexer->extractHyperLinks($html);
     $GLOBALS['T3_VAR']['ext']['indexed_search']['indexLocalFiles'] = $savedValue;
     $this->assertEquals(1, count($result), 'Wrong number of parsed links');
     $this->assertEquals($result[0]['localPath'], $this->temporaryFileName, 'Local path is incorrect');
 }
Ejemplo n.º 13
0
 /**
  * Get the ICS events in an array
  *
  * @param string $paramUrl
  *
  * @return array
  */
 function toArray($paramUrl)
 {
     $tempFileName = GeneralUtility::getFileAbsFileName('typo3temp/calendarize_temp_' . GeneralUtility::shortMD5($paramUrl));
     if (filemtime($tempFileName) < time() - 60 * 60) {
         $icsFile = GeneralUtility::getUrl($paramUrl);
         GeneralUtility::writeFile($tempFileName, $icsFile);
     }
     $backend = new ICalParser();
     if ($backend->parseFromFile($tempFileName)) {
         return $backend->getEvents();
     }
     return array();
 }
Ejemplo n.º 14
0
 /**
  * Get the ICS events in an array
  *
  * @param string $paramUrl
  *
  * @return array
  */
 function toArray($paramUrl)
 {
     $tempFileName = $this->getCheckedCacheFolder() . GeneralUtility::shortMD5($paramUrl);
     if (!is_file($tempFileName) || filemtime($tempFileName) < time() - DateTimeUtility::SECONDS_HOUR) {
         $icsFile = GeneralUtility::getUrl($paramUrl);
         GeneralUtility::writeFile($tempFileName, $icsFile);
     }
     $backend = new ICalParser();
     if ($backend->parseFromFile($tempFileName)) {
         return $backend->getEvents();
     }
     return [];
 }
 /**
  * Entry method
  *
  * @return array As defined in initializeResultArray() of AbstractNode
  */
 public function render()
 {
     $languageService = $this->getLanguageService();
     $table = $this->data['tableName'];
     $row = $this->data['databaseRow'];
     $fieldName = $this->data['fieldName'];
     // field name of the flex form field in DB
     $parameterArray = $this->data['parameterArray'];
     $flexFormDataStructureArray = $this->data['flexFormDataStructureArray'];
     $flexFormCurrentLanguage = $this->data['flexFormCurrentLanguage'];
     $flexFormRowData = $this->data['flexFormRowData'];
     $resultArray = $this->initializeResultArray();
     $resultArray['requireJsModules'][] = 'TYPO3/CMS/Backend/Tabs';
     $domIdPrefix = 'DTM-' . GeneralUtility::shortMD5($this->data['parameterArray']['itemFormElName'] . $flexFormCurrentLanguage);
     $tabCounter = 0;
     $tabElements = array();
     foreach ($flexFormDataStructureArray['sheets'] as $sheetName => $sheetDataStructure) {
         $flexFormRowSheetDataSubPart = $flexFormRowData['data'][$sheetName][$flexFormCurrentLanguage];
         if (!is_array($sheetDataStructure['ROOT']['el'])) {
             $resultArray['html'] .= LF . 'No Data Structure ERROR: No [\'ROOT\'][\'el\'] found for sheet "' . $sheetName . '".';
             continue;
         }
         $tabCounter++;
         // Assemble key for loading the correct CSH file
         // @todo: what is that good for? That is for the title of single elements ... see FlexFormElementContainer!
         $dsPointerFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$fieldName]['config']['ds_pointerField'], true);
         $parameterArray['_cshKey'] = $table . '.' . $fieldName;
         foreach ($dsPointerFields as $key) {
             if ((string) $row[$key] !== '') {
                 $parameterArray['_cshKey'] .= '.' . $row[$key];
             }
         }
         $options = $this->data;
         $options['flexFormDataStructureArray'] = $sheetDataStructure['ROOT']['el'];
         $options['flexFormRowData'] = $flexFormRowSheetDataSubPart;
         $options['flexFormFormPrefix'] = '[data][' . $sheetName . '][' . $flexFormCurrentLanguage . ']';
         $options['parameterArray'] = $parameterArray;
         // Merge elements of this tab into a single list again and hand over to
         // palette and single field container to render this group
         $options['tabAndInlineStack'][] = array('tab', $domIdPrefix . '-' . $tabCounter);
         $options['renderType'] = 'flexFormElementContainer';
         $childReturn = $this->nodeFactory->create($options)->render();
         $tabElements[] = array('label' => !empty($sheetDataStructure['ROOT']['sheetTitle']) ? $languageService->sL($sheetDataStructure['ROOT']['sheetTitle']) : $sheetName, 'content' => $childReturn['html'], 'description' => $sheetDataStructure['ROOT']['sheetDescription'] ? $languageService->sL($sheetDataStructure['ROOT']['sheetDescription']) : '', 'linkTitle' => $sheetDataStructure['ROOT']['sheetShortDescr'] ? $languageService->sL($sheetDataStructure['ROOT']['sheetShortDescr']) : '');
         $childReturn['html'] = '';
         $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childReturn);
     }
     // Feed everything to document template for tab rendering
     $resultArray['html'] = $this->renderTabMenu($tabElements, $domIdPrefix);
     return $resultArray;
 }
    /**
     * Creates the HTML (mixture of a <form> and a JavaScript section) for the JavaScript menu (basically an array of selector boxes with onchange handlers)
     *
     * @return string The HTML code for the menu
     */
    public function writeMenu()
    {
        if (!$this->id) {
            return '';
        }
        $levels = MathUtility::forceIntegerInRange($this->mconf['levels'], 1, 5);
        $this->levels = $levels;
        $uniqueParam = GeneralUtility::shortMD5(microtime(), 5);
        $this->JSVarName = 'eid' . $uniqueParam;
        $this->JSMenuName = $this->mconf['menuName'] ?: 'JSmenu' . $uniqueParam;
        $JScode = '
var ' . $this->JSMenuName . ' = new JSmenu(' . $levels . ', ' . GeneralUtility::quoteJSvalue($this->JSMenuName . 'Form') . ');';
        for ($a = 1; $a <= $levels; $a++) {
            $JScode .= '
var ' . $this->JSVarName . $a . '=0;';
        }
        $JScode .= $this->generate_level($levels, 1, $this->id, $this->menuArr, $this->MP_array) . LF;
        $GLOBALS['TSFE']->additionalHeaderData['JSMenuCode'] = '<script type="text/javascript" src="' . $GLOBALS['TSFE']->absRefPrefix . 'typo3/sysext/frontend/Resources/Public/JavaScript/jsfunc.menu.js"></script>';
        $GLOBALS['TSFE']->additionalJavaScript['JSCode'] .= $JScode;
        // Printing:
        $allFormCode = '';
        for ($a = 1; $a <= $this->levels; $a++) {
            $formCode = '';
            $levelConf = $this->mconf[$a . '.'];
            $length = $levelConf['width'] ?: 14;
            $lengthStr = '';
            for ($b = 0; $b < $length; $b++) {
                $lengthStr .= '_';
            }
            $height = $levelConf['elements'] ?: 5;
            $formCode .= '<select name="selector' . $a . '" onchange="' . $this->JSMenuName . '.act(' . $a . ');"' . ($levelConf['additionalParams'] ? ' ' . $levelConf['additionalParams'] : '') . '>';
            for ($b = 0; $b < $height; $b++) {
                $formCode .= '<option value="0">';
                if ($b === 0) {
                    $formCode .= $lengthStr;
                }
                $formCode .= '</option>';
            }
            $formCode .= '</select>';
            $allFormCode .= $this->WMcObj->wrap($formCode, $levelConf['wrap']);
        }
        $formContent = $this->WMcObj->wrap($allFormCode, $this->mconf['wrap']);
        $formCode = '<form action="" method="post" style="margin: 0 0 0 0;" name="' . $this->JSMenuName . 'Form">' . $formContent . '</form>';
        $formCode .= '<script type="text/javascript"> /*<![CDATA[*/ ' . $this->JSMenuName . '.writeOut(1,' . $this->JSMenuName . '.openID,1); /*]]>*/ </script>';
        return $this->WMcObj->wrap($formCode, $this->mconf['wrapAfterTags']);
    }
Ejemplo n.º 17
0
 /**
  * Entry method
  *
  * @return array As defined in initializeResultArray() of AbstractNode
  * @throws \RuntimeException
  */
 public function render()
 {
     $languageService = $this->getLanguageService();
     // All the fields to handle in a flat list
     $fieldsArray = $this->data['fieldsArray'];
     // Create a nested array from flat fieldArray list
     $tabsArray = array();
     // First element will be a --div--, so it is safe to start -1 here to trigger 0 as first array index
     $currentTabIndex = -1;
     foreach ($fieldsArray as $fieldString) {
         $fieldArray = $this->explodeSingleFieldShowItemConfiguration($fieldString);
         if ($fieldArray['fieldName'] === '--div--') {
             $currentTabIndex++;
             if (empty($fieldArray['fieldLabel'])) {
                 throw new \RuntimeException('A --div-- has no label (--div--;fieldLabel) in showitem of ' . implode(',', $fieldsArray), 1426454001);
             }
             $tabsArray[$currentTabIndex] = array('label' => $languageService->sL($fieldArray['fieldLabel']), 'elements' => array());
         } else {
             $tabsArray[$currentTabIndex]['elements'][] = $fieldArray;
         }
     }
     $resultArray = $this->initializeResultArray();
     $resultArray['requireJsModules'][] = 'TYPO3/CMS/Backend/Tabs';
     $domIdPrefix = 'DTM-' . GeneralUtility::shortMD5($this->data['tableName'] . $this->data['databaseRow']['uid']);
     $tabCounter = 0;
     $tabElements = array();
     foreach ($tabsArray as $tabWithLabelAndElements) {
         $tabCounter++;
         $elements = $tabWithLabelAndElements['elements'];
         // Merge elements of this tab into a single list again and hand over to
         // palette and single field container to render this group
         $options = $this->data;
         $options['tabAndInlineStack'][] = array('tab', $domIdPrefix . '-' . $tabCounter);
         $options['fieldsArray'] = array();
         foreach ($elements as $element) {
             $options['fieldsArray'][] = implode(';', $element);
         }
         $options['renderType'] = 'paletteAndSingleContainer';
         $childArray = $this->nodeFactory->create($options)->render();
         $tabElements[] = array('label' => $tabWithLabelAndElements['label'], 'content' => $childArray['html']);
         $childArray['html'] = '';
         $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childArray);
     }
     $resultArray['html'] = $this->renderTabMenu($tabElements, $domIdPrefix);
     return $resultArray;
 }
Ejemplo n.º 18
0
    /**
     * Renders form
     *
     * @param \Ameos\AmeosForm\Form\AbstractForm $form the form
     * @param string $method method
     * @param string $enctype enctype
     * @param string $action action
     * @param string $class class
     * @param string $id id
     * @return string html
     */
    public function render($form, $method = 'post', $enctype = 'multipart/form-data', $action = '', $class = '', $id = '')
    {
        $enctype = $enctype == '' ? '' : ' enctype="' . $enctype . '"';
        $action = $action == '' ? '' : ' action="' . $action . '"';
        $class = $class == '' ? '' : ' class="' . $class . '"';
        $id = $id == '' ? '' : ' id="' . $id . '"';
        if (!is_object($form)) {
            return 'Form is not valid. May be it\'s not assigned to the view.';
        }
        foreach ($form->getElements() as $elementName => $element) {
            $this->templateVariableContainer->add($elementName, $element);
        }
        if (strpos($form->getMode(), 'crud') !== FALSE) {
            $errors = $form->getErrors();
            if (!empty($errors)) {
                $this->templateVariableContainer->add('errors', $errors);
            }
        }
        $output = $this->renderChildren();
        foreach ($form->getElements() as $elementName => $element) {
            $this->templateVariableContainer->remove($elementName);
        }
        if (strpos($form->getMode(), 'crud') !== FALSE && !empty($errors)) {
            $this->templateVariableContainer->remove('errors');
        }
        if (TYPO3_MODE == 'FE') {
            if (!$form->isSubmitted()) {
                $csrftoken = GeneralUtility::shortMD5(time() . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']);
                $GLOBALS['TSFE']->fe_user->setKey('ses', $form->getIdentifier() . '-csrftoken', $csrftoken);
                $GLOBALS['TSFE']->storeSessionData();
            } else {
                $csrftoken = $GLOBALS['TSFE']->fe_user->getKey('ses', $form->getIdentifier() . '-csrftoken');
            }
        } else {
            $csrftoken = 'notoken';
        }
        $output = '<form method="' . $method . '" ' . $id . $enctype . $class . $action . '>' . $output . '
			<input type="hidden" id="' . $form->getIdentifier() . '-issubmitted" value="1" name="' . $form->getIdentifier() . '[issubmitted]" />';
        if ($form->csrftokenIsEnabled()) {
            $output .= '<input type="hidden" id="' . $form->getIdentifier() . '-csrftoken" value="' . $csrftoken . '" name="' . $form->getIdentifier() . '[csrftoken]" />';
        }
        $output .= '</form>';
        return $output;
    }
Ejemplo n.º 19
0
 /**
  * Render the captcha audio rendering request icon
  *
  * @param string suffix to be appended to the extenstion key when forming css class names
  * @return string The html used to render the captcha audio rendering request icon
  */
 public function render($suffix = '')
 {
     $value = '';
     // Get the plugin configuration
     $settings = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, $this->extensionName, $this->pluginName);
     // Get the translation view helper
     $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
     $translator = $objectManager->get('SJBR\\SrFreecap\\ViewHelpers\\TranslateViewHelper');
     $translator->injectConfigurationManager($this->configurationManager);
     // Get browser info: in IE 8, we will use a simple link, as dynamic insertion of object element gives unpredictable results
     $browserInfo = \TYPO3\CMS\Core\Utility\ClientUtility::getBrowserInfo(\TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('HTTP_USER_AGENT'));
     $browerIsIE8 = $browserInfo['browser'] == 'msie' && $browserInfo['version'] == '8';
     // Generate the icon
     if ($settings['accessibleOutput'] && in_array('mcrypt', get_loaded_extensions()) && intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem'])) {
         $fakeId = \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5(uniqid(rand()), 5);
         $siteURL = \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
         $urlParams = array('eID' => 'sr_freecap_EidDispatcher', 'id' => $GLOBALS['TSFE']->id, 'vendorName' => 'SJBR', 'extensionName' => $this->extensionName, 'pluginName' => 'AudioPlayer', 'controllerName' => 'AudioPlayer', 'actionName' => 'play', 'formatName' => $browerIsIE8 ? 'mp3' : 'wav');
         $L = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('L');
         if (isset($L)) {
             $urlParams['L'] = htmlspecialchars($L);
         }
         if ($GLOBALS['TSFE']->MP) {
             $urlParams['MP'] = $GLOBALS['TSFE']->MP;
         }
         $audioURL = $siteURL . 'index.php?' . ltrim(\TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl('', $urlParams), '&');
         if ($settings['accessibleOutputImage']) {
             if ($browerIsIE8) {
                 $value = '<a href="' . $audioURL . '&set=' . rand() . '" title="' . $translator->render('click_here_accessible') . '">' . '<img alt="' . $translator->render('click_here_accessible') . '"' . ' src="' . $siteURL . str_replace(PATH_site, '', \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($settings['accessibleOutputImage'])) . '"' . $this->getClassAttribute('image-accessible', $suffix) . ' />' . '</a>';
             } else {
                 $value = '<input type="image" alt="' . $translator->render('click_here_accessible') . '"' . ' title="' . $translator->render('click_here_accessible') . '"' . ' src="' . $siteURL . str_replace(PATH_site, '', \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($settings['accessibleOutputImage'])) . '"' . ' onclick="' . $this->extensionName . '.playCaptcha(\'' . $fakeId . '\', \'' . $audioURL . '\', \'' . $translator->render('noPlayMessage') . '\');return false;" style="cursor: pointer;"' . $this->getClassAttribute('image-accessible', $suffix) . ' />';
             }
         } else {
             if ($browerIsIE8) {
                 $value = '<span id="tx_srfreecap_captcha_playLink_' . $fakeId . '"' . $this->getClassAttribute('accessible-link', $suffix) . '>' . $translator->render('click_here_accessible_before_link') . '<a href="' . $audioURL . '&set=' . rand() . '"' . ' title="' . $translator->render('click_here_accessible') . '">' . $translator->render('click_here_accessible_link') . '</a>' . $translator->render('click_here_accessible_after_link') . '</span>';
             } else {
                 $value = '<span id="tx_srfreecap_captcha_playLink_' . $fakeId . '"' . $this->getClassAttribute('accessible-link', $suffix) . '>' . $translator->render('click_here_accessible_before_link') . '<a onClick="' . $this->extensionName . '.playCaptcha(\'' . $fakeId . '\', \'' . $audioURL . '\', \'' . $translator->render('noPlayMessage') . '\');" style="cursor: pointer;" title="' . $translator->render('click_here_accessible') . '">' . $translator->render('click_here_accessible_link') . '</a>' . $translator->render('click_here_accessible_after_link') . '</span>';
             }
         }
         $value .= '<span' . $this->getClassAttribute('accessible', $suffix) . ' id="tx_srfreecap_captcha_playAudio_' . $fakeId . '"></span>';
     }
     return $value;
 }
Ejemplo n.º 20
0
 /**
  * Return basket has value
  *
  * @return string Basket hash value
  */
 public function getBasketHashValue()
 {
     $result = FALSE;
     if (!$GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_commerce_pi1.']['dontUseBasketHashValue'] && count($this->basketItems) > 0) {
         $result = \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5(serialize($this->basketItems));
     }
     return $result;
 }
Ejemplo n.º 21
0
    /**
     * Constructor function for script class.
     *
     * @return void
     * @todo Define visibility
     */
    public function init()
    {
        // Setting GPvars:
        $this->backPath = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('backPath');
        $this->item = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('item');
        $this->reloadListFrame = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('reloadListFrame');
        // Setting pseudo module name
        $this->MCONF['name'] = 'xMOD_alt_clickmenu.php';
        // Takes the backPath as a parameter BUT since we are worried about someone forging a backPath (XSS security hole) we will check with sent md5 hash:
        $inputBP = explode('|', $this->backPath);
        if (count($inputBP) == 2 && $inputBP[1] == \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($inputBP[0] . '|' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) {
            $this->backPath = $inputBP[0];
        } else {
            $this->backPath = $GLOBALS['BACK_PATH'];
        }
        // Setting internal array of classes for extending the clickmenu:
        $this->extClassArray = $GLOBALS['TBE_MODULES_EXT']['xMOD_alt_clickmenu']['extendCMclasses'];
        // Traversing that array and setting files for inclusion:
        if (is_array($this->extClassArray)) {
            foreach ($this->extClassArray as $extClassConf) {
                if ($extClassConf['path']) {
                    $this->include_once[] = $extClassConf['path'];
                }
            }
        }
        // Initialize template object
        if (!$this->ajax) {
            $this->doc = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Template\\DocumentTemplate');
            $this->doc->backPath = $GLOBALS['BACK_PATH'];
        }
        // Setting mode for display and background image in the top frame
        $this->dontDisplayTopFrameCM = $this->doc->isCMlayers() && !$GLOBALS['BE_USER']->getTSConfigVal('options.contextMenu.options.alwaysShowClickMenuInTopFrame');
        if ($this->dontDisplayTopFrameCM) {
            $this->doc->bodyTagId .= '-notop';
        }
        // Setting clickmenu timeout
        $secs = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($GLOBALS['BE_USER']->getTSConfigVal('options.contextMenu.options.clickMenuTimeOut'), 1, 100, 5);
        // default is 5
        // Setting the JavaScript controlling the timer on the page
        $listFrameDoc = $this->reloadListFrame != 2 ? 'top.content.list_frame' : 'top.content';
        $this->doc->JScode .= $this->doc->wrapScriptTags('
	var date = new Date();
	var mo_timeout = Math.floor(date.getTime()/1000);

	roImg = "' . \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIconClasses('status-status-current') . '";

	routImg = "t3-icon-empty";

	function mo(c) {	//
		var name="roimg_"+c;
		document.getElementById(name).className = roImg;
		updateTime();
	}
	function mout(c) {	//
		var name="roimg_"+c;
		document[name].src = routImg;
		updateTime();
	}
	function updateTime() {	//
		date = new Date();
		mo_timeout = Math.floor(date.getTime()/1000);
	}
	function timeout_func() {	//
		date = new Date();
		if (Math.floor(date.getTime()/1000)-mo_timeout > ' . $secs . ') {
			hideCM();
			return false;
		} else {
			window.setTimeout("timeout_func();",1*1000);
		}
	}
	function hideCM() {	//
		window.location.href="alt_topmenu_dummy.php";
		return false;
	}

		// Start timer
	timeout_func();

	' . ($this->reloadListFrame ? '
		// Reload list frame:
	if(' . $listFrameDoc . '){' . $listFrameDoc . '.location.href=' . $listFrameDoc . '.location.href;}' : '') . '
		');
    }
Ejemplo n.º 22
0
    /**
     * Generates the JavaScript code for the backend,
     * and since we're loading a backend module outside of the actual backend
     * this copies parts of the backend.php
     *
     * @return 	string
     */
    protected function generateJavascript()
    {
        $pathTYPO3 = GeneralUtility::dirname(GeneralUtility::getIndpEnv('SCRIPT_NAME')) . '/';
        // If another page module was specified, replace the default Page module with the new one
        $newPageModule = trim($GLOBALS['BE_USER']->getTSConfigVal('options.overridePageModule'));
        $pageModule = BackendUtility::isModuleSetInTBE_MODULES($newPageModule) ? $newPageModule : 'web_layout';
        if (!$GLOBALS['BE_USER']->check('modules', $pageModule)) {
            $pageModule = '';
        }
        // Determine security level from conf vars and default to super challenged
        if ($GLOBALS['TYPO3_CONF_VARS']['BE']['loginSecurityLevel']) {
            $loginSecurityLevel = $GLOBALS['TYPO3_CONF_VARS']['BE']['loginSecurityLevel'];
        } else {
            $loginSecurityLevel = 'superchallenged';
        }
        $t3Configuration = array('siteUrl' => GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), 'PATH_typo3' => $pathTYPO3, 'PATH_typo3_enc' => rawurlencode($pathTYPO3), 'username' => htmlspecialchars($GLOBALS['BE_USER']->user['username']), 'uniqueID' => GeneralUtility::shortMD5(uniqid('', TRUE)), 'securityLevel' => $loginSecurityLevel, 'TYPO3_mainDir' => TYPO3_mainDir, 'pageModule' => $pageModule, 'inWorkspace' => $GLOBALS['BE_USER']->workspace !== 0 ? 1 : 0, 'workspaceFrontendPreviewEnabled' => $GLOBALS['BE_USER']->user['workspace_preview'] ? 1 : 0, 'veriCode' => $GLOBALS['BE_USER']->veriCode(), 'denyFileTypes' => PHP_EXTENSIONS_DEFAULT, 'moduleMenuWidth' => $this->menuWidth - 1, 'topBarHeight' => isset($GLOBALS['TBE_STYLES']['dims']['topFrameH']) ? (int) $GLOBALS['TBE_STYLES']['dims']['topFrameH'] : 30, 'showRefreshLoginPopup' => isset($GLOBALS['TYPO3_CONF_VARS']['BE']['showRefreshLoginPopup']) ? (int) $GLOBALS['TYPO3_CONF_VARS']['BE']['showRefreshLoginPopup'] : FALSE, 'listModulePath' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extRelPath('recordlist') . 'mod1/', 'debugInWindow' => $GLOBALS['BE_USER']->uc['debugInWindow'] ? 1 : 0, 'ContextHelpWindows' => array('width' => 600, 'height' => 400));
        $t3LLLcore = array('waitTitle' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_logging_in'), 'refresh_login_failed' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_failed'), 'refresh_login_failed_message' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_failed_message'), 'refresh_login_title' => sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_title'), htmlspecialchars($GLOBALS['BE_USER']->user['username'])), 'login_expired' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_expired'), 'refresh_login_username' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_username'), 'refresh_login_password' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_password'), 'refresh_login_emptyPassword' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_emptyPassword'), 'refresh_login_button' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_button'), 'refresh_logout_button' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_logout_button'), 'please_wait' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.please_wait'), 'loadingIndicator' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:loadingIndicator'), 'be_locked' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.be_locked'), 'refresh_login_countdown_singular' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_countdown_singular'), 'refresh_login_countdown' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_countdown'), 'login_about_to_expire' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_about_to_expire'), 'login_about_to_expire_title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_about_to_expire_title'), 'refresh_login_refresh_button' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_refresh_button'), 'refresh_direct_logout_button' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_direct_logout_button'), 'tabs_closeAll' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:tabs.closeAll'), 'tabs_closeOther' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:tabs.closeOther'), 'tabs_close' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:tabs.close'), 'tabs_openInBrowserWindow' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:tabs.openInBrowserWindow'), 'donateWindow_title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:donateWindow.title'), 'donateWindow_message' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:donateWindow.message'), 'donateWindow_button_donate' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:donateWindow.button_donate'), 'donateWindow_button_disable' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:donateWindow.button_disable'), 'donateWindow_button_postpone' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:donateWindow.button_postpone'));
        $js = '
		TYPO3.configuration = ' . json_encode($t3Configuration) . ';
		TYPO3.LLL = {
			core : ' . json_encode($t3LLLcore) . '
		};

		/**
		 * TypoSetup object.
		 */
		function typoSetup()	{	//
			this.PATH_typo3 = TYPO3.configuration.PATH_typo3;
			this.PATH_typo3_enc = TYPO3.configuration.PATH_typo3_enc;
			this.username = TYPO3.configuration.username;
			this.uniqueID = TYPO3.configuration.uniqueID;
			this.navFrameWidth = 0;
			this.securityLevel = TYPO3.configuration.securityLevel;
			this.veriCode = TYPO3.configuration.veriCode;
			this.denyFileTypes = TYPO3.configuration.denyFileTypes;
		}
		var TS = new typoSetup();
			//backwards compatibility
		';
        return $js;
    }
Ejemplo n.º 23
0
 /**
  * Creates the icon file for the function getIcon()
  *
  * @param string $iconfile Original unprocessed Icon file, relative path to PATH_typo3
  * @param string $mode Mode string, eg. "deleted" or "futuretiming" determining how the icon will look
  * @param integer $user The number of the fe_group record uid if applicable
  * @param boolean $protectSection Flag determines if the protected-section icon should be applied.
  * @param string $absFile Absolute path to file from which to create the icon.
  * @param string $iconFileName_stateTagged The filename that this icon should have had, basically [icon base name]_[flags].[extension] - used for part of temporary filename
  * @return string Filename relative to PATH_typo3
  * @access private
  */
 public static function makeIcon($iconfile, $mode, $user, $protectSection, $absFile, $iconFileName_stateTagged)
 {
     $iconFileName = 'icon_' . GeneralUtility::shortMD5($iconfile . '|' . $mode . '|-' . $user . '|' . $protectSection) . '_' . $iconFileName_stateTagged . '.' . ($GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib_png'] ? 'png' : 'gif');
     $mainpath = '../typo3temp/' . $iconFileName;
     $path = PATH_site . 'typo3temp/' . $iconFileName;
     if (file_exists(PATH_typo3 . 'icons/' . $iconFileName)) {
         // Returns if found in typo3/icons/
         return 'icons/' . $iconFileName;
     } elseif (file_exists($path)) {
         // Returns if found in ../typo3temp/icons/
         return $mainpath;
     } else {
         // Makes icon:
         if (file_exists($absFile)) {
             if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib']) {
                 // Create image pointer, if possible
                 $im = self::imagecreatefrom($absFile);
                 if ($im < 0) {
                     return $iconfile;
                 }
                 // Converting to gray scale, dimming the icon:
                 if ($mode == 'disabled' or $mode != 'futuretiming' && $mode != 'no_icon_found' && !(!$mode && $user)) {
                     $totalImageColors = ImageColorsTotal($im);
                     for ($c = 0; $c < $totalImageColors; $c++) {
                         $cols = ImageColorsForIndex($im, $c);
                         $newcol = round(($cols['red'] + $cols['green'] + $cols['blue']) / 3);
                         $lighten = $mode == 'disabled' ? 2.5 : 2;
                         $newcol = round(255 - (255 - $newcol) / $lighten);
                         ImageColorSet($im, $c, $newcol, $newcol, $newcol);
                     }
                 }
                 // Applying user icon, if there are access control on the item:
                 if ($user) {
                     if ($user < 100) {
                         // Apply user number only if lower than 100
                         $black = ImageColorAllocate($im, 0, 0, 0);
                         imagefilledrectangle($im, 0, 0, $user > 10 ? 9 : 5, 8, $black);
                         $white = ImageColorAllocate($im, 255, 255, 255);
                         imagestring($im, 1, 1, 1, $user, $white);
                     }
                     $ol_im = self::imagecreatefrom($GLOBALS['BACK_PATH'] . 'gfx/overlay_group.gif');
                     if ($ol_im < 0) {
                         return $iconfile;
                     }
                     self::imagecopyresized($im, $ol_im, 0, 0, 0, 0, imagesx($ol_im), imagesy($ol_im), imagesx($ol_im), imagesy($ol_im));
                 }
                 // Applying overlay based on mode:
                 if ($mode) {
                     unset($ol_im);
                     switch ($mode) {
                         case 'deleted':
                             $ol_im = self::imagecreatefrom($GLOBALS['BACK_PATH'] . 'gfx/overlay_deleted.gif');
                             break;
                         case 'futuretiming':
                             $ol_im = self::imagecreatefrom($GLOBALS['BACK_PATH'] . 'gfx/overlay_timing.gif');
                             break;
                         case 'timing':
                             $ol_im = self::imagecreatefrom($GLOBALS['BACK_PATH'] . 'gfx/overlay_timing.gif');
                             break;
                         case 'hiddentiming':
                             $ol_im = self::imagecreatefrom($GLOBALS['BACK_PATH'] . 'gfx/overlay_hidden_timing.gif');
                             break;
                         case 'no_icon_found':
                             $ol_im = self::imagecreatefrom($GLOBALS['BACK_PATH'] . 'gfx/overlay_no_icon_found.gif');
                             break;
                         case 'disabled':
                             // is already greyed - nothing more
                             $ol_im = 0;
                             break;
                         case 'hidden':
                         default:
                             $ol_im = self::imagecreatefrom($GLOBALS['BACK_PATH'] . 'gfx/overlay_hidden.gif');
                     }
                     if ($ol_im < 0) {
                         return $iconfile;
                     }
                     if ($ol_im) {
                         self::imagecopyresized($im, $ol_im, 0, 0, 0, 0, imagesx($ol_im), imagesy($ol_im), imagesx($ol_im), imagesy($ol_im));
                     }
                 }
                 // Protect-section icon:
                 if ($protectSection) {
                     $ol_im = self::imagecreatefrom($GLOBALS['BACK_PATH'] . 'gfx/overlay_sub5.gif');
                     if ($ol_im < 0) {
                         return $iconfile;
                     }
                     self::imagecopyresized($im, $ol_im, 0, 0, 0, 0, imagesx($ol_im), imagesy($ol_im), imagesx($ol_im), imagesy($ol_im));
                 }
                 // Create the image as file, destroy GD image and return:
                 @self::imagemake($im, $path);
                 GeneralUtility::gif_compress($path, 'IM');
                 ImageDestroy($im);
                 return $mainpath;
             } else {
                 return $iconfile;
             }
         } else {
             return $GLOBALS['BACK_PATH'] . 'gfx/fileicons/default.gif';
         }
     }
 }
Ejemplo n.º 24
0
 /**
  * Returns the checksum for this task's configuration, also taking the file and task type into account.
  *
  * @return string
  */
 public function getConfigurationChecksum()
 {
     return \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5(implode('|', $this->getChecksumData()));
 }
 /**
  * Find managed files which are referred to more than one time
  * Fix methods: API in \TYPO3\CMS\Core\Database\ReferenceIndex that allows to
  * change the value of a reference (we could copy the file) or remove reference
  *
  * @return array
  */
 public function main()
 {
     // Initialize result array:
     $resultArray = array('message' => $this->cli_help['name'] . LF . LF . $this->cli_help['description'], 'headers' => array('multipleReferencesList_count' => array('Number of multi-reference files', '(See below)', 0), 'singleReferencesList_count' => array('Number of files correctly referenced', 'The amount of correct 1-1 references', 0), 'multipleReferencesList' => array('Entries with files having multiple references', 'These are serious problems that should be resolved ASAP to prevent data loss! ' . $this->label_infoString, 3), 'dirname_registry' => array('Registry of directories in which files are found.', 'Registry includes which table/field pairs store files in them plus how many files their store.', 0), 'missingFiles' => array('Tracking missing files', '(Extra feature, not related to tracking of double references. Further, the list may include more files than found in the missing_files()-test because this list includes missing files from deleted records.)', 0), 'warnings' => array('Warnings picked up', '', 2)), 'multipleReferencesList_count' => array('count' => 0), 'singleReferencesList_count' => array('count' => 0), 'multipleReferencesList' => array(), 'dirname_registry' => array(), 'missingFiles' => array(), 'warnings' => array());
     // Select all files in the reference table not found by a soft reference parser (thus TCA configured)
     $recs = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_refindex', 'ref_table=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('_FILE', 'sys_refindex') . ' AND softref_key=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('', 'sys_refindex'), '', 'sorting DESC');
     // Traverse the files and put into a large table:
     $tempCount = array();
     if (is_array($recs)) {
         foreach ($recs as $rec) {
             // Compile info string for location of reference:
             $infoString = $this->infoStr($rec);
             // Registering occurencies in directories:
             $resultArray['dirname_registry'][dirname($rec['ref_string'])][$rec['tablename'] . ':' . $rec['field']]++;
             // Handle missing file:
             if (!@is_file(PATH_site . $rec['ref_string'])) {
                 $resultArray['missingFiles'][$rec['ref_string']][$rec['hash']] = $infoString;
                 ksort($resultArray['missingFiles'][$rec['ref_string']]);
             }
             // Add entry if file has multiple references pointing to it:
             if (isset($tempCount[$rec['ref_string']])) {
                 if (!is_array($resultArray['multipleReferencesList'][$rec['ref_string']])) {
                     $resultArray['multipleReferencesList'][$rec['ref_string']] = array();
                     $resultArray['multipleReferencesList'][$rec['ref_string']][$tempCount[$rec['ref_string']][1]] = $tempCount[$rec['ref_string']][0];
                 }
                 $resultArray['multipleReferencesList'][$rec['ref_string']][$rec['hash']] = $infoString;
                 ksort($resultArray['multipleReferencesList'][$rec['ref_string']]);
             } else {
                 $tempCount[$rec['ref_string']] = array($infoString, $rec['hash']);
             }
         }
     }
     ksort($resultArray['missingFiles']);
     ksort($resultArray['multipleReferencesList']);
     // Add count for multi-references:
     $resultArray['multipleReferencesList_count']['count'] = count($resultArray['multipleReferencesList']);
     $resultArray['singleReferencesList_count']['count'] = count($tempCount) - $resultArray['multipleReferencesList_count']['count'];
     // Sort dirname registry and add warnings for directories outside uploads/
     ksort($resultArray['dirname_registry']);
     foreach ($resultArray['dirname_registry'] as $dir => $temp) {
         ksort($resultArray['dirname_registry'][$dir]);
         if (!\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($dir, 'uploads/')) {
             $resultArray['warnings'][\TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($dir)] = 'Directory "' . $dir . '" was outside uploads/ which is unusual practice in TYPO3 although not forbidden. Directory used by the following table:field pairs: ' . implode(',', array_keys($temp));
         }
     }
     return $resultArray;
 }
 /**
  * Generates the name of the cached file.
  *
  * @param string $sourcePath
  * @param string $languageKey
  * @return void
  */
 protected function generateCacheFileName($sourcePath, $languageKey)
 {
     $this->hashSource = substr($sourcePath, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($sourcePath)) . '|version=2.3';
     $this->cacheFileName = PATH_site . 'typo3temp/llxml/' . substr(basename($sourcePath), 10, 15) . '_' . \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($this->hashSource) . '.' . $languageKey . '.' . $this->targetCharset . '.cache';
 }
Ejemplo n.º 27
0
 /**
  * Writes contents in a file in typo3temp and returns the file name
  *
  * @param string $label: A label to insert at the beginning of the name of the file
  * @param string $fileExtension: The file extension of the file, defaulting to 'js'
  * @param string $contents: The contents to write into the file
  * @return string The name of the file written to typo3temp
  * @throws \RuntimeException If writing to file failed
  */
 protected function writeTemporaryFile($label, $fileExtension = 'js', $contents = '')
 {
     $relativeFilename = 'typo3temp/RteHtmlArea/' . str_replace('-', '_', $label) . '_' . GeneralUtility::shortMD5($contents, 20) . '.' . $fileExtension;
     $destination = PATH_site . $relativeFilename;
     if (!file_exists($destination)) {
         $minifiedJavaScript = '';
         if ($fileExtension === 'js' && $contents !== '') {
             $minifiedJavaScript = GeneralUtility::minifyJavaScript($contents);
         }
         $failure = GeneralUtility::writeFileToTypo3tempDir($destination, $minifiedJavaScript ? $minifiedJavaScript : $contents);
         if ($failure) {
             throw new \RuntimeException($failure, 1294585668);
         }
     }
     if ($this->isFrontend() || $this->isFrontendEditActive()) {
         $fileName = $relativeFilename;
     } else {
         $fileName = '../' . $relativeFilename;
     }
     return GeneralUtility::resolveBackPath($fileName);
 }
Ejemplo n.º 28
0
 /**
  * Transformation handler: 'ts_images' / direction: "db"
  * Processing images inserted in the RTE.
  * This is used when content goes from the RTE to the database.
  * Images inserted in the RTE has an absolute URL applied to the src attribute. This URL is converted to a relative URL
  * If it turns out that the URL is from another website than the current the image is read from that external URL and moved to the local server.
  * Also "magic" images are processed here.
  *
  * @param string $value The content from RTE going to Database
  * @return string Processed content
  */
 public function TS_images_db($value)
 {
     // Split content by <img> tags and traverse the resulting array for processing:
     $imgSplit = $this->splitTags('img', $value);
     if (count($imgSplit) > 1) {
         $siteUrl = $this->siteUrl();
         $sitePath = str_replace(GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST'), '', $siteUrl);
         /** @var $resourceFactory Resource\ResourceFactory */
         $resourceFactory = Resource\ResourceFactory::getInstance();
         /** @var $magicImageService Resource\Service\MagicImageService */
         $magicImageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Service\MagicImageService::class);
         $magicImageService->setMagicImageMaximumDimensions($this->tsConfig);
         foreach ($imgSplit as $k => $v) {
             // Image found, do processing:
             if ($k % 2) {
                 // Get attributes
                 $attribArray = $this->get_tag_attributes_classic($v, 1);
                 // It's always an absolute URL coming from the RTE into the Database.
                 $absoluteUrl = trim($attribArray['src']);
                 // Make path absolute if it is relative and we have a site path which is not '/'
                 $pI = pathinfo($absoluteUrl);
                 if ($sitePath && !$pI['scheme'] && GeneralUtility::isFirstPartOfStr($absoluteUrl, $sitePath)) {
                     // If site is in a subpath (eg. /~user_jim/) this path needs to be removed because it will be added with $siteUrl
                     $absoluteUrl = substr($absoluteUrl, strlen($sitePath));
                     $absoluteUrl = $siteUrl . $absoluteUrl;
                 }
                 // Image dimensions set in the img tag, if any
                 $imgTagDimensions = $this->getWHFromAttribs($attribArray);
                 if ($imgTagDimensions[0]) {
                     $attribArray['width'] = $imgTagDimensions[0];
                 }
                 if ($imgTagDimensions[1]) {
                     $attribArray['height'] = $imgTagDimensions[1];
                 }
                 $originalImageFile = null;
                 if ($attribArray['data-htmlarea-file-uid']) {
                     // An original image file uid is available
                     try {
                         /** @var $originalImageFile Resource\File */
                         $originalImageFile = $resourceFactory->getFileObject(intval($attribArray['data-htmlarea-file-uid']));
                     } catch (Resource\Exception\FileDoesNotExistException $fileDoesNotExistException) {
                         // Log the fact the file could not be retrieved.
                         $message = sprintf('Could not find file with uid "%s"', $attribArray['data-htmlarea-file-uid']);
                         $this->getLogger()->error($message);
                     }
                 }
                 if ($originalImageFile instanceof Resource\File) {
                     // Public url of local file is relative to the site url, absolute otherwise
                     if ($absoluteUrl == $originalImageFile->getPublicUrl() || $absoluteUrl == $siteUrl . $originalImageFile->getPublicUrl()) {
                         // This is a plain image, i.e. reference to the original image
                         if ($this->procOptions['plainImageMode']) {
                             // "plain image mode" is configured
                             // Find the dimensions of the original image
                             $imageInfo = array($originalImageFile->getProperty('width'), $originalImageFile->getProperty('height'));
                             if (!$imageInfo[0] || !$imageInfo[1]) {
                                 $filePath = $originalImageFile->getForLocalProcessing(false);
                                 $imageInfo = @getimagesize($filePath);
                             }
                             $attribArray = $this->applyPlainImageModeSettings($imageInfo, $attribArray);
                         }
                     } else {
                         // Magic image case: get a processed file with the requested configuration
                         $imageConfiguration = array('width' => $imgTagDimensions[0], 'height' => $imgTagDimensions[1]);
                         $magicImage = $magicImageService->createMagicImage($originalImageFile, $imageConfiguration);
                         $attribArray['width'] = $magicImage->getProperty('width');
                         $attribArray['height'] = $magicImage->getProperty('height');
                         $attribArray['src'] = $magicImage->getPublicUrl();
                     }
                 } elseif (!GeneralUtility::isFirstPartOfStr($absoluteUrl, $siteUrl) && !$this->procOptions['dontFetchExtPictures'] && TYPO3_MODE === 'BE') {
                     // External image from another URL: in that case, fetch image, unless the feature is disabled or we are not in backend mode
                     // Fetch the external image
                     $externalFile = $this->getUrl($absoluteUrl);
                     if ($externalFile) {
                         $pU = parse_url($absoluteUrl);
                         $pI = pathinfo($pU['path']);
                         if (GeneralUtility::inList('gif,png,jpeg,jpg', strtolower($pI['extension']))) {
                             $fileName = GeneralUtility::shortMD5($absoluteUrl) . '.' . $pI['extension'];
                             // We insert this image into the user default upload folder
                             list($table, $field) = explode(':', $this->elRef);
                             $folder = $GLOBALS['BE_USER']->getDefaultUploadFolder($this->recPid, $table, $field);
                             $fileObject = $folder->createFile($fileName)->setContents($externalFile);
                             $imageConfiguration = array('width' => $attribArray['width'], 'height' => $attribArray['height']);
                             $magicImage = $magicImageService->createMagicImage($fileObject, $imageConfiguration);
                             $attribArray['width'] = $magicImage->getProperty('width');
                             $attribArray['height'] = $magicImage->getProperty('height');
                             $attribArray['data-htmlarea-file-uid'] = $fileObject->getUid();
                             $attribArray['src'] = $magicImage->getPublicUrl();
                         }
                     }
                 } elseif (GeneralUtility::isFirstPartOfStr($absoluteUrl, $siteUrl)) {
                     // Finally, check image as local file (siteURL equals the one of the image)
                     // Image has no data-htmlarea-file-uid attribute
                     // Relative path, rawurldecoded for special characters.
                     $path = rawurldecode(substr($absoluteUrl, strlen($siteUrl)));
                     // Absolute filepath, locked to relative path of this project
                     $filepath = GeneralUtility::getFileAbsFileName($path);
                     // Check file existence (in relative directory to this installation!)
                     if ($filepath && @is_file($filepath)) {
                         // Treat it as a plain image
                         if ($this->procOptions['plainImageMode']) {
                             // If "plain image mode" has been configured
                             // Find the original dimensions of the image
                             $imageInfo = @getimagesize($filepath);
                             $attribArray = $this->applyPlainImageModeSettings($imageInfo, $attribArray);
                         }
                         // Let's try to find a file uid for this image
                         try {
                             $fileOrFolderObject = $resourceFactory->retrieveFileOrFolderObject($path);
                             if ($fileOrFolderObject instanceof Resource\FileInterface) {
                                 $fileIdentifier = $fileOrFolderObject->getIdentifier();
                                 $fileObject = $fileOrFolderObject->getStorage()->getFile($fileIdentifier);
                                 // @todo if the retrieved file is a processed file, get the original file...
                                 $attribArray['data-htmlarea-file-uid'] = $fileObject->getUid();
                             }
                         } catch (Resource\Exception\ResourceDoesNotExistException $resourceDoesNotExistException) {
                             // Nothing to be done if file/folder not found
                         }
                     }
                 }
                 // Remove width and height from style attribute
                 $attribArray['style'] = preg_replace('/((?:^|)\\s*(?:width|height)\\s*:[^;]*(?:$|;))/si', '', $attribArray['style']);
                 // Must have alt attribute
                 if (!isset($attribArray['alt'])) {
                     $attribArray['alt'] = '';
                 }
                 // Convert absolute to relative url
                 if (GeneralUtility::isFirstPartOfStr($attribArray['src'], $siteUrl)) {
                     $attribArray['src'] = $this->relBackPath . substr($attribArray['src'], strlen($siteUrl));
                 }
                 $imgSplit[$k] = '<img ' . GeneralUtility::implodeAttributes($attribArray, 1, 1) . ' />';
             }
         }
     }
     return implode('', $imgSplit);
 }
Ejemplo n.º 29
0
 /**
  * Renders the actual image
  *
  * @param \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $contentObject
  * @param $file
  * @param array $fileConfiguration
  * @return array
  */
 public function getImgResource(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $contentObject, $file, array $fileConfiguration)
 {
     if ($fileConfiguration['import.']) {
         $ifile = $contentObject->stdWrap('', $fileConfiguration['import.']);
         if ($ifile) {
             $file = $fileConfiguration['import'] . $ifile;
         }
     }
     if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($file)) {
         $file = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\ResourceFactory')->getFileObject($file);
     }
     if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
         $theImage = $file->getForLocalProcessing(FALSE);
     } else {
         // clean ../ sections of the path and resolve to proper string.
         // This is necessary for the \TYPO3\CMS\Core\Resource\Service\FrontendContentAdapterService to work.
         $file = \TYPO3\CMS\Core\Utility\GeneralUtility::resolveBackPath($file);
         $theImage = $GLOBALS['TSFE']->tmpl->getFileName($file);
         if (!$theImage) {
             return array();
         }
     }
     $fileConfiguration = $this->processFileConfiguration($fileConfiguration, $contentObject);
     $maskArray = $fileConfiguration['m.'];
     $maskImages = array();
     // Must render mask images and include in hash-calculating - else we
     // cannot be sure the filename is unique for the setup!
     if (is_array($maskArray)) {
         $maskImages['m_mask'] = $this->getImgResource($contentObject, $maskArray['mask'], $maskArray['mask.']);
         $maskImages['m_bgImg'] = $this->getImgResource($contentObject, $maskArray['bgImg'], $maskArray['bgImg.']);
         $maskImages['m_bottomImg'] = $this->getImgResource($contentObject, $maskArray['bottomImg'], $maskArray['bottomImg.']);
         $maskImages['m_bottomImg_mask'] = $this->getImgResource($contentObject, $maskArray['bottomImg_mask'], $maskArray['bottomImg_mask.']);
     }
     // TODO use \TYPO3\CMS\Core\Resource\FileInterface here
     if ($file instanceof \TYPO3\CMS\Core\Resource\FileReference) {
         $hash = $file->getOriginalFile()->calculateChecksum();
     } else {
         $hash = \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($theImage . serialize($fileConfiguration) . serialize($maskImages));
     }
     if (isset($GLOBALS['TSFE']->tmpl->fileCache[$hash])) {
         return $GLOBALS['TSFE']->tmpl->fileCache[$hash];
     }
     /** @var $gifCreator tslib_gifbuilder */
     $gifCreator = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tslib_gifbuilder');
     $gifCreator->init();
     if ($GLOBALS['TSFE']->config['config']['meaningfulTempFilePrefix']) {
         $filename = basename($theImage);
         // Remove extension
         $filename = substr($filename, 0, strrpos($filename, '.'));
         $tempFilePrefixLength = intval($GLOBALS['TSFE']->config['config']['meaningfulTempFilePrefix']);
         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
             /** @var $t3libCsInstance \TYPO3\CMS\Core\Charset\CharsetConverter */
             $t3libCsInstance = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter');
             $filenamePrefix = $t3libCsInstance->substr('utf-8', $filename, 0, $tempFilePrefixLength);
         } else {
             // Strip everything non-ascii
             $filename = preg_replace('/[^A-Za-z0-9_-]/', '', trim($filename));
             $filenamePrefix = substr($filename, 0, $tempFilePrefixLength);
         }
         $gifCreator->filenamePrefix = $filenamePrefix . '_';
         unset($filename);
     }
     if ($fileConfiguration['sample']) {
         $gifCreator->scalecmd = '-sample';
         $GLOBALS['TT']->setTSlogMessage('Sample option: Images are scaled with -sample.');
     }
     if ($fileConfiguration['alternativeTempPath'] && \TYPO3\CMS\Core\Utility\GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['FE']['allowedTempPaths'], $fileConfiguration['alternativeTempPath'])) {
         $gifCreator->tempPath = $fileConfiguration['alternativeTempPath'];
         $GLOBALS['TT']->setTSlogMessage('Set alternativeTempPath: ' . $fileConfiguration['alternativeTempPath']);
     }
     if (!trim($fileConfiguration['ext'])) {
         $fileConfiguration['ext'] = 'web';
     }
     $options = array();
     if ($fileConfiguration['maxW']) {
         $options['maxW'] = $fileConfiguration['maxW'];
     }
     if ($fileConfiguration['maxH']) {
         $options['maxH'] = $fileConfiguration['maxH'];
     }
     if ($fileConfiguration['minW']) {
         $options['minW'] = $fileConfiguration['minW'];
     }
     if ($fileConfiguration['minH']) {
         $options['minH'] = $fileConfiguration['minH'];
     }
     if ($fileConfiguration['noScale']) {
         $options['noScale'] = $fileConfiguration['noScale'];
     }
     $fileInformation = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($theImage);
     $imgExt = strtolower($fileInformation['fileext']) == $gifCreator->gifExtension ? $gifCreator->gifExtension : 'jpg';
     // If no mask  is used or ImageMagick is disabled, processing is quite simple
     if (!is_array($maskArray) || !$GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) {
         $fileConfiguration['params'] = $this->modifyImageMagickStripProfileParameters($fileConfiguration['params'], $fileConfiguration);
         $GLOBALS['TSFE']->tmpl->fileCache[$hash] = $gifCreator->imageMagickConvert($theImage, $fileConfiguration['ext'], $fileConfiguration['width'], $fileConfiguration['height'], $fileConfiguration['params'], $fileConfiguration['frame'], $options);
         if (($fileConfiguration['reduceColors'] || $imgExt === 'png' && !$gifCreator->png_truecolor) && is_file($GLOBALS['TSFE']->tmpl->fileCache[$hash][3])) {
             $reduced = $gifCreator->IMreduceColors($GLOBALS['TSFE']->tmpl->fileCache[$hash][3], \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($fileConfiguration['reduceColors'], 256, $gifCreator->truecolorColors, 256));
             if (is_file($reduced)) {
                 unlink($GLOBALS['TSFE']->tmpl->fileCache[$hash][3]);
                 rename($reduced, $GLOBALS['TSFE']->tmpl->fileCache[$hash][3]);
             }
         }
     } else {
         // Filename:
         $fileDestination = $gifCreator->tempPath . $hash . '.' . $imgExt;
         // Generate!
         if (!file_exists($fileDestination)) {
             $this->processMask($maskImages, $gifCreator, $theImage, $fileConfiguration, $options, $fileDestination);
         }
         // Finish off
         if (($fileConfiguration['reduceColors'] || $imgExt === 'png' && !$gifCreator->png_truecolor) && is_file($fileDestination)) {
             $reduced = $gifCreator->IMreduceColors($fileDestination, \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($fileConfiguration['reduceColors'], 256, $gifCreator->truecolorColors, 256));
             if (is_file($reduced)) {
                 unlink($fileDestination);
                 rename($reduced, $fileDestination);
             }
         }
         $GLOBALS['TSFE']->tmpl->fileCache[$hash] = $gifCreator->getImageDimensions($fileDestination);
     }
     $GLOBALS['TSFE']->tmpl->fileCache[$hash]['origFile'] = $theImage;
     // This is needed by tslib_gifbuilder, in order for the setup-array to create a unique filename hash.
     $GLOBALS['TSFE']->tmpl->fileCache[$hash]['origFile_mtime'] = @filemtime($theImage);
     $GLOBALS['TSFE']->tmpl->fileCache[$hash]['fileCacheHash'] = $hash;
     if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface && \TYPO3\CMS\Core\Utility\GeneralUtility::isAbsPath($GLOBALS['TSFE']->tmpl->fileCache[$hash][3])) {
         $GLOBALS['TSFE']->tmpl->fileCache[$hash][3] = $file->getPublicUrl();
     }
     $imageResource = $GLOBALS['TSFE']->tmpl->fileCache[$hash];
     return $imageResource;
 }
Ejemplo n.º 30
0
 /**
  * Processing of the storage command LOAD, SAVE, REMOVE
  *
  * @param string $mconfName Name of the module to store the settings for. Default: $this->getModule()->MCONF['name'] (current module)
  * @return string Storage message. Also set in $this->msg
  */
 public function processStoreControl($mconfName = '')
 {
     $this->initStorage();
     $storeControl = GeneralUtility::_GP('storeControl');
     $storeIndex = $storeControl['STORE'];
     $msg = '';
     $saveSettings = false;
     $writeArray = array();
     if (is_array($storeControl)) {
         if ($this->writeDevLog) {
             GeneralUtility::devLog('Store command: ' . GeneralUtility::arrayToLogString($storeControl), __CLASS__, 0);
         }
         // Processing LOAD
         if ($storeControl['LOAD'] && $storeIndex) {
             $writeArray = $this->getStoredData($storeIndex, $writeArray);
             $saveSettings = true;
             $msg = '\'' . $this->storedSettings[$storeIndex]['title'] . '\' preset loaded!';
         } elseif ($storeControl['SAVE']) {
             if (trim($storeControl['title'])) {
                 // Get the data to store
                 $newEntry = $this->compileEntry($storeControl);
                 // Create an index for the storage array
                 if (!$storeIndex) {
                     $storeIndex = GeneralUtility::shortMD5($newEntry['title']);
                 }
                 // Add data to the storage array
                 $this->storedSettings[$storeIndex] = $newEntry;
                 $saveSettings = true;
                 $msg = '\'' . $newEntry['title'] . '\' preset saved!';
             } else {
                 $msg = 'Please enter a name for the preset!';
             }
         } elseif ($storeControl['REMOVE'] and $storeIndex) {
             // Removing entry
             $msg = '\'' . $this->storedSettings[$storeIndex]['title'] . '\' preset entry removed!';
             unset($this->storedSettings[$storeIndex]);
             $saveSettings = true;
         }
         $this->msg = $msg;
         if ($saveSettings) {
             $this->writeStoredSetting($writeArray, $mconfName);
         }
     }
     return $this->msg;
 }