TYPO3CMS  8
 All Classes Namespaces Files Functions Variables Pages
SearchController.php
Go to the documentation of this file.
1 <?php
2 namespace TYPO3\CMS\IndexedSearch\Controller;
3 
4 /*
5  * This file is part of the TYPO3 CMS project.
6  *
7  * It is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License, either version 2
9  * of the License, or any later version.
10  *
11  * For the full copyright and license information, please read the
12  * LICENSE.txt file that was distributed with this source code.
13  *
14  * The TYPO3 project - inspiring people to share!
15  */
16 
25 
33 {
39  protected $sword = null;
40 
44  protected $searchWords = [];
45 
49  protected $searchData;
50 
60  protected $searchRootPageIdList = 0;
61 
65  protected $defaultResultNumber = 10;
66 
70  protected $availableResultsNumbers = [];
71 
77  protected $searchRepository = null;
78 
84  protected $lexerObj;
85 
90  protected $externalParsers = [];
91 
97  protected $firstRow = [];
98 
104  protected $domainRecords = [];
105 
112 
118  protected $resultSections = [];
119 
125  protected $pathCache = [];
126 
132  protected $iconFileNameCache = [];
133 
139  protected $indexerConfig = [];
140 
146  protected $enableMetaphoneSearch = false;
147 
152 
156  protected $charsetConverter;
157 
161  public function injectTypoScriptService(\TYPO3\CMS\Extbase\Service\TypoScriptService $typoScriptService)
162  {
163  $this->typoScriptService = $typoScriptService;
164  }
165 
172  public function initialize($searchData = [])
173  {
174  $this->charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
175  if (!is_array($searchData)) {
176  $searchData = [];
177  }
178 
179  // check if TypoScript is loaded
180  if (!isset($this->settings['results'])) {
181  $this->redirect('noTypoScript');
182  }
183 
184  // Sets availableResultsNumbers - has to be called before request settings are read to avoid DoS attack
185  $this->availableResultsNumbers = array_filter(GeneralUtility::intExplode(',', $this->settings['blind']['numberOfResults']));
186 
187  // Sets default result number if at least one availableResultsNumbers exists
188  if (isset($this->availableResultsNumbers[0])) {
189  $this->defaultResultNumber = $this->availableResultsNumbers[0];
190  }
191 
192  $this->loadSettings();
193 
194  // setting default values
195  if (is_array($this->settings['defaultOptions'])) {
196  $searchData = array_merge($this->settings['defaultOptions'], $searchData);
197  }
198  // Indexer configuration from Extension Manager interface:
199  $this->indexerConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search'], ['allowed_classes' => false]);
200  $this->enableMetaphoneSearch = (bool)$this->indexerConfig['enableMetaphoneSearch'];
201  $this->initializeExternalParsers();
202  // If "_sections" is set, this value overrides any existing value.
203  if ($searchData['_sections']) {
204  $searchData['sections'] = $searchData['_sections'];
205  }
206  // If "_sections" is set, this value overrides any existing value.
207  if ($searchData['_freeIndexUid'] !== '' && $searchData['_freeIndexUid'] !== '_') {
208  $searchData['freeIndexUid'] = $searchData['_freeIndexUid'];
209  }
210  $searchData['numberOfResults'] = $this->getNumberOfResults($searchData['numberOfResults']);
211  // This gets the search-words into the $searchWordArray
212  $this->setSword($searchData['sword']);
213  // Add previous search words to current
214  if ($searchData['sword_prev_include'] && $searchData['sword_prev']) {
215  $this->setSword(trim($searchData['sword_prev']) . ' ' . $this->getSword());
216  }
217  $this->searchWords = $this->getSearchWords($searchData['defaultOperand']);
218  // This is the id of the site root.
219  // This value may be a commalist of integer (prepared for this)
220  $this->searchRootPageIdList = (int)$GLOBALS['TSFE']->config['rootLine'][0]['uid'];
221  // Setting the list of root PIDs for the search. Notice, these page IDs MUST
222  // have a TypoScript template with root flag on them! Basically this list is used
223  // to select on the "rl0" field and page ids are registered as "rl0" only if
224  // a TypoScript template record with root flag is there.
225  // This happens AFTER the use of $this->searchRootPageIdList above because
226  // the above will then fetch the menu for the CURRENT site - regardless
227  // of this kind of searching here. Thus a general search will lookup in
228  // the WHOLE database while a specific section search will take the current sections.
229  if ($this->settings['rootPidList']) {
230  $this->searchRootPageIdList = implode(',', GeneralUtility::intExplode(',', $this->settings['rootPidList']));
231  }
232  $this->searchRepository = GeneralUtility::makeInstance(\TYPO3\CMS\IndexedSearch\Domain\Repository\IndexSearchRepository::class);
233  $this->searchRepository->initialize($this->settings, $searchData, $this->externalParsers, $this->searchRootPageIdList);
234  $this->searchData = $searchData;
235  // Calling hook for modification of initialized content
236  if ($hookObj = $this->hookRequest('initialize_postProc')) {
237  $hookObj->initialize_postProc();
238  }
239  return $searchData;
240  }
241 
249  public function searchAction($search = [])
250  {
251  $searchData = $this->initialize($search);
252  // Find free index uid:
253  $freeIndexUid = $searchData['freeIndexUid'];
254  if ($freeIndexUid == -2) {
255  $freeIndexUid = $this->settings['defaultFreeIndexUidList'];
256  } elseif (!isset($searchData['freeIndexUid'])) {
257  // index configuration is disabled
258  $freeIndexUid = -1;
259  }
260  $indexCfgs = GeneralUtility::intExplode(',', $freeIndexUid);
261  $resultsets = [];
262  foreach ($indexCfgs as $freeIndexUid) {
263  // Get result rows
264  $tstamp1 = GeneralUtility::milliseconds();
265  if ($hookObj = $this->hookRequest('getResultRows')) {
266  $resultData = $hookObj->getResultRows($this->searchWords, $freeIndexUid);
267  } else {
268  $resultData = $this->searchRepository->doSearch($this->searchWords, $freeIndexUid);
269  }
270  // Display search results
271  $tstamp2 = GeneralUtility::milliseconds();
272  if ($hookObj = $this->hookRequest('getDisplayResults')) {
273  $resultsets[$freeIndexUid] = $hookObj->getDisplayResults($this->searchWords, $resultData, $freeIndexUid);
274  } else {
275  $resultsets[$freeIndexUid] = $this->getDisplayResults($this->searchWords, $resultData, $freeIndexUid);
276  }
277  $tstamp3 = GeneralUtility::milliseconds();
278  // Create header if we are searching more than one indexing configuration
279  if (count($indexCfgs) > 1) {
280  if ($freeIndexUid > 0) {
281  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
282  ->getQueryBuilderForTable('index_config');
283  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
284  $indexCfgRec = $queryBuilder
285  ->select('*')
286  ->from('index_config')
287  ->where(
288  $queryBuilder->expr()->eq(
289  'uid',
290  $queryBuilder->createNamedParameter($freeIndexUid, \PDO::PARAM_INT)
291  )
292  )
293  ->execute()
294  ->fetch();
295  $categoryTitle = $indexCfgRec['title'];
296  } else {
297  $categoryTitle = LocalizationUtility::translate('indexingConfigurationHeader.' . $freeIndexUid, 'IndexedSearch');
298  }
299  $resultsets[$freeIndexUid]['categoryTitle'] = $categoryTitle;
300  }
301  // Write search statistics
302  $this->writeSearchStat($searchData, $this->searchWords, $resultData['count'], [$tstamp1, $tstamp2, $tstamp3]);
303  }
304  $this->view->assign('resultsets', $resultsets);
305  $this->view->assign('searchParams', $searchData);
306  $this->view->assign('searchWords', $this->searchWords);
307  }
308 
309  /****************************************
310  * functions to make the result rows and result sets
311  * ready for the output
312  ***************************************/
321  protected function getDisplayResults($searchWords, $resultData, $freeIndexUid = -1)
322  {
323  $result = [
324  'count' => $resultData['count'],
325  'searchWords' => $searchWords
326  ];
327  // Perform display of result rows array
328  if ($resultData) {
329  // Set first selected row (for calculation of ranking later)
330  $this->firstRow = $resultData['firstRow'];
331  // Result display here
332  $result['rows'] = $this->compileResultRows($resultData['resultRows'], $freeIndexUid);
333  $result['affectedSections'] = $this->resultSections;
334  // Browsing box
335  if ($resultData['count']) {
336  // could we get this in the view?
337  if ($this->searchData['group'] == 'sections' && $freeIndexUid <= 0) {
338  $resultSectionsCount = count($this->resultSections);
339  $result['sectionText'] = sprintf(LocalizationUtility::translate('result.' . ($resultSectionsCount > 1 ? 'inNsections' : 'inNsection'), 'IndexedSearch'), $resultSectionsCount);
340  }
341  }
342  }
343  // Print a message telling which words in which sections we searched for
344  if (substr($this->searchData['sections'], 0, 2) === 'rl') {
345  $result['searchedInSectionInfo'] = LocalizationUtility::translate('result.inSection', 'IndexedSearch') . ' "' . $this->getPathFromPageId(substr($this->searchData['sections'], 4)) . '"';
346  }
347  return $result;
348  }
349 
358  protected function compileResultRows($resultRows, $freeIndexUid = -1)
359  {
360  $finalResultRows = [];
361  // Transfer result rows to new variable,
362  // performing some mapping of sub-results etc.
363  $newResultRows = [];
364  foreach ($resultRows as $row) {
365  $id = md5($row['phash_grouping']);
366  if (is_array($newResultRows[$id])) {
367  // swapping:
368  if (!$newResultRows[$id]['show_resume'] && $row['show_resume']) {
369  // Remove old
370  $subrows = $newResultRows[$id]['_sub'];
371  unset($newResultRows[$id]['_sub']);
372  $subrows[] = $newResultRows[$id];
373  // Insert new:
374  $newResultRows[$id] = $row;
375  $newResultRows[$id]['_sub'] = $subrows;
376  } else {
377  $newResultRows[$id]['_sub'][] = $row;
378  }
379  } else {
380  $newResultRows[$id] = $row;
381  }
382  }
383  $resultRows = $newResultRows;
384  $this->resultSections = [];
385  if ($freeIndexUid <= 0 && $this->searchData['group'] == 'sections') {
386  $rl2flag = substr($this->searchData['sections'], 0, 2) == 'rl';
387  $sections = [];
388  foreach ($resultRows as $row) {
389  $id = $row['rl0'] . '-' . $row['rl1'] . ($rl2flag ? '-' . $row['rl2'] : '');
390  $sections[$id][] = $row;
391  }
392  $this->resultSections = [];
393  foreach ($sections as $id => $resultRows) {
394  $rlParts = explode('-', $id);
395  if ($rlParts[2]) {
396  $theId = $rlParts[2];
397  $theRLid = 'rl2_' . $rlParts[2];
398  } elseif ($rlParts[1]) {
399  $theId = $rlParts[1];
400  $theRLid = 'rl1_' . $rlParts[1];
401  } else {
402  $theId = $rlParts[0];
403  $theRLid = '0';
404  }
405  $sectionName = $this->getPathFromPageId($theId);
406  $sectionName = ltrim($sectionName, '/');
407  if (!trim($sectionName)) {
408  $sectionTitleLinked = LocalizationUtility::translate('result.unnamedSection', 'IndexedSearch') . ':';
409  } else {
410  $onclick = 'document.forms[\'tx_indexedsearch\'][\'tx_indexedsearch_pi2[search][_sections]\'].value=' . GeneralUtility::quoteJSvalue($theRLid) . ';document.forms[\'tx_indexedsearch\'].submit();return false;';
411  $sectionTitleLinked = '<a href="#" onclick="' . htmlspecialchars($onclick) . '">' . $sectionName . ':</a>';
412  }
413  $resultRowsCount = count($resultRows);
414  $this->resultSections[$id] = [$sectionName, $resultRowsCount];
415  // Add section header
416  $finalResultRows[] = [
417  'isSectionHeader' => true,
418  'numResultRows' => $resultRowsCount,
419  'sectionId' => $id,
420  'sectionTitle' => $sectionTitleLinked
421  ];
422  // Render result rows
423  foreach ($resultRows as $row) {
424  $finalResultRows[] = $this->compileSingleResultRow($row);
425  }
426  }
427  } else {
428  // flat mode or no sections at all
429  foreach ($resultRows as $row) {
430  $finalResultRows[] = $this->compileSingleResultRow($row);
431  }
432  }
433  return $finalResultRows;
434  }
435 
443  protected function compileSingleResultRow($row, $headerOnly = 0)
444  {
445  $specRowConf = $this->getSpecialConfigurationForResultRow($row);
446  $resultData = $row;
447  $resultData['headerOnly'] = $headerOnly;
448  $resultData['CSSsuffix'] = $specRowConf['CSSsuffix'] ? '-' . $specRowConf['CSSsuffix'] : '';
449  if ($this->multiplePagesType($row['item_type'])) {
450  $dat = unserialize($row['cHashParams']);
451  $pp = explode('-', $dat['key']);
452  if ($pp[0] != $pp[1]) {
453  $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.page', 'IndexedSearch') . ' ' . $dat['key'];
454  } else {
455  $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.pages', 'IndexedSearch') . ' ' . $pp[0];
456  }
457  }
458  $title = $resultData['item_title'] . $resultData['titleaddition'];
459  $title = $this->charsetConverter->crop('utf-8', $title, $this->settings['results.']['titleCropAfter'], $this->settings['results.']['titleCropSignifier']);
460  // If external media, link to the media-file instead.
461  if ($row['item_type']) {
462  if ($row['show_resume']) {
463  // Can link directly.
464  $targetAttribute = '';
465  if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
466  $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
467  }
468  $title = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($title) . '</a>';
469  } else {
470  // Suspicious, so linking to page instead...
471  $copiedRow = $row;
472  unset($copiedRow['cHashParams']);
473  $title = $this->linkPage($row['page_id'], htmlspecialchars($title), $copiedRow);
474  }
475  } else {
476  // Else the page:
477  // Prepare search words for markup in content:
478  $markUpSwParams = [];
479  if ($this->settings['forwardSearchWordsInResultLink']['_typoScriptNodeValue']) {
480  if ($this->settings['forwardSearchWordsInResultLink']['no_cache']) {
481  $markUpSwParams = ['no_cache' => 1];
482  }
483  foreach ($this->searchWords as $d) {
484  $markUpSwParams['sword_list'][] = $d['sword'];
485  }
486  }
487  $title = $this->linkPage($row['data_page_id'], htmlspecialchars($title), $row, $markUpSwParams);
488  }
489  $resultData['title'] = $title;
490  $resultData['icon'] = $this->makeItemTypeIcon($row['item_type'], '', $specRowConf);
491  $resultData['rating'] = $this->makeRating($row);
492  $resultData['description'] = $this->makeDescription(
493  $row,
494  (bool)!($this->searchData['extResume'] && !$headerOnly),
495  $this->settings['results.']['summaryCropAfter']
496  );
497  $resultData['language'] = $this->makeLanguageIndication($row);
498  $resultData['size'] = GeneralUtility::formatSize($row['item_size']);
499  $resultData['created'] = $row['item_crdate'];
500  $resultData['modified'] = $row['item_mtime'];
501  $pI = parse_url($row['data_filename']);
502  if ($pI['scheme']) {
503  $targetAttribute = '';
504  if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
505  $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
506  }
507  $resultData['path'] = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($row['data_filename']) . '</a>';
508  } else {
509  $pathId = $row['data_page_id'] ?: $row['page_id'];
510  $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
511  $pathStr = $this->getPathFromPageId($pathId, $pathMP);
512  $resultData['path'] = $this->linkPage($pathId, $pathStr, [
513  'cHashParams' => $row['cHashParams'],
514  'data_page_type' => $row['data_page_type'],
515  'data_page_mp' => $pathMP,
516  'sys_language_uid' => $row['sys_language_uid']
517  ]);
518  // check if the access is restricted
519  if (is_array($this->requiredFrontendUsergroups[$pathId]) && !empty($this->requiredFrontendUsergroups[$pathId])) {
520  $resultData['access'] = '<img src="' . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath('indexed_search')
521  . 'Resources/Public/Icons/FileTypes/locked.gif" width="12" height="15" vspace="5" title="'
522  . sprintf(LocalizationUtility::translate('result.memberGroups', 'IndexedSearch'), implode(',', array_unique($this->requiredFrontendUsergroups[$pathId])))
523  . '" alt="" />';
524  }
525  }
526  // If there are subrows (eg. subpages in a PDF-file or if a duplicate page
527  // is selected due to user-login (phash_grouping))
528  if (is_array($row['_sub'])) {
529  $resultData['subresults'] = [];
530  if ($this->multiplePagesType($row['item_type'])) {
531  $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'IndexedSearch');
532  foreach ($row['_sub'] as $subRow) {
533  $resultData['subresults']['items'][] = $this->compileSingleResultRow($subRow, 1);
534  }
535  } else {
536  $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'IndexedSearch');
537  $resultData['subresults']['info'] = LocalizationUtility::translate('result.otherPageAsWell', 'IndexedSearch');
538  }
539  }
540  return $resultData;
541  }
542 
550  protected function getSpecialConfigurationForResultRow($row)
551  {
552  $pathId = $row['data_page_id'] ?: $row['page_id'];
553  $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
554  $rl = $GLOBALS['TSFE']->sys_page->getRootLine($pathId, $pathMP);
555  $specConf = $this->settings['specialConfiguration']['0'];
556  if (is_array($rl)) {
557  foreach ($rl as $dat) {
558  if (is_array($this->settings['specialConfiguration'][$dat['uid']])) {
559  $specConf = $this->settings['specialConfiguration'][$dat['uid']];
560  $specConf['_pid'] = $dat['uid'];
561  break;
562  }
563  }
564  }
565  return $specConf;
566  }
567 
575  protected function makeRating($row)
576  {
577  switch ((string)$this->searchData['sortOrder']) {
578  case 'rank_count':
579  return $row['order_val'] . ' ' . LocalizationUtility::translate('result.ratingMatches', 'IndexedSearch');
580  break;
581  case 'rank_first':
582  return ceil(MathUtility::forceIntegerInRange((255 - $row['order_val']), 1, 255) / 255 * 100) . '%';
583  break;
584  case 'rank_flag':
585  if ($this->firstRow['order_val2']) {
586  // (3 MSB bit, 224 is highest value of order_val1 currently)
587  $base = $row['order_val1'] * 256;
588  // 15-3 MSB = 12
589  $freqNumber = $row['order_val2'] / $this->firstRow['order_val2'] * pow(2, 12);
590  $total = MathUtility::forceIntegerInRange($base + $freqNumber, 0, 32767);
591  return ceil(log($total) / log(32767) * 100) . '%';
592  }
593  break;
594  case 'rank_freq':
595  $max = 10000;
596  $total = MathUtility::forceIntegerInRange($row['order_val'], 0, $max);
597  return ceil(log($total) / log($max) * 100) . '%';
598  break;
599  case 'crdate':
600  return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_crdate'], 0);
601  break;
602  case 'mtime':
603  return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_mtime'], 0);
604  break;
605  default:
606  return ' ';
607  }
608  }
609 
616  protected function makeLanguageIndication($row)
617  {
618  $output = '&nbsp;';
619  // If search result is a TYPO3 page:
620  if ((string)$row['item_type'] === '0') {
621  // If TypoScript is used to render the flag:
622  if (is_array($this->settings['flagRendering'])) {
624  $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
625  $cObj->setCurrentVal($row['sys_language_uid']);
626  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['flagRendering']);
627  $output = $cObj->cObjGetSingle($this->settings['flagRendering']['_typoScriptNodeValue'], $typoScriptArray);
628  }
629  }
630  return $output;
631  }
632 
641  public function makeItemTypeIcon($imageType, $alt, $specRowConf)
642  {
643  // Build compound key if item type is 0, iconRendering is not used
644  // and specialConfiguration.[pid].pageIcon was set in TS
645  if ($imageType === '0' && $specRowConf['_pid'] && is_array($specRowConf['pageIcon']) && !is_array($this->settings['iconRendering'])) {
646  $imageType .= ':' . $specRowConf['_pid'];
647  }
648  if (!isset($this->iconFileNameCache[$imageType])) {
649  $this->iconFileNameCache[$imageType] = '';
650  // If TypoScript is used to render the icon:
651  if (is_array($this->settings['iconRendering'])) {
653  $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
654  $cObj->setCurrentVal($imageType);
655  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['iconRendering']);
656  $this->iconFileNameCache[$imageType] = $cObj->cObjGetSingle($this->settings['iconRendering']['_typoScriptNodeValue'], $typoScriptArray);
657  } else {
658  // Default creation / finding of icon:
659  $icon = '';
660  if ($imageType === '0' || substr($imageType, 0, 2) == '0:') {
661  if (is_array($specRowConf['pageIcon'])) {
662  $this->iconFileNameCache[$imageType] = $GLOBALS['TSFE']->cObj->cObjGetSingle('IMAGE', $specRowConf['pageIcon']);
663  } else {
664  $icon = 'EXT:indexed_search/Resources/Public/Icons/FileTypes/pages.gif';
665  }
666  } elseif ($this->externalParsers[$imageType]) {
667  $icon = $this->externalParsers[$imageType]->getIcon($imageType);
668  }
669  if ($icon) {
670  $fullPath = GeneralUtility::getFileAbsFileName($icon);
671  if ($fullPath) {
672  $info = @getimagesize($fullPath);
674  $this->iconFileNameCache[$imageType] = is_array($info) ? '<img src="' . $iconPath . '" ' . $info[3] . ' title="' . htmlspecialchars($alt) . '" alt="" />' : '';
675  }
676  }
677  }
678  }
679  return $this->iconFileNameCache[$imageType];
680  }
681 
691  protected function makeDescription($row, $noMarkup = false, $length = 180)
692  {
693  if ($row['show_resume']) {
694  if (!$noMarkup) {
695  $markedSW = '';
696  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('index_fulltext');
697  $ftdrow = $queryBuilder
698  ->select('*')
699  ->from('index_fulltext')
700  ->where(
701  $queryBuilder->expr()->eq(
702  'phash',
703  $queryBuilder->createNamedParameter($row['phash'], \PDO::PARAM_INT)
704  )
705  )
706  ->execute()
707  ->fetch();
708  if ($ftdrow !== false) {
709  // Cut HTTP references after some length
710  $content = preg_replace('/(http:\\/\\/[^ ]{' . $this->settings['results.']['hrefInSummaryCropAfter'] . '})([^ ]+)/i', '$1...', $ftdrow['fulltextdata']);
711  $markedSW = $this->markupSWpartsOfString($content);
712  }
713  }
714  if (!trim($markedSW)) {
715  $outputStr = $this->charsetConverter->crop('utf-8', $row['item_description'], $length, $this->settings['results.']['summaryCropSignifier']);
716  $outputStr = htmlspecialchars($outputStr);
717  }
718  $output = $outputStr ?: $markedSW;
719  } else {
720  $output = '<span class="noResume">' . LocalizationUtility::translate('result.noResume', 'IndexedSearch') . '</span>';
721  }
722  return $output;
723  }
724 
731  protected function markupSWpartsOfString($str)
732  {
733  $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
734  // Init:
735  $str = str_replace('&nbsp;', ' ', $htmlParser->bidir_htmlspecialchars($str, -1));
736  $str = preg_replace('/\\s\\s+/', ' ', $str);
737  $swForReg = [];
738  // Prepare search words for regex:
739  foreach ($this->searchWords as $d) {
740  $swForReg[] = preg_quote($d['sword'], '/');
741  }
742  $regExString = '(' . implode('|', $swForReg) . ')';
743  // Split and combine:
744  $parts = preg_split('/' . $regExString . '/i', ' ' . $str . ' ', 20000, PREG_SPLIT_DELIM_CAPTURE);
745  // Constants:
746  $summaryMax = $this->settings['results.']['markupSW_summaryMax'];
747  $postPreLgd = $this->settings['results.']['markupSW_postPreLgd'];
748  $postPreLgd_offset = $this->settings['results.']['markupSW_postPreLgd_offset'];
749  $divider = $this->settings['results.']['markupSW_divider'];
750  $occurencies = (count($parts) - 1) / 2;
751  if ($occurencies) {
752  $postPreLgd = MathUtility::forceIntegerInRange($summaryMax / $occurencies, $postPreLgd, $summaryMax / 2);
753  }
754  // Variable:
755  $summaryLgd = 0;
756  $output = [];
757  // Shorten in-between strings:
758  foreach ($parts as $k => $strP) {
759  if ($k % 2 == 0) {
760  // Find length of the summary part:
761  $strLen = mb_strlen($parts[$k], 'utf-8');
762  $output[$k] = $parts[$k];
763  // Possibly shorten string:
764  if (!$k) {
765  // First entry at all (only cropped on the frontside)
766  if ($strLen > $postPreLgd) {
767  $output[$k] = $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', $this->charsetConverter->crop('utf-8', $parts[$k], -($postPreLgd - $postPreLgd_offset)));
768  }
769  } elseif ($summaryLgd > $summaryMax || !isset($parts[$k + 1])) {
770  // In case summary length is exceed OR if there are no more entries at all:
771  if ($strLen > $postPreLgd) {
772  $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', $this->charsetConverter->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider;
773  }
774  } else {
775  if ($strLen > $postPreLgd * 2) {
776  $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', $this->charsetConverter->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', $this->charsetConverter->crop('utf-8', $parts[$k], -($postPreLgd - $postPreLgd_offset)));
777  }
778  }
779  $summaryLgd += mb_strlen($output[$k], 'utf-8');
780  // Protect output:
781  $output[$k] = htmlspecialchars($output[$k]);
782  // If summary lgd is exceed, break the process:
783  if ($summaryLgd > $summaryMax) {
784  break;
785  }
786  } else {
787  $summaryLgd += mb_strlen($strP, 'utf-8');
788  $output[$k] = '<strong class="tx-indexedsearch-redMarkup">' . htmlspecialchars($parts[$k]) . '</strong>';
789  }
790  }
791  // Return result:
792  return implode('', $output);
793  }
794 
804  protected function writeSearchStat($searchParams, $searchWords, $count, $pt)
805  {
806  $insertFields = [
807  'searchstring' => $this->getSword(),
808  'searchoptions' => serialize([$searchParams, $searchWords, $pt]),
809  'feuser_id' => (int)$GLOBALS['TSFE']->fe_user->user['uid'],
810  // cookie as set or retrieved. If people has cookies disabled this will vary all the time
811  'cookie' => $GLOBALS['TSFE']->fe_user->id,
812  // Remote IP address
813  'IP' => GeneralUtility::getIndpEnv('REMOTE_ADDR'),
814  // Number of hits on the search
815  'hits' => (int)$count,
816  // Time stamp
817  'tstamp' => $GLOBALS['EXEC_TIME']
818  ];
819  $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_search_stat');
820  $connection->insert('index_stat_search', $insertFields);
821  $newId = $connection->lastInsertId('index_stat_search');
822  if ($newId) {
823  $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_stat_word');
824  foreach ($searchWords as $val) {
825  $insertFields = [
826  'word' => $val['sword'],
827  'index_stat_search_id' => $newId,
828  // Time stamp
829  'tstamp' => $GLOBALS['EXEC_TIME'],
830  // search page id for indexed search stats
831  'pageid' => $GLOBALS['TSFE']->id
832  ];
833  $connection->insert('index_stat_word', $insertFields);
834  }
835  }
836  }
837 
854  protected function getSearchWords($defaultOperator)
855  {
856  // Shorten search-word string to max 200 bytes (does NOT take multibyte charsets into account - but never mind,
857  // shortening the string here is only a run-away feature!)
858  $searchWords = substr($this->getSword(), 0, 200);
859  // Convert to UTF-8 + conv. entities (was also converted during indexing!)
860  $searchWords = $this->charsetConverter->conv($searchWords, $GLOBALS['TSFE']->metaCharset, 'utf-8');
861  $searchWords = $this->charsetConverter->entities_to_utf8($searchWords);
862  $sWordArray = false;
863  if ($hookObj = $this->hookRequest('getSearchWords')) {
864  $sWordArray = $hookObj->getSearchWords_splitSWords($searchWords, $defaultOperator);
865  } else {
866  // sentence
867  if ($this->searchData['searchType'] == 20) {
868  $sWordArray = [
869  [
870  'sword' => trim($searchWords),
871  'oper' => 'AND'
872  ]
873  ];
874  } else {
875  // case-sensitive. Defines the words, which will be
876  // operators between words
877  $operatorTranslateTable = [
878  ['+', 'AND'],
879  ['|', 'OR'],
880  ['-', 'AND NOT'],
881  // Add operators for various languages
882  // Converts the operators to lowercase
883  [mb_strtolower(LocalizationUtility::translate('localizedOperandAnd', 'IndexedSearch'), 'utf-8'), 'AND'],
884  [mb_strtolower(LocalizationUtility::translate('localizedOperandOr', 'IndexedSearch'), 'utf-8'), 'OR'],
885  [mb_strtolower(LocalizationUtility::translate('localizedOperandNot', 'IndexedSearch'), 'utf-8'), 'AND NOT']
886  ];
887  $swordArray = \TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::getExplodedSearchString($searchWords, $defaultOperator == 1 ? 'OR' : 'AND', $operatorTranslateTable);
888  if (is_array($swordArray)) {
889  $sWordArray = $this->procSearchWordsByLexer($swordArray);
890  }
891  }
892  }
893  return $sWordArray;
894  }
895 
904  {
905  $newSearchWords = [];
906  // Init lexer (used to post-processing of search words)
907  $lexerObjRef = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ?: \TYPO3\CMS\IndexedSearch\Lexer::class;
908  $this->lexerObj = GeneralUtility::getUserObj($lexerObjRef);
909  // Traverse the search word array
910  foreach ($searchWords as $wordDef) {
911  // No space in word (otherwise it might be a sentense in quotes like "there is").
912  if (strpos($wordDef['sword'], ' ') === false) {
913  // Split the search word by lexer:
914  $res = $this->lexerObj->split2Words($wordDef['sword']);
915  // Traverse lexer result and add all words again:
916  foreach ($res as $word) {
917  $newSearchWords[] = [
918  'sword' => $word,
919  'oper' => $wordDef['oper']
920  ];
921  }
922  } else {
923  $newSearchWords[] = $wordDef;
924  }
925  }
926  return $newSearchWords;
927  }
928 
936  public function formAction($search = [])
937  {
938  $searchData = $this->initialize($search);
939  // Adding search field value
940  $this->view->assign('sword', $this->getSword());
941  // Extended search
942  if ($search['extendedSearch']) {
943  // "Search for"
944  $allSearchTypes = $this->getAllAvailableSearchTypeOptions();
945  $this->view->assign('allSearchTypes', $allSearchTypes);
946  $allDefaultOperands = $this->getAllAvailableOperandsOptions();
947  $this->view->assign('allDefaultOperands', $allDefaultOperands);
948  $showTypeSearch = !empty($allSearchTypes) || !empty($allDefaultOperands);
949  $this->view->assign('showTypeSearch', $showTypeSearch);
950  // "Search in"
951  $allMediaTypes = $this->getAllAvailableMediaTypesOptions();
952  $this->view->assign('allMediaTypes', $allMediaTypes);
953  $allLanguageUids = $this->getAllAvailableLanguageOptions();
954  $this->view->assign('allLanguageUids', $allLanguageUids);
955  $showMediaAndLanguageSearch = !empty($allMediaTypes) || !empty($allLanguageUids);
956  $this->view->assign('showMediaAndLanguageSearch', $showMediaAndLanguageSearch);
957  // Sections
958  $allSections = $this->getAllAvailableSectionsOptions();
959  $this->view->assign('allSections', $allSections);
960  // Free Indexing Configurations
961  $allIndexConfigurations = $this->getAllAvailableIndexConfigurationsOptions();
962  $this->view->assign('allIndexConfigurations', $allIndexConfigurations);
963  // Sorting
964  $allSortOrders = $this->getAllAvailableSortOrderOptions();
965  $this->view->assign('allSortOrders', $allSortOrders);
966  $allSortDescendings = $this->getAllAvailableSortDescendingOptions();
967  $this->view->assign('allSortDescendings', $allSortDescendings);
968  $showSortOrders = !empty($allSortOrders) || !empty($allSortDescendings);
969  $this->view->assign('showSortOrders', $showSortOrders);
970  // Limits
971  $allNumberOfResults = $this->getAllAvailableNumberOfResultsOptions();
972  $this->view->assign('allNumberOfResults', $allNumberOfResults);
973  $allGroups = $this->getAllAvailableGroupOptions();
974  $this->view->assign('allGroups', $allGroups);
975  }
976  $this->view->assign('searchParams', $searchData);
977  }
978 
982  public function noTypoScriptAction()
983  {
984  }
985 
986  /****************************************
987  * building together the available options for every dropdown
988  ***************************************/
994  protected function getAllAvailableSearchTypeOptions()
995  {
996  $allOptions = [];
997  $types = [0, 1, 2, 3, 10, 20];
998  $blindSettings = $this->settings['blind'];
999  if (!$blindSettings['searchType']) {
1000  foreach ($types as $typeNum) {
1001  $allOptions[$typeNum] = LocalizationUtility::translate('searchTypes.' . $typeNum, 'IndexedSearch');
1002  }
1003  }
1004  // Remove this option if metaphone search is disabled)
1005  if (!$this->enableMetaphoneSearch) {
1006  unset($allOptions[10]);
1007  }
1008  // disable single entries by TypoScript
1009  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['searchType']);
1010  return $allOptions;
1011  }
1012 
1018  protected function getAllAvailableOperandsOptions()
1019  {
1020  $allOptions = [];
1021  $blindSettings = $this->settings['blind'];
1022  if (!$blindSettings['defaultOperand']) {
1023  $allOptions = [
1024  0 => LocalizationUtility::translate('defaultOperands.0', 'IndexedSearch'),
1025  1 => LocalizationUtility::translate('defaultOperands.1', 'IndexedSearch')
1026  ];
1027  }
1028  // disable single entries by TypoScript
1029  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['defaultOperand']);
1030  return $allOptions;
1031  }
1032 
1039  {
1040  $allOptions = [];
1041  $mediaTypes = [-1, 0, -2];
1042  $blindSettings = $this->settings['blind'];
1043  if (!$blindSettings['mediaType']) {
1044  foreach ($mediaTypes as $mediaType) {
1045  $allOptions[$mediaType] = LocalizationUtility::translate('mediaTypes.' . $mediaType, 'IndexedSearch');
1046  }
1047  // Add media to search in:
1048  $additionalMedia = trim($this->settings['mediaList']);
1049  if ($additionalMedia !== '') {
1050  $additionalMedia = GeneralUtility::trimExplode(',', $additionalMedia, true);
1051  } else {
1052  $additionalMedia = [];
1053  }
1054  foreach ($this->externalParsers as $extension => $obj) {
1055  // Skip unwanted extensions
1056  if (!empty($additionalMedia) && !in_array($extension, $additionalMedia)) {
1057  continue;
1058  }
1059  if ($name = $obj->searchTypeMediaTitle($extension)) {
1060  $translatedName = LocalizationUtility::translate('mediaTypes.' . $extension, 'IndexedSearch');
1061  $allOptions[$extension] = $translatedName ?: $name;
1062  }
1063  }
1064  }
1065  // disable single entries by TypoScript
1066  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['mediaType']);
1067  return $allOptions;
1068  }
1069 
1075  protected function getAllAvailableLanguageOptions()
1076  {
1077  $allOptions = [
1078  '-1' => LocalizationUtility::translate('languageUids.-1', 'IndexedSearch'),
1079  '0' => LocalizationUtility::translate('languageUids.0', 'IndexedSearch')
1080  ];
1081  $blindSettings = $this->settings['blind'];
1082  if (!$blindSettings['languageUid']) {
1083  // Add search languages
1084  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1085  ->getQueryBuilderForTable('sys_language');
1086  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1087  $result = $queryBuilder
1088  ->select('uid', 'title')
1089  ->from('sys_language')
1090  ->execute();
1091 
1092  while ($lang = $result->fetch()) {
1093  $allOptions[$lang['uid']] = $lang['title'];
1094  }
1095  // disable single entries by TypoScript
1096  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['languageUid']);
1097  } else {
1098  $allOptions = [];
1099  }
1100  return $allOptions;
1101  }
1102 
1112  protected function getAllAvailableSectionsOptions()
1113  {
1114  $allOptions = [];
1115  $sections = [0, -1, -2, -3];
1116  $blindSettings = $this->settings['blind'];
1117  if (!$blindSettings['sections']) {
1118  foreach ($sections as $section) {
1119  $allOptions[$section] = LocalizationUtility::translate('sections.' . $section, 'IndexedSearch');
1120  }
1121  }
1122  // Creating levels for section menu:
1123  // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
1124  if ($this->settings['displayLevel1Sections']) {
1125  $firstLevelMenu = $this->getMenuOfPages($this->searchRootPageIdList);
1126  $labelLevel1 = LocalizationUtility::translate('sections.rootLevel1', 'IndexedSearch');
1127  $labelLevel2 = LocalizationUtility::translate('sections.rootLevel2', 'IndexedSearch');
1128  foreach ($firstLevelMenu as $firstLevelKey => $menuItem) {
1129  if (!$menuItem['nav_hide']) {
1130  $allOptions['rl1_' . $menuItem['uid']] = trim($labelLevel1 . ' ' . $menuItem['title']);
1131  if ($this->settings['displayLevel2Sections']) {
1132  $secondLevelMenu = $this->getMenuOfPages($menuItem['uid']);
1133  foreach ($secondLevelMenu as $secondLevelKey => $menuItemLevel2) {
1134  if (!$menuItemLevel2['nav_hide']) {
1135  $allOptions['rl2_' . $menuItemLevel2['uid']] = trim($labelLevel2 . ' ' . $menuItemLevel2['title']);
1136  } else {
1137  unset($secondLevelMenu[$secondLevelKey]);
1138  }
1139  }
1140  $allOptions['rl2_' . implode(',', array_keys($secondLevelMenu))] = LocalizationUtility::translate('sections.rootLevel2All', 'IndexedSearch');
1141  }
1142  } else {
1143  unset($firstLevelMenu[$firstLevelKey]);
1144  }
1145  }
1146  $allOptions['rl1_' . implode(',', array_keys($firstLevelMenu))] = LocalizationUtility::translate('sections.rootLevel1All', 'IndexedSearch');
1147  }
1148  // disable single entries by TypoScript
1149  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sections']);
1150  return $allOptions;
1151  }
1152 
1159  {
1160  $allOptions = [
1161  '-1' => LocalizationUtility::translate('indexingConfigurations.-1', 'IndexedSearch'),
1162  '-2' => LocalizationUtility::translate('indexingConfigurations.-2', 'IndexedSearch'),
1163  '0' => LocalizationUtility::translate('indexingConfigurations.0', 'IndexedSearch')
1164  ];
1165  $blindSettings = $this->settings['blind'];
1166  if (!$blindSettings['indexingConfigurations']) {
1167  // add an additional index configuration
1168  if ($this->settings['defaultFreeIndexUidList']) {
1169  $uidList = GeneralUtility::intExplode(',', $this->settings['defaultFreeIndexUidList']);
1170  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1171  ->getQueryBuilderForTable('index_config');
1172  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1173  $result = $queryBuilder
1174  ->select('uid', 'title')
1175  ->from('index_config')
1176  ->where(
1177  $queryBuilder->expr()->in(
1178  'uid',
1179  $queryBuilder->createNamedParameter($uidList, Connection::PARAM_INT_ARRAY)
1180  )
1181  )
1182  ->execute();
1183 
1184  while ($row = $result->fetch()) {
1185  $allOptions[$row['uid']]= $row['title'];
1186  }
1187  }
1188  // disable single entries by TypoScript
1189  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['indexingConfigurations']);
1190  } else {
1191  $allOptions = [];
1192  }
1193  return $allOptions;
1194  }
1195 
1205  protected function getAllAvailableSortOrderOptions()
1206  {
1207  $allOptions = [];
1208  $sortOrders = ['rank_flag', 'rank_freq', 'rank_first', 'rank_count', 'mtime', 'title', 'crdate'];
1209  $blindSettings = $this->settings['blind'];
1210  if (!$blindSettings['sortOrder']) {
1211  foreach ($sortOrders as $order) {
1212  $allOptions[$order] = LocalizationUtility::translate('sortOrders.' . $order, 'IndexedSearch');
1213  }
1214  }
1215  // disable single entries by TypoScript
1216  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sortOrder.']);
1217  return $allOptions;
1218  }
1219 
1225  protected function getAllAvailableGroupOptions()
1226  {
1227  $allOptions = [];
1228  $blindSettings = $this->settings['blind'];
1229  if (!$blindSettings['groupBy']) {
1230  $allOptions = [
1231  'sections' => LocalizationUtility::translate('groupBy.sections', 'IndexedSearch'),
1232  'flat' => LocalizationUtility::translate('groupBy.flat', 'IndexedSearch')
1233  ];
1234  }
1235  // disable single entries by TypoScript
1236  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['groupBy.']);
1237  return $allOptions;
1238  }
1239 
1246  {
1247  $allOptions = [];
1248  $blindSettings = $this->settings['blind'];
1249  if (!$blindSettings['descending']) {
1250  $allOptions = [
1251  0 => LocalizationUtility::translate('sortOrders.descending', 'IndexedSearch'),
1252  1 => LocalizationUtility::translate('sortOrders.ascending', 'IndexedSearch')
1253  ];
1254  }
1255  // disable single entries by TypoScript
1256  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['descending.']);
1257  return $allOptions;
1258  }
1259 
1266  {
1267  $allOptions = [];
1268  if (count($this->availableResultsNumbers) > 1) {
1269  $allOptions = array_combine($this->availableResultsNumbers, $this->availableResultsNumbers);
1270  }
1271  // disable single entries by TypoScript
1272  $allOptions = $this->removeOptionsFromOptionList($allOptions, $this->settings['blind']['numberOfResults']);
1273  return $allOptions;
1274  }
1275 
1283  protected function removeOptionsFromOptionList($allOptions, $blindOptions)
1284  {
1285  if (is_array($blindOptions)) {
1286  foreach ($blindOptions as $key => $val) {
1287  if ($val == 1) {
1288  unset($allOptions[$key]);
1289  }
1290  }
1291  }
1292  return $allOptions;
1293  }
1294 
1305  protected function linkPage($pageUid, $linkText, $row = [], $markUpSwParams = [])
1306  {
1307  // Parameters for link
1308  $urlParameters = (array)unserialize($row['cHashParams']);
1309  // Add &type and &MP variable:
1310  if ($row['data_page_mp']) {
1311  $urlParameters['MP'] = $row['data_page_mp'];
1312  }
1313  $urlParameters['L'] = intval($row['sys_language_uid']);
1314  // markup-GET vars:
1315  $urlParameters = array_merge($urlParameters, $markUpSwParams);
1316  // This will make sure that the path is retrieved if it hasn't been
1317  // already. Used only for the sake of the domain_record thing.
1318  if (!is_array($this->domainRecords[$pageUid])) {
1319  $this->getPathFromPageId($pageUid);
1320  }
1321  $target = '';
1322  // If external domain, then link to that:
1323  if (!empty($this->domainRecords[$pageUid])) {
1324  $scheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
1325  $firstDomain = reset($this->domainRecords[$pageUid]);
1326  $additionalParams = '';
1327  if (is_array($urlParameters) && !empty($urlParameters)) {
1328  $additionalParams = GeneralUtility::implodeArrayForUrl('', $urlParameters);
1329  }
1330  $uri = $scheme . $firstDomain . '/index.php?id=' . $pageUid . $additionalParams;
1331  if ($target = $this->settings['detectDomainRecords.']['target']) {
1332  $target = ' target="' . $target . '"';
1333  }
1334  } else {
1335  $uriBuilder = $this->controllerContext->getUriBuilder();
1336  $uri = $uriBuilder->setTargetPageUid($pageUid)->setTargetPageType($row['data_page_type'])->setUseCacheHash(true)->setArguments($urlParameters)->build();
1337  }
1338  return '<a href="' . htmlspecialchars($uri) . '"' . $target . '>' . $linkText . '</a>';
1339  }
1340 
1347  protected function getMenuOfPages($pageUid)
1348  {
1349  if ($this->settings['displayLevelxAllTypes']) {
1350  $menu = [];
1351  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1352  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1353  $result = $queryBuilder
1354  ->select('uid', 'title')
1355  ->from('pages')
1356  ->where(
1357  $queryBuilder->expr()->eq(
1358  'pid',
1359  $queryBuilder->createNamedParameter($pageUid, \PDO::PARAM_INT)
1360  )
1361  )
1362  ->orderBy('sorting')
1363  ->execute();
1364 
1365  while ($row = $result->fetch()) {
1366  $menu[$row['uid']] = $GLOBALS['TSFE']->sys_page->getPageOverlay($row);
1367  }
1368  } else {
1369  $menu = $GLOBALS['TSFE']->sys_page->getMenu($pageUid);
1370  }
1371  return $menu;
1372  }
1373 
1381  protected function getPathFromPageId($id, $pathMP = '')
1382  {
1383  $identStr = $id . '|' . $pathMP;
1384  if (!isset($this->pathCache[$identStr])) {
1385  $this->requiredFrontendUsergroups[$id] = [];
1386  $this->domainRecords[$id] = [];
1387  $rl = $GLOBALS['TSFE']->sys_page->getRootLine($id, $pathMP);
1388  $path = '';
1389  $pageCount = count($rl);
1390  if (is_array($rl) && !empty($rl)) {
1391  $breadcrumbWrap = isset($this->settings['breadcrumbWrap']) ? $this->settings['breadcrumbWrap'] : '/';
1392  $breadcrumbWraps = $GLOBALS['TSFE']->tmpl->splitConfArray(['wrap' => $breadcrumbWrap], $pageCount);
1393  foreach ($rl as $k => $v) {
1394  // Check fe_user
1395  if ($v['fe_group'] && ($v['uid'] == $id || $v['extendToSubpages'])) {
1396  $this->requiredFrontendUsergroups[$id][] = $v['fe_group'];
1397  }
1398  // Check sys_domain
1399  if ($this->settings['detectDomainRcords']) {
1400  $domainName = $this->getFirstSysDomainRecordForPage($v['uid']);
1401  if ($domainName) {
1402  $this->domainRecords[$id][] = $domainName;
1403  // Set path accordingly
1404  $path = $domainName . $path;
1405  break;
1406  }
1407  }
1408  // Stop, if we find that the current id is the current root page.
1409  if ($v['uid'] == $GLOBALS['TSFE']->config['rootLine'][0]['uid']) {
1410  array_pop($breadcrumbWraps);
1411  break;
1412  }
1413  $path = $GLOBALS['TSFE']->cObj->wrap(htmlspecialchars($v['title']), array_pop($breadcrumbWraps)['wrap']) . $path;
1414  }
1415  }
1416  $this->pathCache[$identStr] = $path;
1417  }
1418  return $this->pathCache[$identStr];
1419  }
1420 
1427  protected function getFirstSysDomainRecordForPage($id)
1428  {
1429  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_domain');
1430  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1431  $row = $queryBuilder
1432  ->select('domainName')
1433  ->from('sys_domain')
1434  ->where(
1435  $queryBuilder->expr()->eq(
1436  'pid',
1437  $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
1438  )
1439  )
1440  ->orderBy('sorting')
1441  ->setMaxResults(1)
1442  ->execute()
1443  ->fetch();
1444 
1445  return rtrim($row['domainName'], '/');
1446  }
1447 
1454  protected function initializeExternalParsers()
1455  {
1456  // Initialize external document parsers for icon display and other soft operations
1457  if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'])) {
1458  foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'] as $extension => $_objRef) {
1459  $this->externalParsers[$extension] = GeneralUtility::getUserObj($_objRef);
1460  // Init parser and if it returns FALSE, unset its entry again
1461  if (!$this->externalParsers[$extension]->softInit($extension)) {
1462  unset($this->externalParsers[$extension]);
1463  }
1464  }
1465  }
1466  }
1467 
1474  protected function hookRequest($functionName)
1475  {
1476  // Hook: menuConfig_preProcessModMenu
1477  if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]) {
1478  $hookObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]);
1479  if (method_exists($hookObj, $functionName)) {
1480  $hookObj->pObj = $this;
1481  return $hookObj;
1482  }
1483  }
1484  return null;
1485  }
1486 
1493  protected function multiplePagesType($item_type)
1494  {
1495  return is_object($this->externalParsers[$item_type]) && $this->externalParsers[$item_type]->isMultiplePageExtension($item_type);
1496  }
1497 
1501  protected function loadSettings()
1502  {
1503  if (!is_array($this->settings['results.'])) {
1504  $this->settings['results.'] = [];
1505  }
1506  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['results']);
1507 
1508  $this->settings['results.']['summaryCropAfter'] = MathUtility::forceIntegerInRange(
1509  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropAfter'], $typoScriptArray['summaryCropAfter.']),
1510  10, 5000, 180
1511  );
1512  $this->settings['results.']['summaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropSignifier'], $typoScriptArray['summaryCropSignifier.']);
1513  $this->settings['results.']['titleCropAfter'] = MathUtility::forceIntegerInRange(
1514  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropAfter'], $typoScriptArray['titleCropAfter.']),
1515  10, 500, 50
1516  );
1517  $this->settings['results.']['titleCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropSignifier'], $typoScriptArray['titleCropSignifier.']);
1518  $this->settings['results.']['markupSW_summaryMax'] = MathUtility::forceIntegerInRange(
1519  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_summaryMax'], $typoScriptArray['markupSW_summaryMax.']),
1520  10, 5000, 300
1521  );
1522  $this->settings['results.']['markupSW_postPreLgd'] = MathUtility::forceIntegerInRange(
1523  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd'], $typoScriptArray['markupSW_postPreLgd.']),
1524  1, 500, 60
1525  );
1526  $this->settings['results.']['markupSW_postPreLgd_offset'] = MathUtility::forceIntegerInRange(
1527  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd_offset'], $typoScriptArray['markupSW_postPreLgd_offset.']),
1528  1, 50, 5
1529  );
1530  $this->settings['results.']['markupSW_divider'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_divider'], $typoScriptArray['markupSW_divider.']);
1531  $this->settings['results.']['hrefInSummaryCropAfter'] = MathUtility::forceIntegerInRange(
1532  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropAfter'], $typoScriptArray['hrefInSummaryCropAfter.']),
1533  10, 400, 60
1534  );
1535  $this->settings['results.']['hrefInSummaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropSignifier'], $typoScriptArray['hrefInSummaryCropSignifier.']);
1536  }
1537 
1544  protected function getNumberOfResults($numberOfResults)
1545  {
1546  $numberOfResults = intval($numberOfResults);
1547 
1548  return (in_array($numberOfResults, $this->availableResultsNumbers)) ?
1549  $numberOfResults : $this->defaultResultNumber;
1550  }
1551 
1556  public function setSword($sword)
1557  {
1558  $this->sword = $sword;
1559  }
1560 
1565  public function getSword()
1566  {
1567  return $this->sword;
1568  }
1569 }
static trimExplode($delim, $string, $removeEmptyValues=false, $limit=0)
redirect($actionName, $controllerName=null, $extensionName=null, array $arguments=null, $pageUid=null, $delay=0, $statusCode=303)
writeSearchStat($searchParams, $searchWords, $count, $pt)
static implodeArrayForUrl($name, array $theArray, $str= '', $skipBlank=false, $rawurlencodeParamName=false)
static formatSize($sizeInBytes, $labels= '', $base=0)
makeDescription($row, $noMarkup=false, $length=180)
static translate($key, $extensionName, $arguments=null)
linkPage($pageUid, $linkText, $row=[], $markUpSwParams=[])
if(TYPO3_MODE=== 'BE') $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsfebeuserauth.php']['frontendEditingController']['default']
static makeInstance($className,...$constructorArguments)
static getExplodedSearchString($sword, $defaultOperator, $operatorTranslateTable)
static forceIntegerInRange($theInt, $min, $max=2000000000, $defaultValue=0)
Definition: MathUtility.php:31
static getFileAbsFileName($filename, $_=null, $_2=null)
getDisplayResults($searchWords, $resultData, $freeIndexUid=-1)
injectTypoScriptService(\TYPO3\CMS\Extbase\Service\TypoScriptService $typoScriptService)
static intExplode($delimiter, $string, $removeEmptyValues=false, $limit=0)