Example #1
0
 /**
  * Adds a key to the storage or removes existing key
  *
  * @param string $key The key
  * @return void
  * @see \TYPO3\CMS\Rsaauth\Storage\AbstractStorage::put()
  */
 public function put($key)
 {
     if ($key == null) {
         // Remove existing key
         list($keyId) = $_SESSION['tx_rsaauth_key'];
         if (MathUtility::canBeInterpretedAsInteger($keyId)) {
             $this->databaseConnection->exec_DELETEquery('tx_rsaauth_keys', 'uid=' . $keyId);
             unset($_SESSION['tx_rsaauth_key']);
         }
     } else {
         // Add key
         // Get split point. First part is always smaller than the second
         // because it goes to the file system
         $keyLength = strlen($key);
         $splitPoint = rand((int) ($keyLength / 10), (int) ($keyLength / 2));
         // Get key parts
         $keyPart1 = substr($key, 0, $splitPoint);
         $keyPart2 = substr($key, $splitPoint);
         // Store part of the key in the database
         //
         // Notice: we may not use TCEmain below to insert key part into the
         // table because TCEmain requires a valid BE user!
         $time = $GLOBALS['EXEC_TIME'];
         $this->databaseConnection->exec_INSERTquery('tx_rsaauth_keys', array('pid' => 0, 'crdate' => $time, 'key_value' => $keyPart2));
         $keyId = $this->databaseConnection->sql_insert_id();
         // Store another part in session
         $_SESSION['tx_rsaauth_key'] = array($keyId, $keyPart1);
     }
     // Remove expired keys (more than 30 minutes old)
     $this->databaseConnection->exec_DELETEquery('tx_rsaauth_keys', 'crdate<' . ($GLOBALS['EXEC_TIME'] - 30 * 60));
 }
Example #2
0
 /**
  * Constructor
  */
 public function __construct()
 {
     // we check for existence of our targetDirectory
     if (!is_dir(PATH_site . $this->targetDirectory)) {
         GeneralUtility::mkdir_deep(PATH_site . $this->targetDirectory);
     }
     // if enabled, we check whether we should auto-create the .htaccess file
     if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['generateApacheHtaccess']) {
         // check whether .htaccess exists
         $htaccessPath = PATH_site . $this->targetDirectory . '.htaccess';
         if (!file_exists($htaccessPath)) {
             GeneralUtility::writeFile($htaccessPath, $this->htaccessTemplate);
         }
     }
     // decide whether we should create gzipped versions or not
     $compressionLevel = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['compressionLevel'];
     // we need zlib for gzencode()
     if (extension_loaded('zlib') && $compressionLevel) {
         $this->createGzipped = true;
         // $compressionLevel can also be TRUE
         if (MathUtility::canBeInterpretedAsInteger($compressionLevel)) {
             $this->gzipCompressionLevel = (int) $compressionLevel;
         }
     }
     $this->setInitialPaths();
 }
