/** * Determines whether the URL matches a domain * in the sys_domain databse table. * * @param string $url Absolute URL which needs to be checked * @return boolean Whether the URL is considered to be local */ protected function isInLocalDomain($url) { $result = FALSE; if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($url)) { $parsedUrl = parse_url($url); if ($parsedUrl['scheme'] === 'http' || $parsedUrl['scheme'] === 'https') { $host = $parsedUrl['host']; // Removes the last path segment and slash sequences like /// (if given): $path = preg_replace('#/+[^/]*$#', '', $parsedUrl['path']); $cObj = new ContentObjectRenderer(); $localDomains = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('domainName', 'sys_domain', '1=1' . $cObj->enableFields('sys_domain')); if (is_array($localDomains)) { foreach ($localDomains as $localDomain) { // strip trailing slashes (if given) $domainName = rtrim($localDomain['domainName'], '/'); if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($host . $path . '/', $domainName . '/')) { $result = TRUE; break; } } } } } return $result; }
/** * @param $status * @param $table * @param $id * @param $fieldArray * @param $self */ function processDatamap_postProcessFieldArray($status, $table, $id, &$fieldArray, &$self) { if ($table == 'tx_html5videoplayer_domain_model_video') { $data = $fieldArray; if ($status == 'update') { $data = array_merge($GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'tx_html5videoplayer_domain_model_video', 'uid=' . (int) $id), $data); } $vimeoUrl = $data['vimeo']; if (($status == 'update' || $status == 'new') && $vimeoUrl != '' && GeneralUtility::isValidUrl($vimeoUrl)) { if (preg_match('/https?:\\/\\/(?:www\\.)?vimeo.com\\/(?:channels\\/(?:\\w+\\/)?|groups\\/([^\\/]*)\\/videos\\/|album\\/(\\d+)\\/video\\/|)(\\d+)(?:$|\\/|\\?)/i', $vimeoUrl, $matches)) { $videoId = $matches[3]; $videoData = unserialize(GeneralUtility::getUrl('http://vimeo.com/api/v2/video/' . $videoId . '.php')); if (is_array($videoData)) { // We're only interested in index zero. $videoData = $videoData[0]; if (!isset($data['title']) || trim($data['title']) == '') { $fieldArray['title'] = $videoData['title']; } if (!isset($data['description']) || trim($data['description']) == '') { $fieldArray['description'] = $videoData['description']; } if (!isset($data['posterimage']) || trim($data['posterimage']) == '') { $resourceFactory = ResourceFactory::getInstance(); $folder = $resourceFactory->retrieveFileOrFolderObject($this->getUploadFolder()); $thumbnailData = GeneralUtility::getUrl($videoData['thumbnail_large']); $file = $folder->createFile(basename($videoData['thumbnail_large']) . '.jpg'); $file->setContents($thumbnailData); $fieldArray['posterimage'] = 'file:' . $file->getUid(); } } } } } }
/** * Generate Google tool url for sitemap submit */ protected function getGoogleSitemapToolUrl() { $url = $this->toolUrl . urlencode($this->xmlSiteUrl); if (!GeneralUtility::isValidUrl($url)) { return null; } return $url; }
/** * Validate required variables * * @param string $defaultDomain * @throws \TYPO3\CMS\Core\Exception * @return boolean */ protected function validateVariables($defaultDomain) { if (empty($defaultDomain)) { throw new \TYPO3\CMS\Core\Exception('No default domain configured'); } elseif (GeneralUtility::isValidUrl($defaultDomain) === false) { throw new \TYPO3\CMS\Core\Exception('Default domain invalid'); } return true; }
/** * Get url * * @param bool $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all. * @return string */ public function getUrl($relativeToCurrentScript = false) { $url = $this->url; if ($relativeToCurrentScript && !GeneralUtility::isValidUrl($url)) { $absolutePathToContainingFolder = PathUtility::dirname(PATH_site . $url); $pathPart = PathUtility::getRelativePathTo($absolutePathToContainingFolder); $filePart = substr(PATH_site . $url, strlen($absolutePathToContainingFolder) + 1); $url = $pathPart . $filePart; } return $url; }
/** * Validates that a specified field has valid url syntax. * * @param array &$check The TypoScript settings for this error check * @param string $name The field name * @param array &$gp The current GET/POST parameters * @return string The error string */ public function check() { $checkFailed = ''; if (isset($this->gp[$this->formFieldName]) && strlen(trim($this->gp[$this->formFieldName])) > 0) { $valid = \TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($this->gp[$this->formFieldName]); if (!$valid) { $checkFailed = $this->getCheckFailed(); } } return $checkFailed; }
/** * Returns TRUE, if the given property ($propertyValue) is a valid URL / URI. * * If at least one error occurred, the result is FALSE. * * @param mixed $value The value that should be validated * * @return boolean TRUE if the value is valid, FALSE if an error occured */ public function isValid($value) { if (empty($value)) { return TRUE; } if (GeneralUtility::isValidUrl($value) === FALSE) { $this->addError('The given subject was not a valid URL.', 1392679659); return FALSE; } return TRUE; }
/** * Validates the additional fields' values * * @param array $submittedData An array containing the data submitted by the add/edit task form * @param \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $schedulerModule Reference to the scheduler backend module * @return boolean TRUE if validation was ok (or selected class is not relevant), FALSE otherwise */ public function validateAdditionalFields(array &$submittedData, SchedulerModuleController $schedulerModule) { $validInput = TRUE; $urlsToCrawl = GeneralUtility::trimExplode(LF, $submittedData[$this->fieldPrefix . 'UrlsToCrawl'], TRUE); foreach ($urlsToCrawl as $url) { if (!GeneralUtility::isValidUrl($url)) { $validInput = FALSE; break; } } if (empty($submittedData[$this->fieldPrefix . 'UrlsToCrawl']) || !$validInput) { $message = htmlspecialchars($GLOBALS['LANG']->sL('LLL:EXT:minicrawler/locallang.xml:scheduler.error.urlNotValid')); $schedulerModule->addMessage($message, FlashMessage::ERROR); $validInput = FALSE; } return $validInput; }
/** * Modify the given times via the configuration * * @param array $times * @param Configuration $configuration * * @return void */ public function handleConfiguration(array &$times, Configuration $configuration) { $url = $configuration->getExternalIcsUrl(); if (!GeneralUtility::isValidUrl($url)) { HelperUtility::createFlashMessage('Configuration with invalid ICS URL: ' . $url, 'Index ICS URL', FlashMessage::ERROR); return; } $events = $this->icsReaderService->toArray($url); foreach ($events as $event) { /** @var $event ICalEvent */ $startTime = DateTimeUtility::getDaySecondsOfDateTime($event->getStart()); $endTime = DateTimeUtility::getDaySecondsOfDateTime($event->getEnd()); if ($endTime === self::DAY_END) { $endTime = 0; } $entry = ['pid' => 0, 'start_date' => $event->getStart(), 'end_date' => $event->getEnd() ?: $event->getStart(), 'start_time' => $startTime, 'end_time' => $endTime, 'all_day' => $endTime === 0]; $times[] = $entry; } }
/** * Determines the base URL for this driver, from the configuration or * the TypoScript frontend object * * @return void */ protected function determineBaseUrl() { if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($this->absoluteBasePath, PATH_site)) { // use site-relative URLs // TODO add unit test $this->baseUri = substr($this->absoluteBasePath, strlen(PATH_site)); } elseif (isset($this->configuration['baseUri']) && \TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($this->configuration['baseUri'])) { $this->baseUri = rtrim($this->configuration['baseUri'], '/') . '/'; } else { } }
/** * Determines the base URL for this driver, from the configuration or * the TypoScript frontend object * * @return void */ protected function determineBaseUrl() { // only calculate baseURI if the storage does not enforce jumpUrl Script if ($this->hasCapability(ResourceStorage::CAPABILITY_PUBLIC)) { if (GeneralUtility::isFirstPartOfStr($this->absoluteBasePath, PATH_site)) { // use site-relative URLs $temporaryBaseUri = rtrim(PathUtility::stripPathSitePrefix($this->absoluteBasePath), '/'); if ($temporaryBaseUri !== '') { $uriParts = explode('/', $temporaryBaseUri); $uriParts = array_map('rawurlencode', $uriParts); $temporaryBaseUri = implode('/', $uriParts) . '/'; } $this->baseUri = $temporaryBaseUri; } elseif (isset($this->configuration['baseUri']) && GeneralUtility::isValidUrl($this->configuration['baseUri'])) { $this->baseUri = rtrim($this->configuration['baseUri'], '/') . '/'; } } }
/** * Processes a physical unit for the Solr index * * @access protected * * @param tx_dlf_document &$doc: The METS document * @param integer $page: The page number * @param array $physicalUnit: Array of the physical unit to process * * @return integer 0 on success or 1 on failure */ protected static function processPhysical(tx_dlf_document &$doc, $page, array $physicalUnit) { $errors = 0; // Read extension configuration. $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::$extKey]); if (!empty($physicalUnit['files'][$extConf['fileGrpFulltext']])) { $file = $doc->getFileLocation($physicalUnit['files'][$extConf['fileGrpFulltext']]); // Load XML file. if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($file) || version_compare(phpversion(), '5.3.3', '<')) { // Set user-agent to identify self when fetching XML data. if (!empty($extConf['useragent'])) { @ini_set('user_agent', $extConf['useragent']); } // Turn off libxml's error logging. $libxmlErrors = libxml_use_internal_errors(TRUE); // disable entity loading $previousValueOfEntityLoader = libxml_disable_entity_loader(TRUE); // Load XML from file. $xml = simplexml_load_string(file_get_contents($file)); // reset entity loader setting libxml_disable_entity_loader($previousValueOfEntityLoader); // Reset libxml's error logging. libxml_use_internal_errors($libxmlErrors); if ($xml === FALSE) { return 1; } } else { return 1; } // Load class. if (!class_exists('Apache_Solr_Document')) { require_once \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:' . self::$extKey . '/lib/SolrPhpClient/Apache/Solr/Document.php'); } // Create new Solr document. $solrDoc = new Apache_Solr_Document(); // Create unique identifier from document's UID and unit's XML ID. $solrDoc->setField('id', $doc->uid . $physicalUnit['id']); $solrDoc->setField('uid', $doc->uid); $solrDoc->setField('pid', $doc->pid); $solrDoc->setField('page', $page); if (!empty($physicalUnit['files'][$extConf['fileGrpThumbs']])) { $solrDoc->setField('thumbnail', $doc->getFileLocation($physicalUnit['files'][$extConf['fileGrpThumbs']])); } $solrDoc->setField('partof', $doc->parentId); $solrDoc->setField('root', $doc->rootId); $solrDoc->setField('sid', $physicalUnit['id']); $solrDoc->setField('toplevel', FALSE); $solrDoc->setField('type', $physicalUnit['type'], self::$fields['fieldboost']['type']); $solrDoc->setField('fulltext', tx_dlf_alto::getRawText($xml)); try { self::$solr->service->addDocument($solrDoc); } catch (Exception $e) { if (!defined('TYPO3_cliMode')) { $message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', tx_dlf_helper::getLL('flash.solrException', TRUE) . '<br />' . htmlspecialchars($e->getMessage()), tx_dlf_helper::getLL('flash.error', TRUE), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, TRUE); tx_dlf_helper::addMessage($message); } return 1; } } return $errors; }
/** * Load XML file from URL * * @access protected * * @param string $location: The URL of the file to load * * @return boolean TRUE on success or FALSE on failure */ protected function load($location) { // Load XML file. if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($location) || version_compare(phpversion(), '5.3.3', '<')) { // Load extension configuration $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['dlf']); // Set user-agent to identify self when fetching XML data. if (!empty($extConf['useragent'])) { @ini_set('user_agent', $extConf['useragent']); } // Turn off libxml's error logging. $libxmlErrors = libxml_use_internal_errors(TRUE); // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept $previousValueOfEntityLoader = libxml_disable_entity_loader(TRUE); // Load XML from file. $xml = simplexml_load_string(file_get_contents($location)); // reset entity loader setting libxml_disable_entity_loader($previousValueOfEntityLoader); // Reset libxml's error logging. libxml_use_internal_errors($libxmlErrors); // Set some basic properties. if ($xml !== FALSE) { $this->xml = $xml; return TRUE; } else { if (TYPO3_DLOG) { \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_document->load(' . $location . ')] Could not load XML file from "' . $location . '"', self::$extKey, SYSLOG_SEVERITY_ERROR); } } } else { if (TYPO3_DLOG) { \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_document->load(' . $location . ')] Invalid file location "' . $location . '" for document loading', self::$extKey, SYSLOG_SEVERITY_ERROR); } } return FALSE; }
/** * @param array $files * @param boolean $onlyProperties * @throws Exception * @return array|NULL */ public function preprocessImages($files, $onlyProperties = FALSE) { if (TRUE === empty($files)) { return NULL; } if ('BE' === TYPO3_MODE) { $this->simulateFrontendEnvironment(); } $setup = array('width' => $this->arguments['width'], 'height' => $this->arguments['height'], 'minW' => $this->arguments['minWidth'], 'minH' => $this->arguments['minHeight'], 'maxW' => $this->arguments['maxWidth'], 'maxH' => $this->arguments['maxHeight'], 'treatIdAsReference' => FALSE); $images = array(); foreach ($files as $file) { $imageInfo = $this->contentObject->getImgResource($file->getUid(), $setup); $GLOBALS['TSFE']->lastImageInfo = $imageInfo; if (FALSE === is_array($imageInfo)) { throw new Exception('Could not get image resource for "' . htmlspecialchars($file->getCombinedIdentifier()) . '".', 1253191060); } if ((double) substr(TYPO3_version, 0, 3) < 7.1) { $imageInfo[3] = GeneralUtility::png_to_gif_by_imagemagick($imageInfo[3]); } else { $imageInfo[3] = GraphicalFunctions::pngToGifByImagemagick($imageInfo[3]); } $imageInfo[3] = GeneralUtility::png_to_gif_by_imagemagick($imageInfo[3]); $GLOBALS['TSFE']->imagesOnPage[] = $imageInfo[3]; if (TRUE === GeneralUtility::isValidUrl($imageInfo[3])) { $imageSource = $imageInfo[3]; } else { $imageSource = $GLOBALS['TSFE']->absRefPrefix . GeneralUtility::rawUrlEncodeFP($imageInfo[3]); } if (TRUE === $onlyProperties) { $file = ResourceUtility::getFileArray($file); } $images[] = array('info' => $imageInfo, 'source' => $imageSource, 'file' => $file); } if ('BE' === TYPO3_MODE) { $this->resetFrontendEnvironment(); } return $images; }
/** * @test * @dataProvider getPublicUrlReturnsValidUrlContainingSpecialCharacters_dataProvider */ public function getPublicUrlReturnsValidUrlContainingSpecialCharacters($fileIdentifier) { $baseUri = 'http://example.org/foobar/' . uniqid(); $fixture = $this->createDriverFixture(array('baseUri' => $baseUri)); $publicUrl = $fixture->getPublicUrl($fileIdentifier); $this->assertTrue(GeneralUtility::isValidUrl($publicUrl), 'getPublicUrl did not return a valid URL:' . $publicUrl); }
/** * Method sets URL of repository WSDL. * * @param string $url URL of repository WSDL * @return void * @see $wsdlUrl, getWsdlUrl() */ public function setWsdlUrl($url) { if (!empty($url) && \TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($url)) { $this->wsdlUrl = $url; } }
/** * Determines whether the URL matches a domain * in the sys_domain database table. * * @param string $url Absolute URL which needs to be checked * @return bool Whether the URL is considered to be local */ protected function isInLocalDomain($url) { $result = false; if (GeneralUtility::isValidUrl($url)) { $parsedUrl = parse_url($url); if ($parsedUrl['scheme'] === 'http' || $parsedUrl['scheme'] === 'https') { $host = $parsedUrl['host']; // Removes the last path segment and slash sequences like /// (if given): $path = preg_replace('#/+[^/]*$#', '', $parsedUrl['path']); $localDomains = $this->databaseConnection->exec_SELECTgetRows('domainName', 'sys_domain', '1=1' . $this->cObj->enableFields('sys_domain')); if (is_array($localDomains)) { foreach ($localDomains as $localDomain) { // strip trailing slashes (if given) $domainName = rtrim($localDomain['domainName'], '/'); if (GeneralUtility::isFirstPartOfStr($host . $path . '/', $domainName . '/')) { $result = true; break; } } } } } return $result; }
/** * 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; } // 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/amd/template.tmpl'), '###TEMPLATE###'); } $markerArray = array('###OWNER###' => '', '###OWNERSITEURL###' => '', '###OWNERLOGO###' => '', '###OWNERCONTACT###' => '', '###LOCALVIEW###' => '', '###LOCALVIEWURL###' => '', '###SPONSOR###' => '', '###SPONSORSITEURL###' => '', '###SPONSORLOGO###' => ''); $subpart = ''; // Get legal and contact information. $legalContact = $this->doc->mets->xpath('//mets:amdSec/mets:rightsMD/mets:mdWrap[@OTHERMDTYPE="DVRIGHTS"]/mets:xmlData'); if ($legalContact) { $rights = $legalContact[0]->children('http://dfg-viewer.de/')->rights; // if no children found in given namespace, skip the following section if ($rights) { // Get owner. $markerArray['###OWNER###'] = htmlspecialchars(trim((string) $rights->owner)); // Get owner's site URL. if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl(trim((string) $rights->ownerSiteURL)) || version_compare(phpversion(), '5.3.3', '<')) { $markerArray['###OWNERSITEURL###'] = htmlspecialchars(trim((string) $rights->ownerSiteURL)); } // Get owner's logo. if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl(trim((string) $rights->ownerLogo)) || version_compare(phpversion(), '5.3.3', '<')) { $markerArray['###OWNERLOGO###'] = htmlspecialchars(trim((string) $rights->ownerLogo)); } // Get owner's contact information. if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl(trim((string) $rights->ownerContact)) || version_compare(phpversion(), '5.3.3', '<')) { $markerArray['###OWNERCONTACT###'] = htmlspecialchars(trim((string) $rights->ownerContact)); } elseif (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl('mailto:' . trim((string) $rights->ownerContact)) || version_compare(phpversion(), '5.3.3', '<')) { $markerArray['###OWNERCONTACT###'] = htmlspecialchars('mailto:' . trim((string) $rights->ownerContact)); } // Get sponsor. $markerArray['###SPONSOR###'] = htmlspecialchars(trim((string) $rights->sponsor)); // Get sponsor's site URL. if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl(trim((string) $rights->sponsorSiteURL)) || version_compare(phpversion(), '5.3.3', '<')) { $markerArray['###SPONSORSITEURL###'] = htmlspecialchars(trim((string) $rights->sponsorSiteURL)); } // Get sponsor's logo. if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl(trim((string) $rights->sponsorLogo)) || version_compare(phpversion(), '5.3.3', '<')) { $markerArray['###SPONSORLOGO###'] = htmlspecialchars(trim((string) $rights->sponsorLogo)); } } } // Get digital provenance information. $digiProv = $this->doc->mets->xpath('//mets:amdSec/mets:digiprovMD/mets:mdWrap[@OTHERMDTYPE="DVLINKS"]/mets:xmlData'); if ($digiProv) { $links = $digiProv[0]->children('http://dfg-viewer.de/')->links; // if no children found with given namespace, skip the following section if ($links) { // Get sub-template. $referencesTmpl = $this->cObj->getSubpart($this->template, '###REFERENCES###'); foreach ($links->reference as $reference) { if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl(trim((string) $reference)) || version_compare(phpversion(), '5.3.3', '<')) { $refMarkerArray = array('###CATALOG###' => '', '###REFERENCEURL###' => ''); // Get catalog references. $refMarkerArray['###CATALOG###'] = htmlspecialchars(trim((string) $reference->attributes()->linktext)); if (empty($refMarkerArray['###CATALOG###'])) { $refMarkerArray['###CATALOG###'] = $this->pi_getLL('opac', '', TRUE); } $refMarkerArray['###REFERENCEURL###'] = htmlspecialchars(trim((string) $reference)); $subpart .= $this->cObj->substituteMarkerArray($referencesTmpl, $refMarkerArray); } } // Get local view. $markerArray['###LOCALVIEW###'] = $this->pi_getLL('localview', '', TRUE); if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl(trim((string) $links->presentation)) || version_compare(phpversion(), '5.3.3', '<')) { $markerArray['###LOCALVIEWURL###'] = htmlspecialchars(trim((string) $links->presentation)); } } } // Set logo of German Research Foundation as default. if (empty($markerArray['###SPONSORLOGO###'])) { $markerArray['###SPONSOR###'] = $this->pi_getLL('dfg', '', TRUE); $markerArray['###SPONSORSITEURL###'] = $this->pi_getLL('dfgLink', '', TRUE); $markerArray['###SPONSORLOGO###'] = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey) . 'res/images/dfglogo.png'; } return $this->cObj->substituteSubpart($this->cObj->substituteMarkerArray($this->template, $markerArray), '###REFERENCES###', $subpart, TRUE); }
/** * Creates a merged file with given file type * * @param array $filesToInclude Files which should be merged, paths relative to root path * @param string $type File type * * @throws \InvalidArgumentException * @return mixed Filename of the merged file */ protected function createMergedFile(array $filesToInclude, $type = 'css') { // Get file type $type = strtolower(trim($type, '. ')); if (empty($type)) { throw new \InvalidArgumentException('No valid file type given for files to be merged.', 1308957498); } // we add up the filenames, filemtimes and filsizes to later build a checksum over // it and include it in the temporary file name $unique = ''; foreach ($filesToInclude as $key => $filename) { if (GeneralUtility::isValidUrl($filename)) { // check if it is possibly a local file with fully qualified URL if (GeneralUtility::isOnCurrentHost($filename) && GeneralUtility::isFirstPartOfStr($filename, GeneralUtility::getIndpEnv('TYPO3_SITE_URL'))) { // attempt to turn it into a local file path $localFilename = substr($filename, strlen(GeneralUtility::getIndpEnv('TYPO3_SITE_URL'))); if (@is_file(GeneralUtility::resolveBackPath($this->rootPath . $localFilename))) { $filesToInclude[$key] = $localFilename; } else { $filesToInclude[$key] = $this->retrieveExternalFile($filename); } } else { $filesToInclude[$key] = $this->retrieveExternalFile($filename); } $filename = $filesToInclude[$key]; } $filenameAbsolute = GeneralUtility::resolveBackPath($this->rootPath . $filename); if (@file_exists($filenameAbsolute)) { $fileStatus = stat($filenameAbsolute); $unique .= $filenameAbsolute . $fileStatus['mtime'] . $fileStatus['size']; } else { $unique .= $filenameAbsolute; } } $targetFile = $this->targetDirectory . 'merged-' . md5($unique) . '.' . $type; // if the file doesn't already exist, we create it if (!file_exists(PATH_site . $targetFile)) { $concatenated = ''; // concatenate all the files together foreach ($filesToInclude as $filename) { $contents = GeneralUtility::getUrl(GeneralUtility::resolveBackPath($this->rootPath . $filename)); // only fix paths if files aren't already in typo3temp (already processed) if ($type === 'css' && !GeneralUtility::isFirstPartOfStr($filename, $this->targetDirectory)) { $contents = $this->cssFixRelativeUrlPaths($contents, PathUtility::dirname($filename) . '/'); } $concatenated .= LF . $contents; } // move @charset, @import and @namespace statements to top of new file if ($type === 'css') { $concatenated = $this->cssFixStatements($concatenated); } GeneralUtility::writeFile(PATH_site . $targetFile, $concatenated); } return $targetFile; }
/** * Determines whether the URL matches a domain * in the sys_domain database table. * * @param string $url Absolute URL which needs to be checked * @return bool Whether the URL is considered to be local */ protected function isInLocalDomain($url) { $result = false; if (GeneralUtility::isValidUrl($url)) { $parsedUrl = parse_url($url); if ($parsedUrl['scheme'] === 'http' || $parsedUrl['scheme'] === 'https') { $host = $parsedUrl['host']; // Removes the last path segment and slash sequences like /// (if given): $path = preg_replace('#/+[^/]*$#', '', $parsedUrl['path']); $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_domain'); $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class)); $localDomains = $queryBuilder->select('domainName')->from('sys_domain')->execute()->fetchAll(); if (is_array($localDomains)) { foreach ($localDomains as $localDomain) { // strip trailing slashes (if given) $domainName = rtrim($localDomain['domainName'], '/'); if (GeneralUtility::isFirstPartOfStr($host . $path . '/', $domainName . '/')) { $result = true; break; } } } } } return $result; }
/** * @return array * TODO: Duck type this thing */ protected function generateTags() { $tags = array(); foreach ($this->arguments as $k => $v) { if ($v) { $k = GeneralUtility::camelCaseToLowerCaseUnderscored($k); switch ($k) { case 'merge': break; case 'image': if ($this->canAddImages()) { if (!GeneralUtility::isValidUrl($v)) { $v = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . $v; if (!GeneralUtility::isValidUrl($v)) { break; } } $temp = '<meta property="og:' . strtolower($k) . '"' . ' content="' . htmlspecialchars($v) . '" />'; if (!$this->alreadyUsingTag($temp)) { $this->increaseImageCount(); $this->trackTag($temp); $tags[$k] = $temp; } } break; default: $temp = '<meta property="og:' . strtolower($k) . '"' . ' content="' . htmlspecialchars($v) . '" />'; if (!$this->alreadyUsingTag($temp)) { $this->trackTag($temp); $tags[$k] = $temp; } break; } } } return $tags; }
/** * Turns a relative source URI into an absolute URL * if required * * @param string $src * @return string */ public function preprocessSourceUri($src) { if (false === empty($GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_vhs.']['settings.']['prependPath'])) { $src = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_vhs.']['settings.']['prependPath'] . $src; } elseif ('BE' === TYPO3_MODE || false === (bool) $this->arguments['relative']) { if (GeneralUtility::isValidUrl($src)) { $src = ltrim($src, '/'); } else { $src = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . ltrim($src, '/'); } } return $src; }
/** * Resolves the URL of an file * * @param string $file * @return string|NULL */ protected function retrieveMediaUrl($file) { $returnValue = NULL; // because the file value can possibly have link parameters, use explode to split all values $fileParts = explode(' ', $file); /** @var $mediaWizard \TYPO3\CMS\Mediace\MediaWizard\MediaWizardProviderInterface */ $mediaWizard = \TYPO3\CMS\Mediace\MediaWizard\MediaWizardProviderManager::getValidMediaWizardProvider($fileParts[0]); // Get the path relative to the page currently outputted if (substr($fileParts[0], 0, 5) === 'file:') { $fileUid = substr($fileParts[0], 5); if (!empty($fileUid) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($fileUid)) { $fileObject = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->getFileObject($fileUid); if ($fileObject instanceof \TYPO3\CMS\Core\Resource\FileInterface) { $returnValue = $fileObject->getPublicUrl(); } } } elseif (is_file(PATH_site . $fileParts[0])) { $returnValue = $GLOBALS['TSFE']->tmpl->getFileName($fileParts[0]); } elseif ($mediaWizard !== NULL) { $jumpUrlEnabled = $GLOBALS['TSFE']->config['config']['jumpurl_enable']; $GLOBALS['TSFE']->config['config']['jumpurl_enable'] = 0; $returnValue = $this->cObj->typoLink_URL(array('parameter' => $mediaWizard->rewriteUrl($fileParts[0]))); $GLOBALS['TSFE']->config['config']['jumpurl_enable'] = $jumpUrlEnabled; } elseif (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($fileParts[0])) { $returnValue = $fileParts[0]; } return $returnValue; }
/** * Creates a link to a given page with a given link text * * @param array Array of arguments, [0] is the link text, [1] is the (optional) page Id to link to (otherwise TSFE->id), [2] are additional URL parameters, [3] use cache, defaults to FALSE, [4] additional A tag parameters * @return string complete anchor tag with URL and link text */ public function execute(array $arguments = array()) { $linkText = $arguments[0]; $additionalParameters = $arguments[2] ? $arguments[2] : ''; $useCache = $arguments[3] ? TRUE : FALSE; $ATagParams = $arguments[4] ? $arguments[4] : ''; // by default or if no link target is set, link to the current page $linkTarget = $GLOBALS['TSFE']->id; // if the link target is a number, interprete it as a page ID $linkArgument = trim($arguments[1]); if (is_numeric($linkArgument)) { $linkTarget = intval($linkArgument); } elseif (!empty($linkArgument) && is_string($linkArgument)) { if (Tx_Solr_Util::isValidTypoScriptPath($linkArgument)) { try { $typoscript = Tx_Solr_Util::getTypoScriptObject($linkArgument); $pathExploded = explode('.', $linkArgument); $lastPathSegment = array_pop($pathExploded); $linkTarget = intval($typoscript[$lastPathSegment]); } catch (InvalidArgumentException $e) { // ignore exceptions caused by markers, but accept the exception for wrong TS paths if (substr($linkArgument, 0, 3) != '###') { throw $e; } } } elseif (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($linkArgument) || \TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl(\TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . '/' . $linkArgument)) { // $linkTarget is an URL $linkTarget = filter_var($linkArgument, FILTER_SANITIZE_URL); } } $linkConfiguration = array('useCacheHash' => $useCache, 'no_cache' => FALSE, 'parameter' => $linkTarget, 'additionalParams' => $additionalParameters, 'ATagParams' => $ATagParams); return $this->contentObject->typoLink($linkText, $linkConfiguration); }
/** * Determines a page ID's URL. * * Tries to find a domain record to use to build an URL for a given page ID * and then actually build and return the page URL. * * @param Item $item Item to index * @param integer $language The language id * @return string URL to send the index request to * @throws \RuntimeException */ protected function getDataUrl(Item $item, $language = 0) { $scheme = 'http'; $host = $item->getSite()->getDomain(); $path = '/'; $pageId = $item->getRecordUid(); // deprecated if (!empty($this->options['scheme'])) { GeneralUtility::devLog('Using deprecated option "scheme" to set the scheme (http / https) for the page indexer frontend helper. Use plugin.tx_solr.index.queue.pages.indexer.frontendDataHelper.scheme instead', 'solr', 2); $scheme = $this->options['scheme']; } // check whether we should use ssl / https if (!empty($this->options['frontendDataHelper.']['scheme'])) { $scheme = $this->options['frontendDataHelper.']['scheme']; } // overwriting the host if (!empty($this->options['frontendDataHelper.']['host'])) { $host = $this->options['frontendDataHelper.']['host']; } // setting a path if TYPO3 is installed in a sub directory if (!empty($this->options['frontendDataHelper.']['path'])) { $path = $this->options['frontendDataHelper.']['path']; } $mountPointParameter = $this->getMountPageDataUrlParameter($item); $dataUrl = $scheme . '://' . $host . $path . 'index.php?id=' . $pageId; $dataUrl .= $mountPointParameter !== '' ? '&MP=' . $mountPointParameter : ''; $dataUrl .= '&L=' . $language; if (!GeneralUtility::isValidUrl($dataUrl)) { GeneralUtility::devLog('Could not create a valid URL to get frontend data while trying to index a page.', 'solr', 3, array('item' => (array) $item, 'constructed URL' => $dataUrl, 'scheme' => $scheme, 'host' => $host, 'path' => $path, 'page ID' => $pageId, 'indexer options' => $this->options)); throw new \RuntimeException('Could not create a valid URL to get frontend data while trying to index a page. Created URL: ' . $dataUrl, 1311080805); } if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['IndexQueuePageIndexer']['dataUrlModifier']) { $dataUrlModifier = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['IndexQueuePageIndexer']['dataUrlModifier']); if ($dataUrlModifier instanceof PageIndexerDataUrlModifier) { $dataUrl = $dataUrlModifier->modifyDataUrl($dataUrl, array('item' => $item, 'scheme' => $scheme, 'host' => $host, 'path' => $path, 'pageId' => $pageId, 'language' => $language)); } else { throw new \RuntimeException($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['IndexQueuePageIndexer']['dataUrlModifier'] . ' is not an implementation of ApacheSolrForTypo3\\Solr\\IndexQueue\\PageIndexerDataUrlModifier', 1290523345); } } return $dataUrl; }
/** * Resolves the URL of an file * * @param $media * * @return null|string */ protected function retrieveMediaUrl($media) { $returnValue = NULL; if (class_exists('TYPO3\\CMS\\Mediace\\MediaWizard\\MediaWizardProviderManager')) { // 7.2 $mediaWizard = \TYPO3\CMS\Mediace\MediaWizard\MediaWizardProviderManager::getValidMediaWizardProvider($media); } elseif (class_exists('TYPO3\\CMS\\Frontend\\MediaWizard\\MediaWizardProviderManager')) { // before 7.2 $mediaWizard = \TYPO3\CMS\Frontend\MediaWizard\MediaWizardProviderManager::getValidMediaWizardProvider($media); } else { throw new \Exception('You are running TYPO3 > CMS 7.2. Please install the mediace extension', 12367238462384.0); } // Get the path relative to the page currently outputted if (substr($media, 0, 5) === "file:") { $fileUid = substr($media, 5); if (MathUtility::canBeInterpretedAsInteger($fileUid)) { $fileObject = ResourceFactory::getInstance()->getFileObject($fileUid); if ($fileObject instanceof FileInterface) { $returnValue = $fileObject->getPublicUrl(); } } } elseif (is_file(PATH_site . $media)) { $returnValue = $GLOBALS['TSFE']->tmpl->getFileName($media); } elseif ($mediaWizard !== NULL) { $cObj = new ContentObjectRenderer(); $returnValue = $cObj->typoLink_URL(array('parameter' => $mediaWizard->rewriteUrl($media))); } elseif (GeneralUtility::isValidUrl($media)) { $returnValue = $media; } return $returnValue; }
/** * Returns a publicly accessible URL for a file. * * WARNING: Access to the file may be restricted by further means, e.g. * some web-based authentication. You have to take care of this yourself. * * @param ResourceInterface $resourceObject The file or folder object * @param bool $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all (only for the LocalDriver) * @return string */ public function getPublicUrl(ResourceInterface $resourceObject, $relativeToCurrentScript = false) { $publicUrl = null; if ($this->isOnline()) { // Pre-process the public URL by an accordant slot $this->emitPreGeneratePublicUrlSignal($resourceObject, $relativeToCurrentScript, array('publicUrl' => &$publicUrl)); if ($publicUrl === null && $resourceObject instanceof File && ($helper = OnlineMediaHelperRegistry::getInstance()->getOnlineMediaHelper($resourceObject)) !== false) { $publicUrl = $helper->getPublicUrl($resourceObject, $relativeToCurrentScript); } // If slot did not handle the signal, use the default way to determine public URL if ($publicUrl === null) { if ($this->hasCapability(self::CAPABILITY_PUBLIC)) { $publicUrl = $this->driver->getPublicUrl($resourceObject->getIdentifier()); } if ($publicUrl === null && $resourceObject instanceof FileInterface) { $queryParameterArray = array('eID' => 'dumpFile', 't' => ''); if ($resourceObject instanceof File) { $queryParameterArray['f'] = $resourceObject->getUid(); $queryParameterArray['t'] = 'f'; } elseif ($resourceObject instanceof ProcessedFile) { $queryParameterArray['p'] = $resourceObject->getUid(); $queryParameterArray['t'] = 'p'; } $queryParameterArray['token'] = GeneralUtility::hmac(implode('|', $queryParameterArray), 'resourceStorageDumpFile'); $publicUrl = 'index.php?' . str_replace('+', '%20', http_build_query($queryParameterArray)); } // If requested, make the path relative to the current script in order to make it possible // to use the relative file if ($publicUrl !== null && $relativeToCurrentScript && !GeneralUtility::isValidUrl($publicUrl)) { $absolutePathToContainingFolder = PathUtility::dirname(PATH_site . $publicUrl); $pathPart = PathUtility::getRelativePathTo($absolutePathToContainingFolder); $filePart = substr(PATH_site . $publicUrl, strlen($absolutePathToContainingFolder) + 1); $publicUrl = $pathPart . $filePart; } } } return $publicUrl; }
/** * Get the url to jump to as set by Direct Mail * * @return void * @throws \Exception */ public function preprocessRequest($parameter, $parentObject) { $db = $this->getDatabaseConnection(); $jumpUrlVariables = GeneralUtility::_GET(); $mid = $jumpUrlVariables['mid']; $rid = $jumpUrlVariables['rid']; $aC = $jumpUrlVariables['aC']; $responseType = 0; if ($mid) { // overwrite the jumpUrl with the one from the &jumpurl= get parameter $jumpurl = $jumpUrlVariables['jumpurl']; // this will split up the "rid=f_13667", where the first part // is the DB table name and the second part the UID of the record in the DB table $recipientTable = ''; $recipientUid = ''; if (!empty($rid)) { list($recipientTable, $recipientUid) = explode('_', $rid); } $urlId = 0; if (MathUtility::canBeInterpretedAsInteger($jumpurl)) { // fetch the direct mail record where the mailing was sent (for this message) $resMailing = $db->exec_SELECTquery('mailContent, page, authcode_fieldList', 'sys_dmail', 'uid = ' . intval($mid)); if ($row = $db->sql_fetch_assoc($resMailing)) { $mailContent = unserialize(base64_decode($row['mailContent'])); $urlId = $jumpurl; if ($jumpurl >= 0) { // Link (number) $responseType = 1; $jumpurl = $mailContent['html']['hrefs'][$urlId]['absRef']; } else { // Link (number, plaintext) $responseType = 2; $jumpurl = $mailContent['plain']['link_ids'][abs($urlId)]; } $jumpurl = htmlspecialchars_decode(urldecode($jumpurl)); switch ($recipientTable) { case 't': $theTable = 'tt_address'; break; case 'f': $theTable = 'fe_users'; break; default: $theTable = ''; } if ($theTable) { $recipRow = $this->getRawRecord($theTable, $recipientUid); if (is_array($recipRow)) { $authCode = GeneralUtility::stdAuthCode($recipRow, $row['authcode_fieldList'] ? $row['authcode_fieldList'] : 'uid'); // check if supplied aC identical with counted authCode if ($aC != '' && $aC == $authCode) { $rowFieldsArray = explode(',', $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['direct_mail']['defaultRecipFields']); if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['direct_mail']['addRecipFields']) { $rowFieldsArray = array_merge($rowFieldsArray, explode(',', $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['direct_mail']['addRecipFields'])); } reset($rowFieldsArray); foreach ($rowFieldsArray as $substField) { $jumpurl = str_replace('###USER_' . $substField . '###', $recipRow[$substField], $jumpurl); } // Put in the tablename of the userinformation $jumpurl = str_replace('###SYS_TABLE_NAME###', substr($theTable, 0, 1), $jumpurl); // Put in the uid of the mail-record $jumpurl = str_replace('###SYS_MAIL_ID###', $mid, $jumpurl); // If authCode is provided, keep it. $jumpurl = str_replace('###SYS_AUTHCODE###', $aC, $jumpurl); // Auto Login an FE User, only possible if we're allowed to set the $_POST variables and // in the authcode_fieldlist the field "password" is computed in as well // TODO: add a switch in Direct Mail configuration to decide if this option should be enabled by default if ($theTable == 'fe_users' && $aC != '' && $aC == $authCode && GeneralUtility::inList($row['authcode_fieldList'], 'password')) { $_POST['user'] = $recipRow['username']; $_POST['pass'] = $recipRow['password']; $_POST['pid'] = $recipRow['pid']; $_POST['logintype'] = 'login'; } } else { throw new \Exception('authCode: Calculated authCode did not match the submitted authCode.', 1376899631); } } } } $db->sql_free_result($resMailing); if (!$jumpurl) { die('Error: No further link. Please report error to the mail sender.'); } else { // jumpurl has been validated by lookup of id in direct_mail tables // for this reason it is save to set the juHash // set juHash as done for external_url in core: http://forge.typo3.org/issues/46071 GeneralUtility::_GETset(GeneralUtility::hmac($jumpurl, 'jumpurl'), 'juHash'); } } else { // jumpUrl is not an integer -- then this is a URL, that means that the "dmailerping" // functionality was used to count the number of "opened mails" received (url, dmailerping) // Check if jumpurl is a valid link to a "dmailerping.gif" // Make $checkPath an absolute path pointing to dmailerping.gif so it can get checked via ::isAllowedAbsPath() // and remove an eventual "/" at beginning of $jumpurl (because PATH_site already contains "/" at the end) $checkPath = PATH_site . preg_replace('#^/#', '', $jumpurl); // Now check if $checkPath is a valid path and points to a "/dmailerping.gif" if (preg_match('#/dmailerping\\.(gif|png)$#', $checkPath) && GeneralUtility::isAllowedAbsPath($checkPath)) { // set juHash as done for external_url in core: http://forge.typo3.org/issues/46071 GeneralUtility::_GETset(GeneralUtility::hmac($jumpurl, 'jumpurl'), 'juHash'); $responseType = -1; } elseif (GeneralUtility::isValidUrl($jumpurl) && preg_match('#^(http://|https://)#', $jumpurl)) { // Also allow jumpurl to be a valid URL GeneralUtility::_GETset(GeneralUtility::hmac($jumpurl, 'jumpurl'), 'juHash'); $responseType = -1; } // to count the dmailerping correctly, we need something unique $recipientUid = $aC; } if ($responseType != 0) { $insertFields = array('mid' => intval($mid), 'tstamp' => time(), 'url' => $jumpurl, 'response_type' => intval($responseType), 'url_id' => intval($urlId), 'rtbl' => $recipientTable, 'rid' => $recipientUid); $db->exec_INSERTquery('sys_dmail_maillog', $insertFields); } } // finally set the jumpURL to the TSFE object if (!empty($jumpurl)) { GeneralUtility::_GETset($jumpurl, 'jumpurl'); } }
/** * @test * @dataProvider isValidUrlInvalidRessourceDataProvider */ public function validURLReturnsFalseForInvalidRessoure($url) { $this->assertFalse(Utility\GeneralUtility::isValidUrl($url)); }
/** * Creates a merged file with given file type * * @param array $filesToInclude Files which should be merged, paths relative to root path * @param string $type File type * @return mixed Filename of the merged file */ protected function createMergedFile(array $filesToInclude, $type = 'css') { // Get file type $type = strtolower(trim($type, '. ')); if (empty($type)) { throw new \InvalidArgumentException('Error in TYPO3\\CMS\\Core\\Resource\\ResourceCompressor: No valid file type given for merged file', 1308957498); } // we add up the filenames, filemtimes and filsizes to later build a checksum over // it and include it in the temporary file name $unique = ''; foreach ($filesToInclude as $key => $filename) { if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($filename)) { $filesToInclude[$key] = $this->retrieveExternalFile($filename); $filename = $filesToInclude[$key]; } $filepath = \TYPO3\CMS\Core\Utility\GeneralUtility::resolveBackPath($this->rootPath . $filename); $unique .= $filename . filemtime($filepath) . filesize($filepath); } $targetFile = $this->targetDirectory . 'merged-' . md5($unique) . '.' . $type; // if the file doesn't already exist, we create it if (!file_exists(PATH_site . $targetFile)) { $concatenated = ''; // concatenate all the files together foreach ($filesToInclude as $filename) { $contents = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl(\TYPO3\CMS\Core\Utility\GeneralUtility::resolveBackPath($this->rootPath . $filename)); // only fix paths if files aren't already in typo3temp (already processed) if ($type === 'css' && !\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($filename, $this->targetDirectory)) { $contents = $this->cssFixRelativeUrlPaths($contents, dirname($filename) . '/'); } $concatenated .= LF . $contents; } // move @charset, @import and @namespace statements to top of new file if ($type === 'css') { $concatenated = $this->cssFixStatements($concatenated); } \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile(PATH_site . $targetFile, $concatenated); } return $targetFile; }