예제 #1
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 = Tx_Solr_Util::getSolrConfiguration();
     $contentObject = t3lib_div::makeInstance('tslib_cObj');
     $defaultImagePrefix = 'EXT:solr/Resources/Images/Indicator';
     switch ($sortDirection) {
         case 'asc':
             $imageConfiguration = $configuration['viewHelpers.']['sortIndicator.']['up.'];
             if (!isset($imageConfiguration['file'])) {
                 $imageConfiguration['file'] = $defaultImagePrefix . 'Up.png';
             }
             $content = $contentObject->IMAGE($imageConfiguration);
             break;
         case 'desc':
             $imageConfiguration = $configuration['viewHelpers.']['sortIndicator.']['down.'];
             if (!isset($imageConfiguration['file'])) {
                 $imageConfiguration['file'] = $defaultImagePrefix . 'Down.png';
             }
             $content = $contentObject->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;
 }
예제 #2
0
파일: Link.php 프로젝트: punktDe/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, 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);
 }
예제 #3
0
 /**
  * Initializes the search component.
  *
  * Sets the debug query parameter
  *
  */
 public function initializeSearchComponent()
 {
     $solrConfiguration = Tx_Solr_Util::getSolrConfiguration();
     if ($solrConfiguration['enableDebugMode']) {
         $this->query->setDebugMode();
     }
 }
예제 #4
0
 /**
  * Constructor for class Tx_Solr_ViewHelper_Multivalue
  *
  */
 public function __construct(array $arguments = array())
 {
     $configuration = Tx_Solr_Util::getSolrConfiguration();
     if (!empty($configuration['viewhelpers.']['multivalue.']['glue'])) {
         $this->glue = $configuration['viewhelpers.']['multivalue.']['glue'];
     }
 }
예제 #5
0
 /**
  * Expects a timestamp and converts it to an ISO 8601 date as needed by Solr.
  *
  * Example date output format: 1995-12-31T23:59:59Z
  * The trailing "Z" designates UTC time and is mandatory
  *
  * @param array Array of values, an array because of multivalued fields
  * @return array Modified array of values
  */
 public function process(array $values)
 {
     $results = array();
     foreach ($values as $timestamp) {
         $results[] = Tx_Solr_Util::timestampToIso($timestamp);
     }
     return $results;
 }
 /**
  * Initializes the search component.
  *
  */
 public function initializeSearchComponent()
 {
     $solrConfiguration = Tx_Solr_Util::getSolrConfiguration();
     if (!empty($solrConfiguration['statistics'])) {
         $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['modifySearchQuery']['statistics'] = 'Tx_Solr_Query_Modifier_Statistics';
         $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['processSearchResponse']['statistics'] = 'Tx_Solr_Response_Processor_StatisticsWriter';
     }
 }
예제 #7
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 = Tx_Solr_Util::getSolrConfiguration();
     $this->facetConfiguration = $solrConfiguration['search.']['faceting.']['facets.'][$this->facetName . '.'];
 }
 /**
  * Works through the indexing queue and indexes the queued items into Solr.
  *
  * @return	boolean	Returns TRUE on success, FALSE if no items were indexed or none were found.
  * @see	typo3/sysext/scheduler/tx_scheduler_Task#execute()
  */
 public function execute()
 {
     $executionSucceeded = FALSE;
     $this->configuration = Tx_Solr_Util::getSolrConfigurationFromPageId($this->site->getRootPageId());
     $this->indexItems();
     $this->cleanIndex();
     $executionSucceeded = TRUE;
     return $executionSucceeded;
 }
예제 #9
0
 /**
  * Constructor.
  *
  * @param Tx_Solr_Facet_Facet $facet The facet to render.
  */
 public function __construct(Tx_Solr_Facet_Facet $facet)
 {
     $this->search = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Tx_Solr_Search');
     $this->facet = $facet;
     $this->facetName = $facet->getName();
     $this->solrConfiguration = Tx_Solr_Util::getSolrConfiguration();
     $this->facetConfiguration = $this->solrConfiguration['search.']['faceting.']['facets.'][$this->facetName . '.'];
     $this->linkTargetPageId = $GLOBALS['TSFE']->id;
     $this->queryLinkBuilder = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Tx_Solr_Query_LinkBuilder', $this->search->getQuery());
 }