Example #3
0
 /**
  * Generates news site map.
  *
  * @return    void
  */
 protected function generateSitemapContent()
 {
     if (count($this->pidList) > 0) {
         $languageCondition = '';
         $language = GeneralUtility::_GP('L');
         if (MathUtility::canBeInterpretedAsInteger($language)) {
             $languageCondition = ' AND sys_language_uid=' . $language;
         }
         /** @noinspection PhpUndefinedMethodInspection */
         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'tx_t3blog_post', 'pid IN (' . implode(',', $this->pidList) . ')' . $languageCondition . $this->cObj->enableFields('tx_t3blog_post'), '', 'date DESC', $this->offset . ',' . $this->limit);
         /** @noinspection PhpUndefinedMethodInspection */
         $rowCount = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
         /** @noinspection PhpUndefinedMethodInspection */
         while (FALSE !== ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {
             if ($url = $this->getPostItemUrl($row)) {
                 echo $this->renderer->renderEntry($url, $row['title'], $row['date'], '', $row['tagClouds']);
             }
         }
         /** @noinspection PhpUndefinedMethodInspection */
         $GLOBALS['TYPO3_DB']->sql_free_result($res);
         if ($rowCount === 0) {
             echo '<!-- It appears that there are no tx_t3blog_post entries. If your ' . 'blog storage sysfolder is outside of the rootline, you may ' . 'want to use the dd_googlesitemap.skipRootlineCheck=1 TS ' . 'setup option. Beware: it is insecure and may cause certain ' . 'undesired effects! Better move your news sysfolder ' . 'inside the rootline! -->';
         }
     }
 }
 /**
  * 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');
         }
     }
 }
    /**
     * Check needed framework configuration
     *
     * @param array $settings
     * @return void
     * @throws InvalidConfigurationException
     */
    public static function validateFrameworkConfiguration(array $settings)
    {
        if (empty($settings['persistence']['storagePid']) || !MathUtility::canBeInterpretedAsInteger($settings['persistence']['storagePid'])) {
            throw new InvalidConfigurationException('No valid persistence storage pid setting detected.
				Make sure plugin.tx_t3extblog.persistence.storagePid is a valid page uid.', 1344375015);
        }
    }
 /**
  * @param array $tsConfig
  * @param array $userArguments
  *
  * @return string
  */
 public function main(array $tsConfig, $userArguments = [])
 {
     $url = $tsConfig['url'];
     $regExpCurlyBraceOpen = preg_quote(rawurlencode('{'), '@');
     $regExpCurlyBraceClose = preg_quote(rawurlencode('}'), '@');
     $pattern = "@{$regExpCurlyBraceOpen}product{$regExpCurlyBraceClose}@i";
     // Return if argument to be replaced is not set!
     if (!preg_match($pattern, $url)) {
         return $tsConfig['TAG'];
     }
     /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $db */
     $db = $GLOBALS['TYPO3_DB'];
     /**
      * <a href="' . $finalTagParts['url'] . '"' . $finalTagParts['targetParams'] . $finalTagParts['aTagParams'] . '>
      *
      * @see http://docs.typo3.org/typo3cms/TyposcriptReference/Functions/Typolink/Index.html
      */
     $return = '<a href="%1$s"%2$s>';
     $product = false;
     // get necessary params to apply; replace in url
     if ($page = $db->exec_SELECTgetSingleRow('tx_product', 'pages', 'uid=' . $GLOBALS['TSFE']->id)) {
         if (MathUtility::canBeInterpretedAsInteger($page['tx_product']) && MathUtility::convertToPositiveInteger($page['tx_product'])) {
             $product = MathUtility::convertToPositiveInteger($page['tx_product']);
         }
     }
     /** @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $contentObject */
     $contentObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
     $url = str_ireplace($GLOBALS['TSFE']->baseUrl, '', $contentObject->getTypoLink_URL($userArguments['targetPid'], $product ? ['product' => $product] : []));
     return sprintf($return, $url, $tsConfig['targetParams'] . $tsConfig['aTagParams']);
 }
Example #7
0
 /**
  * @param int $value
  * @param int $bit
  * @return bool
  */
 public function render($value = null, $bit = 0)
 {
     if ($value === null) {
         $value = $this->renderChildren();
     }
     return \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($bit) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($value) ? ((int) $bit & (int) $value) > 0 : false;
 }
 /**
  * Verify TS objects
  *
  * @param array $propertyArray
  * @param string $parentType
  * @param string $parentValue
  * @return array
  * @todo Define visibility
  */
 public function verify_TSobjects($propertyArray, $parentType, $parentValue)
 {
     $TSobjTable = array('PAGE' => array('prop' => array('typeNum' => 'int', '1,2,3' => 'COBJ', 'bodyTag' => 'string')), 'TEXT' => array('prop' => array('value' => 'string')), 'HTML' => array('prop' => array('value' => 'stdWrap')), 'stdWrap' => array('prop' => array('field' => 'string', 'current' => 'boolean')));
     $TSobjDataTypes = array('COBJ' => 'TEXT,CONTENT', 'PAGE' => 'PAGE', 'stdWrap' => '');
     if ($parentType) {
         if (isset($TSobjDataTypes[$parentType]) && (!$TSobjDataTypes[$parentType] || \TYPO3\CMS\Core\Utility\GeneralUtility::inlist($TSobjDataTypes[$parentType], $parentValue))) {
             $ObjectKind = $parentValue;
         } else {
             // Object kind is "" if it should be known.
             $ObjectKind = '';
         }
     } else {
         // If parentType is not given, then it can be anything. Free.
         $ObjectKind = $parentValue;
     }
     if ($ObjectKind && is_array($TSobjTable[$ObjectKind])) {
         $result = array();
         if (is_array($propertyArray)) {
             foreach ($propertyArray as $key => $val) {
                 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($key)) {
                     // If num-arrays
                     $result[$key] = $TSobjTable[$ObjectKind]['prop']['1,2,3'];
                 } else {
                     // standard
                     $result[$key] = $TSobjTable[$ObjectKind]['prop'][$key];
                 }
             }
         }
         return $result;
     }
 }
 /**
  * Import command
  *
  * @param string $icsCalendarUri
  * @param int    $pid
  */
 public function importCommand($icsCalendarUri = null, $pid = null)
 {
     if ($icsCalendarUri === null || !filter_var($icsCalendarUri, FILTER_VALIDATE_URL)) {
         $this->enqueueMessage('You have to enter a valid URL to the iCalendar ICS', 'Error', FlashMessage::ERROR);
         return;
     }
     if (!MathUtility::canBeInterpretedAsInteger($pid)) {
         $this->enqueueMessage('You have to enter a valid PID for the new created elements', 'Error', FlashMessage::ERROR);
         return;
     }
     // fetch external URI and write to file
     $this->enqueueMessage('Start to checkout the calendar: ' . $icsCalendarUri, 'Calendar', FlashMessage::INFO);
     $relativeIcalFile = 'typo3temp/ical.' . GeneralUtility::shortMD5($icsCalendarUri) . '.ical';
     $absoluteIcalFile = GeneralUtility::getFileAbsFileName($relativeIcalFile);
     $content = GeneralUtility::getUrl($icsCalendarUri);
     GeneralUtility::writeFile($absoluteIcalFile, $content);
     // get Events from file
     $icalEvents = $this->getIcalEvents($absoluteIcalFile);
     $this->enqueueMessage('Found ' . sizeof($icalEvents) . ' events in the given calendar', 'Items', FlashMessage::INFO);
     $events = $this->prepareEvents($icalEvents);
     $this->enqueueMessage('Found ' . sizeof($events) . ' events in ' . $icsCalendarUri, 'Items', FlashMessage::INFO);
     /** @var Dispatcher $signalSlotDispatcher */
     $signalSlotDispatcher = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
     $this->enqueueMessage('Send the ' . __CLASS__ . '::importCommand signal for each event.', 'Signal', FlashMessage::INFO);
     foreach ($events as $event) {
         $arguments = ['event' => $event, 'commandController' => $this, 'pid' => $pid, 'handled' => false];
         $signalSlotDispatcher->dispatch(__CLASS__, 'importCommand', $arguments);
     }
 }
