/** * Check if a connection to a Solr server could be established with the given credentials. * * @access public * * @param array &$params: An array with parameters * @param \TYPO3\CMS\Core\TypoScript\ConfigurationForm &$pObj: The parent object * * @return string Message informing the user of success or failure */ public function checkSolrConnection(&$params, &$pObj) { // Prepend username and password to hostname. if (!empty($this->conf['solrUser']) && !empty($this->conf['solrPass'])) { $host = $this->conf['solrUser'] . ':' . $this->conf['solrPass'] . '@' . (!empty($this->conf['solrHost']) ? $this->conf['solrHost'] : 'localhost'); } else { $host = !empty($this->conf['solrHost']) ? $this->conf['solrHost'] : 'localhost'; } // Set port if not set. $port = !empty($this->conf['solrPort']) ? \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->conf['solrPort'], 0, 65535, 8180) : 8180; // Trim path and append trailing slash. $path = !empty($this->conf['solrPath']) ? trim($this->conf['solrPath'], '/') . '/' : ''; // Build request URI. $url = 'http://' . $host . ':' . $port . '/' . $path . 'admin/cores'; $context = stream_context_create(array('http' => array('method' => 'GET', 'user_agent' => !empty($this->conf['useragent']) ? $this->conf['useragent'] : ini_get('user_agent')))); // Try to connect to Solr server. $response = @simplexml_load_string(file_get_contents($url, FALSE, $context)); // Check status code. if ($response) { $status = $response->xpath('//lst[@name="responseHeader"]/int[@name="status"]'); if (is_array($status)) { $message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', sprintf($GLOBALS['LANG']->getLL('solr.status'), (string) $status[0]), $GLOBALS['LANG']->getLL('solr.connected'), $status[0] == 0 ? \TYPO3\CMS\Core\Messaging\FlashMessage::OK : \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING, FALSE); $this->content .= $message->render(); return $this->content; } } $message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', sprintf($GLOBALS['LANG']->getLL('solr.error'), $url), $GLOBALS['LANG']->getLL('solr.notConnected'), \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING, FALSE); $this->content .= $message->render(); return $this->content; }
/** * Breaks content lines into a bullet list * * @param ContentObjectRenderer $contentObject * @param string $str Content string to make into a bullet list * * @return string Processed value */ function breakBulletList($contentObject, $str) { $type = $contentObject->data['layout']; $type = MathUtility::forceIntegerInRange($type, 0, 3); $tConf = $this->configuration['bulletlist.'][$type . '.']; $cParts = explode(chr(10), $str); $lines = array(); $c = 0; foreach ($cParts as $substrs) { if (!strlen($substrs)) { continue; } $c++; $bullet = $tConf['bullet'] ? $tConf['bullet'] : ' - '; $bLen = strlen($bullet); $bullet = substr(str_replace('#', $c, $bullet), 0, $bLen); $secondRow = substr($tConf['secondRow'] ? $tConf['secondRow'] : str_pad('', strlen($bullet), ' '), 0, $bLen); $lines[] = $bullet . $this->breakLines($substrs, chr(10) . $secondRow, Configuration::getPlainTextWith() - $bLen); $blanks = MathUtility::forceIntegerInRange($tConf['blanks'], 0, 1000); if ($blanks) { $lines[] = str_pad('', $blanks - 1, chr(10)); } } return implode(chr(10), $lines); }
/** * This method actually does the processing of files locally * * takes the original file (on remote storages this will be fetched from the remote server) * does the IM magic on the local server by creating a temporary typo3temp/ file * copies the typo3temp/ file to the processing folder of the target storage * removes the typo3temp/ file * * @param TaskInterface $task * @return array */ public function process(TaskInterface $task) { $targetFile = $task->getTargetFile(); // Merge custom configuration with default configuration $configuration = array_merge(array('width' => 64, 'height' => 64), $task->getConfiguration()); $configuration['width'] = Utility\MathUtility::forceIntegerInRange($configuration['width'], 1, 1000); $configuration['height'] = Utility\MathUtility::forceIntegerInRange($configuration['height'], 1, 1000); $originalFileName = $targetFile->getOriginalFile()->getForLocalProcessing(FALSE); // Create a temporary file in typo3temp/ if ($targetFile->getOriginalFile()->getExtension() === 'jpg') { $targetFileExtension = '.jpg'; } else { $targetFileExtension = '.png'; } // Create the thumb filename in typo3temp/preview_....jpg $temporaryFileName = Utility\GeneralUtility::tempnam('preview_') . $targetFileExtension; // Check file extension if ($targetFile->getOriginalFile()->getType() != Resource\File::FILETYPE_IMAGE && !Utility\GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $targetFile->getOriginalFile()->getExtension())) { // Create a default image $this->processor->getTemporaryImageWithText($temporaryFileName, 'Not imagefile!', 'No ext!', $targetFile->getOriginalFile()->getName()); } else { // Create the temporary file if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) { $parameters = '-sample ' . $configuration['width'] . 'x' . $configuration['height'] . ' ' . $this->processor->wrapFileName($originalFileName) . '[0] ' . $this->processor->wrapFileName($temporaryFileName); $cmd = Utility\GeneralUtility::imageMagickCommand('convert', $parameters) . ' 2>&1'; Utility\CommandUtility::exec($cmd); if (!file_exists($temporaryFileName)) { // Create a error gif $this->processor->getTemporaryImageWithText($temporaryFileName, 'No thumb', 'generated!', $targetFile->getOriginalFile()->getName()); } } } return array('filePath' => $temporaryFileName); }
/** * Get all the complex data for the loader. * This return value will be cached and stored in the database * There is no file monitoring for this cache * * @param Loader $autoLoader * @param int $type * * @return array */ public function prepareLoader(Loader $autoLoader, $type) { $slots = []; $slotPath = ExtensionManagementUtility::extPath($autoLoader->getExtensionKey()) . 'Classes/Slots/'; $slotClasses = FileUtility::getBaseFilesInDir($slotPath, 'php'); foreach ($slotClasses as $slot) { $slotClass = ClassNamingUtility::getFqnByPath($autoLoader->getVendorName(), $autoLoader->getExtensionKey(), 'Slots/' . $slot); if (!$autoLoader->isInstantiableClass($slotClass)) { continue; } $methods = ReflectionUtility::getPublicMethods($slotClass); foreach ($methods as $methodReflection) { /** @var MethodReflection $methodReflection */ $tagConfiguration = ReflectionUtility::getTagConfiguration($methodReflection, ['signalClass', 'signalName', 'signalPriority']); foreach ($tagConfiguration['signalClass'] as $key => $signalClass) { if (!isset($tagConfiguration['signalName'][$key])) { continue; } $priority = isset($tagConfiguration['signalPriority'][$key]) ? $tagConfiguration['signalPriority'][$key] : 0; $priority = MathUtility::forceIntegerInRange($priority, 0, 100); $slots[$priority][] = ['signalClassName' => trim($signalClass, '\\'), 'signalName' => $tagConfiguration['signalName'][$key], 'slotClassNameOrObject' => $slotClass, 'slotMethodName' => $methodReflection->getName()]; } } } $slots = $this->flattenSlotsByPriority($slots); return $slots; }
/** * 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; }
/** * The main method of the PlugIn * * @access public * * @param string $content: The PlugIn content * @param array $conf: The PlugIn configuration * * @return string The content that is displayed on the website */ public function main($content, $conf) { $this->init($conf); // Merge configuration with conf array of toolbox. $this->conf = tx_dlf_helper::array_merge_recursive_overrule($this->cObj->data['conf'], $this->conf); // Load current document. $this->loadDocument(); if ($this->doc === NULL || $this->doc->numPages < 1 || empty($this->conf['fileGrpFulltext'])) { // Quit without doing anything if required variables are not set. return $content; } else { // Set default values if not set. // page may be integer or string (physical page attribute) if ((int) $this->piVars['page'] > 0 || empty($this->piVars['page'])) { $this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1); } else { $this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalPages); } $this->piVars['double'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['double'], 0, 1, 0); } // Load template file. if (!empty($this->conf['templateFile'])) { $this->template = $this->cObj->getSubpart($this->cObj->fileResource($this->conf['templateFile']), '###TEMPLATE###'); } else { $this->template = $this->cObj->getSubpart($this->cObj->fileResource('EXT:dlf/plugins/toolbox/tools/fulltext/template.tmpl'), '###TEMPLATE###'); } $fullTextFile = $this->doc->physicalPagesInfo[$this->doc->physicalPages[$this->piVars['page']]]['files'][$this->conf['fileGrpFulltext']]; if (!empty($fullTextFile)) { $markerArray['###FULLTEXT_SELECT###'] = '<a class="select switchoff" id="tx-dlf-tools-fulltext" title="" data-dic="fulltext-on:' . $this->pi_getLL('fulltext-on', '', TRUE) . ';fulltext-off:' . $this->pi_getLL('fulltext-off', '', TRUE) . '"></a>'; } else { $markerArray['###FULLTEXT_SELECT###'] = $this->pi_getLL('fulltext-not-available', '', TRUE); } $content .= $this->cObj->substituteMarkerArray($this->template, $markerArray); return $this->pi_wrapInBaseClass($content); }
/** * Get focus point information * * @param $uid * * @return array|FALSE|NULL */ protected function getCurrentFocusPoint($uid) { $row = GlobalUtility::getDatabaseConnection()->exec_SELECTgetSingleRow('focus_point_x, focus_point_y', 'sys_file_metadata', 'uid=' . $uid); $row['focus_point_x'] = MathUtility::forceIntegerInRange((int) $row['focus_point_x'], -100, 100, 0); $row['focus_point_y'] = MathUtility::forceIntegerInRange((int) $row['focus_point_y'], -100, 100, 0); return $row; }
/** * Construct a status * * All values must be given as constructor arguments. * All strings should be localized. * * @param string $title Status title, eg. "Deprecation log" * @param string $value Status value, eg. "Disabled" * @param string $message Optional message further describing the title/value combination * Example:, eg "The deprecation log is important and does foo, to disable it do bar" * @param integer $severity A severity level. Use one of the constants above! */ public function __construct($title, $value, $message = '', $severity = self::OK) { $this->title = (string) $title; $this->value = (string) $value; $this->message = (string) $message; $this->severity = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($severity, self::NOTICE, self::ERROR, self::OK); }
/** * @param array $arguments * @param \Closure $renderChildrenClosure * @param RenderingContextInterface $renderingContext * * @return string */ public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) { $title = $arguments['title']; $message = $arguments['message']; $state = MathUtility::forceIntegerInRange($arguments['state'], -2, 2, -2); $iconName = $arguments['iconName']; $disableIcon = $arguments['disableIcon']; if ($message === null) { $messageTemplate = $renderChildrenClosure(); } else { $messageTemplate = htmlspecialchars($message); } $classes = [self::STATE_NOTICE => 'notice', self::STATE_INFO => 'info', self::STATE_OK => 'success', self::STATE_WARNING => 'warning', self::STATE_ERROR => 'danger']; $icons = [self::STATE_NOTICE => 'lightbulb-o', self::STATE_INFO => 'info', self::STATE_OK => 'check', self::STATE_WARNING => 'exclamation', self::STATE_ERROR => 'times']; $stateClass = $classes[$state]; $icon = $icons[$state]; if ($iconName !== null) { $icon = $iconName; } $iconTemplate = ''; if (!$disableIcon) { $iconTemplate = '' . '<div class="media-left">' . '<span class="fa-stack fa-lg callout-icon">' . '<i class="fa fa-circle fa-stack-2x"></i>' . '<i class="fa fa-' . htmlspecialchars($icon) . ' fa-stack-1x"></i>' . '</span>' . '</div>'; } $titleTemplate = ''; if ($title !== null) { $titleTemplate = '<h4 class="callout-title">' . htmlspecialchars($title) . '</h4>'; } return '<div class="callout callout-' . htmlspecialchars($stateClass) . '">' . '<div class="media">' . $iconTemplate . '<div class="media-body">' . $titleTemplate . '<div class="callout-body">' . $messageTemplate . '</div>' . '</div>' . '</div>' . '</div>'; }
/** * The main method of the PlugIn * * @access public * * @param string $content: The PlugIn content * @param array $conf: The PlugIn configuration * * @return string The content that is displayed on the website */ public function main($content, $conf) { $this->init($conf); // Merge configuration with conf array of toolbox. $this->conf = tx_dlf_helper::array_merge_recursive_overrule($this->cObj->data['conf'], $this->conf); // Load current document. $this->loadDocument(); if ($this->doc === NULL || $this->doc->numPages < 1 || empty($this->conf['fileGrpDownload'])) { // Quit without doing anything if required variables are not set. return $content; } else { // Set default values if not set. // page may be integer or string (physical page attribute) if ((int) $this->piVars['page'] > 0 || empty($this->piVars['page'])) { $this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1); } else { $this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalPages); } $this->piVars['double'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['double'], 0, 1, 0); } // Load template file. if (!empty($this->conf['templateFile'])) { $this->template = $this->cObj->getSubpart($this->cObj->fileResource($this->conf['templateFile']), '###TEMPLATE###'); } else { $this->template = $this->cObj->getSubpart($this->cObj->fileResource('EXT:dlf/plugins/toolbox/tools/pdf/template.tmpl'), '###TEMPLATE###'); } // Get single page downloads. $markerArray['###PAGE###'] = $this->getPageLink(); // Get work download. $markerArray['###WORK###'] = $this->getWorkLink(); $content .= $this->cObj->substituteMarkerArray($this->template, $markerArray); return $this->pi_wrapInBaseClass($content); }
/** * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'FALSE' then the $zeroValue is applied. * * @param integer $theInt Input value * @param integer $min Lower limit * @param integer $max Higher limit * @param integer $zeroValue Default value if input is FALSE. * @return integer The input value forced into the boundaries of $min and $max * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Math::forceIntegerInRange() instead */ public static function intInRange($theInt, $min, $max = 2000000000, $zeroValue = 0) { if (tx_rnbase_util_TYPO3::isTYPO62OrHigher()) { return \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($theInt, $min, $max, $zeroValue); } elseif (tx_rnbase_util_TYPO3::isTYPO46OrHigher()) { return t3lib_utility_Math::forceIntegerInRange($theInt, $min, $max, $zeroValue); } else { return t3lib_div::intInRange($theInt, $min, $max, $zeroValue); } }
/** * Find orphan records * VERY CPU and memory intensive since it will look up the whole page tree! * * @return array */ public function main() { // Initialize result array: $resultArray = array('message' => $this->cli_help['name'] . LF . LF . $this->cli_help['description'], 'headers' => array('deleted' => array('Index of deleted records', 'These are records from the page tree having the deleted-flag set. The --AUTOFIX option will flush them completely!', 1)), 'deleted' => array()); $startingPoint = $this->cli_isArg('--pid') ? \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->cli_argValue('--pid'), 0) : 0; $depth = $this->cli_isArg('--depth') ? \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->cli_argValue('--depth'), 0) : 1000; $this->genTree($startingPoint, $depth, (int) $this->cli_argValue('--echotree')); $resultArray['deleted'] = $this->recStats['deleted']; return $resultArray; }
/** * @param array $arguments * @param \Closure $renderChildrenClosure * @param RenderingContextInterface $renderingContext * * @return string */ public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) { $maximumNumberOfResultPages = $arguments['maximumNumberOfResultPages']; $numberOfResults = $arguments['numberOfResults']; $resultsPerPage = $arguments['resultsPerPage']; $currentPage = $arguments['currentPage']; $freeIndexUid = $arguments['freeIndexUid']; if ($resultsPerPage <= 0) { $resultsPerPage = 10; } $pageCount = (int) ceil($numberOfResults / $resultsPerPage); // only show the result browser if more than one page is needed if ($pageCount === 1) { return ''; } // Check if $currentPage is in range $currentPage = MathUtility::forceIntegerInRange($currentPage, 0, $pageCount - 1); $content = ''; // prev page // show on all pages after the 1st one if ($currentPage > 0) { $label = LocalizationUtility::translate('displayResults.previous', 'IndexedSearch'); $content .= '<li>' . self::makecurrentPageSelector_link($label, $currentPage - 1, $freeIndexUid) . '</li>'; } // Check if $maximumNumberOfResultPages is in range $maximumNumberOfResultPages = MathUtility::forceIntegerInRange($maximumNumberOfResultPages, 1, $pageCount, 10); // Assume $currentPage is in the middle and calculate the index limits of the result page listing $minPage = $currentPage - (int) floor($maximumNumberOfResultPages / 2); $maxPage = $minPage + $maximumNumberOfResultPages - 1; // Check if the indexes are within the page limits if ($minPage < 0) { $maxPage -= $minPage; $minPage = 0; } elseif ($maxPage >= $pageCount) { $minPage -= $maxPage - $pageCount + 1; $maxPage = $pageCount - 1; } $pageLabel = LocalizationUtility::translate('displayResults.page', 'IndexedSearch'); for ($a = $minPage; $a <= $maxPage; $a++) { $label = trim($pageLabel . ' ' . ($a + 1)); $label = self::makecurrentPageSelector_link($label, $a, $freeIndexUid); if ($a === $currentPage) { $content .= '<li class="tx-indexedsearch-browselist-currentPage"><strong>' . $label . '</strong></li>'; } else { $content .= '<li>' . $label . '</li>'; } } // next link if ($currentPage < $pageCount - 1) { $label = LocalizationUtility::translate('displayResults.next', 'IndexedSearch'); $content .= '<li>' . self::makecurrentPageSelector_link($label, $currentPage + 1, $freeIndexUid) . '</li>'; } return '<ul class="tx-indexedsearch-browsebox">' . $content . '</ul>'; }
/** * Forces the integer $theInt into the boundaries of $min and $max. * If the $theInt is 'FALSE' then the $zeroValue is applied. * * @param integer $theInt Input value * @param integer $min Lower limit * @param integer $max Higher limit * @param integer $zeroValue Default value if input is FALSE. * @return integer The input value forced into the boundaries of $min and $max */ public static function forceIntegerInRange($theInt, $min, $max = 2000000000, $zeroValue = 0) { $result = ''; if (self::isEqualOrHigherSixZero()) { $result = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($theInt, $min, $max, $zeroValue); } elseif (class_exists('t3lib_utility_Math')) { $result = t3lib_utility_Math::forceIntegerInRange($theInt, $min, $max, $zeroValue); } else { $result = t3lib_div::intInRange($theInt, $min, $max, $zeroValue); } return $result; }
/** * Set the point (between -100 and 100) * * @param int $x * @param int $y * @return void */ public function setCurrentPoint($x, $y) { $values = ['focus_point_x' => MathUtility::forceIntegerInRange($x, -100, 100, 0), 'focus_point_y' => MathUtility::forceIntegerInRange($y, -100, 100, 0)]; GlobalUtility::getDatabaseConnection()->exec_UPDATEquery('sys_file_reference', 'uid=' . $this->getReferenceUid(), $values); // save also to the file $reference = ResourceFactory::getInstance()->getFileReferenceObject($this->getReferenceUid()); $fileUid = $reference->getOriginalFile()->getUid(); $row = GlobalUtility::getDatabaseConnection()->exec_SELECTgetSingleRow('*', 'sys_file_metadata', 'file=' . $fileUid); if ($row) { GlobalUtility::getDatabaseConnection()->exec_UPDATEquery('sys_file_metadata', 'uid=' . $row['uid'], $values); } }
/** * Render t3editor element * * @return array As defined in initializeResultArray() of AbstractNode */ public function render() { $resultArray = $this->initializeResultArray(); $parameterArray = $this->globalOptions['parameterArray']; $rows = MathUtility::forceIntegerInRange($parameterArray['fieldConf']['config']['rows'] ?: 10, 1, 40); $t3editor = GeneralUtility::makeInstance(T3editor::class); $t3editor->setMode(isset($parameterArray['fieldConf']['config']['format']) ? $parameterArray['fieldConf']['config']['format'] : T3editor::MODE_MIXED); $doc = $GLOBALS['SOBE']->doc; $attributes = 'rows="' . $rows . '"' . ' wrap="off"' . ' style="width:96%; height: 60%;"' . ' onchange="' . $parameterArray['fieldChangeFunc']['TBE_EDITOR_fieldChanged'] . '" '; $resultArray['html'] = $t3editor->getCodeEditor($parameterArray['itemFormElName'], 'text-monospace enable-tab', $parameterArray['itemFormElValue'], $attributes, $this->globalOptions['table'] . ' > ' . $this->globalOptions['fieldName'], array('target' => 0)); $resultArray['html'] .= $t3editor->getJavascriptCode($doc); return $resultArray; }
/** * This method actually does the processing of files locally * * takes the original file (on remote storages this will be fetched from the remote server) * does the IM magic on the local server by creating a temporary typo3temp/ file * copies the typo3temp/ file to the processing folder of the target storage * removes the typo3temp/ file * * The returned array has the following structure: * width => 100 * height => 200 * filePath => /some/path * * If filePath isn't set but width and height are the original file is used as ProcessedFile * with the returned width and height. This is for example useful for SVG images. * * @param TaskInterface $task * @return array|NULL */ public function process(TaskInterface $task) { $sourceFile = $task->getSourceFile(); // Merge custom configuration with default configuration $configuration = array_merge(array('width' => 64, 'height' => 64), $task->getConfiguration()); $configuration['width'] = MathUtility::forceIntegerInRange($configuration['width'], 1); $configuration['height'] = MathUtility::forceIntegerInRange($configuration['height'], 1); // Do not scale up if the source file has a size and the target size is larger if ($sourceFile->getProperty('width') > 0 && $sourceFile->getProperty('height') > 0 && $configuration['width'] > $sourceFile->getProperty('width') && $configuration['height'] > $sourceFile->getProperty('height')) { return NULL; } return $this->generatePreviewFromFile($sourceFile, $configuration, $this->getTemporaryFilePath($task)); }
/** * Find orphan records * VERY CPU and memory intensive since it will look up the whole page tree! * * @return array */ public function main() { // Initialize result array: $resultArray = array('message' => $this->cli_help['name'] . LF . LF . $this->cli_help['description'], 'headers' => array('dirty' => array('', '', 2)), 'dirty' => array()); $startingPoint = $this->cli_isArg('--pid') ? \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->cli_argValue('--pid'), 0) : 0; $depth = $this->cli_isArg('--depth') ? \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->cli_argValue('--depth'), 0) : 1000; $this->cleanFlexForm_dirtyFields =& $resultArray['dirty']; // Do not repair flexform data in deleted records. $this->genTree_traverseDeleted = false; $this->genTree($startingPoint, $depth, (int) $this->cli_argValue('--echotree'), 'main_parseTreeCallBack'); asort($resultArray); return $resultArray; }
/** * generates a copy of a give image with a specific width * * @param string $src path of the image to convert * @param integer $width width to convert the image to * @param string $format format of the resulting copy * @param string $quality quality of the resulting copy * @param string $treatIdAsReference given src argument is a sys_file_reference record * @param array $params additional params for the image rendering * @return string */ public function getImgResource($src, $width, $format, $quality, $treatIdAsReference, $params = null) { $setup = ['width' => $width, 'treatIdAsReference' => $treatIdAsReference]; if (false === empty($format)) { $setup['ext'] = $format; } if (0 < intval($quality)) { $quality = MathUtility::forceIntegerInRange($quality, 10, 100, 75); $setup['params'] .= ' -quality ' . $quality; } if ('BE' === TYPO3_MODE && '../' === substr($src, 0, 3)) { $src = substr($src, 3); } return $this->contentObject->getImgResource($src, $setup); }
/** * Set and validate minitems and maxitems in config * * @param array $result Result array * @param string $fieldName Current handle field name * @return array Modified item array * @return array */ protected function initializeMinMaxItems(array $result, $fieldName) { $config = $result['processedTca']['columns'][$fieldName]['config']; $minItems = 0; if (isset($config['minitems'])) { $minItems = MathUtility::forceIntegerInRange($config['minitems'], 0); } $result['processedTca']['columns'][$fieldName]['config']['minitems'] = $minItems; $maxItems = 100000; if (isset($config['maxitems'])) { $maxItems = MathUtility::forceIntegerInRange($config['maxitems'], 1); } $result['processedTca']['columns'][$fieldName]['config']['maxitems'] = $maxItems; return $result; }
/** * Creates a magic image * * @param Resource\File $imageFileObject: the original image file * @param array $fileConfiguration (width, height) * @return Resource\ProcessedFile */ public function createMagicImage(Resource\File $imageFileObject, array $fileConfiguration) { // Process dimensions $maxWidth = MathUtility::forceIntegerInRange($fileConfiguration['width'], 0, $this->magicImageMaximumWidth); $maxHeight = MathUtility::forceIntegerInRange($fileConfiguration['height'], 0, $this->magicImageMaximumHeight); if (!$maxWidth) { $maxWidth = $this->magicImageMaximumWidth; } if (!$maxHeight) { $maxHeight = $this->magicImageMaximumHeight; } // Create the magic image $magicImage = $imageFileObject->process(Resource\ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, array('width' => $maxWidth . 'm', 'height' => $maxHeight . 'm')); return $magicImage; }
/** * 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']); }
/** * Main render function * * @param integer $maximumNumberOfResultPages The number of page links shown * @param integer $numberOfResults Total number of results * @param integer $resultsPerPage Number of results per page * @param integer $currentPage The current page starting with 0 * @param string|NULL $freeIndexUid List of integers pointing to free indexing configurations to search. -1 represents no filtering, 0 represents TYPO3 pages only, any number above zero is a uid of an indexing configuration! * @return string The content */ public function render($maximumNumberOfResultPages, $numberOfResults, $resultsPerPage, $currentPage = 0, $freeIndexUid = NULL) { $pageCount = ceil($numberOfResults / $resultsPerPage); // only show the result browser if more than one page is needed if ($pageCount === 1) { return ''; } // Check if $currentPage is in range $currentPage = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($currentPage, 0, $pageCount - 1); $content = ''; // prev page // show on all pages after the 1st one if ($currentPage > 0) { $label = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('displayResults.previous', 'IndexedSearch'); $content .= '<li>' . $this->makecurrentPageSelector_link($label, $currentPage - 1, $freeIndexUid) . '</li>'; } // Check if $maximumNumberOfResultPages is in range $maximumNumberOfResultPages = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($maximumNumberOfResultPages, 1, $pageCount, 10); // Assume $currentPage is in the middle and calculate the index limits of the result page listing $minPage = $currentPage - floor($maximumNumberOfResultPages / 2); $maxPage = $minPage + $maximumNumberOfResultPages - 1; // Check if the indexes are within the page limits if ($minPage < 0) { $maxPage -= $minPage; $minPage = 0; } elseif ($maxPage >= $pageCount) { $minPage -= $maxPage - $pageCount + 1; $maxPage = $pageCount - 1; } $pageLabel = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('displayResults.page', 'IndexedSearch'); for ($a = $minPage; $a <= $maxPage; $a++) { $label = trim($pageLabel . ' ' . ($a + 1)); $label = $this->makecurrentPageSelector_link($label, $a, $freeIndexUid); if ($a === $currentPage) { $content .= '<li class="tx-indexedsearch-browselist-currentPage"><strong>' . $label . '</strong></li>'; } else { $content .= '<li>' . $label . '</li>'; } } // next link if ($currentPage < $pageCount - 1) { $label = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('displayResults.next', 'IndexedSearch'); $content .= '<li>' . $this->makecurrentPageSelector_link($label, $currentPage + 1, $freeIndexUid) . '</li>'; } return '<ul class="tx-indexedsearch-browsebox">' . $content . '</ul>'; }
/** * Rendering the cObject, HRULER * * @param array $conf Array of TypoScript properties * @return string Output */ public function render($conf = array()) { $lineThickness = isset($conf['lineThickness.']) ? $this->cObj->stdWrap($conf['lineThickness'], $conf['lineThickness.']) : $conf['lineThickness']; $lineThickness = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($lineThickness, 1, 50); $lineColor = isset($conf['lineColor.']) ? $this->cObj->stdWrap($conf['lineColor'], $conf['lineColor.']) : $conf['lineColor']; if (!$lineColor) { $lineColor = 'black'; } $spaceBefore = isset($conf['spaceLeft.']) ? intval($this->cObj->stdWrap($conf['spaceLeft'], $conf['spaceLeft.'])) : intval($conf['spaceLeft']); $spaceAfter = isset($conf['spaceRight.']) ? intval($this->cObj->stdWrap($conf['spaceRight'], $conf['spaceRight.'])) : intval($conf['spaceRight']); $tableWidth = isset($conf['tableWidth.']) ? intval($this->cObj->stdWrap($conf['tableWidth'], $conf['tableWidth.'])) : intval($conf['tableWidth']); if (!$tableWidth) { $tableWidth = '99%'; } $theValue = ''; $theValue .= '<table border="0" cellspacing="0" cellpadding="0" width="' . htmlspecialchars($tableWidth) . '" summary=""><tr>'; if ($spaceBefore) { $theValue .= '<td width="1"> <img src="' . $GLOBALS['TSFE']->absRefPrefix . 'clear.gif" width="' . $spaceBefore . '" height="1" alt="" title="" /> </td>'; } $theValue .= '<td bgcolor="' . $lineColor . '"> <img src="' . $GLOBALS['TSFE']->absRefPrefix . 'clear.gif" width="1" height="' . $lineThickness . '" alt="" title="" /> </td>'; if ($spaceAfter) { $theValue .= '<td width="1"> <img src="' . $GLOBALS['TSFE']->absRefPrefix . 'clear.gif" width="' . $spaceAfter . '" height="1" alt="" title="" /> </td>'; } $theValue .= '</tr></table>'; if (isset($conf['stdWrap.'])) { $theValue = $this->cObj->stdWrap($theValue, $conf['stdWrap.']); } return $theValue; }
/** * Process file * Create static image preview for Online Media item when possible * * @param FileProcessingService $fileProcessingService * @param AbstractDriver $driver * @param ProcessedFile $processedFile * @param File $file * @param string $taskType * @param array $configuration */ public function processFile(FileProcessingService $fileProcessingService, AbstractDriver $driver, ProcessedFile $processedFile, File $file, $taskType, array $configuration) { if ($taskType !== 'Image.Preview' && $taskType !== 'Image.CropScaleMask') { return; } // Check if processing is needed if (!$this->needsReprocessing($processedFile)) { return; } // Check if there is a OnlineMediaHelper registered for this file type $helper = OnlineMediaHelperRegistry::getInstance()->getOnlineMediaHelper($file); if ($helper === false) { return; } // Check if helper provides a preview image $temporaryFileName = $helper->getPreviewImage($file); if (empty($temporaryFileName) || !file_exists($temporaryFileName)) { return; } $temporaryFileNameForResizedThumb = uniqid(PATH_site . 'typo3temp/var/transient/online_media_' . $file->getHashedIdentifier()) . '.jpg'; switch ($taskType) { case 'Image.Preview': // Merge custom configuration with default configuration $configuration = array_merge(array('width' => 64, 'height' => 64), $configuration); $configuration['width'] = MathUtility::forceIntegerInRange($configuration['width'], 1, 1000); $configuration['height'] = MathUtility::forceIntegerInRange($configuration['height'], 1, 1000); $this->resizeImage($temporaryFileName, $temporaryFileNameForResizedThumb, $configuration); break; case 'Image.CropScaleMask': $this->cropScaleImage($temporaryFileName, $temporaryFileNameForResizedThumb, $configuration); break; } GeneralUtility::unlink_tempfile($temporaryFileName); if (is_file($temporaryFileNameForResizedThumb)) { $processedFile->setName($this->getTargetFileName($processedFile)); list($width, $height) = getimagesize($temporaryFileNameForResizedThumb); $processedFile->updateProperties(array('width' => $width, 'height' => $height, 'size' => filesize($temporaryFileNameForResizedThumb), 'checksum' => $processedFile->getTask()->getConfigurationChecksum())); $processedFile->updateWithLocalFile($temporaryFileNameForResizedThumb); GeneralUtility::unlink_tempfile($temporaryFileNameForResizedThumb); /** @var ProcessedFileRepository $processedFileRepository */ $processedFileRepository = GeneralUtility::makeInstance(ProcessedFileRepository::class); $processedFileRepository->add($processedFile); } }
/** * hook that is called when no prepared command was found * * @param string $command the command to be executed * @param string $table the table of the record * @param int $id the ID of the record * @param mixed $value the value containing the data * @param bool $commandIsProcessed can be set so that other hooks or * @param DataHandler $tcemainObj reference to the main tcemain object * @return void */ public function processCmdmap($command, $table, $id, $value, &$commandIsProcessed, DataHandler $tcemainObj) { // custom command "version" if ($command == 'version') { $commandIsProcessed = TRUE; $action = (string) $value['action']; $comment = !empty($value['comment']) ? $value['comment'] : ''; $notificationAlternativeRecipients = isset($value['notificationAlternativeRecipients']) && is_array($value['notificationAlternativeRecipients']) ? $value['notificationAlternativeRecipients'] : array(); switch ($action) { case 'new': // check if page / branch versioning is needed, // or if "element" version can be used $versionizeTree = -1; if (isset($value['treeLevels'])) { $versionizeTree = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($value['treeLevels'], -1, 100); } if ($table == 'pages' && $versionizeTree >= 0) { $this->versionizePages($id, $value['label'], $versionizeTree, $tcemainObj); } else { $tcemainObj->versionizeRecord($table, $id, $value['label']); } break; case 'swap': $this->version_swap($table, $id, $value['swapWith'], $value['swapIntoWS'], $tcemainObj, $comment, TRUE, $notificationAlternativeRecipients); break; case 'clearWSID': $this->version_clearWSID($table, $id, FALSE, $tcemainObj); break; case 'flush': $this->version_clearWSID($table, $id, TRUE, $tcemainObj); break; case 'setStage': $elementIds = GeneralUtility::trimExplode(',', $id, TRUE); foreach ($elementIds as $elementId) { $this->version_setStage($table, $elementId, $value['stageId'], $comment, TRUE, $tcemainObj, $notificationAlternativeRecipients); } break; default: // Do nothing } } }
/** * The main method of the PlugIn * * @access public * * @param string $content: The PlugIn content * @param array $conf: The PlugIn configuration * * @return string The content that is displayed on the website */ public function main($content, $conf) { $this->init($conf); // Load current document. $this->loadDocument(); if ($this->doc === NULL) { // Quit without doing anything if required variables are not set. return $content; } else { // Set default values if not set. $this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['page'], 1, $this->doc->numPages, 1); } $toc = $this->doc->tableOfContents; // Load template file. if (!empty($this->conf['templateFile'])) { $this->template = $this->cObj->getSubpart($this->cObj->fileResource($this->conf['templateFile']), '###TEMPLATE###'); } else { $this->template = $this->cObj->getSubpart($this->cObj->fileResource('EXT:dfgviewer/plugins/newspaper-years/template.tmpl'), '###TEMPLATE###'); } // Get subpart templates $subparts['template'] = $this->template; $subparts['year'] = $this->cObj->getSubpart($subparts['template'], '###LISTYEAR###'); $years = $toc[0]['children']; $subYearPartContent = ''; foreach ($years as $id => $year) { $yearLabel = empty($year['label']) ? $year['orderlabel'] : $year['label']; if (empty($yearLabel)) { // if neither order nor orderlabel is set, use the id... $yearLabel = (string) $id; } if (strlen($year['points']) > 0) { $linkConf = array('useCacheHash' => 1, 'parameter' => $this->conf['targetPid'], 'additionalParams' => '&' . $this->prefixId . '[id]=' . urlencode($year['points']), 'title' => $yearLabel); $yearText = $this->cObj->typoLink($yearLabel, $linkConf); } else { $yearText = $yearLabel; } $yearArray = array('###YEARNAME###' => $yearText); $subYearPartContent .= $this->cObj->substituteMarkerArray($subparts['year'], $yearArray); } // fill the week markers return $this->cObj->substituteSubpart($subparts['template'], '###LISTYEAR###', $subYearPartContent); }
/** * Render t3editor element * * @return array As defined in initializeResultArray() of AbstractNode */ public function render() { $this->getLanguageService()->includeLLFile('EXT:t3editor/Resources/Private/Language/locallang.xlf'); $this->relExtPath = ExtensionManagementUtility::extRelPath('t3editor'); $this->resultArray = $this->initializeResultArray(); $parameterArray = $this->data['parameterArray']; $rows = MathUtility::forceIntegerInRange($parameterArray['fieldConf']['config']['rows'] ?: 10, 1, 40); $this->setMode(isset($parameterArray['fieldConf']['config']['format']) ? $parameterArray['fieldConf']['config']['format'] : T3editor::MODE_MIXED); $attributes = array(); $attributes['rows'] = $rows; $attributes['wrap'] = 'off'; $attributes['style'] = 'width:100%;'; $attributes['onchange'] = GeneralUtility::quoteJSvalue($parameterArray['fieldChangeFunc']['TBE_EDITOR_fieldChanged']); $attributeString = ''; foreach ($attributes as $param => $value) { $attributeString .= $param . '="' . htmlspecialchars($value) . '" '; } $this->resultArray['html'] = $this->getHTMLCodeForEditor($parameterArray['itemFormElName'], 'text-monospace enable-tab', $parameterArray['itemFormElValue'], $attributeString, $this->data['tableName'] . ' > ' . $this->data['fieldName'], array('target' => 0)); $this->initJavascriptCode(); return $this->resultArray; }
/** * Rendering the cObject FILES * * @param array $conf Array of TypoScript properties * @return string Output */ public function render($conf = array()) { if (!empty($conf['if.']) && !$this->cObj->checkIf($conf['if.'])) { return ''; } $fileCollector = $this->findAndSortFiles($conf); $fileObjects = $fileCollector->getFiles(); $availableFileObjectCount = count($fileObjects); // optionSplit applied to conf to allow different settings per file $splitConf = $GLOBALS['TSFE']->tmpl->splitConfArray($conf, $availableFileObjectCount); $start = 0; if (!empty($conf['begin'])) { $start = (int) $conf['begin']; } if (!empty($conf['begin.'])) { $start = (int) $this->cObj->stdWrap($start, $conf['begin.']); } $start = MathUtility::forceIntegerInRange($start, 0, $availableFileObjectCount); $limit = $availableFileObjectCount; if (!empty($conf['maxItems'])) { $limit = (int) $conf['maxItems']; } if (!empty($conf['maxItems.'])) { $limit = (int) $this->cObj->stdWrap($limit, $conf['maxItems.']); } $end = MathUtility::forceIntegerInRange($start + $limit, $start, $availableFileObjectCount); $GLOBALS['TSFE']->register['FILES_COUNT'] = min($limit, $availableFileObjectCount); $fileObjectCounter = 0; $keys = array_keys($fileObjects); $content = ''; for ($i = $start; $i < $end; $i++) { $key = $keys[$i]; $fileObject = $fileObjects[$key]; $GLOBALS['TSFE']->register['FILE_NUM_CURRENT'] = $fileObjectCounter; $this->cObj->setCurrentFile($fileObject); $content .= $this->cObj->cObjGetSingle($splitConf[$key]['renderObj'], $splitConf[$key]['renderObj.']); $fileObjectCounter++; } return $this->cObj->stdWrap($content, $conf['stdWrap.']); }
/** * main render function * * @param array $details an array with the browser settings * @param integer $maximumNumberOfResultPages * @param integer $numberOfResults * @param integer $resultsPerPage * @param integer $currentPage * @return the content */ public function render($maximumNumberOfResultPages, $numberOfResults, $resultsPerPage, $currentPage = 1) { $maximumNumberOfResultPages = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($maximumNumberOfResultPages, 1, 100, 10); $pageCount = ceil($numberOfResults / $resultsPerPage); $content = ''; // only show the result browser if more than one page is needed if ($pageCount > 1) { $currentPage = intval($currentPage); // prev page // show on all pages after the 1st one if ($currentPage > 0) { $label = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('displayResults.previous', 'indexed_search'); $content .= '<li>' . $this->makecurrentPageSelector_link($label, $currentPage - 1, $freeIndexUid) . '</li>'; } for ($a = 0; $a < $pageCount; $a++) { $min = max(0, $currentPage + 1 - ceil($maximumNumberOfResultPages / 2)); $max = $min + $maximumNumberOfResultPages; if ($max > $pageCount) { $min = $min - ($max - $pageCount); } if ($a >= $min && $a < $max) { $label = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('displayResults.page', 'indexed_search'); $label = trim($label . ' ' . ($a + 1)); $label = $this->makecurrentPageSelector_link($label, $a, $freeIndexUid); if ($a == $currentPage) { $content .= '<li class="tx-indexedsearch-browselist-currentPage"><strong>' . $label . '</strong></li>'; } else { $content .= '<li>' . $label . '</li>'; } } } // next link if ($currentPage + 1 < $pageCount) { $label = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('displayResults.next', 'indexed_search'); $content = '<li>' . $this->makecurrentPageSelector_link($label, $currentPage + 1, $freeIndexUid) . '</li>'; } $content = '<ul class="tx-indexedsearch-browsebox">' . $content . '</ul>'; } return $content; }