예제 #10
0
 /**
  * Parses the given date range from a GET parameter and returns a Solr
  * date range filter.
  *
  * @param string $rangeFilter The range filter query string from the query URL
  * @param array $configuration Facet configuration
  * @return string Lucene query language filter to be used for querying Solr
  */
 public function decodeFilter($dateRange, array $configuration = array())
 {
     list($dateRangeStart, $dateRangeEnd) = explode(self::DELIMITER, $dateRange);
     $dateRangeEnd .= '59';
     // adding 59 seconds
     // TODO for PHP 5.3 use date_parse_from_format() / date_create_from_format() / DateTime::createFromFormat()
     $dateRangeFilter = '[' . Tx_Solr_Util::timestampToIso(strtotime($dateRangeStart));
     $dateRangeFilter .= ' TO ';
     $dateRangeFilter .= Tx_Solr_Util::timestampToIso(strtotime($dateRangeEnd)) . ']';
     return $dateRangeFilter;
 }
예제 #11
0
 /**
  * Constructor.
  *
  * @param Tx_Solr_Query $query Solr query
  */
 public function __construct(Tx_Solr_Query $query)
 {
     $this->solrConfiguration = Tx_Solr_Util::getSolrConfiguration();
     $this->contentObject = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tslib_cObj');
     $this->query = $query;
     $targetPageUid = $this->contentObject->stdWrap($this->solrConfiguration['search.']['targetPage'], $this->solrConfiguration['search.']['targetPage.']);
     $this->linkTargetPageId = $targetPageUid;
     if (empty($this->linkTargetPageId)) {
         $this->linkTargetPageId = $GLOBALS['TSFE']->id;
     }
 }
예제 #12
0
 public function setUp()
 {
     Tx_Solr_Util::initializeTsfe('1');
     $GLOBALS['TSFE']->tmpl->getFileName_backPath = PATH_site;
     $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['search.']['targetPage'] = '0';
     $GLOBALS['TSFE']->tmpl->setup['config.']['tx_realurl_enable'] = '0';
     // setup up ts objects
     $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['search.']['detailPage'] = 5050;
     $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['renderObjects.'] = array('testContent' => 'TEXT', 'testContent.' => array('field' => 'argument_0'), 'testContent2' => 'TEXT', 'testContent2.' => array('field' => 'argument_1', 'stripHtml' => 1));
     $this->fixtures = array('argument content', '<span>argument content with html</span>', 'third argument content');
     $this->viewHelper = new Tx_Solr_viewhelper_Ts();
 }
예제 #13
0
파일: Crop.php 프로젝트: punktDe/solr
 /**
  * constructor for class Tx_Solr_ViewHelper_Crop
  */
 public function __construct(array $arguments = array())
 {
     $configuration = Tx_Solr_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'];
     }
 }
 public function setUp()
 {
     Tx_Solr_Util::initializeTsfe('1');
     $GLOBALS['TSFE']->tmpl->getFileName_backPath = PATH_site;
     $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['search.']['targetPage'] = '0';
     $GLOBALS['TSFE']->tmpl->setup['config.']['tx_realurl_enable'] = '0';
     $facetName = 'TestFacet';
     $facetOptions = array('testoption' => 1);
     $facetConfiguration = array('selectingSelectedFacetOptionRemovesFilter' => 0, 'renderingInstruction');
     $parentPlugin = t3lib_div::makeInstance('Tx_Solr_PiResults_Results');
     $parentPlugin->cObj = t3lib_div::makeInstance('tslib_cObj');
     $parentPlugin->main('', array());
     $query = t3lib_div::makeInstance('Tx_Solr_Query', array('test'));
     $this->facetRenderer = t3lib_div::makeInstance('Tx_Solr_Facet_SimpleFacetRenderer', $facetName, $facetOptions, $facetConfiguration, $parentPlugin->getTemplate(), $query);
     $this->facetRenderer->setLinkTargetPageId($parentPlugin->getLinkTargetPageId());
 }
 /**
  * Modifies the given document and returns the modified document as result.
  *
  * @param Tx_Solr_PiResults_ResultsCommand $resultCommand The search result command
  * @param array $resultDocument Result document as array
  * @return array The document with fields as array
  */
 public function modifyResultDocument($resultCommand, array $resultDocument)
 {
     $this->search = $resultCommand->getParentPlugin()->getSearch();
     $configuration = Tx_Solr_Util::getSolrConfiguration();
     $highlightedContent = $this->search->getHighlightedContent();
     $highlightFields = \TYPO3\CMS\Core\Utility\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[] = tx_solr_Template::escapeMarkers($fragment);
             }
             $resultDocument[$highlightField] = implode(' ' . $configuration['search.']['results.']['resultsHighlighting.']['fragmentSeparator'] . ' ', $fragments);
         }
     }
     return $resultDocument;
 }
 /**
  * Processes a query and its response after searching for that query.
  *
  * @param	Tx_Solr_Query	The query that has been searched for.
  * @param	Apache_Solr_Response	The response for the last query.
  */
 public function processResponse(Tx_Solr_Query $query, Apache_Solr_Response $response)
 {
     $urlParameters = t3lib_div::_GP('tx_solr');
     $keywords = $query->getKeywords();
     $filters = isset($urlParameters['filter']) ? $urlParameters['filter'] : array();
     if (empty($keywords)) {
         // do not track empty queries
         return;
     }
     $keywords = t3lib_div::removeXSS($keywords);
     $keywords = htmlentities($keywords, ENT_QUOTES, $GLOBALS['TSFE']->metaCharset);
     $configuration = Tx_Solr_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' => (int) get_object_vars($response->spellcheck->suggestions), '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(t3lib_div::getIndpEnv('REMOTE_ADDR'), $ipMaskLength), 'page' => (int) $urlParameters['page'], 'keywords' => $keywords, 'filters' => serialize($filters), 'sorting' => $urlParameters['sort'] ? $urlParameters['sort'] : '', 'parameters' => serialize($response->responseHeader->params));
     $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_solr_statistics', $insertFields);
 }