Example #10
0
 /**
  * This method forwards the call to Bootstrap's run() method. This method is invoked by the mod.php
  * function of TYPO3.
  *
  * @param string $moduleSignature
  * @throws \RuntimeException
  * @return boolean TRUE, if the request request could be dispatched
  * @see run()
  */
 public function callModule($moduleSignature)
 {
     if (!isset($GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature])) {
         return FALSE;
     }
     $moduleConfiguration = $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature];
     // Check permissions and exit if the user has no permission for entry
     $GLOBALS['BE_USER']->modAccess($moduleConfiguration, TRUE);
     $id = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('id');
     if ($id && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($id)) {
         // Check page access
         $permClause = $GLOBALS['BE_USER']->getPagePermsClause(TRUE);
         $access = is_array(\TYPO3\CMS\Backend\Utility\BackendUtility::readPageAccess((int) $id, $permClause));
         if (!$access) {
             throw new \RuntimeException('You don\'t have access to this page', 1289917924);
         }
     }
     // BACK_PATH is the path from the typo3/ directory from within the
     // directory containing the controller file. We are using mod.php dispatcher
     // and thus we are already within typo3/ because we call typo3/mod.php
     $GLOBALS['BACK_PATH'] = '';
     $configuration = array('extensionName' => $moduleConfiguration['extensionName'], 'pluginName' => $moduleSignature);
     if (isset($moduleConfiguration['vendorName'])) {
         $configuration['vendorName'] = $moduleConfiguration['vendorName'];
     }
     $bootstrap = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Core\\BootstrapInterface');
     $content = $bootstrap->run('', $configuration);
     print $content;
     return TRUE;
 }
Example #11
0
 /**
  * @param mixed $value
  * @return bool
  */
 public function render($value = '')
 {
     if ($value === null) {
         $value = $this->renderChildren();
     }
     return \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($value);
 }
Example #12
0
 /**
  * Clears URL cache for records.
  *
  * Currently only clears URL cache for pages but should also clear alias
  * cache for records later.
  *
  * @param array $parameters
  * @return void
  */
 public function clearUrlCacheForRecords(array $parameters)
 {
     if ($parameters['table'] == 'pages' && MathUtility::canBeInterpretedAsInteger($parameters['uid'])) {
         $cacheInstance = CacheFactory::getCache();
         $cacheInstance->clearUrlCacheForPage($parameters['uid']);
     }
 }
Example #13
0
 /**
  * Get the Records
  *
  * @param integer                                        $startPage
  * @param array                                          $basePages
  * @param Tx_GoogleServices_Controller_SitemapController $obj
  *
  * @throws Exception
  * @return Tx_GoogleServices_Domain_Model_Node
  */
 public function getRecords($startPage, $basePages, Tx_GoogleServices_Controller_SitemapController $obj)
 {
     $nodes = array();
     if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('tt_news')) {
         return $nodes;
     }
     if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($GLOBALS['TSFE']->tmpl->setup['plugin.']['tt_news.']['singlePid'])) {
         throw new Exception('You have to set tt_news singlePid.');
     }
     $singlePid = intval($GLOBALS['TSFE']->tmpl->setup['plugin.']['tt_news.']['singlePid']);
     $news = $this->getRecordsByField('tt_news', 'pid', implode(',', $basePages));
     foreach ($news as $record) {
         // Alternative Single PID
         $alternativeSinglePid = $this->alternativeSinglePid($record['uid']);
         $linkPid = $alternativeSinglePid ? $alternativeSinglePid : $singlePid;
         // Build URL
         $url = $obj->getUriBuilder()->setArguments(array('tx_ttnews' => array('tt_news' => $record['uid'])))->setTargetPageUid($linkPid)->build();
         // can't generate a valid url
         if (!strlen($url)) {
             continue;
         }
         // Build Node
         $node = new Tx_GoogleServices_Domain_Model_Node();
         $node->setLoc($url);
         $node->setPriority($this->getPriority($record));
         $node->setChangefreq('monthly');
         $node->setLastmod($this->getModifiedDate($record));
         $nodes[] = $node;
     }
     return $nodes;
 }
