/**
  * @test
  */
 public function canGetVariants()
 {
     $this->indexPageIdsFromFixture('can_get_searchResultSet.xml', [1, 2, 3, 4, 5, 6, 7, 8]);
     sleep(1);
     $solrConnection = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\ConnectionManager')->getConnectionByPageId(1, 0, 0);
     $typoScriptConfiguration = Util::getSolrConfiguration();
     $typoScriptConfiguration->mergeSolrConfiguration(['search.' => ['variants' => 1, 'variants.' => ['variantField' => 'subTitle', 'expand' => 1, 'limit' => 11]]]);
     $this->assertTrue($typoScriptConfiguration->getSearchVariants(), 'Variants are not enabled');
     $this->assertEquals('subTitle', $typoScriptConfiguration->getSearchVariantsField());
     $this->assertEquals(11, $typoScriptConfiguration->getSearchVariantsLimit());
     $search = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Search', $solrConnection);
     /** @var $searchResultsSetService \ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\SearchResultSetService */
     $searchResultsSetService = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Domain\\Search\\ResultSet\\SearchResultSetService', $typoScriptConfiguration, $search);
     /** @var $searchRequest SearchRequest */
     $searchRequest = GeneralUtility::makeInstance(SearchRequest::class);
     $searchRequest->setRawQueryString('*');
     $searchResultSet = $searchResultsSetService->search($searchRequest);
     $searchResults = $searchResultSet->getSearchResults();
     $firstResult = $searchResults[0];
     // We assume that the first result has three variants.
     $this->assertSame(3, count($firstResult->getVariants()));
     // And every variant is indicated to be a variant.
     foreach ($firstResult->getVariants() as $variant) {
         $this->assertTrue($variant->getIsVariant(), 'Document should be a variant');
     }
 }
예제 #2
0
파일: Ts.php 프로젝트: sitegeist/ext-solr
 /**
  * Resolves a TS path and returns its value
  *
  * @param string $path a TS path, separated with dots
  * @return string
  */
 protected function resolveTypoScriptPath($path, $arguments = null)
 {
     $value = '';
     $pathExploded = explode('.', trim($path));
     $lastPathSegment = array_pop($pathExploded);
     /** @var \ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration $configuration */
     $configuration = Util::getSolrConfiguration();
     $pathBranch = $configuration->getObjectByPath($path);
     // generate ts content
     $cObj = $this->getContentObject();
     if (!isset($pathBranch[$lastPathSegment . '.'])) {
         $value = htmlspecialchars($pathBranch[$lastPathSegment]);
     } else {
         if (count($arguments)) {
             $data = array('arguments' => $arguments);
             $numberOfArguments = count($arguments);
             for ($i = 0; $i < $numberOfArguments; $i++) {
                 $data['argument_' . $i] = $arguments[$i];
             }
             $cObj->start($data);
         }
         $value = $cObj->cObjGetSingle($pathBranch[$lastPathSegment], $pathBranch[$lastPathSegment . '.']);
     }
     return $value;
 }
예제 #3
0
 /**
  * Initializes the search component.
  *
  * Sets the debug query parameter
  *
  */
 public function initializeSearchComponent()
 {
     $solrConfiguration = Util::getSolrConfiguration();
     if ($solrConfiguration->getEnabledDebugMode()) {
         $this->query->setDebugMode();
     }
 }
예제 #4
0
 /**
  * @return TypoScriptConfiguration|array
  */
 protected function getConfiguration()
 {
     if ($this->configuration == null) {
         $this->configuration = Util::getSolrConfiguration();
     }
     return $this->configuration;
 }
예제 #5
0
 /**
  * Constructor
  *
  * @param array $arguments
  */
 public function __construct(array $arguments = array())
 {
     $configuration = Util::getSolrConfiguration();
     if (!empty($configuration['viewhelpers.']['multivalue.']['glue'])) {
         $this->glue = $configuration['viewhelpers.']['multivalue.']['glue'];
     }
 }
