TYPO3 CMS  TYPO3_8-7
SearchController.php
Go to the documentation of this file.
1 <?php
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 
29 
37 {
43  protected $sword = '';
44 
48  protected $searchWords = [];
49 
53  protected $searchData;
54 
64  protected $searchRootPageIdList = 0;
65 
69  protected $defaultResultNumber = 10;
70 
74  protected $availableResultsNumbers = [];
75 
81  protected $searchRepository = null;
82 
88  protected $lexerObj;
89 
94  protected $externalParsers = [];
95 
101  protected $firstRow = [];
102 
108  protected $domainRecords = [];
109 
116 
122  protected $resultSections = [];
123 
129  protected $pathCache = [];
130 
136  protected $iconFileNameCache = [];
137 
143  protected $indexerConfig = [];
144 
150  protected $enableMetaphoneSearch = false;
151 
156 
160  protected $charsetConverter;
161 
166  {
167  $this->typoScriptService = $typoScriptService;
168  }
169 
176  public function initialize($searchData = [])
177  {
178  $this->charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
179  if (!is_array($searchData)) {
180  $searchData = [];
181  }
182 
183  // check if TypoScript is loaded
184  if (!isset($this->settings['results'])) {
185  $this->redirect('noTypoScript');
186  }
187 
188  // Sets availableResultsNumbers - has to be called before request settings are read to avoid DoS attack
189  $this->availableResultsNumbers = array_filter(GeneralUtility::intExplode(',', $this->settings['blind']['numberOfResults']));
190 
191  // Sets default result number if at least one availableResultsNumbers exists
192  if (isset($this->availableResultsNumbers[0])) {
193  $this->defaultResultNumber = $this->availableResultsNumbers[0];
194  }
195 
196  $this->loadSettings();
197 
198  // setting default values
199  if (is_array($this->settings['defaultOptions'])) {
200  $searchData = array_merge($this->settings['defaultOptions'], $searchData);
201  }
202  // Indexer configuration from Extension Manager interface:
203  $this->indexerConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search'], ['allowed_classes' => false]);
204  $this->enableMetaphoneSearch = (bool)$this->indexerConfig['enableMetaphoneSearch'];
205  $this->initializeExternalParsers();
206  // If "_sections" is set, this value overrides any existing value.
207  if ($searchData['_sections']) {
208  $searchData['sections'] = $searchData['_sections'];
209  }
210  // If "_sections" is set, this value overrides any existing value.
211  if ($searchData['_freeIndexUid'] !== '' && $searchData['_freeIndexUid'] !== '_') {
212  $searchData['freeIndexUid'] = $searchData['_freeIndexUid'];
213  }
214  $searchData['numberOfResults'] = $this->getNumberOfResults($searchData['numberOfResults']);
215  // This gets the search-words into the $searchWordArray
216  $this->setSword($searchData['sword']);
217  // Add previous search words to current
218  if ($searchData['sword_prev_include'] && $searchData['sword_prev']) {
219  $this->setSword(trim($searchData['sword_prev']) . ' ' . $this->getSword());
220  }
221  $this->searchWords = $this->getSearchWords($searchData['defaultOperand']);
222  // This is the id of the site root.
223  // This value may be a commalist of integer (prepared for this)
224  $this->searchRootPageIdList = (int)$GLOBALS['TSFE']->config['rootLine'][0]['uid'];
225  // Setting the list of root PIDs for the search. Notice, these page IDs MUST
226  // have a TypoScript template with root flag on them! Basically this list is used
227  // to select on the "rl0" field and page ids are registered as "rl0" only if
228  // a TypoScript template record with root flag is there.
229  // This happens AFTER the use of $this->searchRootPageIdList above because
230  // the above will then fetch the menu for the CURRENT site - regardless
231  // of this kind of searching here. Thus a general search will lookup in
232  // the WHOLE database while a specific section search will take the current sections.
233  if ($this->settings['rootPidList']) {
234  $this->searchRootPageIdList = implode(',', GeneralUtility::intExplode(',', $this->settings['rootPidList']));
235  }
236  $this->searchRepository = GeneralUtility::makeInstance(\TYPO3\CMS\IndexedSearch\Domain\Repository\IndexSearchRepository::class);
237  $this->searchRepository->initialize($this->settings, $searchData, $this->externalParsers, $this->searchRootPageIdList);
238  $this->searchData = $searchData;
239  // Calling hook for modification of initialized content
240  if ($hookObj = $this->hookRequest('initialize_postProc')) {
241  $hookObj->initialize_postProc();
242  }
243  return $searchData;
244  }
245 
252  public function searchAction($search = [])
253  {
254  $searchData = $this->initialize($search);
255  // Find free index uid:
256  $freeIndexUid = $searchData['freeIndexUid'];
257  if ($freeIndexUid == -2) {
258  $freeIndexUid = $this->settings['defaultFreeIndexUidList'];
259  } elseif (!isset($searchData['freeIndexUid'])) {
260  // index configuration is disabled
261  $freeIndexUid = -1;
262  }
263 
264  if (!empty($searchData['extendedSearch'])) {
265  $this->view->assignMultiple($this->processExtendedSearchParameters());
266  }
267 
268  $indexCfgs = GeneralUtility::intExplode(',', $freeIndexUid);
269  $resultsets = [];
270  foreach ($indexCfgs as $freeIndexUid) {
271  // Get result rows
272  $tstamp1 = GeneralUtility::milliseconds();
273  if ($hookObj = $this->hookRequest('getResultRows')) {
274  $resultData = $hookObj->getResultRows($this->searchWords, $freeIndexUid);
275  } else {
276  $resultData = $this->searchRepository->doSearch($this->searchWords, $freeIndexUid);
277  }
278  // Display search results
279  $tstamp2 = GeneralUtility::milliseconds();
280  if ($hookObj = $this->hookRequest('getDisplayResults')) {
281  $resultsets[$freeIndexUid] = $hookObj->getDisplayResults($this->searchWords, $resultData, $freeIndexUid);
282  } else {
283  $resultsets[$freeIndexUid] = $this->getDisplayResults($this->searchWords, $resultData, $freeIndexUid);
284  }
285  $tstamp3 = GeneralUtility::milliseconds();
286  // Create header if we are searching more than one indexing configuration
287  if (count($indexCfgs) > 1) {
288  if ($freeIndexUid > 0) {
289  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
290  ->getQueryBuilderForTable('index_config');
291  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
292  $indexCfgRec = $queryBuilder
293  ->select('*')
294  ->from('index_config')
295  ->where(
296  $queryBuilder->expr()->eq(
297  'uid',
298  $queryBuilder->createNamedParameter($freeIndexUid, \PDO::PARAM_INT)
299  )
300  )
301  ->execute()
302  ->fetch();
303  $categoryTitle = $indexCfgRec['title'];
304  } else {
305  $categoryTitle = LocalizationUtility::translate('indexingConfigurationHeader.' . $freeIndexUid, 'IndexedSearch');
306  }
307  $resultsets[$freeIndexUid]['categoryTitle'] = $categoryTitle;
308  }
309  // Write search statistics
310  $this->writeSearchStat($searchData, $this->searchWords, $resultData['count'], [$tstamp1, $tstamp2, $tstamp3]);
311  }
312  $this->view->assign('resultsets', $resultsets);
313  $this->view->assign('searchParams', $searchData);
314  $this->view->assign('searchWords', $this->searchWords);
315  }
316 
317  /****************************************
318  * functions to make the result rows and result sets
319  * ready for the output
320  ***************************************/
329  protected function getDisplayResults($searchWords, $resultData, $freeIndexUid = -1)
330  {
331  $result = [
332  'count' => $resultData['count'],
333  'searchWords' => $searchWords
334  ];
335  // Perform display of result rows array
336  if ($resultData) {
337  // Set first selected row (for calculation of ranking later)
338  $this->firstRow = $resultData['firstRow'];
339  // Result display here
340  $result['rows'] = $this->compileResultRows($resultData['resultRows'], $freeIndexUid);
341  $result['affectedSections'] = $this->resultSections;
342  // Browsing box
343  if ($resultData['count']) {
344  // could we get this in the view?
345  if ($this->searchData['group'] === 'sections' && $freeIndexUid <= 0) {
346  $resultSectionsCount = count($this->resultSections);
347  $result['sectionText'] = sprintf(LocalizationUtility::translate('result.' . ($resultSectionsCount > 1 ? 'inNsections' : 'inNsection'), 'IndexedSearch'), $resultSectionsCount);
348  }
349  }
350  }
351  // Print a message telling which words in which sections we searched for
352  if (substr($this->searchData['sections'], 0, 2) === 'rl') {
353  $result['searchedInSectionInfo'] = LocalizationUtility::translate('result.inSection', 'IndexedSearch') . ' "' . $this->getPathFromPageId(substr($this->searchData['sections'], 4)) . '"';
354  }
355  return $result;
356  }
357 
366  protected function compileResultRows($resultRows, $freeIndexUid = -1)
367  {
368  $finalResultRows = [];
369  // Transfer result rows to new variable,
370  // performing some mapping of sub-results etc.
371  $newResultRows = [];
372  foreach ($resultRows as $row) {
373  $id = md5($row['phash_grouping']);
374  if (is_array($newResultRows[$id])) {
375  // swapping:
376  if (!$newResultRows[$id]['show_resume'] && $row['show_resume']) {
377  // Remove old
378  $subrows = $newResultRows[$id]['_sub'];
379  unset($newResultRows[$id]['_sub']);
380  $subrows[] = $newResultRows[$id];
381  // Insert new:
382  $newResultRows[$id] = $row;
383  $newResultRows[$id]['_sub'] = $subrows;
384  } else {
385  $newResultRows[$id]['_sub'][] = $row;
386  }
387  } else {
388  $newResultRows[$id] = $row;
389  }
390  }
391  $resultRows = $newResultRows;
392  $this->resultSections = [];
393  if ($freeIndexUid <= 0 && $this->searchData['group'] === 'sections') {
394  $rl2flag = substr($this->searchData['sections'], 0, 2) === 'rl';
395  $sections = [];
396  foreach ($resultRows as $row) {
397  $id = $row['rl0'] . '-' . $row['rl1'] . ($rl2flag ? '-' . $row['rl2'] : '');
398  $sections[$id][] = $row;
399  }
400  $this->resultSections = [];
401  foreach ($sections as $id => $resultRows) {
402  $rlParts = explode('-', $id);
403  if ($rlParts[2]) {
404  $theId = $rlParts[2];
405  $theRLid = 'rl2_' . $rlParts[2];
406  } elseif ($rlParts[1]) {
407  $theId = $rlParts[1];
408  $theRLid = 'rl1_' . $rlParts[1];
409  } else {
410  $theId = $rlParts[0];
411  $theRLid = '0';
412  }
413  $sectionName = $this->getPathFromPageId($theId);
414  $sectionName = ltrim($sectionName, '/');
415  if (!trim($sectionName)) {
416  $sectionTitleLinked = LocalizationUtility::translate('result.unnamedSection', 'IndexedSearch') . ':';
417  } else {
418  $onclick = 'document.forms[\'tx_indexedsearch\'][\'tx_indexedsearch_pi2[search][_sections]\'].value=' . GeneralUtility::quoteJSvalue($theRLid) . ';document.forms[\'tx_indexedsearch\'].submit();return false;';
419  $sectionTitleLinked = '<a href="#" onclick="' . htmlspecialchars($onclick) . '">' . $sectionName . ':</a>';
420  }
421  $resultRowsCount = count($resultRows);
422  $this->resultSections[$id] = [$sectionName, $resultRowsCount];
423  // Add section header
424  $finalResultRows[] = [
425  'isSectionHeader' => true,
426  'numResultRows' => $resultRowsCount,
427  'sectionId' => $id,
428  'sectionTitle' => $sectionTitleLinked
429  ];
430  // Render result rows
431  foreach ($resultRows as $row) {
432  $finalResultRows[] = $this->compileSingleResultRow($row);
433  }
434  }
435  } else {
436  // flat mode or no sections at all
437  foreach ($resultRows as $row) {
438  $finalResultRows[] = $this->compileSingleResultRow($row);
439  }
440  }
441  return $finalResultRows;
442  }
443 
451  protected function compileSingleResultRow($row, $headerOnly = 0)
452  {
453  $specRowConf = $this->getSpecialConfigurationForResultRow($row);
454  $resultData = $row;
455  $resultData['headerOnly'] = $headerOnly;
456  $resultData['CSSsuffix'] = $specRowConf['CSSsuffix'] ? '-' . $specRowConf['CSSsuffix'] : '';
457  if ($this->multiplePagesType($row['item_type'])) {
458  $dat = unserialize($row['cHashParams']);
459  $pp = explode('-', $dat['key']);
460  if ($pp[0] != $pp[1]) {
461  $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.page', 'IndexedSearch') . ' ' . $dat['key'];
462  } else {
463  $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.pages', 'IndexedSearch') . ' ' . $pp[0];
464  }
465  }
466  $title = $resultData['item_title'] . $resultData['titleaddition'];
467  $title = GeneralUtility::fixed_lgd_cs($title, $this->settings['results.']['titleCropAfter'], $this->settings['results.']['titleCropSignifier']);
468  // If external media, link to the media-file instead.
469  if ($row['item_type']) {
470  if ($row['show_resume']) {
471  // Can link directly.
472  $targetAttribute = '';
473  if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
474  $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
475  }
476  $title = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($title) . '</a>';
477  } else {
478  // Suspicious, so linking to page instead...
479  $copiedRow = $row;
480  unset($copiedRow['cHashParams']);
481  $title = $this->linkPage($row['page_id'], htmlspecialchars($title), $copiedRow);
482  }
483  } else {
484  // Else the page:
485  // Prepare search words for markup in content:
486  $markUpSwParams = [];
487  if ($this->settings['forwardSearchWordsInResultLink']['_typoScriptNodeValue']) {
488  if ($this->settings['forwardSearchWordsInResultLink']['no_cache']) {
489  $markUpSwParams = ['no_cache' => 1];
490  }
491  foreach ($this->searchWords as $d) {
492  $markUpSwParams['sword_list'][] = $d['sword'];
493  }
494  }
495  $title = $this->linkPage($row['data_page_id'], htmlspecialchars($title), $row, $markUpSwParams);
496  }
497  $resultData['title'] = $title;
498  $resultData['icon'] = $this->makeItemTypeIcon($row['item_type'], '', $specRowConf);
499  $resultData['rating'] = $this->makeRating($row);
500  $resultData['description'] = $this->makeDescription(
501  $row,
502  (bool)!($this->searchData['extResume'] && !$headerOnly),
503  $this->settings['results.']['summaryCropAfter']
504  );
505  $resultData['language'] = $this->makeLanguageIndication($row);
506  $resultData['size'] = GeneralUtility::formatSize($row['item_size']);
507  $resultData['created'] = $row['item_crdate'];
508  $resultData['modified'] = $row['item_mtime'];
509  $pI = parse_url($row['data_filename']);
510  if ($pI['scheme']) {
511  $targetAttribute = '';
512  if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
513  $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
514  }
515  $resultData['path'] = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($row['data_filename']) . '</a>';
516  } else {
517  $pathId = $row['data_page_id'] ?: $row['page_id'];
518  $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
519  $pathStr = $this->getPathFromPageId($pathId, $pathMP);
520  $resultData['path'] = $this->linkPage($pathId, $pathStr, [
521  'cHashParams' => $row['cHashParams'],
522  'data_page_type' => $row['data_page_type'],
523  'data_page_mp' => $pathMP,
524  'sys_language_uid' => $row['sys_language_uid']
525  ]);
526  // check if the access is restricted
527  if (is_array($this->requiredFrontendUsergroups[$pathId]) && !empty($this->requiredFrontendUsergroups[$pathId])) {
528  $resultData['access'] = '<img src="' . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath('indexed_search')
529  . 'Resources/Public/Icons/FileTypes/locked.gif" width="12" height="15" vspace="5" title="'
530  . sprintf(LocalizationUtility::translate('result.memberGroups', 'IndexedSearch'), implode(',', array_unique($this->requiredFrontendUsergroups[$pathId])))
531  . '" alt="" />';
532  }
533  }
534  // If there are subrows (eg. subpages in a PDF-file or if a duplicate page
535  // is selected due to user-login (phash_grouping))
536  if (is_array($row['_sub'])) {
537  $resultData['subresults'] = [];
538  if ($this->multiplePagesType($row['item_type'])) {
539  $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'IndexedSearch');
540  foreach ($row['_sub'] as $subRow) {
541  $resultData['subresults']['items'][] = $this->compileSingleResultRow($subRow, 1);
542  }
543  } else {
544  $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'IndexedSearch');
545  $resultData['subresults']['info'] = LocalizationUtility::translate('result.otherPageAsWell', 'IndexedSearch');
546  }
547  }
548  return $resultData;
549  }
550 
558  protected function getSpecialConfigurationForResultRow($row)
559  {
560  $pathId = $row['data_page_id'] ?: $row['page_id'];
561  $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
562  $rl = $GLOBALS['TSFE']->sys_page->getRootLine($pathId, $pathMP);
563  $specConf = $this->settings['specialConfiguration']['0'];
564  if (is_array($rl)) {
565  foreach ($rl as $dat) {
566  if (is_array($this->settings['specialConfiguration'][$dat['uid']])) {
567  $specConf = $this->settings['specialConfiguration'][$dat['uid']];
568  $specConf['_pid'] = $dat['uid'];
569  break;
570  }
571  }
572  }
573  return $specConf;
574  }
575 
583  protected function makeRating($row)
584  {
585  switch ((string)$this->searchData['sortOrder']) {
586  case 'rank_count':
587  return $row['order_val'] . ' ' . LocalizationUtility::translate('result.ratingMatches', 'IndexedSearch');
588  break;
589  case 'rank_first':
590  return ceil(MathUtility::forceIntegerInRange((255 - $row['order_val']), 1, 255) / 255 * 100) . '%';
591  break;
592  case 'rank_flag':
593  if ($this->firstRow['order_val2']) {
594  // (3 MSB bit, 224 is highest value of order_val1 currently)
595  $base = $row['order_val1'] * 256;
596  // 15-3 MSB = 12
597  $freqNumber = $row['order_val2'] / $this->firstRow['order_val2'] * pow(2, 12);
598  $total = MathUtility::forceIntegerInRange($base + $freqNumber, 0, 32767);
599  return ceil(log($total) / log(32767) * 100) . '%';
600  }
601  break;
602  case 'rank_freq':
603  $max = 10000;
604  $total = MathUtility::forceIntegerInRange($row['order_val'], 0, $max);
605  return ceil(log($total) / log($max) * 100) . '%';
606  break;
607  case 'crdate':
608  return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_crdate'], 0);
609  break;
610  case 'mtime':
611  return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_mtime'], 0);
612  break;
613  default:
614  return ' ';
615  }
616  }
617 
624  protected function makeLanguageIndication($row)
625  {
626  $output = '&nbsp;';
627  // If search result is a TYPO3 page:
628  if ((string)$row['item_type'] === '0') {
629  // If TypoScript is used to render the flag:
630  if (is_array($this->settings['flagRendering'])) {
632  $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
633  $cObj->setCurrentVal($row['sys_language_uid']);
634  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['flagRendering']);
635  $output = $cObj->cObjGetSingle($this->settings['flagRendering']['_typoScriptNodeValue'], $typoScriptArray);
636  }
637  }
638  return $output;
639  }
640 
649  public function makeItemTypeIcon($imageType, $alt, $specRowConf)
650  {
651  // Build compound key if item type is 0, iconRendering is not used
652  // and specialConfiguration.[pid].pageIcon was set in TS
653  if ($imageType === '0' && $specRowConf['_pid'] && is_array($specRowConf['pageIcon']) && !is_array($this->settings['iconRendering'])) {
654  $imageType .= ':' . $specRowConf['_pid'];
655  }
656  if (!isset($this->iconFileNameCache[$imageType])) {
657  $this->iconFileNameCache[$imageType] = '';
658  // If TypoScript is used to render the icon:
659  if (is_array($this->settings['iconRendering'])) {
661  $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
662  $cObj->setCurrentVal($imageType);
663  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['iconRendering']);
664  $this->iconFileNameCache[$imageType] = $cObj->cObjGetSingle($this->settings['iconRendering']['_typoScriptNodeValue'], $typoScriptArray);
665  } else {
666  // Default creation / finding of icon:
667  $icon = '';
668  if ($imageType === '0' || substr($imageType, 0, 2) === '0:') {
669  if (is_array($specRowConf['pageIcon'])) {
670  $this->iconFileNameCache[$imageType] = $GLOBALS['TSFE']->cObj->cObjGetSingle('IMAGE', $specRowConf['pageIcon']);
671  } else {
672  $icon = 'EXT:indexed_search/Resources/Public/Icons/FileTypes/pages.gif';
673  }
674  } elseif ($this->externalParsers[$imageType]) {
675  $icon = $this->externalParsers[$imageType]->getIcon($imageType);
676  }
677  if ($icon) {
678  $fullPath = GeneralUtility::getFileAbsFileName($icon);
679  if ($fullPath) {
680  $imageInfo = GeneralUtility::makeInstance(ImageInfo::class, $fullPath);
681  $iconPath = PathUtility::stripPathSitePrefix($fullPath);
682  $this->iconFileNameCache[$imageType] = $imageInfo->getWidth()
683  ? '<img src="' . $iconPath
684  . '" width="' . $imageInfo->getWidth()
685  . '" height="' . $imageInfo->getHeight()
686  . '" title="' . htmlspecialchars($alt) . '" alt="" />'
687  : '';
688  }
689  }
690  }
691  }
692  return $this->iconFileNameCache[$imageType];
693  }
694 
704  protected function makeDescription($row, $noMarkup = false, $length = 180)
705  {
706  if ($row['show_resume']) {
707  if (!$noMarkup) {
708  $markedSW = '';
709  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('index_fulltext');
710  $ftdrow = $queryBuilder
711  ->select('*')
712  ->from('index_fulltext')
713  ->where(
714  $queryBuilder->expr()->eq(
715  'phash',
716  $queryBuilder->createNamedParameter($row['phash'], \PDO::PARAM_INT)
717  )
718  )
719  ->execute()
720  ->fetch();
721  if ($ftdrow !== false) {
722  // Cut HTTP references after some length
723  $content = preg_replace('/(http:\\/\\/[^ ]{' . $this->settings['results.']['hrefInSummaryCropAfter'] . '})([^ ]+)/i', '$1...', $ftdrow['fulltextdata']);
724  $markedSW = $this->markupSWpartsOfString($content);
725  }
726  }
727  if (!trim($markedSW)) {
728  $outputStr = GeneralUtility::fixed_lgd_cs($row['item_description'], $length, $this->settings['results.']['summaryCropSignifier']);
729  $outputStr = htmlspecialchars($outputStr);
730  }
731  $output = $outputStr ?: $markedSW;
732  } else {
733  $output = '<span class="noResume">' . LocalizationUtility::translate('result.noResume', 'IndexedSearch') . '</span>';
734  }
735  return $output;
736  }
737 
744  protected function markupSWpartsOfString($str)
745  {
746  $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
747  // Init:
748  $str = str_replace('&nbsp;', ' ', $htmlParser->bidir_htmlspecialchars($str, -1));
749  $str = preg_replace('/\\s\\s+/', ' ', $str);
750  $swForReg = [];
751  // Prepare search words for regex:
752  foreach ($this->searchWords as $d) {
753  $swForReg[] = preg_quote($d['sword'], '/');
754  }
755  $regExString = '(' . implode('|', $swForReg) . ')';
756  // Split and combine:
757  $parts = preg_split('/' . $regExString . '/i', ' ' . $str . ' ', 20000, PREG_SPLIT_DELIM_CAPTURE);
758  // Constants:
759  $summaryMax = $this->settings['results.']['markupSW_summaryMax'];
760  $postPreLgd = $this->settings['results.']['markupSW_postPreLgd'];
761  $postPreLgd_offset = $this->settings['results.']['markupSW_postPreLgd_offset'];
762  $divider = $this->settings['results.']['markupSW_divider'];
763  $occurencies = (count($parts) - 1) / 2;
764  if ($occurencies) {
765  $postPreLgd = MathUtility::forceIntegerInRange($summaryMax / $occurencies, $postPreLgd, $summaryMax / 2);
766  }
767  // Variable:
768  $summaryLgd = 0;
769  $output = [];
770  // Shorten in-between strings:
771  foreach ($parts as $k => $strP) {
772  if ($k % 2 == 0) {
773  // Find length of the summary part:
774  $strLen = mb_strlen($parts[$k], 'utf-8');
775  $output[$k] = $parts[$k];
776  // Possibly shorten string:
777  if (!$k) {
778  // First entry at all (only cropped on the frontside)
779  if ($strLen > $postPreLgd) {
780  $output[$k] = $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', GeneralUtility::fixed_lgd_cs($parts[$k], -($postPreLgd - $postPreLgd_offset)));
781  }
782  } elseif ($summaryLgd > $summaryMax || !isset($parts[$k + 1])) {
783  // In case summary length is exceed OR if there are no more entries at all:
784  if ($strLen > $postPreLgd) {
785  $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', GeneralUtility::fixed_lgd_cs($parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider;
786  }
787  } else {
788  if ($strLen > $postPreLgd * 2) {
789  $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', GeneralUtility::fixed_lgd_cs($parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', GeneralUtility::fixed_lgd_cs($parts[$k], -($postPreLgd - $postPreLgd_offset)));
790  }
791  }
792  $summaryLgd += mb_strlen($output[$k], 'utf-8');
793  // Protect output:
794  $output[$k] = htmlspecialchars($output[$k]);
795  // If summary lgd is exceed, break the process:
796  if ($summaryLgd > $summaryMax) {
797  break;
798  }
799  } else {
800  $summaryLgd += mb_strlen($strP, 'utf-8');
801  $output[$k] = '<strong class="tx-indexedsearch-redMarkup">' . htmlspecialchars($parts[$k]) . '</strong>';
802  }
803  }
804  // Return result:
805  return implode('', $output);
806  }
807 
816  protected function writeSearchStat($searchParams, $searchWords, $count, $pt)
817  {
818  $searchWord = $this->getSword();
819  if (empty($searchWord) && empty($searchWords)) {
820  return;
821  }
822 
823  $ipAddress = '';
824  try {
825  $ipMask = isset($this->indexerConfig['trackIpInStatistic']) ? (int)$this->indexerConfig['trackIpInStatistic'] : 2;
826  $ipAddress = IpAnonymizationUtility::anonymizeIp(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $ipMask);
827  } catch (\Exception $e) {
828  }
829  $insertFields = [
830  'searchstring' => $searchWord,
831  'searchoptions' => serialize([$searchParams, $searchWords, $pt]),
832  'feuser_id' => (int)$GLOBALS['TSFE']->fe_user->user['uid'],
833  // cookie as set or retrieved. If people has cookies disabled this will vary all the time
834  'cookie' => $GLOBALS['TSFE']->fe_user->id,
835  // Remote IP address
836  'IP' => $ipAddress,
837  // Number of hits on the search
838  'hits' => (int)$count,
839  // Time stamp
840  'tstamp' => $GLOBALS['EXEC_TIME']
841  ];
842  $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_search_stat');
843  $connection->insert(
844  'index_stat_search',
845  $insertFields,
846  ['searchoptions' => Connection::PARAM_LOB]
847  );
848  $newId = $connection->lastInsertId('index_stat_search');
849  if ($newId) {
850  $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_stat_word');
851  foreach ($searchWords as $val) {
852  $insertFields = [
853  'word' => $val['sword'],
854  'index_stat_search_id' => $newId,
855  // Time stamp
856  'tstamp' => $GLOBALS['EXEC_TIME'],
857  // search page id for indexed search stats
858  'pageid' => $GLOBALS['TSFE']->id
859  ];
860  $connection->insert('index_stat_word', $insertFields);
861  }
862  }
863  }
864 
881  protected function getSearchWords($defaultOperator)
882  {
883  // Shorten search-word string to max 200 bytes - shortening the string here is only a run-away feature!
884  $searchWords = mb_substr($this->getSword(), 0, 200);
885  // Convert to UTF-8 + conv. entities (was also converted during indexing!)
886  if ($GLOBALS['TSFE']->metaCharset && $GLOBALS['TSFE']->metaCharset !== 'utf-8') {
887  $searchWords = mb_convert_encoding($searchWords, 'utf-8', $GLOBALS['TSFE']->metaCharset);
888  $searchWords = html_entity_decode($searchWords);
889  }
890  $sWordArray = false;
891  if ($hookObj = $this->hookRequest('getSearchWords')) {
892  $sWordArray = $hookObj->getSearchWords_splitSWords($searchWords, $defaultOperator);
893  } else {
894  // sentence
895  if ($this->searchData['searchType'] == 20) {
896  $sWordArray = [
897  [
898  'sword' => trim($searchWords),
899  'oper' => 'AND'
900  ]
901  ];
902  } else {
903  // case-sensitive. Defines the words, which will be
904  // operators between words
905  $operatorTranslateTable = [
906  ['+', 'AND'],
907  ['|', 'OR'],
908  ['-', 'AND NOT'],
909  // Add operators for various languages
910  // Converts the operators to lowercase
911  [mb_strtolower(LocalizationUtility::translate('localizedOperandAnd', 'IndexedSearch'), 'utf-8'), 'AND'],
912  [mb_strtolower(LocalizationUtility::translate('localizedOperandOr', 'IndexedSearch'), 'utf-8'), 'OR'],
913  [mb_strtolower(LocalizationUtility::translate('localizedOperandNot', 'IndexedSearch'), 'utf-8'), 'AND NOT']
914  ];
915  $swordArray = \TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::getExplodedSearchString($searchWords, $defaultOperator == 1 ? 'OR' : 'AND', $operatorTranslateTable);
916  if (is_array($swordArray)) {
917  $sWordArray = $this->procSearchWordsByLexer($swordArray);
918  }
919  }
920  }
921  return $sWordArray;
922  }
923 
932  {
933  $newSearchWords = [];
934  // Init lexer (used to post-processing of search words)
935  $lexerObjRef = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ?: \TYPO3\CMS\IndexedSearch\Lexer::class;
936  $this->lexerObj = GeneralUtility::getUserObj($lexerObjRef);
937  // Traverse the search word array
938  foreach ($searchWords as $wordDef) {
939  // No space in word (otherwise it might be a sentense in quotes like "there is").
940  if (strpos($wordDef['sword'], ' ') === false) {
941  // Split the search word by lexer:
942  $res = $this->lexerObj->split2Words($wordDef['sword']);
943  // Traverse lexer result and add all words again:
944  foreach ($res as $word) {
945  $newSearchWords[] = [
946  'sword' => $word,
947  'oper' => $wordDef['oper']
948  ];
949  }
950  } else {
951  $newSearchWords[] = $wordDef;
952  }
953  }
954  return $newSearchWords;
955  }
956 
963  public function formAction($search = [])
964  {
965  $searchData = $this->initialize($search);
966  // Adding search field value
967  $this->view->assign('sword', $this->getSword());
968  // Extended search
969  if (!empty($searchData['extendedSearch'])) {
970  $this->view->assignMultiple($this->processExtendedSearchParameters());
971  }
972  $this->view->assign('searchParams', $searchData);
973  }
974 
978  public function noTypoScriptAction()
979  {
980  }
981 
982  /****************************************
983  * building together the available options for every dropdown
984  ***************************************/
990  protected function getAllAvailableSearchTypeOptions()
991  {
992  $allOptions = [];
993  $types = [0, 1, 2, 3, 10, 20];
994  $blindSettings = $this->settings['blind'];
995  if (!$blindSettings['searchType']) {
996  foreach ($types as $typeNum) {
997  $allOptions[$typeNum] = LocalizationUtility::translate('searchTypes.' . $typeNum, 'IndexedSearch');
998  }
999  }
1000  // Remove this option if metaphone search is disabled)
1001  if (!$this->enableMetaphoneSearch) {
1002  unset($allOptions[10]);
1003  }
1004  // disable single entries by TypoScript
1005  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['searchType']);
1006  return $allOptions;
1007  }
1008 
1014  protected function getAllAvailableOperandsOptions()
1015  {
1016  $allOptions = [];
1017  $blindSettings = $this->settings['blind'];
1018  if (!$blindSettings['defaultOperand']) {
1019  $allOptions = [
1020  0 => LocalizationUtility::translate('defaultOperands.0', 'IndexedSearch'),
1021  1 => LocalizationUtility::translate('defaultOperands.1', 'IndexedSearch')
1022  ];
1023  }
1024  // disable single entries by TypoScript
1025  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['defaultOperand']);
1026  return $allOptions;
1027  }
1028 
1035  {
1036  $allOptions = [];
1037  $mediaTypes = [-1, 0, -2];
1038  $blindSettings = $this->settings['blind'];
1039  if (!$blindSettings['mediaType']) {
1040  foreach ($mediaTypes as $mediaType) {
1041  $allOptions[$mediaType] = LocalizationUtility::translate('mediaTypes.' . $mediaType, 'IndexedSearch');
1042  }
1043  // Add media to search in:
1044  $additionalMedia = trim($this->settings['mediaList']);
1045  if ($additionalMedia !== '') {
1046  $additionalMedia = GeneralUtility::trimExplode(',', $additionalMedia, true);
1047  } else {
1048  $additionalMedia = [];
1049  }
1050  foreach ($this->externalParsers as $extension => $obj) {
1051  // Skip unwanted extensions
1052  if (!empty($additionalMedia) && !in_array($extension, $additionalMedia)) {
1053  continue;
1054  }
1055  if ($name = $obj->searchTypeMediaTitle($extension)) {
1056  $translatedName = LocalizationUtility::translate('mediaTypes.' . $extension, 'IndexedSearch');
1057  $allOptions[$extension] = $translatedName ?: $name;
1058  }
1059  }
1060  }
1061  // disable single entries by TypoScript
1062  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['mediaType']);
1063  return $allOptions;
1064  }
1065 
1071  protected function getAllAvailableLanguageOptions()
1072  {
1073  $allOptions = [
1074  '-1' => LocalizationUtility::translate('languageUids.-1', 'IndexedSearch'),
1075  '0' => LocalizationUtility::translate('languageUids.0', 'IndexedSearch')
1076  ];
1077  $blindSettings = $this->settings['blind'];
1078  if (!$blindSettings['languageUid']) {
1079  // Add search languages
1080  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1081  ->getQueryBuilderForTable('sys_language');
1082  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1083  $result = $queryBuilder
1084  ->select('uid', 'title')
1085  ->from('sys_language')
1086  ->execute();
1087 
1088  while ($lang = $result->fetch()) {
1089  $allOptions[$lang['uid']] = $lang['title'];
1090  }
1091  // disable single entries by TypoScript
1092  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['languageUid']);
1093  } else {
1094  $allOptions = [];
1095  }
1096  return $allOptions;
1097  }
1098 
1108  protected function getAllAvailableSectionsOptions()
1109  {
1110  $allOptions = [];
1111  $sections = [0, -1, -2, -3];
1112  $blindSettings = $this->settings['blind'];
1113  if (!$blindSettings['sections']) {
1114  foreach ($sections as $section) {
1115  $allOptions[$section] = LocalizationUtility::translate('sections.' . $section, 'IndexedSearch');
1116  }
1117  }
1118  // Creating levels for section menu:
1119  // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
1120  if ($this->settings['displayLevel1Sections']) {
1121  $firstLevelMenu = $this->getMenuOfPages($this->searchRootPageIdList);
1122  $labelLevel1 = LocalizationUtility::translate('sections.rootLevel1', 'IndexedSearch');
1123  $labelLevel2 = LocalizationUtility::translate('sections.rootLevel2', 'IndexedSearch');
1124  foreach ($firstLevelMenu as $firstLevelKey => $menuItem) {
1125  if (!$menuItem['nav_hide']) {
1126  $allOptions['rl1_' . $menuItem['uid']] = trim($labelLevel1 . ' ' . $menuItem['title']);
1127  if ($this->settings['displayLevel2Sections']) {
1128  $secondLevelMenu = $this->getMenuOfPages($menuItem['uid']);
1129  foreach ($secondLevelMenu as $secondLevelKey => $menuItemLevel2) {
1130  if (!$menuItemLevel2['nav_hide']) {
1131  $allOptions['rl2_' . $menuItemLevel2['uid']] = trim($labelLevel2 . ' ' . $menuItemLevel2['title']);
1132  } else {
1133  unset($secondLevelMenu[$secondLevelKey]);
1134  }
1135  }
1136  $allOptions['rl2_' . implode(',', array_keys($secondLevelMenu))] = LocalizationUtility::translate('sections.rootLevel2All', 'IndexedSearch');
1137  }
1138  } else {
1139  unset($firstLevelMenu[$firstLevelKey]);
1140  }
1141  }
1142  $allOptions['rl1_' . implode(',', array_keys($firstLevelMenu))] = LocalizationUtility::translate('sections.rootLevel1All', 'IndexedSearch');
1143  }
1144  // disable single entries by TypoScript
1145  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sections']);
1146  return $allOptions;
1147  }
1148 
1155  {
1156  $allOptions = [
1157  '-1' => LocalizationUtility::translate('indexingConfigurations.-1', 'IndexedSearch'),
1158  '-2' => LocalizationUtility::translate('indexingConfigurations.-2', 'IndexedSearch'),
1159  '0' => LocalizationUtility::translate('indexingConfigurations.0', 'IndexedSearch')
1160  ];
1161  $blindSettings = $this->settings['blind'];
1162  if (!$blindSettings['indexingConfigurations']) {
1163  // add an additional index configuration
1164  if ($this->settings['defaultFreeIndexUidList']) {
1165  $uidList = GeneralUtility::intExplode(',', $this->settings['defaultFreeIndexUidList']);
1166  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1167  ->getQueryBuilderForTable('index_config');
1168  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1169  $result = $queryBuilder
1170  ->select('uid', 'title')
1171  ->from('index_config')
1172  ->where(
1173  $queryBuilder->expr()->in(
1174  'uid',
1175  $queryBuilder->createNamedParameter($uidList, Connection::PARAM_INT_ARRAY)
1176  )
1177  )
1178  ->execute();
1179 
1180  while ($row = $result->fetch()) {
1181  $allOptions[$row['uid']]= $row['title'];
1182  }
1183  }
1184  // disable single entries by TypoScript
1185  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['indexingConfigurations']);
1186  } else {
1187  $allOptions = [];
1188  }
1189  return $allOptions;
1190  }
1191 
1201  protected function getAllAvailableSortOrderOptions()
1202  {
1203  $allOptions = [];
1204  $sortOrders = ['rank_flag', 'rank_freq', 'rank_first', 'rank_count', 'mtime', 'title', 'crdate'];
1205  $blindSettings = $this->settings['blind'];
1206  if (!$blindSettings['sortOrder']) {
1207  foreach ($sortOrders as $order) {
1208  $allOptions[$order] = LocalizationUtility::translate('sortOrders.' . $order, 'IndexedSearch');
1209  }
1210  }
1211  // disable single entries by TypoScript
1212  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sortOrder.']);
1213  return $allOptions;
1214  }
1215 
1221  protected function getAllAvailableGroupOptions()
1222  {
1223  $allOptions = [];
1224  $blindSettings = $this->settings['blind'];
1225  if (!$blindSettings['groupBy']) {
1226  $allOptions = [
1227  'sections' => LocalizationUtility::translate('groupBy.sections', 'IndexedSearch'),
1228  'flat' => LocalizationUtility::translate('groupBy.flat', 'IndexedSearch')
1229  ];
1230  }
1231  // disable single entries by TypoScript
1232  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['groupBy.']);
1233  return $allOptions;
1234  }
1235 
1242  {
1243  $allOptions = [];
1244  $blindSettings = $this->settings['blind'];
1245  if (!$blindSettings['descending']) {
1246  $allOptions = [
1247  0 => LocalizationUtility::translate('sortOrders.descending', 'IndexedSearch'),
1248  1 => LocalizationUtility::translate('sortOrders.ascending', 'IndexedSearch')
1249  ];
1250  }
1251  // disable single entries by TypoScript
1252  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['descending.']);
1253  return $allOptions;
1254  }
1255 
1262  {
1263  $allOptions = [];
1264  if (count($this->availableResultsNumbers) > 1) {
1265  $allOptions = array_combine($this->availableResultsNumbers, $this->availableResultsNumbers);
1266  }
1267  // disable single entries by TypoScript
1268  $allOptions = $this->removeOptionsFromOptionList($allOptions, $this->settings['blind']['numberOfResults']);
1269  return $allOptions;
1270  }
1271 
1279  protected function removeOptionsFromOptionList($allOptions, $blindOptions)
1280  {
1281  if (is_array($blindOptions)) {
1282  foreach ($blindOptions as $key => $val) {
1283  if ($val == 1) {
1284  unset($allOptions[$key]);
1285  }
1286  }
1287  }
1288  return $allOptions;
1289  }
1290 
1301  protected function linkPage($pageUid, $linkText, $row = [], $markUpSwParams = [])
1302  {
1303  $pageLanguage = $GLOBALS['TSFE']->sys_language_content;
1304  // Parameters for link
1305  $urlParameters = (array)unserialize($row['cHashParams']);
1306  // Add &type and &MP variable:
1307  if ($row['data_page_mp']) {
1308  $urlParameters['MP'] = $row['data_page_mp'];
1309  }
1310  if (($pageLanguage === 0 && $row['sys_language_uid'] > 0) || $pageLanguage > 0) {
1311  $urlParameters['L'] = (int)$row['sys_language_uid'];
1312  }
1313  // markup-GET vars:
1314  $urlParameters = array_merge($urlParameters, $markUpSwParams);
1315  // This will make sure that the path is retrieved if it hasn't been
1316  // already. Used only for the sake of the domain_record thing.
1317  if (!is_array($this->domainRecords[$pageUid])) {
1318  $this->getPathFromPageId($pageUid);
1319  }
1320  $target = '';
1321  // If external domain, then link to that:
1322  if (!empty($this->domainRecords[$pageUid])) {
1323  $scheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
1324  $firstDomain = reset($this->domainRecords[$pageUid]);
1325  $additionalParams = '';
1326  if (is_array($urlParameters) && !empty($urlParameters)) {
1327  $additionalParams = GeneralUtility::implodeArrayForUrl('', $urlParameters);
1328  }
1329  $uri = $scheme . $firstDomain . '/index.php?id=' . $pageUid . $additionalParams;
1330  if ($target = $this->settings['detectDomainRecords.']['target']) {
1331  $target = ' target="' . $target . '"';
1332  }
1333  } else {
1334  $uriBuilder = $this->controllerContext->getUriBuilder();
1335  $uri = $uriBuilder->setTargetPageUid($pageUid)->setTargetPageType($row['data_page_type'])->setUseCacheHash(true)->setArguments($urlParameters)->build();
1336  }
1337  return '<a href="' . htmlspecialchars($uri) . '"' . $target . '>' . $linkText . '</a>';
1338  }
1339 
1346  protected function getMenuOfPages($pageUid)
1347  {
1348  if ($this->settings['displayLevelxAllTypes']) {
1349  $menu = [];
1350  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1351  $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1352  $result = $queryBuilder
1353  ->select('uid', 'title')
1354  ->from('pages')
1355  ->where(
1356  $queryBuilder->expr()->eq(
1357  'pid',
1358  $queryBuilder->createNamedParameter($pageUid, \PDO::PARAM_INT)
1359  )
1360  )
1361  ->orderBy('sorting')
1362  ->execute();
1363 
1364  while ($row = $result->fetch()) {
1365  $menu[$row['uid']] = $GLOBALS['TSFE']->sys_page->getPageOverlay($row);
1366  }
1367  } else {
1368  $menu = $GLOBALS['TSFE']->sys_page->getMenu($pageUid);
1369  }
1370  return $menu;
1371  }
1372 
1380  protected function getPathFromPageId($id, $pathMP = '')
1381  {
1382  $identStr = $id . '|' . $pathMP;
1383  if (!isset($this->pathCache[$identStr])) {
1384  $this->requiredFrontendUsergroups[$id] = [];
1385  $this->domainRecords[$id] = [];
1386  $rl = $GLOBALS['TSFE']->sys_page->getRootLine($id, $pathMP);
1387  $path = '';
1388  $pageCount = count($rl);
1389  if (is_array($rl) && !empty($rl)) {
1390  $breadcrumbWrap = isset($this->settings['breadcrumbWrap']) ? $this->settings['breadcrumbWrap'] : '/';
1391  $breadcrumbWraps = GeneralUtility::makeInstance(TypoScriptService::class)
1392  ->explodeConfigurationForOptionSplit(['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['detectDomainRecords']) {
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 
1452  protected function initializeExternalParsers()
1453  {
1454  // Initialize external document parsers for icon display and other soft operations
1455  if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'])) {
1456  foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'] as $extension => $_objRef) {
1457  $this->externalParsers[$extension] = GeneralUtility::getUserObj($_objRef);
1458  // Init parser and if it returns FALSE, unset its entry again
1459  if (!$this->externalParsers[$extension]->softInit($extension)) {
1460  unset($this->externalParsers[$extension]);
1461  }
1462  }
1463  }
1464  }
1465 
1472  protected function hookRequest($functionName)
1473  {
1474  // Hook: menuConfig_preProcessModMenu
1475  if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]) {
1476  $hookObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]);
1477  if (method_exists($hookObj, $functionName)) {
1478  $hookObj->pObj = $this;
1479  return $hookObj;
1480  }
1481  }
1482  return null;
1483  }
1484 
1491  protected function multiplePagesType($item_type)
1492  {
1493  return is_object($this->externalParsers[$item_type]) && $this->externalParsers[$item_type]->isMultiplePageExtension($item_type);
1494  }
1495 
1503  protected function processExtendedSearchParameters()
1504  {
1505  $allSearchTypes = $this->getAllAvailableSearchTypeOptions();
1506  $allDefaultOperands = $this->getAllAvailableOperandsOptions();
1507  $allMediaTypes = $this->getAllAvailableMediaTypesOptions();
1508  $allLanguageUids = $this->getAllAvailableLanguageOptions();
1509  $allSortOrders = $this->getAllAvailableSortOrderOptions();
1510  $allSortDescendings = $this->getAllAvailableSortDescendingOptions();
1511 
1512  return [
1513  'allSearchTypes' => $allSearchTypes,
1514  'allDefaultOperands' => $allDefaultOperands,
1515  'showTypeSearch' => !empty($allSearchTypes) || !empty($allDefaultOperands),
1516  'allMediaTypes' => $allMediaTypes,
1517  'allLanguageUids' => $allLanguageUids,
1518  'showMediaAndLanguageSearch' => !empty($allMediaTypes) || !empty($allLanguageUids),
1519  'allSections' => $this->getAllAvailableSectionsOptions(),
1520  'allIndexConfigurations' => $this->getAllAvailableIndexConfigurationsOptions(),
1521  'allSortOrders' => $allSortOrders,
1522  'allSortDescendings' => $allSortDescendings,
1523  'showSortOrders' => !empty($allSortOrders) || !empty($allSortDescendings),
1524  'allNumberOfResults' => $this->getAllAvailableNumberOfResultsOptions(),
1525  'allGroups' => $this->getAllAvailableGroupOptions()
1526  ];
1527  }
1528 
1532  protected function loadSettings()
1533  {
1534  if (!is_array($this->settings['results.'])) {
1535  $this->settings['results.'] = [];
1536  }
1537  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['results']);
1538 
1539  $this->settings['results.']['summaryCropAfter'] = MathUtility::forceIntegerInRange(
1540  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropAfter'], $typoScriptArray['summaryCropAfter.']),
1541  10,
1542  5000,
1543  180
1544  );
1545  $this->settings['results.']['summaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropSignifier'], $typoScriptArray['summaryCropSignifier.']);
1546  $this->settings['results.']['titleCropAfter'] = MathUtility::forceIntegerInRange(
1547  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropAfter'], $typoScriptArray['titleCropAfter.']),
1548  10,
1549  500,
1550  50
1551  );
1552  $this->settings['results.']['titleCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropSignifier'], $typoScriptArray['titleCropSignifier.']);
1553  $this->settings['results.']['markupSW_summaryMax'] = MathUtility::forceIntegerInRange(
1554  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_summaryMax'], $typoScriptArray['markupSW_summaryMax.']),
1555  10,
1556  5000,
1557  300
1558  );
1559  $this->settings['results.']['markupSW_postPreLgd'] = MathUtility::forceIntegerInRange(
1560  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd'], $typoScriptArray['markupSW_postPreLgd.']),
1561  1,
1562  500,
1563  60
1564  );
1565  $this->settings['results.']['markupSW_postPreLgd_offset'] = MathUtility::forceIntegerInRange(
1566  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd_offset'], $typoScriptArray['markupSW_postPreLgd_offset.']),
1567  1,
1568  50,
1569  5
1570  );
1571  $this->settings['results.']['markupSW_divider'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_divider'], $typoScriptArray['markupSW_divider.']);
1572  $this->settings['results.']['hrefInSummaryCropAfter'] = MathUtility::forceIntegerInRange(
1573  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropAfter'], $typoScriptArray['hrefInSummaryCropAfter.']),
1574  10,
1575  400,
1576  60
1577  );
1578  $this->settings['results.']['hrefInSummaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropSignifier'], $typoScriptArray['hrefInSummaryCropSignifier.']);
1579  }
1580 
1587  protected function getNumberOfResults($numberOfResults)
1588  {
1589  $numberOfResults = (int)$numberOfResults;
1590 
1591  return (in_array($numberOfResults, $this->availableResultsNumbers)) ?
1592  $numberOfResults : $this->defaultResultNumber;
1593  }
1594 
1599  public function setSword($sword)
1600  {
1601  $this->sword = (string)$sword;
1602  }
1603 
1608  public function getSword()
1609  {
1610  return (string)$this->sword;
1611  }
1612 }
makeDescription($row, $noMarkup=false, $length=180)
injectTypoScriptService(\TYPO3\CMS\Core\TypoScript\TypoScriptService $typoScriptService)
static intExplode($delimiter, $string, $removeEmptyValues=false, $limit=0)
getDisplayResults($searchWords, $resultData, $freeIndexUid=-1)
static forceIntegerInRange($theInt, $min, $max=2000000000, $defaultValue=0)
Definition: MathUtility.php:31
static getFileAbsFileName($filename, $_=null, $_2=null)
static translate($key, $extensionName=null, $arguments=null)
redirect($actionName, $controllerName=null, $extensionName=null, array $arguments=null, $pageUid=null, $delay=0, $statusCode=303)
const static anonymizeIp(string $address, int $mask=null)
static trimExplode($delim, $string, $removeEmptyValues=false, $limit=0)
static makeInstance($className,... $constructorArguments)
static implodeArrayForUrl($name, array $theArray, $str='', $skipBlank=false, $rawurlencodeParamName=false)
static getExplodedSearchString($sword, $defaultOperator, $operatorTranslateTable)
static fixed_lgd_cs($string, $chars, $appendString='...')
static formatSize($sizeInBytes, $labels='', $base=0)
if(TYPO3_MODE==='BE') $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsfebeuserauth.php']['frontendEditingController']['default']
linkPage($pageUid, $linkText, $row=[], $markUpSwParams=[])
writeSearchStat($searchParams, $searchWords, $count, $pt)