Example #14
0
 /**
  * Clears path and URL caches if the page was deleted.
  *
  * @param string $table
  * @param string|int $id
  */
 public function processCmdmap_deleteAction($table, $id)
 {
     if (($table === 'pages' || $table === 'pages_language_overlay') && MathUtility::canBeInterpretedAsInteger($id)) {
         $this->cache->clearPathCacheForPage((int) $id);
         $this->cache->clearUrlCacheForPage((int) $id);
     }
 }
Example #15
0
 /**
  * This method is called by a hook in the TYPO3 core when a record is saved.
  *
  * We use the tx_linkhandler for backend "save & show" button to display records on the configured detail view page.
  *
  * @param  string  $status                                  Type of database operation i.e. new/update.
  * @param  string  $table                                   The table currently being processed.
  * @param  integer $id                                      The records id (if any).
  * @param  array   $fieldArray                              The field names and their values to be processed (passed by reference).
  * @param  \TYPO3\CMS\Core\DataHandling\DataHandler $pObj   Reference to the parent object.
  */
 public function processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $pObj)
 {
     if (isset($GLOBALS['_POST']['_savedokview_x'])) {
         $settingFound = FALSE;
         $currentPageId = \TYPO3\CMS\Core\Utility\MathUtility::convertToPositiveInteger($GLOBALS['_POST']['popViewId']);
         $rootPageData = $this->getRootPage($currentPageId);
         $defaultPageId = isset($rootPageData) && array_key_exists('uid', $rootPageData) ? $rootPageData['uid'] : $currentPageId;
         $pagesTsConfig = \TYPO3\CMS\Backend\Utility\BackendUtility::getPagesTSconfig($currentPageId);
         $handlerConfigurationStruct = $pagesTsConfig['mod.']['tx_linkhandler.'];
         // search for the current setting for given table
         foreach ($pagesTsConfig['mod.']['tx_linkhandler.'] as $key => $handler) {
             if (is_array($handler) && $handler['listTables'] === $table) {
                 $settingFound = TRUE;
                 $selectedConfiguration = $key;
                 break;
             }
         }
         if ($settingFound) {
             $l18nPointer = array_key_exists('transOrigPointerField', $GLOBALS['TCA'][$table]['ctrl']) ? $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] : '';
             if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($id)) {
                 $id = $pObj->substNEWwithIDs[$id];
             }
             if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($id)) {
                 $recordArray = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord($table, $id);
             } else {
                 $recordArray = $fieldArray;
             }
             if (array_key_exists('previewPageId', $handlerConfigurationStruct[$selectedConfiguration]) && \TYPO3\CMS\Core\Utility\MathUtility::convertToPositiveInteger($handlerConfigurationStruct[$selectedConfiguration]['previewPageId']) > 0) {
                 $previewPageId = \TYPO3\CMS\Core\Utility\MathUtility::convertToPositiveInteger($handlerConfigurationStruct[$selectedConfiguration]['previewPageId']);
             } else {
                 $previewPageId = \TYPO3\CMS\Core\Utility\MathUtility::convertToPositiveInteger($defaultPageId);
             }
             if ($GLOBALS['BE_USER']->workspace != 0) {
                 $timeToLiveHours = intval($GLOBALS['BE_USER']->getTSConfigVal('options.workspaces.previewLinkTTLHours')) ? intval($GLOBALS['BE_USER']->getTSConfigVal('options.workspaces.previewLinkTTLHours')) : 24 * 2;
                 $wsPreviewValue = ';' . $GLOBALS['BE_USER']->workspace . ':' . $GLOBALS['BE_USER']->user['uid'] . ':' . 60 * 60 * $timeToLiveHours;
                 // get record UID for
                 if (array_key_exists($l18nPointer, $recordArray) && $recordArray[$l18nPointer] > 0 && $recordArray['sys_language_uid'] > 0) {
                     $id = $recordArray[$l18nPointer];
                 } elseif (array_key_exists('t3ver_oid', $recordArray) && intval($recordArray['t3ver_oid']) > 0) {
                     // this makes no sense because we already receive the UID of the WS-Placeholder which will be the real record in the LIVE-WS
                     $id = $recordArray['t3ver_oid'];
                 }
             } else {
                 $wsPreviewValue = '';
                 if (array_key_exists($l18nPointer, $recordArray) && $recordArray[$l18nPointer] > 0 && $recordArray['sys_language_uid'] > 0) {
                     $id = $recordArray[$l18nPointer];
                 }
             }
             $previewDomainRootline = \TYPO3\CMS\Backend\Utility\BackendUtility::BEgetRootLine($previewPageId);
             $previewDomain = \TYPO3\CMS\Backend\Utility\BackendUtility::getViewDomain($previewPageId, $previewDomainRootline);
             $linkParamValue = 'record:' . $table . ':' . $id;
             $queryString = '&eID=linkhandlerPreview&linkParams=' . urlencode($linkParamValue . $wsPreviewValue);
             $languageParam = '&L=' . $recordArray['sys_language_uid'];
             $queryString .= $languageParam . '&authCode=' . \TYPO3\CMS\Core\Utility\GeneralUtility::stdAuthCode($linkParamValue . $wsPreviewValue . intval($recordArray['sys_language_uid']), '', 32);
             $GLOBALS['_POST']['viewUrl'] = $previewDomain . '/index.php?id=' . $previewPageId . $queryString . '&y=';
             $GLOBALS['_POST']['popViewId_addParams'] = $queryString;
         }
     }
 }
 private function _get($key)
 {
     $value = is_array($this->configuration) && array_key_exists($key, $this->configuration) ? $this->configuration[$key] : null;
     if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($value)) {
         return (int) $value;
     }
     return $value;
 }
 /**
  * Enrich the processed record information with the resolved title
  *
  * @param array $result Incoming result array
  * @return array Modified array
  */
 public function addData(array $result)
 {
     if (!$result['isInlineChild']) {
         return $result;
     }
     $result['isOnSymmetricSide'] = MathUtility::canBeInterpretedAsInteger($result['databaseRow']['uid']) && $result['inlineParentConfig']['symmetric_field'] && $result['inlineParentUid'] == $result['databaseRow'][$result['inlineParentConfig']['symmetric_field']][0];
     return $result;
 }
 /**
  * Render method
  *
  * @return string
  */
 public function render()
 {
     if (MathUtility::canBeInterpretedAsInteger($this->arguments['value']) === true) {
         return $this->renderThenChild();
     } else {
         return $this->renderElseChild();
     }
 }