예제 #17
0
파일: Ts.php 프로젝트: romaincanon/ext-solr
 /**
  * Resolves a TS path and returns its value
  *
  * @param string $path a TS path, separated with dots
  * @return string
  * @throws InvalidArgumentException
  */
 protected function resolveTypoScriptPath($path, $arguments = NULL)
 {
     $value = '';
     $pathExploded = explode('.', trim($path));
     $lastPathSegment = array_pop($pathExploded);
     $pathBranch = Tx_Solr_Util::getTypoScriptObject($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;
 }
 /**
  * Renders the block of used / applied facets.
  *
  * @see Tx_Solr_FacetRenderer::render()
  * @return string Rendered HTML representing the used facet.
  */
 public function render()
 {
     $solrConfiguration = Tx_Solr_Util::getSolrConfiguration();
     $facetOption = t3lib_div::makeInstance('Tx_Solr_Facet_FacetOption', $this->facetName, $this->filterValue);
     $facetLinkBuilder = t3lib_div::makeInstance('Tx_Solr_Facet_LinkBuilder', $this->query, $this->facetName, $facetOption);
     /* @var $facetLinkBuilder Tx_Solr_Facet_LinkBuilder */
     $facetLinkBuilder->setLinkTargetPageId($this->linkTargetPageId);
     if ($this->facetConfiguration['type'] == 'hierarchy') {
         // FIXME decouple this
         $filterEncoder = t3lib_div::makeInstance('Tx_Solr_Query_FilterEncoder_Hierarchy');
         $facet = t3lib_div::makeInstance('Tx_Solr_Facet_Facet', $this->facetName);
         $facetRenderer = t3lib_div::makeInstance('Tx_Solr_Facet_HierarchicalFacetRenderer', $facet);
         $facetText = $facetRenderer->getLastPathSegmentFromHierarchicalFacetOption($filterEncoder->decodeFilter($this->filterValue));
     } else {
         $facetText = $facetOption->render();
     }
     $contentObject = t3lib_div::makeInstance('tslib_cObj');
     $facetLabel = $contentObject->stdWrap($solrConfiguration['search.']['faceting.']['facets.'][$this->facetName . '.']['label'], $solrConfiguration['search.']['faceting.']['facets.'][$this->facetName . '.']['label.']);
     $removeFacetText = strtr($solrConfiguration['search.']['faceting.']['removeFacetLinkText'], 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;
 }
    /**
     * Checks whether config.index_enable is set to 1, otherwise indexing will
     * not work.
     *
     * @return	NULL|tx_reports_reports_status_Status	An error status is returned for each site root page config.index_enable = 0.
     */
    protected function getConfigIndexEnableStatus()
    {
        $status = NULL;
        $rootPages = $this->getRootPages();
        $rootPagesWithIndexingOff = array();
        foreach ($rootPages as $rootPage) {
            try {
                Tx_Solr_Util::initializeTsfe($rootPage['uid']);
                if (!$GLOBALS['TSFE']->config['config']['index_enable']) {
                    $rootPagesWithIndexingOff[] = $rootPage;
                }
            } catch (RuntimeException $rte) {
                $rootPagesWithIndexingOff[] = $rootPage;
            } catch (t3lib_error_http_ServiceUnavailableException $sue) {
                if ($sue->getCode() == 1294587218) {
                    //  No TypoScript template found, continue with next site
                    $rootPagesWithIndexingOff[] = $rootPage;
                    continue;
                }
            }
        }
        if (!empty($rootPagesWithIndexingOff)) {
            foreach ($rootPagesWithIndexingOff as $key => $rootPageWithIndexingOff) {
                $rootPagesWithIndexingOff[$key] = '[' . $rootPageWithIndexingOff['uid'] . '] ' . $rootPageWithIndexingOff['title'];
            }
            $status = t3lib_div::makeInstance('tx_reports_reports_status_Status', 'Page Indexing', 'Indexing is disabled', 'You need to set config.index_enable = 1 to allow page indexing.
				The following sites were found with indexing disabled:
				<ul><li>' . implode('</li><li>', $rootPagesWithIndexingOff) . '</li></ul>', tx_reports_reports_status_Status::ERROR);
        }
        return $status;
    }
예제 #20
0
파일: Indexer.php 프로젝트: punktDe/solr
 /**
  * Enables logging dependent on the configuration of the item's site
  *
  * @param	Tx_Solr_IndexQueue_Item	$item An item being indexed
  * @return	void
  */
 protected function setLogging(Tx_Solr_IndexQueue_Item $item)
 {
     // reset
     $this->loggingEnabled = FALSE;
     $solrConfiguration = Tx_Solr_Util::getSolrConfigurationFromPageId($item->getRootPageUid());
     if (!empty($solrConfiguration['logging.']['indexing']) || !empty($solrConfiguration['logging.']['indexing.']['queue']) || !empty($solrConfiguration['logging.']['indexing.']['queue.'][$item->getIndexingConfigurationName()])) {
         $this->loggingEnabled = TRUE;
     }
 }
 /**
  * Builds a map of indexing configuration names to tables to to index.
  *
  * @return array Indexing configuration to database table map
  */
 protected function getIndexQueueConfigurationTableMap()
 {
     $indexingTableMap = array();
     $solrConfiguration = \Tx_Solr_Util::getSolrConfigurationFromPageId($this->site->getRootPageId());
     foreach ($solrConfiguration['index.']['queue.'] as $name => $configuration) {
         if (is_array($configuration)) {
             $name = substr($name, 0, -1);
             if ($solrConfiguration['index.']['queue.'][$name]) {
                 $table = $name;
                 if ($solrConfiguration['index.']['queue.'][$name . '.']['table']) {
                     $table = $solrConfiguration['index.']['queue.'][$name . '.']['table'];
                 }
                 $indexingTableMap[$name] = $table;
             }
         }
     }
     return $indexingTableMap;
 }
예제 #22
0
파일: Results.php 프로젝트: punktDe/solr
 /**
  * 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 = Tx_Solr_Util::getSolrConfiguration();
     $resultsPerPageSwitchOptions = \TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $configuration['search.']['results.']['resultsPerPageSwitchOptions']);
     $solrParameters = array();
     $solrPostParameters = \TYPO3\CMS\Core\Utility\GeneralUtility::_POST('tx_solr');
     $solrGetParameters = \TYPO3\CMS\Core\Utility\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;
 }
예제 #23
0
파일: Template.php 프로젝트: punktDe/solr
 /**
  * Resolves variables to marker. Markers can be simple markers like
  * ###MY_MARKER## or "nested" markers which devide their sub values by a
  * dot: ###MY_MARKER.MY_VALUE### ###MY_MARKER.MY_OTHER_VALUE###.
  *
  * @param	array	array with markers to resolve
  * @param	mixed	the marker's value, which can be an array of values, an object with certain getter methods or a simple string
  * @return	array	with marker as index and value for it
  */
 protected function resolveVariableMarkers(array $markers, $variableValue)
 {
     $resolvedMarkers = array();
     $normalizedKeysArray = array();
     foreach ($variableValue as $key => $value) {
         $key = $this->normalizeString($key);
         $normalizedKeysArray[$key] = $value;
     }
     foreach ($markers as $marker) {
         $dotPosition = strpos($marker, '.');
         if ($dotPosition !== FALSE) {
             $resolvedValue = NULL;
             // the marker contains a dot, thus we have to resolve the
             // second part of the marker
             $valueSelector = substr($marker, $dotPosition + 1);
             $valueSelector = $this->normalizeString($valueSelector);
             if (is_array($variableValue) && array_key_exists($valueSelector, $normalizedKeysArray)) {
                 $resolvedValue = $normalizedKeysArray[$valueSelector];
             } elseif (is_object($variableValue)) {
                 $resolveMethod = 'get' . Tx_Solr_Util::camelize($valueSelector);
                 $resolvedValue = $variableValue->{$resolveMethod}();
             }
         } else {
             $resolvedValue = $variableValue[strtolower($marker)];
         }
         if (is_null($resolvedValue)) {
             if ($this->debugMode) {
                 $resolvedValue = '!!! Marker &quot;' . $marker . '&quot; could not be resolved.';
             } else {
                 $resolvedValue = '';
             }
         }
         if (is_array($resolvedValue)) {
             // handling multivalue fields, @see Tx_Solr_ViewHelper_Multivalue
             $resolvedValue = serialize($resolvedValue);
         }
         $resolvedMarkers[$marker] = $resolvedValue;
     }
     return $resolvedMarkers;
 }
예제 #24
0
 /**
  * Constructor for class Tx_Solr_SpellChecker
  *
  */
 public function __construct()
 {
     $this->search = t3lib_div::makeInstance('Tx_Solr_Search');
     $this->configuration = Tx_Solr_Util::getSolrConfiguration();
 }
예제 #25
0
 /**
  * Adds all the loaded javascript files and snippets to the page.
  *
  * Depending on configuration the Javascript is added in header, footer or
  * not at all if the integrator decides to take care of it himself.
  *
  */
 public function addJavascriptToPage()
 {
     $position = Tx_Solr_Util::getTypoScriptValue('plugin.tx_solr.javascriptFiles.loadIn');
     if (empty($position)) {
         $position = self::POSITION_NONE;
     }
     switch ($position) {
         case self::POSITION_HEADER:
             $this->addJavascriptToPageHeader();
             break;
         case self::POSITION_FOOTER:
             $this->registerForRenderPreProcessHook();
             break;
         case self::POSITION_NONE:
             // do nothing, JS is handled by the integrator
             break;
         default:
             throw new RuntimeException('Invalid value "' . $position . '" for Javascript position. Choose from "header", "footer", or "none".', 1336911986);
     }
 }
 /**
  * Renders the complete facet.
  *
  * @see	Tx_Solr_FacetRenderer::render()
  * @return	string	Rendered HTML representing the facet.
  */
 public function renderFacetOptions()
 {
     $facetOptionLinks = array();
     $solrConfiguration = Tx_Solr_Util::getSolrConfiguration();
     $this->template->workOnSubpart('single_facet_option');
     if (!empty($this->facetConfiguration['manualSortOrder'])) {
         $this->sortFacetOptionsByUserDefinedOrder();
     }
     if (!empty($this->facetConfiguration['reverseOrder'])) {
         $this->facetOptions = array_reverse($this->facetOptions, true);
     }
     $i = 0;
     foreach ($this->facetOptions as $facetOption => $facetOptionResultCount) {
         $facetOption = (string) $facetOption;
         if ($facetOption == '_empty_') {
             // TODO - for now we don't handle facet missing.
             continue;
         }
         $facetOption = t3lib_div::makeInstance('Tx_Solr_Facet_FacetOption', $this->facetName, $facetOption, $facetOptionResultCount);
         /* @var $facetOption Tx_Solr_Facet_FacetOption */
         $facetLinkBuilder = t3lib_div::makeInstance('Tx_Solr_Facet_LinkBuilder', $this->query, $this->facetName, $facetOption);
         /* @var $facetLinkBuilder Tx_Solr_Facet_LinkBuilder */
         $facetLinkBuilder->setLinkTargetPageId($this->linkTargetPageId);
         $optionText = $facetOption->render();
         $optionLink = $facetLinkBuilder->getAddFacetOptionLink($optionText);
         $optionLinkUrl = $facetLinkBuilder->getAddFacetOptionUrl();
         $optionHidden = '';
         if (++$i > $solrConfiguration['search.']['faceting.']['limit']) {
             $optionHidden = 'tx-solr-facet-hidden';
         }
         $optionSelected = $facetOption->isSelectedInFacet($this->facetName);
         // negating the facet option links to remove a filter
         if ($this->facetConfiguration['selectingSelectedFacetOptionRemovesFilter'] && $optionSelected) {
             $optionLink = $facetLinkBuilder->getRemoveFacetOptionLink($optionText);
             $optionLinkUrl = $facetLinkBuilder->getRemoveFacetOptionUrl();
         } elseif ($this->facetConfiguration['singleOptionMode']) {
             $optionLink = $facetLinkBuilder->getReplaceFacetOptionLink($optionText);
             $optionLinkUrl = $facetLinkBuilder->getReplaceFacetOptionUrl();
         }
         $facetOptionLinks[] = array('hidden' => $optionHidden, 'link' => $optionLink, 'url' => $optionLinkUrl, 'text' => $optionText, 'value' => $facetOption->getValue(), 'count' => $facetOption->getNumberOfResults(), 'selected' => $optionSelected ? '1' : '0', 'facet_name' => $this->facetName);
     }
     $this->template->addLoop('facet_links', 'facet_link', $facetOptionLinks);
     return $this->template->render();
 }
예제 #27
0
파일: Faceting.php 프로젝트: punktDe/solr
 /**
  * constructor for class Tx_Solr_Query_Modifier_Faceting
  */
 public function __construct()
 {
     $this->configuration = Tx_Solr_Util::getSolrConfiguration();
     $this->facetRendererFactory = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Tx_Solr_Facet_FacetRendererFactory', $this->configuration['search.']['faceting.']['facets.']);
 }
예제 #28
0
 /**
  * Enables the query's elevation mode.
  *
  * @param Tx_Solr_Query $query The query to modify
  * @return Tx_Solr_Query The modified query with enabled elevation mode
  */
 public function modifyQuery(Tx_Solr_Query $query)
 {
     $configuration = Tx_Solr_Util::getSolrConfiguration();
     $query->setQueryElevation($configuration['search.']['elevation'], $configuration['search.']['elevation.']['forceElevation'], $configuration['search.']['elevation.']['markElevatedResults']);
     return $query;
 }
예제 #29
0
파일: Relevance.php 프로젝트: punktDe/solr
 /**
  * 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
         \TYPO3\CMS\Core\Utility\GeneralUtility::deprecationLog('You are using an old notation of the ' . 'releavnace 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 = Tx_Solr_Util::getSolrConfiguration();
             if ($solrConfiguration['logging.']['exceptions']) {
                 \TYPO3\CMS\Core\Utility\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;
 }
예제 #30
0
 /**
  * Builds the Solr document for the current page.
  *
  * @return Apache_Solr_Document A document representing the page
  */
 protected function getPageDocument()
 {
     $document = GeneralUtility::makeInstance('Apache_Solr_Document');
     /* @var $document	Apache_Solr_Document */
     $site = Tx_Solr_Site::getSiteByPageId($this->page->id);
     $pageRecord = $this->page->page;
     self::$pageSolrDocumentId = $documentId = Tx_Solr_Util::getPageDocumentId($this->page->id, $this->page->type, $this->page->sys_language_uid, $this->getDocumentIdGroups());
     $document->setField('id', $documentId);
     $document->setField('site', $site->getDomain());
     $document->setField('siteHash', $site->getSiteHash());
     $document->setField('appKey', 'EXT:solr');
     $document->setField('type', 'pages');
     // system fields
     $document->setField('uid', $this->page->id);
     $document->setField('pid', $pageRecord['pid']);
     $document->setField('typeNum', $this->page->type);
     $document->setField('created', $pageRecord['crdate']);
     $document->setField('changed', $pageRecord['tstamp']);
     $document->setField('rootline', $this->page->id);
     // access
     $document->setField('access', (string) $this->pageAccessRootline);
     if ($this->page->page['endtime']) {
         $document->setField('endtime', $pageRecord['endtime']);
     }
     // content
     $document->setField('title', $this->contentExtractor->getPageTitle());
     $document->setField('subTitle', $pageRecord['subtitle']);
     $document->setField('navTitle', $pageRecord['nav_title']);
     $document->setField('author', $pageRecord['author']);
     $document->setField('description', $pageRecord['description']);
     $document->setField('abstract', $pageRecord['abstract']);
     $document->setField('content', $this->contentExtractor->getIndexableContent());
     $document->setField('url', $this->pageUrl);
     // keywords, multi valued
     $keywords = array_unique(GeneralUtility::trimExplode(',', $pageRecord['keywords'], TRUE));
     foreach ($keywords as $keyword) {
         $document->addField('keywords', $keyword);
     }
     // content from several tags like headers, anchors, ...
     $tagContent = $this->contentExtractor->getTagContent();
     foreach ($tagContent as $fieldName => $fieldValue) {
         $document->setField($fieldName, $fieldValue);
     }
     return $document;
 }