예제 #6
0
파일: Link.php 프로젝트: sitegeist/ext-solr
 /**
  * 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, interpret it as a page ID
     $linkArgument = trim($arguments[1]);
     if (is_numeric($linkArgument)) {
         $linkTarget = intval($linkArgument);
     } elseif (!empty($linkArgument) && is_string($linkArgument)) {
         /** @var \ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration $configuration */
         $configuration = Util::getSolrConfiguration();
         if ($configuration->isValidPath($linkArgument)) {
             try {
                 $typoscript = $configuration->getObjectByPath($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 (GeneralUtility::isValidUrl($linkArgument) || GeneralUtility::isValidUrl(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);
 }
예제 #7
0
 /**
  * Returns an URL that switches the sorting indicator according to the
  * given sorting direction
  *
  * @param array $arguments Expects 'asc' or 'desc' as sorting direction in key 0
  * @return string
  * @throws \InvalidArgumentException when providing an invalid sorting direction
  */
 public function execute(array $arguments = array())
 {
     $content = '';
     $sortDirection = trim($arguments[0]);
     $configuration = Util::getSolrConfiguration();
     $contentObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
     $defaultImagePrefix = 'EXT:solr/Resources/Public/Images/Indicator';
     $sortViewHelperConfiguration = $configuration->getViewHelpersSortIndicatorConfiguration();
     switch ($sortDirection) {
         case 'asc':
             $imageConfiguration = $sortViewHelperConfiguration['up.'];
             if (!isset($imageConfiguration['file'])) {
                 $imageConfiguration['file'] = $defaultImagePrefix . 'Up.png';
             }
             $content = $contentObject->cObjGetSingle('IMAGE', $imageConfiguration);
             break;
         case 'desc':
             $imageConfiguration = $sortViewHelperConfiguration['down.'];
             if (!isset($imageConfiguration['file'])) {
                 $imageConfiguration['file'] = $defaultImagePrefix . 'Down.png';
             }
             $content = $contentObject->cObjGetSingle('IMAGE', $imageConfiguration);
             break;
         case '###SORT.CURRENT_DIRECTION###':
         case '':
             // ignore
             break;
         default:
             throw new \InvalidArgumentException('Invalid sorting direction "' . $arguments[0] . '", must be "asc" or "desc".', 1390868460);
     }
     return $content;
 }
예제 #8
0
 /**
  * Renders the block of used / applied facets.
  *
  * @return string Rendered HTML representing the used facet.
  */
 public function render()
 {
     $solrConfiguration = Util::getSolrConfiguration();
     $facetOption = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Facet\\FacetOption', $this->facetName, $this->filterValue);
     $facetLinkBuilder = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Facet\\LinkBuilder', $this->query, $this->facetName, $facetOption);
     /* @var $facetLinkBuilder LinkBuilder */
     $facetLinkBuilder->setLinkTargetPageId($this->linkTargetPageId);
     if ($this->facetConfiguration['type'] == 'hierarchy') {
         // FIXME decouple this
         $filterEncoder = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Query\\FilterEncoder\\Hierarchy');
         $facet = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Facet\\Facet', $this->facetName);
         $facetRenderer = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Facet\\HierarchicalFacetRenderer', $facet);
         $facetText = $facetRenderer->getLastPathSegmentFromHierarchicalFacetOption($filterEncoder->decodeFilter($this->filterValue));
     } else {
         $facetText = $facetOption->render();
     }
     $facetText = $this->getModifiedFacetTextFromHook($facetText);
     $contentObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
     $facetConfiguration = $solrConfiguration->getSearchFacetingFacetByName($this->facetName);
     $facetLabel = $contentObject->stdWrap($facetConfiguration['label'], $facetConfiguration['label.']);
     $removeFacetText = strtr($solrConfiguration->getSearchFacetingRemoveFacetLinkText(), array('@facetValue' => $this->filterValue, '@facetName' => $this->facetName, '@facetLabel' => $facetLabel, '@facetText' => $facetText));
     $removeFacetLink = $facetLinkBuilder->getRemoveFacetOptionLink($removeFacetText);
     $removeFacetUrl = $facetLinkBuilder->getRemoveFacetOptionUrl();
     $facetToRemove = array('link' => $removeFacetLink, 'url' => $removeFacetUrl, 'text' => $removeFacetText, 'value' => $this->filterValue, 'facet_name' => $this->facetName);
     return $facetToRemove;
 }
예제 #9
0
파일: Date.php 프로젝트: sitegeist/ext-solr
 /**
  * Constructor
  *
  * @param array $arguments
  */
 public function __construct(array $arguments = array())
 {
     if (is_null($this->dateFormat) || is_null($this->contentObject)) {
         $configuration = Util::getSolrConfiguration();
         $this->dateFormat = $configuration->getValueByPathOrDefaultValue('plugin.tx_solr.general.dateFormat.', array('date' => 'd.m.Y H:i'));
         $this->contentObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
     }
 }
예제 #10
0
 /**
  * Constructor.
  *
  * @param string $facetName Facet Name
  * @param int|string $facetOptionValue Facet option value
  * @param int $facetOptionNumberOfResults number of results to be returned when applying this option's filter
  */
 public function __construct($facetName, $facetOptionValue, $facetOptionNumberOfResults = 0)
 {
     $this->facetName = $facetName;
     $this->value = $facetOptionValue;
     $this->numberOfResults = intval($facetOptionNumberOfResults);
     $solrConfiguration = Util::getSolrConfiguration();
     $this->facetConfiguration = $solrConfiguration->getSearchFacetingFacetByName($this->facetName);
 }
예제 #11
0
파일: Search.php 프로젝트: hnadler/ext-solr
 /**
  * Constructor
  *
  * @param SolrService $solrConnection The Solr connection to use for searching
  */
 public function __construct(SolrService $solrConnection = null)
 {
     $this->solr = $solrConnection;
     if (is_null($solrConnection)) {
         $this->solr = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\ConnectionManager')->getConnectionByPageId($GLOBALS['TSFE']->id, $GLOBALS['TSFE']->sys_language_uid);
     }
     $this->configuration = Util::getSolrConfiguration();
 }
예제 #12
0
 /**
  * Constructor.
  *
  * @param string $facetName Facet Name
  * @param integer|string $facetOptionValue Facet option value
  * @param integer $facetOptionNumberOfResults number of results to be returned when applying this option's filter
  */
 public function __construct($facetName, $facetOptionValue, $facetOptionNumberOfResults = 0)
 {
     $this->facetName = $facetName;
     $this->value = $facetOptionValue;
     $this->numberOfResults = intval($facetOptionNumberOfResults);
     $solrConfiguration = Util::getSolrConfiguration();
     $this->facetConfiguration = $solrConfiguration['search.']['faceting.']['facets.'][$this->facetName . '.'];
 }
예제 #13
0
파일: Date.php 프로젝트: hnadler/ext-solr
 /**
  * Constructor
  *
  * @param array $arguments
  */
 public function __construct(array $arguments = array())
 {
     if (is_null($this->dateFormat) || is_null($this->contentObject)) {
         $configuration = Util::getSolrConfiguration();
         $this->dateFormat = $configuration['general.']['dateFormat.'];
         $this->contentObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
     }
 }
예제 #14
0
 /**
  * Initializes the search component.
  *
  */
 public function initializeSearchComponent()
 {
     $solrConfiguration = Util::getSolrConfiguration();
     if (!empty($solrConfiguration['statistics'])) {
         $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['modifySearchQuery']['statistics'] = 'ApacheSolrForTypo3\\Solr\\Query\\Modifier\\Statistics';
         $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['processSearchResponse']['statistics'] = 'ApacheSolrForTypo3\\Solr\\Response\\Processor\\StatisticsWriter';
     }
 }
예제 #15
0
 /**
  * @param TypoScriptConfiguration $solrConfiguration
  */
 public function __construct($solrConfiguration = null)
 {
     if (!is_null($solrConfiguration)) {
         $this->configuration = $solrConfiguration;
     } else {
         $this->configuration = Util::getSolrConfiguration();
     }
     $this->allConfiguredFacets = $this->configuration->getSearchFacetingFacets();
     $this->facetRendererFactory = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Facet\\FacetRendererFactory', $this->allConfiguredFacets);
 }
예제 #16
0
파일: Crop.php 프로젝트: nxpthx/ext-solr
 /**
  * Constructor
  */
 public function __construct(array $arguments = array())
 {
     $configuration = Util::getSolrConfiguration();
     if (!empty($configuration['viewHelpers.']['crop.']['maxLength'])) {
         $this->maxLength = $configuration['viewHelpers.']['crop.']['maxLength'];
     }
     if (!empty($configuration['viewHelpers.']['crop.']['cropIndicator'])) {
         $this->cropIndicator = $configuration['viewHelpers.']['crop.']['cropIndicator'];
     }
     if (isset($configuration['viewHelpers.']['crop.']['cropFullWords'])) {
         $this->cropFullWords = (bool) $configuration['viewHelpers.']['crop.']['cropFullWords'];
     }
 }
예제 #17
0
 /**
  * Modifies the given query and returns the modified query as result
  *
  * @param ResultsCommand $resultCommand The search result command
  * @param array $resultDocument Result document
  * @return array The document with fields as array
  */
 public function modifyResultDocument(ResultsCommand $resultCommand, array $resultDocument)
 {
     $this->search = $resultCommand->getParentPlugin()->getSearchResultSetService()->getSearch();
     // only check whether a BE user is logged in, don't need to check
     // for enabled score analysis as we wouldn't be here if it was disabled
     if ($GLOBALS['TSFE']->beUserLogin) {
         $configuration = Util::getSolrConfiguration();
         $queryFields = $configuration->getSearchQueryQueryFields();
         $debugData = $this->search->getDebugResponse()->explain->{$resultDocument['id']};
         $scoreCalculationService = GeneralUtility::makeInstance(ScoreCalculationService::class);
         $resultDocument['score_analysis'] = $scoreCalculationService->getRenderedScores($debugData, $queryFields);
     }
     return $resultDocument;
 }
예제 #18
0
 /**
  * Modifies the given document and returns the modified document as result.
  *
  * @param ResultsCommand $resultCommand The search result command
  * @param array $resultDocument Result document as array
  * @return array The document with fields as array
  */
 public function modifyResultDocument(ResultsCommand $resultCommand, array $resultDocument)
 {
     $this->search = $resultCommand->getParentPlugin()->getSearch();
     $configuration = Util::getSolrConfiguration();
     $highlightedContent = $this->search->getHighlightedContent();
     $highlightFields = GeneralUtility::trimExplode(',', $configuration['search.']['results.']['resultsHighlighting.']['highlightFields'], true);
     foreach ($highlightFields as $highlightField) {
         if (!empty($highlightedContent->{$resultDocument['id']}->{$highlightField}[0])) {
             $fragments = array();
             foreach ($highlightedContent->{$resultDocument['id']}->{$highlightField} as $fragment) {
                 $fragments[] = Template::escapeMarkers($fragment);
             }
             $resultDocument[$highlightField] = implode(' ' . $configuration['search.']['results.']['resultsHighlighting.']['fragmentSeparator'] . ' ', $fragments);
         }
     }
     return $resultDocument;
 }
예제 #19
0
 /**
  * SuggestQuery constructor.
  *
  * @param string $keywords
  * @param TypoScriptConfiguration $solrConfiguration
  */
 public function __construct($keywords, $solrConfiguration = null)
 {
     $keywords = (string) $keywords;
     if ($solrConfiguration == null) {
         $solrConfiguration = Util::getSolrConfiguration();
     }
     parent::__construct('', $solrConfiguration);
     $this->configuration = $solrConfiguration->getObjectByPathOrDefault('plugin.tx_solr.suggest.', []);
     if (!empty($this->configuration['treatMultipleTermsAsSingleTerm'])) {
         $this->prefix = $this->escape($keywords);
     } else {
         $matches = array();
         preg_match('/^(:?(.* |))([^ ]+)$/', $keywords, $matches);
         $fullKeywords = trim($matches[2]);
         $partialKeyword = trim($matches[3]);
         $this->setKeywords($fullKeywords);
         $this->prefix = $this->escape($partialKeyword);
     }
     $this->setAlternativeQuery('*:*');
 }
예제 #20
0
파일: Lll.php 프로젝트: sitegeist/ext-solr
 /**
  * Loads the initially defined local lang file
  *
  * @return void
  */
 protected function loadLL()
 {
     $configuration = Util::getSolrConfiguration();
     $this->localLang[$this->languageFile] = $this->languageFactory->getParsedData($this->languageFile, $this->llKey, $GLOBALS['TSFE']->renderCharset, 3);
     $localLangConfiguration = $configuration->getLocalLangConfiguration();
     if (count($localLangConfiguration) == 0) {
         return;
     }
     // Overlaying labels from TypoScript (including fictitious language keys for non-system languages!):
     foreach ($localLangConfiguration as $language => $overrideLabels) {
         $language = substr($language, 0, -1);
         if (is_array($overrideLabels)) {
             foreach ($overrideLabels as $labelKey => $overrideLabel) {
                 if (!is_array($overrideLabel)) {
                     $this->localLang[$this->languageFile][$language][$labelKey] = array(array('source' => $overrideLabel));
                 }
             }
         }
     }
 }
예제 #21
0
 /**
  * Processes a query and its response after searching for that query.
  *
  * @param Query $query The query that has been searched for.
  * @param \Apache_Solr_Response $response The response for the last query.
  */
 public function processResponse(Query $query, \Apache_Solr_Response $response)
 {
     $urlParameters = GeneralUtility::_GP('tx_solr');
     $keywords = $query->getKeywords();
     $filters = isset($urlParameters['filter']) ? $urlParameters['filter'] : array();
     if (empty($keywords)) {
         // do not track empty queries
         return;
     }
     $keywords = $this->sanitizeString($keywords);
     $sorting = '';
     if (!empty($urlParameters['sort'])) {
         $sorting = $this->sanitizeString($urlParameters['sort']);
     }
     $configuration = Util::getSolrConfiguration();
     if ($configuration['search.']['frequentSearches.']['useLowercaseKeywords']) {
         $keywords = strtolower($keywords);
     }
     $ipMaskLength = (int) $configuration['statistics.']['anonymizeIP'];
     $insertFields = array('pid' => $GLOBALS['TSFE']->id, 'root_pid' => $GLOBALS['TSFE']->tmpl->rootLine[0]['uid'], 'tstamp' => $GLOBALS['EXEC_TIME'], 'language' => $GLOBALS['TSFE']->sys_language_uid, 'num_found' => $response->response->numFound, 'suggestions_shown' => is_object($response->spellcheck->suggestions) ? (int) get_object_vars($response->spellcheck->suggestions) : 0, 'time_total' => $response->debug->timing->time, 'time_preparation' => $response->debug->timing->prepare->time, 'time_processing' => $response->debug->timing->process->time, 'feuser_id' => (int) $GLOBALS['TSFE']->fe_user->user['uid'], 'cookie' => $GLOBALS['TSFE']->fe_user->id, 'ip' => $this->applyIpMask(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $ipMaskLength), 'page' => (int) $urlParameters['page'], 'keywords' => $keywords, 'filters' => serialize($filters), 'sorting' => $sorting, 'parameters' => serialize($response->responseHeader->params));
     $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_solr_statistics', $insertFields);
 }
예제 #22
0
    /**
     * Gets a Solr connection.
     *
     * Instead of generating a new connection with each call, connections are
     * kept and checked whether the requested connection already exists. If a
     * connection already exists, it's reused.
     *
     * @param string $host Solr host (optional)
     * @param integer $port Solr port (optional)
     * @param string $path Solr path (optional)
     * @param string $scheme Solr scheme, defaults to http, can be https (optional)
     * @return SolrService A solr connection.
     */
    public function getConnection($host = '', $port = 8080, $path = '/solr/', $scheme = 'http')
    {
        $connection = null;
        if (empty($host)) {
            GeneralUtility::devLog('ApacheSolrForTypo3\\Solr\\ConnectionManager::getConnection() called with empty
				host parameter. Using configuration from TSFE, might be
				inaccurate. Always provide a host or use the getConnectionBy*
				methods.', 'solr', 2);
            $configuration = Util::getSolrConfiguration();
            $solrConfiguration = $configuration['solr.'];
            $host = $solrConfiguration['host'];
            $port = $solrConfiguration['port'];
            $path = $solrConfiguration['path'];
            $scheme = $solrConfiguration['scheme'];
        }
        $connectionHash = md5($scheme . '://' . $host . $port . $path);
        if (!isset(self::$connections[$connectionHash])) {
            $connection = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\SolrService', $host, $port, $path, $scheme);
            self::$connections[$connectionHash] = $connection;
        }
        return self::$connections[$connectionHash];
    }
 /**
  * Constructor.
  *
  * @param Facet $facet The facet to render.
  */
 public function __construct(Facet $facet)
 {
     $this->search = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Search');
     $this->facet = $facet;
     $this->facetName = $facet->getName();
     $this->solrConfiguration = Util::getSolrConfiguration();
     $this->facetConfiguration = $this->solrConfiguration['search.']['faceting.']['facets.'][$this->facetName . '.'];
     $this->linkTargetPageId = $GLOBALS['TSFE']->id;
     $this->queryLinkBuilder = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Query\\LinkBuilder', $this->search->getQuery());
 }
예제 #24
0
 /**
  * Returns the number of results per Page.
  *
  * Also influences how many result documents are returned by the Solr
  * server as the return value is used in the Solr "rows" GET parameter.
  *
  * @return int number of results to show per page
  */
 public function getNumberOfResultsPerPage()
 {
     $configuration = Util::getSolrConfiguration();
     $resultsPerPageSwitchOptions = GeneralUtility::intExplode(',', $configuration['search.']['results.']['resultsPerPageSwitchOptions']);
     $solrParameters = array();
     $solrPostParameters = GeneralUtility::_POST('tx_solr');
     $solrGetParameters = GeneralUtility::_GET('tx_solr');
     // check for GET parameters, POST takes precedence
     if (isset($solrGetParameters) && is_array($solrGetParameters)) {
         $solrParameters = $solrGetParameters;
     }
     if (isset($solrPostParameters) && is_array($solrPostParameters)) {
         $solrParameters = $solrPostParameters;
     }
     if (isset($solrParameters['resultsPerPage']) && in_array($solrParameters['resultsPerPage'], $resultsPerPageSwitchOptions)) {
         $GLOBALS['TSFE']->fe_user->setKey('ses', 'tx_solr_resultsPerPage', intval($solrParameters['resultsPerPage']));
         $this->resultsPerPageChanged = true;
     }
     $defaultNumberOfResultsShown = $this->conf['search.']['results.']['resultsPerPage'];
     $userSetNumberOfResultsShown = $GLOBALS['TSFE']->fe_user->getKey('ses', 'tx_solr_resultsPerPage');
     $currentNumberOfResultsShown = $defaultNumberOfResultsShown;
     if (!is_null($userSetNumberOfResultsShown) && in_array($userSetNumberOfResultsShown, $resultsPerPageSwitchOptions)) {
         $currentNumberOfResultsShown = (int) $userSetNumberOfResultsShown;
     }
     $rawUserQuery = $this->getRawUserQuery();
     if (($this->conf['search.']['initializeWithEmptyQuery'] || $this->conf['search.']['initializeWithQuery']) && !$this->conf['search.']['showResultsOfInitialEmptyQuery'] && !$this->conf['search.']['showResultsOfInitialQuery'] && empty($rawUserQuery)) {
         // initialize search with an empty query, which would by default return all documents
         // anyway, tell Solr to not return any result documents
         // Solr will still return facets though
         $currentNumberOfResultsShown = 0;
     }
     return $currentNumberOfResultsShown;
 }
예제 #25
0
 /**
  * Gets the document's score.
  *
  * @param string $document The result document as serialized array
  * @return float The document's score
  * @throws \RuntimeException if the serialized result document array cannot be unserialized
  */
 protected function getScore($document)
 {
     $rawDocument = $document;
     $score = 0;
     if (is_numeric($document)) {
         // backwards compatibility
         GeneralUtility::deprecationLog('You are using an old notation of the ' . 'relevance view helpers. The notation used to be ' . '###RELEVANCE:###RESULT_DOCUMENT.SCORE######, please change ' . 'this to simply provide the whole result document: ' . '###RELEVANCE:###RESULT_DOCUMENT######');
         return $document;
     }
     $document = unserialize($document);
     if (is_array($document)) {
         $score = $document['score'];
     } else {
         if ($rawDocument == '###RESULT_DOCUMENT###') {
             // unresolved marker
             // may happen when using search.spellchecking.searchUsingSpellCheckerSuggestion
             // -> ignore
         } else {
             $solrConfiguration = Util::getSolrConfiguration();
             if ($solrConfiguration['logging.']['exceptions']) {
                 GeneralUtility::devLog('Could not resolve document score for relevance calculation', 'solr', 3, array('rawDocument' => $rawDocument, 'unserializedDocument' => $document));
             }
             throw new \RuntimeException('Could not resolve document score for relevance calculation', 1343670545);
         }
     }
     return $score;
 }
예제 #26
0
 /**
  * Constructor
  *
  */
 public function __construct()
 {
     $this->configuration = Util::getSolrConfiguration();
 }
예제 #27
0
 /**
  * Constructor
  *
  */
 public function __construct($keywords)
 {
     $this->solrConfiguration = Util::getSolrConfiguration();
     $this->fieldList = array('*', 'score');
     $this->setKeywords($keywords);
     $this->sorting = '';
     // What fields to search
     if (!empty($this->solrConfiguration['search.']['query.']['queryFields'])) {
         $this->setQueryFieldsFromString($this->solrConfiguration['search.']['query.']['queryFields']);
     }
     // What fields to return from Solr
     if (!empty($this->solrConfiguration['search.']['query.']['returnFields'])) {
         $this->fieldList = GeneralUtility::trimExplode(',', $this->solrConfiguration['search.']['query.']['returnFields']);
     }
     $this->linkTargetPageId = $this->solrConfiguration['search.']['targetPage'];
     if (empty($this->linkTargetPageId)) {
         $this->linkTargetPageId = $GLOBALS['TSFE']->id;
     }
     $this->id = ++self::$idCount;
 }
예제 #28
0
 /**
  * Constructor.
  *
  * @param Query $query Solr query
  */
 public function __construct(Query $query)
 {
     $this->solrConfiguration = Util::getSolrConfiguration();
     $this->contentObject = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
     $this->query = $query;
     $targetPageUid = $this->contentObject->stdWrap($this->solrConfiguration->getSearchTargetPage(), $this->solrConfiguration->getSearchTargetPageConfiguration());
     $this->linkTargetPageId = $targetPageUid;
 }
예제 #29
0
파일: SortUrl.php 프로젝트: nxpthx/ext-solr
 /**
  * Constructor
  *
  * @param array $arguments
  */
 public function __construct(array $arguments = array())
 {
     $this->search = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Search');
     $this->configuration = Util::getSolrConfiguration();
     $this->queryLinkBuilder = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\Query\\LinkBuilder', $this->search->getQuery());
 }
예제 #30
0
    /**
     * Renders an overview of how the score for a certain document has been
     * calculated.
     *
     * @param array $highScores The result document which to analyse
     * @return string The HTML showing the score analysis
     */
    protected function renderScoreAnalysis(array $highScores)
    {
        $configuration = Util::getSolrConfiguration();
        $content = '';
        $scores = array();
        $totalScore = 0;
        foreach ($highScores as $field => $highScore) {
            $pattern = '/' . $highScore['field'] . '\\^([\\d.]*)/';
            $matches = array();
            preg_match_all($pattern, $configuration->getSearchQueryQueryFields(), $matches);
            $scores[] = '
				<td>+ ' . $highScore['score'] . '</td>
				<td>' . $highScore['field'] . '</td>
				<td>' . $matches[1][0] . '</td>';
            $totalScore += $highScore['score'];
        }
        $content = '<table style="width: 100%; border: 1px solid #aaa; font-size: 11px; background-color: #eee;">
			<tr style="border-bottom: 2px solid #aaa; font-weight: bold;"><td>Score</td><td>Field</td><td>Boost</td></tr><tr>' . implode('</tr><tr>', $scores) . '</tr>
			<tr><td colspan="3"><hr style="border-top: 1px solid #aaa; height: 0; padding: 0; margin: 0;" /></td></tr>
			<tr><td colspan="3">= ' . $totalScore . ' (Inaccurate analysis! Not all parts of the score have been taken into account.)</td></tr>
			</table>';
        return $content;
    }