Example #19
0
 /**
  * Validates whether the submitted language parameter can be
  * interpreted as integer value.
  *
  * @param stdClass $parameters
  * @return integer|NULL
  */
 protected function validateLanguageParameter(\stdClass $parameters)
 {
     $language = NULL;
     if (isset($parameters->language) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($parameters->language)) {
         $language = $parameters->language;
     }
     return $language;
 }
 /**
  * Validates the additional fields' values
  *
  * @param array $submittedData
  * @param \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $schedulerModule
  * @return bool
  */
 public function validateAdditionalFields(array &$submittedData, \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $schedulerModule)
 {
     $isValid = TRUE;
     if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($submittedData['storagePid']) || $submittedData['storagePid'] < 0) {
         $isValid = FALSE;
         $schedulerModule->addMessage('You must set a storage pid', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
     }
     return $isValid;
 }
    /**
     * Hook that determines whether a user has access to modify a table.
     * We "abuse" it here to actually check if access is allowed to sys_file_metadata.
     *
     *
     * @param int &$accessAllowed Whether the user has access to modify a table
     * @param string $table The name of the table to be modified
     * @param DataHandler $parent The calling parent object
     * @throws \UnexpectedValueException
     * @return void
     */
    public function checkModifyAccessList(&$accessAllowed, $table, DataHandler $parent)
    {
        if ($table === 'sys_file_metadata') {
            if (isset($parent->cmdmap[$table]) && is_array($parent->cmdmap[$table])) {
                foreach ($parent->cmdmap[$table] as $id => $command) {
                    if (empty($id) || !MathUtility::canBeInterpretedAsInteger($id)) {
                        throw new \UnexpectedValueException('Integer expected for data manipulation command.
							This can only happen in the case of an attack attempt or when something went horribly wrong.
							To not compromise security, we exit here.', 1399982816);
                    }
                    $fileMetadataRecord = BackendUtility::getRecord('sys_file_metadata', $id);
                    $accessAllowed = $this->checkFileWriteAccessForFileMetaData($fileMetadataRecord);
                    if (!$accessAllowed) {
                        // If for any item in the array, access is not allowed, we deny the whole operation
                        break;
                    }
                }
            }
            if (isset($parent->datamap[$table]) && is_array($parent->datamap[$table])) {
                foreach ($parent->datamap[$table] as $id => $data) {
                    $recordAccessAllowed = FALSE;
                    if (strpos($id, 'NEW') === FALSE) {
                        $fileMetadataRecord = BackendUtility::getRecord('sys_file_metadata', $id);
                        if ($fileMetadataRecord !== NULL) {
                            if ($parent->isImporting && empty($fileMetadataRecord['file'])) {
                                // When importing the record was added with an empty file relation as first step
                                $recordAccessAllowed = TRUE;
                            } else {
                                $recordAccessAllowed = $this->checkFileWriteAccessForFileMetaData($fileMetadataRecord);
                            }
                        }
                    } else {
                        // For new records record access is allowed
                        $recordAccessAllowed = TRUE;
                    }
                    if (isset($data['file'])) {
                        if ($parent->isImporting && empty($data['file'])) {
                            // When importing the record will be created with an empty file relation as first step
                            $dataAccessAllowed = TRUE;
                        } elseif (empty($data['file'])) {
                            $dataAccessAllowed = FALSE;
                        } else {
                            $dataAccessAllowed = $this->checkFileWriteAccessForFileMetaData($data);
                        }
                    } else {
                        $dataAccessAllowed = TRUE;
                    }
                    if (!$recordAccessAllowed || !$dataAccessAllowed) {
                        // If for any item in the array, access is not allowed, we deny the whole operation
                        $accessAllowed = FALSE;
                        break;
                    }
                }
            }
        }
    }
 /**
  * Validate additional fields
  *
  * @param array $submittedData Reference to the array containing the data submitted by the user
  * @param \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $parentObject Reference to the calling object (Scheduler's BE module)
  * @return bool True if validation was ok (or selected class is not relevant), false otherwise
  */
 public function validateAdditionalFields(array &$submittedData, \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $parentObject)
 {
     $value = $submittedData['scheduler_fileStorageIndexing_storage'];
     if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($value)) {
         return false;
     } elseif (\TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->getStorageObject($submittedData['scheduler_fileStorageIndexing_storage']) !== null) {
         return true;
     }
     return false;
 }
 /**
  * Creates a backend user.
  *
  * See class documentation for more details.
  */
 public function run()
 {
     $backendUserModelUid = $this->getProcessSettings('modelUid');
     // Checking if something was given in "settings.modelUid".
     if (!MathUtility::canBeInterpretedAsInteger($backendUserModelUid)) {
         $this->addError('duplication_process.backend_user_creation.error.must_be_integer', 1432908303);
         return;
     }
     // Checking if the given backend user is valid.
     /** @var BackendUserRepository $backendUserRepository */
     $backendUserRepository = $this->objectManager->get(BackendUserRepository::class);
     /** @var BackendUser $backendUser */
     $backendUser = $backendUserRepository->findByUid($backendUserModelUid);
     if (!$backendUser) {
         $this->addError('duplication_process.backend_user_creation.error.wrong_uid', 1432908427, ['d' => $backendUserModelUid]);
         return;
     }
     // Creating a new instance of backend user, and copying the values from the model one.
     /** @var BackendUser $backendUserClone */
     $backendUserClone = GeneralUtility::makeInstance(BackendUser::class);
     $backendUserClone->setPid($this->getDuplicatedPageUid());
     $backendUserName = Core::getCleanedValueFromTCA('be_users', 'username', $backendUser->getUserName(), 0);
     $backendUserClone->setUserName($backendUserName);
     /** @var PersistenceManager $persistenceManager */
     $persistenceManager = $this->objectManager->get(PersistenceManager::class);
     $persistenceManager->add($backendUserClone);
     $persistenceManager->persistAll();
     $this->addNotice('duplication_process.backend_user_creation.notice.success', 1432909010, ['s' => $backendUserClone->getUserName()]);
     // Managing base mount.
     $duplicatedPageUid = $this->getDuplicatedPageUid();
     if ($duplicatedPageUid) {
         $this->fixDataBaseMountPointForBackendUser($backendUserClone, $this->getDuplicatedPageUid());
     }
     // Managing file mount.
     $fileMountUid = $this->getProcessSettings('sysFileMountUid');
     if ($fileMountUid) {
         /** @var FileMountRepository $fileMountRepository */
         $fileMountRepository = $this->objectManager->get(FileMountRepository::class);
         /** @var FileMount $fileMount */
         $fileMount = $fileMountRepository->findByUid($fileMountUid);
         if (!$fileMount) {
             $this->addWarning('duplication_process.backend_user_creation.warning.wrong_mount_point_uid', 1432909510, ['s' => $fileMountUid]);
         } else {
             $flag = $this->fixFileMountForBackendUser($backendUserClone, $fileMount);
             if ($flag) {
                 $this->addNotice('duplication_process.backend_user_creation.notice.filemount_association_success', 1432909851, ['s' => $fileMount->getTitle()]);
             }
         }
     }
     // Checking if "settings.createdRecordName" can be used, use self::DEFAULT_CREATED_RECORD_NAME otherwise.
     $backendUserUid = $backendUserClone->getUid();
     $createdRecordName = $this->getProcessSettings('createdRecordName');
     $createdRecordName = !empty($createdRecordName) ? $createdRecordName : self::DEFAULT_CREATED_RECORD_NAME;
     $this->setDuplicationDataValue($createdRecordName, $backendUserUid);
 }
 /**
  * Get List of workspace changes
  *
  * @param \stdClass $parameter
  * @return array $data
  */
 public function getWorkspaceInfos($parameter)
 {
     // To avoid too much work we use -1 to indicate that every page is relevant
     $pageId = $parameter->id > 0 ? $parameter->id : -1;
     if (!isset($parameter->language) || !\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($parameter->language)) {
         $parameter->language = null;
     }
     $versions = $this->getWorkspaceService()->selectVersionsInWorkspace($this->getCurrentWorkspace(), 0, -99, $pageId, $parameter->depth, 'tables_select', $parameter->language);
     $data = $this->getGridDataService()->generateGridListFromVersions($versions, $parameter, $this->getCurrentWorkspace());
     return $data;
 }
 /**
  * Find ProcessedFile by Uid
  *
  * @param int $uid
  * @return object|\TYPO3\CMS\Core\Resource\ProcessedFile
  * @throws \RuntimeException
  * @throws \InvalidArgumentException
  */
 public function findByUid($uid)
 {
     if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($uid)) {
         throw new \InvalidArgumentException('uid has to be integer.', 1316779798);
     }
     $row = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', $this->table, 'uid=' . (int) $uid);
     if (empty($row) || !is_array($row)) {
         throw new \RuntimeException('Could not find row with uid "' . $uid . '" in table ' . $this->table, 1314354065);
     }
     return $this->createDomainObject($row);
 }
 /**
  * Wrapper for t3lib_div::testInt and \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($var)
  * @param mixed $var
  * @return boolean
  */
 public static function isInteger($var)
 {
     if (tx_rnbase_util_TYPO3::isTYPO62OrHigher()) {
         $isInteger = \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($var);
     } elseif (tx_rnbase_util_TYPO3::isTYPO46OrHigher()) {
         $isInteger = t3lib_utility_Math::canBeInterpretedAsInteger($var);
     } else {
         $isInteger = t3lib_div::testInt($var);
     }
     return $isInteger;
 }
Example #27
0
    /**
     * Renders an ajax-enabled text field. Also adds required JS
     *
     * @param string $fieldname The fieldname in the form
     * @param string $table The table we render this selector for
     * @param string $field The field we render this selector for
     * @param array $row The row which is currently edited
     * @param array $config The TSconfig of the field
     * @return string The HTML code for the selector
     */
    public function renderSuggestSelector($fieldname, $table, $field, array $row, array $config)
    {
        /** @var $iconFactory IconFactory */
        $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
        $languageService = $this->getLanguageService();
        $isFlexFormField = $GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'flex';
        if ($isFlexFormField) {
            $fieldPattern = 'data[' . $table . '][' . $row['uid'] . '][';
            $flexformField = str_replace($fieldPattern, '', $fieldname);
            $flexformField = substr($flexformField, 0, -1);
            $field = str_replace(array(']['), '|', $flexformField);
        }
        // Get minimumCharacters from TCA
        $minChars = 0;
        if (isset($config['fieldConf']['config']['wizards']['suggest']['default']['minimumCharacters'])) {
            $minChars = (int) $config['fieldConf']['config']['wizards']['suggest']['default']['minimumCharacters'];
        }
        // Overwrite it with minimumCharacters from TSConfig (TCEFORM) if given
        if (isset($config['fieldTSConfig']['suggest.']['default.']['minimumCharacters'])) {
            $minChars = (int) $config['fieldTSConfig']['suggest.']['default.']['minimumCharacters'];
        }
        $minChars = $minChars > 0 ? $minChars : 2;
        // fetch the TCA field type to hand it over to the JS class
        $type = '';
        if (isset($config['fieldConf']['config']['type'])) {
            $type = $config['fieldConf']['config']['type'];
        }
        $jsRow = '';
        if ($isFlexFormField || !MathUtility::canBeInterpretedAsInteger($row['uid'])) {
            // Ff we have a new record, we hand that row over to JS.
            // This way we can properly retrieve the configuration of our wizard
            // if it is shown in a flexform
            $jsRow = serialize($row);
        }
        $selector = '
		<div class="autocomplete t3-form-suggest-container">
			<div class="input-group">
				<span class="input-group-addon">' . $iconFactory->getIcon('actions-search', Icon::SIZE_SMALL)->render() . '</span>
				<input type="search" class="t3-form-suggest form-control"
					placeholder="' . $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.findRecord') . '"
					data-fieldname="' . $fieldname . '"
					data-table="' . $table . '"
					data-field="' . $field . '"
					data-uid="' . $row['uid'] . '"
					data-pid="' . $row['pid'] . '"
					data-fieldtype="' . $type . '"
					data-minchars="' . $minChars . '"
					data-recorddata="' . htmlspecialchars($jsRow) . '"
				/>
			</div>
		</div>';
        return $selector;
    }
Example #28
0
 /**
  * get the image
  *
  * @param $src
  * @param $treatIdAsReference
  *
  * @return \TYPO3\CMS\Core\Resource\File|FileInterface|\TYPO3\CMS\Core\Resource\FileReference|\TYPO3\CMS\Core\Resource\Folder
  * @throws \TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException
  * @throws \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException
  */
 protected function getImage($src, $treatIdAsReference)
 {
     $resourceFactory = ResourceFactory::getInstance();
     if (!MathUtility::canBeInterpretedAsInteger($src)) {
         return $resourceFactory->retrieveFileOrFolderObject($src);
     }
     if (!$treatIdAsReference) {
         return $resourceFactory->getFileObject($src);
     }
     $image = $resourceFactory->getFileReferenceObject($src);
     return $image->getOriginalFile();
 }
 /**
  * @todo: rewrite function doc
  * @param string $cacheToken The token of the cache file to get the current state of the duplication.
  * @param string $index      The index of the process which will be executed (e.g. "pagesDuplication" or "treeUidAssociation").
  * @param bool   $checkAjax  If true, will call the function "checkAjaxCall" of the current process class.
  * @return    array The result of the function, may contain these keys :
  *                           - "success":      "False" if error(s) occurred, "true" otherwise.
  *                           - "result":       The result of the execution function. Contains useful data for further duplication process steps.
  *                           - "errorMessage": If error(s) occurred, will contain an error message. If the current user is admin, it will get a detailed message.
  */
 private function processDuplication($cacheToken, $index, $checkAjax = false)
 {
     // Getting configuration in cache file.
     $cache = CacheManager::getCacheInstance(CacheManager::CACHE_PROCESSED);
     $cacheData = $cache->get($cacheToken);
     $cacheData = json_decode($cacheData, true);
     /** @var Result $result */
     $result = $this->objectManager->get(Result::class);
     try {
         if (isset($cacheData['duplicationData']['modelPageUid']) && MathUtility::canBeInterpretedAsInteger($cacheData['duplicationData']['modelPageUid']) && $cacheData['duplicationData']['modelPageUid'] > 0) {
             $duplicationConfiguration = AbstractDuplicationProcess::getCleanedDuplicationConfiguration($cacheData['duplicationData']['modelPageUid']);
             if (isset($duplicationConfiguration[$index])) {
                 if (isset($duplicationConfiguration[$index]['class'])) {
                     $class = $duplicationConfiguration[$index]['class'];
                     $settings = array_key_exists('settings', $duplicationConfiguration[$index]) ? is_array($duplicationConfiguration[$index]['settings']) ? $duplicationConfiguration[$index]['settings'] : [] : [];
                     // Calling the function of the current process step.
                     /** @var AbstractDuplicationProcess $class */
                     $class = GeneralUtility::makeInstance($class, $cacheData['duplicationData'], $settings, $cacheData['fieldsValues']);
                     if ($class instanceof AbstractDuplicationProcess) {
                         // @todo : else
                         //                            if (!$checkAjax || ($checkAjax && $class->checkAjaxCall())) {
                         $class->run();
                         $fieldsValues = $class->getFieldsValues();
                         $result->merge($class->getResult());
                         // Saving modified data in cache.
                         $configuration = ['duplicationData' => $class->getDuplicationData(), 'fieldsValues' => $fieldsValues];
                         $cache->set($cacheToken, json_encode($configuration));
                         //                            }
                     } else {
                         throw new \Exception('The class "' . $class . '" must extend "' . AbstractDuplicationProcess::class . '".', 1422887215);
                     }
                 } else {
                     throw new \Exception('The class is not set for the duplication configuration named "' . $index . '".', 1422885526);
                 }
             } else {
                 throw new \Exception('Trying to get the duplication configuration named "' . $index . '" but it does not exist.', 1422885438);
             }
         } else {
             throw new \Exception('The duplication data must contain a valid index for "modelPageUid".', 1422885697);
         }
     } catch (\Exception $exception) {
         /** @var BackendUserAuthentication $backendUser */
         $backendUser = $GLOBALS['BE_USER'];
         // Setting up error message. If the user is admin, it gets a detailed message.
         if ($backendUser->isAdmin()) {
             $errorMessage = Core::translate('duplication_process.process_error_detailed') . ' ' . $exception->getMessage();
         } else {
             $errorMessage = Core::translate('duplication_process.process_error_single');
         }
         $result->addError(new Error($errorMessage, 1431985617));
     }
     return Core::convertValidationResultToArray($result);
 }
 /**
  * Tests if the input can be interpreted as integer.
  *
  * @param mixed $var Any input variable to test
  * @return boolean Returns TRUE if string is an integer
  */
 public static function canBeInterpretedAsInteger($var)
 {
     $result = '';
     if (self::isEqualOrHigherSixZero()) {
         $result = \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($var);
     } elseif (class_exists('t3lib_utility_Math')) {
         $result = t3lib_utility_Math::canBeInterpretedAsInteger($var);
     } else {
         $result = t3lib_div::testInt($var);
     }
     return $result;
 }