TYPO3 CMS  TYPO3_7-6
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 
22 
30 {
36  protected $sword = null;
37 
41  protected $searchWords = [];
42 
46  protected $searchData;
47 
57  protected $searchRootPageIdList = 0;
58 
62  protected $defaultResultNumber = 10;
63 
69  protected $searchRepository = null;
70 
76  protected $lexerObj;
77 
82  protected $externalParsers = [];
83 
89  protected $firstRow = [];
90 
96  protected $domainRecords = [];
97 
104 
110  protected $resultSections = [];
111 
117  protected $pathCache = [];
118 
124  protected $iconFileNameCache = [];
125 
131  protected $indexerConfig = [];
132 
138  protected $enableMetaphoneSearch = false;
139 
144 
148  public function injectTypoScriptService(\TYPO3\CMS\Extbase\Service\TypoScriptService $typoScriptService)
149  {
150  $this->typoScriptService = $typoScriptService;
151  }
152 
159  public function initialize($searchData = [])
160  {
161  if (!is_array($searchData)) {
162  $searchData = [];
163  }
164 
165  // check if TypoScript is loaded
166  if (!isset($this->settings['results'])) {
167  $this->redirect('noTypoScript');
168  }
169 
170  $this->loadSettings();
171 
172  // setting default values
173  if (is_array($this->settings['defaultOptions'])) {
174  $searchData = array_merge($this->settings['defaultOptions'], $searchData);
175  }
176  // Indexer configuration from Extension Manager interface:
177  $this->indexerConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search']);
178  $this->enableMetaphoneSearch = (bool)$this->indexerConfig['enableMetaphoneSearch'];
179  $this->initializeExternalParsers();
180  // If "_sections" is set, this value overrides any existing value.
181  if ($searchData['_sections']) {
182  $searchData['sections'] = $searchData['_sections'];
183  }
184  // If "_sections" is set, this value overrides any existing value.
185  if ($searchData['_freeIndexUid'] !== '' && $searchData['_freeIndexUid'] !== '_') {
186  $searchData['freeIndexUid'] = $searchData['_freeIndexUid'];
187  }
188  $searchData['numberOfResults'] = MathUtility::forceIntegerInRange($searchData['numberOfResults'], 1, 100, $this->defaultResultNumber);
189  // This gets the search-words into the $searchWordArray
190  $this->sword = $searchData['sword'];
191  // Add previous search words to current
192  if ($searchData['sword_prev_include'] && $searchData['sword_prev']) {
193  $this->sword = trim($searchData['sword_prev']) . ' ' . $this->sword;
194  }
195  $this->searchWords = $this->getSearchWords($searchData['defaultOperand']);
196  // This is the id of the site root.
197  // This value may be a commalist of integer (prepared for this)
198  $this->searchRootPageIdList = (int)$GLOBALS['TSFE']->config['rootLine'][0]['uid'];
199  // Setting the list of root PIDs for the search. Notice, these page IDs MUST
200  // have a TypoScript template with root flag on them! Basically this list is used
201  // to select on the "rl0" field and page ids are registered as "rl0" only if
202  // a TypoScript template record with root flag is there.
203  // This happens AFTER the use of $this->searchRootPageIdList above because
204  // the above will then fetch the menu for the CURRENT site - regardless
205  // of this kind of searching here. Thus a general search will lookup in
206  // the WHOLE database while a specific section search will take the current sections.
207  if ($this->settings['rootPidList']) {
208  $this->searchRootPageIdList = implode(',', GeneralUtility::intExplode(',', $this->settings['rootPidList']));
209  }
210  $this->searchRepository = GeneralUtility::makeInstance(\TYPO3\CMS\IndexedSearch\Domain\Repository\IndexSearchRepository::class);
211  $this->searchRepository->initialize($this->settings, $searchData, $this->externalParsers, $this->searchRootPageIdList);
212  $this->searchData = $searchData;
213  // Calling hook for modification of initialized content
214  if ($hookObj = $this->hookRequest('initialize_postProc')) {
215  $hookObj->initialize_postProc();
216  }
217  return $searchData;
218  }
219 
227  public function searchAction($search = [])
228  {
229  $searchData = $this->initialize($search);
230  // Find free index uid:
231  $freeIndexUid = $searchData['freeIndexUid'];
232  if ($freeIndexUid == -2) {
233  $freeIndexUid = $this->settings['defaultFreeIndexUidList'];
234  } elseif (!isset($searchData['freeIndexUid'])) {
235  // index configuration is disabled
236  $freeIndexUid = -1;
237  }
238  $indexCfgs = GeneralUtility::intExplode(',', $freeIndexUid);
239  $resultsets = [];
240  foreach ($indexCfgs as $freeIndexUid) {
241  // Get result rows
242  $tstamp1 = GeneralUtility::milliseconds();
243  if ($hookObj = $this->hookRequest('getResultRows')) {
244  $resultData = $hookObj->getResultRows($this->searchWords, $freeIndexUid);
245  } else {
246  $resultData = $this->searchRepository->doSearch($this->searchWords, $freeIndexUid);
247  }
248  // Display search results
249  $tstamp2 = GeneralUtility::milliseconds();
250  if ($hookObj = $this->hookRequest('getDisplayResults')) {
251  $resultsets[$freeIndexUid] = $hookObj->getDisplayResults($this->searchWords, $resultData, $freeIndexUid);
252  } else {
253  $resultsets[$freeIndexUid] = $this->getDisplayResults($this->searchWords, $resultData, $freeIndexUid);
254  }
255  $tstamp3 = GeneralUtility::milliseconds();
256  // Create header if we are searching more than one indexing configuration
257  if (count($indexCfgs) > 1) {
258  if ($freeIndexUid > 0) {
259  $indexCfgRec = $this->getDatabaseConnection()->exec_SELECTgetSingleRow('title', 'index_config', 'uid=' . (int)$freeIndexUid . $GLOBALS['TSFE']->cObj->enableFields('index_config'));
260  $categoryTitle = $indexCfgRec['title'];
261  } else {
262  $categoryTitle = LocalizationUtility::translate('indexingConfigurationHeader.' . $freeIndexUid, 'IndexedSearch');
263  }
264  $resultsets[$freeIndexUid]['categoryTitle'] = $categoryTitle;
265  }
266  // Write search statistics
267  $this->writeSearchStat($searchData, $this->searchWords, $resultData['count'], [$tstamp1, $tstamp2, $tstamp3]);
268  }
269  $this->view->assign('resultsets', $resultsets);
270  $this->view->assign('searchParams', $searchData);
271  $this->view->assign('searchWords', $this->searchWords);
272  }
273 
274  /****************************************
275  * functions to make the result rows and result sets
276  * ready for the output
277  ***************************************/
286  protected function getDisplayResults($searchWords, $resultData, $freeIndexUid = -1)
287  {
288  $result = [
289  'count' => $resultData['count'],
290  'searchWords' => $searchWords
291  ];
292  // Perform display of result rows array
293  if ($resultData) {
294  // Set first selected row (for calculation of ranking later)
295  $this->firstRow = $resultData['firstRow'];
296  // Result display here
297  $result['rows'] = $this->compileResultRows($resultData['resultRows'], $freeIndexUid);
298  $result['affectedSections'] = $this->resultSections;
299  // Browsing box
300  if ($resultData['count']) {
301  // could we get this in the view?
302  if ($this->searchData['group'] == 'sections' && $freeIndexUid <= 0) {
303  $resultSectionsCount = count($this->resultSections);
304  $result['sectionText'] = sprintf(LocalizationUtility::translate('result.' . ($resultSectionsCount > 1 ? 'inNsections' : 'inNsection'), 'IndexedSearch'), $resultSectionsCount);
305  }
306  }
307  }
308  // Print a message telling which words in which sections we searched for
309  if (substr($this->searchData['sections'], 0, 2) === 'rl') {
310  $result['searchedInSectionInfo'] = LocalizationUtility::translate('result.inSection', 'IndexedSearch') . ' "' . $this->getPathFromPageId(substr($this->searchData['sections'], 4)) . '"';
311  }
312  return $result;
313  }
314 
323  protected function compileResultRows($resultRows, $freeIndexUid = -1)
324  {
325  $finalResultRows = [];
326  // Transfer result rows to new variable,
327  // performing some mapping of sub-results etc.
328  $newResultRows = [];
329  foreach ($resultRows as $row) {
330  $id = md5($row['phash_grouping']);
331  if (is_array($newResultRows[$id])) {
332  // swapping:
333  if (!$newResultRows[$id]['show_resume'] && $row['show_resume']) {
334  // Remove old
335  $subrows = $newResultRows[$id]['_sub'];
336  unset($newResultRows[$id]['_sub']);
337  $subrows[] = $newResultRows[$id];
338  // Insert new:
339  $newResultRows[$id] = $row;
340  $newResultRows[$id]['_sub'] = $subrows;
341  } else {
342  $newResultRows[$id]['_sub'][] = $row;
343  }
344  } else {
345  $newResultRows[$id] = $row;
346  }
347  }
348  $resultRows = $newResultRows;
349  $this->resultSections = [];
350  if ($freeIndexUid <= 0 && $this->searchData['group'] == 'sections') {
351  $rl2flag = substr($this->searchData['sections'], 0, 2) == 'rl';
352  $sections = [];
353  foreach ($resultRows as $row) {
354  $id = $row['rl0'] . '-' . $row['rl1'] . ($rl2flag ? '-' . $row['rl2'] : '');
355  $sections[$id][] = $row;
356  }
357  $this->resultSections = [];
358  foreach ($sections as $id => $resultRows) {
359  $rlParts = explode('-', $id);
360  if ($rlParts[2]) {
361  $theId = $rlParts[2];
362  $theRLid = 'rl2_' . $rlParts[2];
363  } elseif ($rlParts[1]) {
364  $theId = $rlParts[1];
365  $theRLid = 'rl1_' . $rlParts[1];
366  } else {
367  $theId = $rlParts[0];
368  $theRLid = '0';
369  }
370  $sectionName = $this->getPathFromPageId($theId);
371  $sectionName = ltrim($sectionName, '/');
372  if (!trim($sectionName)) {
373  $sectionTitleLinked = LocalizationUtility::translate('result.unnamedSection', 'IndexedSearch') . ':';
374  } else {
375  $onclick = 'document.forms[\'tx_indexedsearch\'][\'tx_indexedsearch_pi2[search][_sections]\'].value=' . GeneralUtility::quoteJSvalue($theRLid) . ';document.forms[\'tx_indexedsearch\'].submit();return false;';
376  $sectionTitleLinked = '<a href="#" onclick="' . htmlspecialchars($onclick) . '">' . $sectionName . ':</a>';
377  }
378  $resultRowsCount = count($resultRows);
379  $this->resultSections[$id] = [$sectionName, $resultRowsCount];
380  // Add section header
381  $finalResultRows[] = [
382  'isSectionHeader' => true,
383  'numResultRows' => $resultRowsCount,
384  'sectionId' => $id,
385  'sectionTitle' => $sectionTitleLinked
386  ];
387  // Render result rows
388  foreach ($resultRows as $row) {
389  $finalResultRows[] = $this->compileSingleResultRow($row);
390  }
391  }
392  } else {
393  // flat mode or no sections at all
394  foreach ($resultRows as $row) {
395  $finalResultRows[] = $this->compileSingleResultRow($row);
396  }
397  }
398  return $finalResultRows;
399  }
400 
408  protected function compileSingleResultRow($row, $headerOnly = 0)
409  {
410  $specRowConf = $this->getSpecialConfigurationForResultRow($row);
411  $resultData = $row;
412  $resultData['headerOnly'] = $headerOnly;
413  $resultData['CSSsuffix'] = $specRowConf['CSSsuffix'] ? '-' . $specRowConf['CSSsuffix'] : '';
414  if ($this->multiplePagesType($row['item_type'])) {
415  $dat = unserialize($row['cHashParams']);
416  $pp = explode('-', $dat['key']);
417  if ($pp[0] != $pp[1]) {
418  $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.page', 'IndexedSearch') . ' ' . $dat['key'];
419  } else {
420  $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.pages', 'IndexedSearch') . ' ' . $pp[0];
421  }
422  }
423  $title = $resultData['item_title'] . $resultData['titleaddition'];
424  $title = $GLOBALS['TSFE']->csConvObj->crop('utf-8', $title, $this->settings['results.']['titleCropAfter'], $this->settings['results.']['titleCropSignifier']);
425  // If external media, link to the media-file instead.
426  if ($row['item_type']) {
427  if ($row['show_resume']) {
428  // Can link directly.
429  $targetAttribute = '';
430  if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
431  $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
432  }
433  $title = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($title) . '</a>';
434  } else {
435  // Suspicious, so linking to page instead...
436  $copiedRow = $row;
437  unset($copiedRow['cHashParams']);
438  $title = $this->linkPage($row['page_id'], htmlspecialchars($title), $copiedRow);
439  }
440  } else {
441  // Else the page:
442  // Prepare search words for markup in content:
443  $markUpSwParams = [];
444  if ($this->settings['forwardSearchWordsInResultLink']['_typoScriptNodeValue']) {
445  if ($this->settings['forwardSearchWordsInResultLink']['no_cache']) {
446  $markUpSwParams = ['no_cache' => 1];
447  }
448  foreach ($this->searchWords as $d) {
449  $markUpSwParams['sword_list'][] = $d['sword'];
450  }
451  }
452  $title = $this->linkPage($row['data_page_id'], htmlspecialchars($title), $row, $markUpSwParams);
453  }
454  $resultData['title'] = $title;
455  $resultData['icon'] = $this->makeItemTypeIcon($row['item_type'], '', $specRowConf);
456  $resultData['rating'] = $this->makeRating($row);
457  $resultData['description'] = $this->makeDescription(
458  $row,
459  (bool)!($this->searchData['extResume'] && !$headerOnly),
460  $this->settings['results.']['summaryCropAfter']
461  );
462  $resultData['language'] = $this->makeLanguageIndication($row);
463  $resultData['size'] = GeneralUtility::formatSize($row['item_size']);
464  $resultData['created'] = $row['item_crdate'];
465  $resultData['modified'] = $row['item_mtime'];
466  $pI = parse_url($row['data_filename']);
467  if ($pI['scheme']) {
468  $targetAttribute = '';
469  if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
470  $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
471  }
472  $resultData['path'] = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($row['data_filename']) . '</a>';
473  } else {
474  $pathId = $row['data_page_id'] ?: $row['page_id'];
475  $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
476  $pathStr = $this->getPathFromPageId($pathId, $pathMP);
477  $resultData['path'] = $this->linkPage($pathId, $pathStr, [
478  'cHashParams' => $row['cHashParams'],
479  'data_page_type' => $row['data_page_type'],
480  'data_page_mp' => $pathMP,
481  'sys_language_uid' => $row['sys_language_uid']
482  ]);
483  // check if the access is restricted
484  if (is_array($this->requiredFrontendUsergroups[$pathId]) && !empty($this->requiredFrontendUsergroups[$pathId])) {
485  $resultData['access'] = '<img src="' . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath('indexed_search')
486  . 'Resources/Public/Icons/FileTypes/locked.gif" width="12" height="15" vspace="5" title="'
487  . sprintf(LocalizationUtility::translate('result.memberGroups', 'IndexedSearch'), implode(',', array_unique($this->requiredFrontendUsergroups[$pathId])))
488  . '" alt="" />';
489  }
490  }
491  // If there are subrows (eg. subpages in a PDF-file or if a duplicate page
492  // is selected due to user-login (phash_grouping))
493  if (is_array($row['_sub'])) {
494  $resultData['subresults'] = [];
495  if ($this->multiplePagesType($row['item_type'])) {
496  $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'IndexedSearch');
497  foreach ($row['_sub'] as $subRow) {
498  $resultData['subresults']['items'][] = $this->compileSingleResultRow($subRow, 1);
499  }
500  } else {
501  $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'IndexedSearch');
502  $resultData['subresults']['info'] = LocalizationUtility::translate('result.otherPageAsWell', 'IndexedSearch');
503  }
504  }
505  return $resultData;
506  }
507 
515  protected function getSpecialConfigurationForResultRow($row)
516  {
517  $pathId = $row['data_page_id'] ?: $row['page_id'];
518  $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
519  $rl = $GLOBALS['TSFE']->sys_page->getRootLine($pathId, $pathMP);
520  $specConf = $this->settings['specialConfiguration']['0'];
521  if (is_array($rl)) {
522  foreach ($rl as $dat) {
523  if (is_array($this->settings['specialConfiguration'][$dat['uid']])) {
524  $specConf = $this->settings['specialConfiguration'][$dat['uid']];
525  $specConf['_pid'] = $dat['uid'];
526  break;
527  }
528  }
529  }
530  return $specConf;
531  }
532 
540  protected function makeRating($row)
541  {
542  switch ((string)$this->searchData['sortOrder']) {
543  case 'rank_count':
544  return $row['order_val'] . ' ' . LocalizationUtility::translate('result.ratingMatches', 'IndexedSearch');
545  break;
546  case 'rank_first':
547  return ceil(MathUtility::forceIntegerInRange((255 - $row['order_val']), 1, 255) / 255 * 100) . '%';
548  break;
549  case 'rank_flag':
550  if ($this->firstRow['order_val2']) {
551  // (3 MSB bit, 224 is highest value of order_val1 currently)
552  $base = $row['order_val1'] * 256;
553  // 15-3 MSB = 12
554  $freqNumber = $row['order_val2'] / $this->firstRow['order_val2'] * pow(2, 12);
555  $total = MathUtility::forceIntegerInRange($base + $freqNumber, 0, 32767);
556  return ceil(log($total) / log(32767) * 100) . '%';
557  }
558  break;
559  case 'rank_freq':
560  $max = 10000;
561  $total = MathUtility::forceIntegerInRange($row['order_val'], 0, $max);
562  return ceil(log($total) / log($max) * 100) . '%';
563  break;
564  case 'crdate':
565  return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_crdate'], 0);
566  break;
567  case 'mtime':
568  return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_mtime'], 0);
569  break;
570  default:
571  return ' ';
572  }
573  }
574 
581  protected function makeLanguageIndication($row)
582  {
583  $output = '&nbsp;';
584  // If search result is a TYPO3 page:
585  if ((string)$row['item_type'] === '0') {
586  // If TypoScript is used to render the flag:
587  if (is_array($this->settings['flagRendering'])) {
589  $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
590  $cObj->setCurrentVal($row['sys_language_uid']);
591  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['flagRendering']);
592  $output = $cObj->cObjGetSingle($this->settings['flagRendering']['_typoScriptNodeValue'], $typoScriptArray);
593  }
594  }
595  return $output;
596  }
597 
606  public function makeItemTypeIcon($imageType, $alt, $specRowConf)
607  {
608  // Build compound key if item type is 0, iconRendering is not used
609  // and specialConfiguration.[pid].pageIcon was set in TS
610  if ($imageType === '0' && $specRowConf['_pid'] && is_array($specRowConf['pageIcon']) && !is_array($this->settings['iconRendering'])) {
611  $imageType .= ':' . $specRowConf['_pid'];
612  }
613  if (!isset($this->iconFileNameCache[$imageType])) {
614  $this->iconFileNameCache[$imageType] = '';
615  // If TypoScript is used to render the icon:
616  if (is_array($this->settings['iconRendering'])) {
618  $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
619  $cObj->setCurrentVal($imageType);
620  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['iconRendering']);
621  $this->iconFileNameCache[$imageType] = $cObj->cObjGetSingle($this->settings['iconRendering']['_typoScriptNodeValue'], $typoScriptArray);
622  } else {
623  // Default creation / finding of icon:
624  $icon = '';
625  if ($imageType === '0' || substr($imageType, 0, 2) == '0:') {
626  if (is_array($specRowConf['pageIcon'])) {
627  $this->iconFileNameCache[$imageType] = $GLOBALS['TSFE']->cObj->cObjGetSingle('IMAGE', $specRowConf['pageIcon']);
628  } else {
629  $icon = 'EXT:indexed_search/Resources/Public/Icons/FileTypes/pages.gif';
630  }
631  } elseif ($this->externalParsers[$imageType]) {
632  $icon = $this->externalParsers[$imageType]->getIcon($imageType);
633  }
634  if ($icon) {
635  $fullPath = GeneralUtility::getFileAbsFileName($icon);
636  if ($fullPath) {
637  $info = @getimagesize($fullPath);
639  $this->iconFileNameCache[$imageType] = is_array($info) ? '<img src="' . $iconPath . '" ' . $info[3] . ' title="' . htmlspecialchars($alt) . '" alt="" />' : '';
640  }
641  }
642  }
643  }
644  return $this->iconFileNameCache[$imageType];
645  }
646 
656  protected function makeDescription($row, $noMarkup = false, $length = 180)
657  {
658  if ($row['show_resume']) {
659  if (!$noMarkup) {
660  $markedSW = '';
661  $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'index_fulltext', 'phash=' . (int)$row['phash']);
662  if ($ftdrow = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
663  // Cut HTTP references after some length
664  $content = preg_replace('/(http:\\/\\/[^ ]{' . $this->settings['results.']['hrefInSummaryCropAfter'] . '})([^ ]+)/i', '$1...', $ftdrow['fulltextdata']);
665  $markedSW = $this->markupSWpartsOfString($content);
666  }
667  $this->getDatabaseConnection()->sql_free_result($res);
668  }
669  if (!trim($markedSW)) {
670  $outputStr = $GLOBALS['TSFE']->csConvObj->crop('utf-8', $row['item_description'], $length, $this->settings['results.']['summaryCropSignifier']);
671  $outputStr = htmlspecialchars($outputStr);
672  }
673  $output = $outputStr ?: $markedSW;
674  $output = $GLOBALS['TSFE']->csConv($output, 'utf-8');
675  } else {
676  $output = '<span class="noResume">' . LocalizationUtility::translate('result.noResume', 'IndexedSearch') . '</span>';
677  }
678  return $output;
679  }
680 
687  protected function markupSWpartsOfString($str)
688  {
689  $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
690  // Init:
691  $str = str_replace('&nbsp;', ' ', $htmlParser->bidir_htmlspecialchars($str, -1));
692  $str = preg_replace('/\\s\\s+/', ' ', $str);
693  $swForReg = [];
694  // Prepare search words for regex:
695  foreach ($this->searchWords as $d) {
696  $swForReg[] = preg_quote($d['sword'], '/');
697  }
698  $regExString = '(' . implode('|', $swForReg) . ')';
699  // Split and combine:
700  $parts = preg_split('/' . $regExString . '/i', ' ' . $str . ' ', 20000, PREG_SPLIT_DELIM_CAPTURE);
701  // Constants:
702  $summaryMax = $this->settings['results.']['markupSW_summaryMax'];
703  $postPreLgd = $this->settings['results.']['markupSW_postPreLgd'];
704  $postPreLgd_offset = $this->settings['results.']['markupSW_postPreLgd_offset'];
705  $divider = $this->settings['results.']['markupSW_divider'];
706  $occurencies = (count($parts) - 1) / 2;
707  if ($occurencies) {
708  $postPreLgd = MathUtility::forceIntegerInRange($summaryMax / $occurencies, $postPreLgd, $summaryMax / 2);
709  }
710  // Variable:
711  $summaryLgd = 0;
712  $output = [];
713  // Shorten in-between strings:
714  foreach ($parts as $k => $strP) {
715  if ($k % 2 == 0) {
716  // Find length of the summary part:
717  $strLen = $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $parts[$k]);
718  $output[$k] = $parts[$k];
719  // Possibly shorten string:
720  if (!$k) {
721  // First entry at all (only cropped on the frontside)
722  if ($strLen > $postPreLgd) {
723  $output[$k] = $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', $GLOBALS['TSFE']->csConvObj->crop('utf-8', $parts[$k], -($postPreLgd - $postPreLgd_offset)));
724  }
725  } elseif ($summaryLgd > $summaryMax || !isset($parts[$k + 1])) {
726  // In case summary length is exceed OR if there are no more entries at all:
727  if ($strLen > $postPreLgd) {
728  $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', $GLOBALS['TSFE']->csConvObj->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider;
729  }
730  } else {
731  if ($strLen > $postPreLgd * 2) {
732  $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', $GLOBALS['TSFE']->csConvObj->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', $GLOBALS['TSFE']->csConvObj->crop('utf-8', $parts[$k], -($postPreLgd - $postPreLgd_offset)));
733  }
734  }
735  $summaryLgd += $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $output[$k]);
736  // Protect output:
737  $output[$k] = htmlspecialchars($output[$k]);
738  // If summary lgd is exceed, break the process:
739  if ($summaryLgd > $summaryMax) {
740  break;
741  }
742  } else {
743  $summaryLgd += $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $strP);
744  $output[$k] = '<strong class="tx-indexedsearch-redMarkup">' . htmlspecialchars($parts[$k]) . '</strong>';
745  }
746  }
747  // Return result:
748  return implode('', $output);
749  }
750 
760  protected function writeSearchStat($searchParams, $searchWords, $count, $pt)
761  {
762  $ipAddress = '';
763  try {
764  $ipMask = isset($this->indexerConfig['trackIpInStatistic']) ? (int)$this->indexerConfig['trackIpInStatistic'] : 2;
765  $ipAddress = IpAnonymizationUtility::anonymizeIp(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $ipMask);
766  } catch (\Exception $e) {
767  }
768 
769  $insertFields = [
770  'searchstring' => $this->sword,
771  'searchoptions' => serialize([$searchParams, $searchWords, $pt]),
772  'feuser_id' => (int)$GLOBALS['TSFE']->fe_user->user['uid'],
773  // cookie as set or retrieved. If people has cookies disabled this will vary all the time
774  'cookie' => $GLOBALS['TSFE']->fe_user->id,
775  // Remote IP address
776  'IP' => $ipAddress,
777  // Number of hits on the search
778  'hits' => (int)$count,
779  // Time stamp
780  'tstamp' => $GLOBALS['EXEC_TIME']
781  ];
782  $this->getDatabaseConnection()->exec_INSERTquery('index_stat_search', $insertFields);
783  $newId = $this->getDatabaseConnection()->sql_insert_id();
784  if ($newId) {
785  foreach ($searchWords as $val) {
786  $insertFields = [
787  'word' => $val['sword'],
788  'index_stat_search_id' => $newId,
789  // Time stamp
790  'tstamp' => $GLOBALS['EXEC_TIME'],
791  // search page id for indexed search stats
792  'pageid' => $GLOBALS['TSFE']->id
793  ];
794  $this->getDatabaseConnection()->exec_INSERTquery('index_stat_word', $insertFields);
795  }
796  }
797  }
798 
815  protected function getSearchWords($defaultOperator)
816  {
817  // Shorten search-word string to max 200 bytes (does NOT take multibyte charsets into account - but never mind,
818  // shortening the string here is only a run-away feature!)
819  $searchWords = substr($this->sword, 0, 200);
820  // Convert to UTF-8 + conv. entities (was also converted during indexing!)
821  $searchWords = $GLOBALS['TSFE']->csConvObj->utf8_encode($searchWords, $GLOBALS['TSFE']->metaCharset);
822  $searchWords = $GLOBALS['TSFE']->csConvObj->entities_to_utf8($searchWords, true);
823  $sWordArray = false;
824  if ($hookObj = $this->hookRequest('getSearchWords')) {
825  $sWordArray = $hookObj->getSearchWords_splitSWords($searchWords, $defaultOperator);
826  } else {
827  // sentence
828  if ($this->searchData['searchType'] == 20) {
829  $sWordArray = [
830  [
831  'sword' => trim($searchWords),
832  'oper' => 'AND'
833  ]
834  ];
835  } else {
836  // case-sensitive. Defines the words, which will be
837  // operators between words
838  $operatorTranslateTable = [
839  ['+', 'AND'],
840  ['|', 'OR'],
841  ['-', 'AND NOT'],
842  // Add operators for various languages
843  // Converts the operators to UTF-8 and lowercase
844  [$GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode(LocalizationUtility::translate('localizedOperandAnd', 'IndexedSearch'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'AND'],
845  [$GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode(LocalizationUtility::translate('localizedOperandOr', 'IndexedSearch'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'OR'],
846  [$GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode(LocalizationUtility::translate('localizedOperandNot', 'IndexedSearch'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'AND NOT']
847  ];
848  $swordArray = \TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::getExplodedSearchString($searchWords, $defaultOperator == 1 ? 'OR' : 'AND', $operatorTranslateTable);
849  if (is_array($swordArray)) {
850  $sWordArray = $this->procSearchWordsByLexer($swordArray);
851  }
852  }
853  }
854  return $sWordArray;
855  }
856 
865  {
866  $newSearchWords = [];
867  // Init lexer (used to post-processing of search words)
868  $lexerObjRef = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ?: \TYPO3\CMS\IndexedSearch\Lexer::class;
869  $this->lexerObj = GeneralUtility::getUserObj($lexerObjRef);
870  // Traverse the search word array
871  foreach ($searchWords as $wordDef) {
872  // No space in word (otherwise it might be a sentense in quotes like "there is").
873  if (strpos($wordDef['sword'], ' ') === false) {
874  // Split the search word by lexer:
875  $res = $this->lexerObj->split2Words($wordDef['sword']);
876  // Traverse lexer result and add all words again:
877  foreach ($res as $word) {
878  $newSearchWords[] = [
879  'sword' => $word,
880  'oper' => $wordDef['oper']
881  ];
882  }
883  } else {
884  $newSearchWords[] = $wordDef;
885  }
886  }
887  return $newSearchWords;
888  }
889 
897  public function formAction($search = [])
898  {
899  $searchData = $this->initialize($search);
900  // Adding search field value
901  $this->view->assign('sword', $this->sword);
902  // Additonal keyword => "Add to current search words"
903  $showAdditionalKeywordSearch = $this->settings['clearSearchBox'] && $this->settings['clearSearchBox']['enableSubSearchCheckBox'];
904  if ($showAdditionalKeywordSearch) {
905  $this->view->assign('previousSearchWord', $this->settings['clearSearchBox'] ? '' : $this->sword);
906  }
907  $this->view->assign('showAdditionalKeywordSearch', $showAdditionalKeywordSearch);
908  // Extended search
909  if ($search['extendedSearch']) {
910  // "Search for"
911  $allSearchTypes = $this->getAllAvailableSearchTypeOptions();
912  $this->view->assign('allSearchTypes', $allSearchTypes);
913  $allDefaultOperands = $this->getAllAvailableOperandsOptions();
914  $this->view->assign('allDefaultOperands', $allDefaultOperands);
915  $showTypeSearch = !empty($allSearchTypes) || !empty($allDefaultOperands);
916  $this->view->assign('showTypeSearch', $showTypeSearch);
917  // "Search in"
918  $allMediaTypes = $this->getAllAvailableMediaTypesOptions();
919  $this->view->assign('allMediaTypes', $allMediaTypes);
920  $allLanguageUids = $this->getAllAvailableLanguageOptions();
921  $this->view->assign('allLanguageUids', $allLanguageUids);
922  $showMediaAndLanguageSearch = !empty($allMediaTypes) || !empty($allLanguageUids);
923  $this->view->assign('showMediaAndLanguageSearch', $showMediaAndLanguageSearch);
924  // Sections
925  $allSections = $this->getAllAvailableSectionsOptions();
926  $this->view->assign('allSections', $allSections);
927  // Free Indexing Configurations
928  $allIndexConfigurations = $this->getAllAvailableIndexConfigurationsOptions();
929  $this->view->assign('allIndexConfigurations', $allIndexConfigurations);
930  // Sorting
931  $allSortOrders = $this->getAllAvailableSortOrderOptions();
932  $this->view->assign('allSortOrders', $allSortOrders);
933  $allSortDescendings = $this->getAllAvailableSortDescendingOptions();
934  $this->view->assign('allSortDescendings', $allSortDescendings);
935  $showSortOrders = !empty($allSortOrders) || !empty($allSortDescendings);
936  $this->view->assign('showSortOrders', $showSortOrders);
937  // Limits
938  $allNumberOfResults = $this->getAllAvailableNumberOfResultsOptions();
939  $this->view->assign('allNumberOfResults', $allNumberOfResults);
940  $allGroups = $this->getAllAvailableGroupOptions();
941  $this->view->assign('allGroups', $allGroups);
942  }
943  $this->view->assign('searchParams', $searchData);
944  }
945 
949  public function noTypoScriptAction()
950  {
951  }
952 
953  /****************************************
954  * building together the available options for every dropdown
955  ***************************************/
961  protected function getAllAvailableSearchTypeOptions()
962  {
963  $allOptions = [];
964  $types = [0, 1, 2, 3, 10, 20];
965  $blindSettings = $this->settings['blind'];
966  if (!$blindSettings['searchType']) {
967  foreach ($types as $typeNum) {
968  $allOptions[$typeNum] = LocalizationUtility::translate('searchTypes.' . $typeNum, 'IndexedSearch');
969  }
970  }
971  // Remove this option if metaphone search is disabled)
972  if (!$this->enableMetaphoneSearch) {
973  unset($allOptions[10]);
974  }
975  // disable single entries by TypoScript
976  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['searchType']);
977  return $allOptions;
978  }
979 
985  protected function getAllAvailableOperandsOptions()
986  {
987  $allOptions = [];
988  $blindSettings = $this->settings['blind'];
989  if (!$blindSettings['defaultOperand']) {
990  $allOptions = [
991  0 => LocalizationUtility::translate('defaultOperands.0', 'IndexedSearch'),
992  1 => LocalizationUtility::translate('defaultOperands.1', 'IndexedSearch')
993  ];
994  }
995  // disable single entries by TypoScript
996  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['defaultOperand']);
997  return $allOptions;
998  }
999 
1006  {
1007  $allOptions = [];
1008  $mediaTypes = [-1, 0, -2];
1009  $blindSettings = $this->settings['blind'];
1010  if (!$blindSettings['mediaType']) {
1011  foreach ($mediaTypes as $mediaType) {
1012  $allOptions[$mediaType] = LocalizationUtility::translate('mediaTypes.' . $mediaType, 'IndexedSearch');
1013  }
1014  // Add media to search in:
1015  $additionalMedia = trim($this->settings['mediaList']);
1016  if ($additionalMedia !== '') {
1017  $additionalMedia = GeneralUtility::trimExplode(',', $additionalMedia, true);
1018  } else {
1019  $additionalMedia = [];
1020  }
1021  foreach ($this->externalParsers as $extension => $obj) {
1022  // Skip unwanted extensions
1023  if (!empty($additionalMedia) && !in_array($extension, $additionalMedia)) {
1024  continue;
1025  }
1026  if ($name = $obj->searchTypeMediaTitle($extension)) {
1027  $translatedName = LocalizationUtility::translate('mediaTypes.' . $extension, 'IndexedSearch');
1028  $allOptions[$extension] = $translatedName ?: $name;
1029  }
1030  }
1031  }
1032  // disable single entries by TypoScript
1033  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['mediaType']);
1034  return $allOptions;
1035  }
1036 
1042  protected function getAllAvailableLanguageOptions()
1043  {
1044  $allOptions = [
1045  '-1' => LocalizationUtility::translate('languageUids.-1', 'IndexedSearch'),
1046  '0' => LocalizationUtility::translate('languageUids.0', 'IndexedSearch')
1047  ];
1048  $blindSettings = $this->settings['blind'];
1049  if (!$blindSettings['languageUid']) {
1050  // Add search languages
1051  $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_language', '1=1' . $GLOBALS['TSFE']->cObj->enableFields('sys_language'));
1052  if ($res) {
1053  while ($lang = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
1054  $allOptions[$lang['uid']] = $lang['title'];
1055  }
1056  }
1057  // disable single entries by TypoScript
1058  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['languageUid']);
1059  } else {
1060  $allOptions = [];
1061  }
1062  return $allOptions;
1063  }
1064 
1074  protected function getAllAvailableSectionsOptions()
1075  {
1076  $allOptions = [];
1077  $sections = [0, -1, -2, -3];
1078  $blindSettings = $this->settings['blind'];
1079  if (!$blindSettings['sections']) {
1080  foreach ($sections as $section) {
1081  $allOptions[$section] = LocalizationUtility::translate('sections.' . $section, 'IndexedSearch');
1082  }
1083  }
1084  // Creating levels for section menu:
1085  // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
1086  if ($this->settings['displayLevel1Sections']) {
1087  $firstLevelMenu = $this->getMenuOfPages($this->searchRootPageIdList);
1088  $labelLevel1 = LocalizationUtility::translate('sections.rootLevel1', 'IndexedSearch');
1089  $labelLevel2 = LocalizationUtility::translate('sections.rootLevel2', 'IndexedSearch');
1090  foreach ($firstLevelMenu as $firstLevelKey => $menuItem) {
1091  if (!$menuItem['nav_hide']) {
1092  $allOptions['rl1_' . $menuItem['uid']] = trim($labelLevel1 . ' ' . $menuItem['title']);
1093  if ($this->settings['displayLevel2Sections']) {
1094  $secondLevelMenu = $this->getMenuOfPages($menuItem['uid']);
1095  foreach ($secondLevelMenu as $secondLevelKey => $menuItemLevel2) {
1096  if (!$menuItemLevel2['nav_hide']) {
1097  $allOptions['rl2_' . $menuItemLevel2['uid']] = trim($labelLevel2 . ' ' . $menuItemLevel2['title']);
1098  } else {
1099  unset($secondLevelMenu[$secondLevelKey]);
1100  }
1101  }
1102  $allOptions['rl2_' . implode(',', array_keys($secondLevelMenu))] = LocalizationUtility::translate('sections.rootLevel2All', 'IndexedSearch');
1103  }
1104  } else {
1105  unset($firstLevelMenu[$firstLevelKey]);
1106  }
1107  }
1108  $allOptions['rl1_' . implode(',', array_keys($firstLevelMenu))] = LocalizationUtility::translate('sections.rootLevel1All', 'IndexedSearch');
1109  }
1110  // disable single entries by TypoScript
1111  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sections']);
1112  return $allOptions;
1113  }
1114 
1121  {
1122  $allOptions = [
1123  '-1' => LocalizationUtility::translate('indexingConfigurations.-1', 'IndexedSearch'),
1124  '-2' => LocalizationUtility::translate('indexingConfigurations.-2', 'IndexedSearch'),
1125  '0' => LocalizationUtility::translate('indexingConfigurations.0', 'IndexedSearch')
1126  ];
1127  $blindSettings = $this->settings['blind'];
1128  if (!$blindSettings['indexingConfigurations']) {
1129  // add an additional index configuration
1130  if ($this->settings['defaultFreeIndexUidList']) {
1131  $uidList = GeneralUtility::intExplode(',', $this->settings['defaultFreeIndexUidList']);
1132  $indexCfgRecords = $this->getDatabaseConnection()->exec_SELECTgetRows('uid,title', 'index_config', 'uid IN (' . implode(',', $uidList) . ')' . $GLOBALS['TSFE']->cObj->enableFields('index_config'), '', '', '', 'uid');
1133  foreach ($uidList as $uidValue) {
1134  if (is_array($indexCfgRecords[$uidValue])) {
1135  $allOptions[$uidValue] = $indexCfgRecords[$uidValue]['title'];
1136  }
1137  }
1138  }
1139  // disable single entries by TypoScript
1140  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['indexingConfigurations']);
1141  } else {
1142  $allOptions = [];
1143  }
1144  return $allOptions;
1145  }
1146 
1156  protected function getAllAvailableSortOrderOptions()
1157  {
1158  $allOptions = [];
1159  $sortOrders = ['rank_flag', 'rank_freq', 'rank_first', 'rank_count', 'mtime', 'title', 'crdate'];
1160  $blindSettings = $this->settings['blind'];
1161  if (!$blindSettings['sortOrder']) {
1162  foreach ($sortOrders as $order) {
1163  $allOptions[$order] = LocalizationUtility::translate('sortOrders.' . $order, 'IndexedSearch');
1164  }
1165  }
1166  // disable single entries by TypoScript
1167  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sortOrder.']);
1168  return $allOptions;
1169  }
1170 
1176  protected function getAllAvailableGroupOptions()
1177  {
1178  $allOptions = [];
1179  $blindSettings = $this->settings['blind'];
1180  if (!$blindSettings['groupBy']) {
1181  $allOptions = [
1182  'sections' => LocalizationUtility::translate('groupBy.sections', 'IndexedSearch'),
1183  'flat' => LocalizationUtility::translate('groupBy.flat', 'IndexedSearch')
1184  ];
1185  }
1186  // disable single entries by TypoScript
1187  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['groupBy.']);
1188  return $allOptions;
1189  }
1190 
1197  {
1198  $allOptions = [];
1199  $blindSettings = $this->settings['blind'];
1200  if (!$blindSettings['descending']) {
1201  $allOptions = [
1202  0 => LocalizationUtility::translate('sortOrders.descending', 'IndexedSearch'),
1203  1 => LocalizationUtility::translate('sortOrders.ascending', 'IndexedSearch')
1204  ];
1205  }
1206  // disable single entries by TypoScript
1207  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['descending.']);
1208  return $allOptions;
1209  }
1210 
1217  {
1218  $allOptions = [];
1219  $blindSettings = $this->settings['blind'];
1220  if (!$blindSettings['numberOfResults']) {
1221  $allOptions = [
1222  10 => 10,
1223  25 => 25,
1224  50 => 50,
1225  100 => 100
1226  ];
1227  }
1228  // disable single entries by TypoScript
1229  $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['numberOfResults']);
1230  return $allOptions;
1231  }
1232 
1240  protected function removeOptionsFromOptionList($allOptions, $blindOptions)
1241  {
1242  if (is_array($blindOptions)) {
1243  foreach ($blindOptions as $key => $val) {
1244  if ($val == 1) {
1245  unset($allOptions[$key]);
1246  }
1247  }
1248  }
1249  return $allOptions;
1250  }
1251 
1262  protected function linkPage($pageUid, $linkText, $row = [], $markUpSwParams = [])
1263  {
1264  // Parameters for link
1265  $urlParameters = (array)unserialize($row['cHashParams']);
1266  // Add &type and &MP variable:
1267  if ($row['data_page_mp']) {
1268  $urlParameters['MP'] = $row['data_page_mp'];
1269  }
1270  $urlParameters['L'] = intval($row['sys_language_uid']);
1271  // markup-GET vars:
1272  $urlParameters = array_merge($urlParameters, $markUpSwParams);
1273  // This will make sure that the path is retrieved if it hasn't been
1274  // already. Used only for the sake of the domain_record thing.
1275  if (!is_array($this->domainRecords[$pageUid])) {
1276  $this->getPathFromPageId($pageUid);
1277  }
1278  $target = '';
1279  // If external domain, then link to that:
1280  if (!empty($this->domainRecords[$pageUid])) {
1281  $scheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
1282  $firstDomain = reset($this->domainRecords[$pageUid]);
1283  $additionalParams = '';
1284  if (is_array($urlParameters) && !empty($urlParameters)) {
1285  $additionalParams = GeneralUtility::implodeArrayForUrl('', $urlParameters);
1286  }
1287  $uri = $scheme . $firstDomain . '/index.php?id=' . $pageUid . $additionalParams;
1288  if ($target = $this->settings['detectDomainRecords.']['target']) {
1289  $target = ' target="' . $target . '"';
1290  }
1291  } else {
1292  $uriBuilder = $this->controllerContext->getUriBuilder();
1293  $uri = $uriBuilder->setTargetPageUid($pageUid)->setTargetPageType($row['data_page_type'])->setUseCacheHash(true)->setArguments($urlParameters)->build();
1294  }
1295  return '<a href="' . htmlspecialchars($uri) . '"' . $target . '>' . $linkText . '</a>';
1296  }
1297 
1304  protected function getMenuOfPages($pageUid)
1305  {
1306  if ($this->settings['displayLevelxAllTypes']) {
1307  $menu = [];
1308  $res = $this->getDatabaseConnection()->exec_SELECTquery('title,uid', 'pages', 'pid=' . (int)$pageUid . $GLOBALS['TSFE']->cObj->enableFields('pages'), '', 'sorting');
1309  while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
1310  $menu[$row['uid']] = $GLOBALS['TSFE']->sys_page->getPageOverlay($row);
1311  }
1312  $this->getDatabaseConnection()->sql_free_result($res);
1313  } else {
1314  $menu = $GLOBALS['TSFE']->sys_page->getMenu($pageUid);
1315  }
1316  return $menu;
1317  }
1318 
1326  protected function getPathFromPageId($id, $pathMP = '')
1327  {
1328  $identStr = $id . '|' . $pathMP;
1329  if (!isset($this->pathCache[$identStr])) {
1330  $this->requiredFrontendUsergroups[$id] = [];
1331  $this->domainRecords[$id] = [];
1332  $rl = $GLOBALS['TSFE']->sys_page->getRootLine($id, $pathMP);
1333  $path = '';
1334  $pageCount = count($rl);
1335  if (is_array($rl) && !empty($rl)) {
1336  $breadcrumbWrap = isset($this->settings['breadcrumbWrap']) ? $this->settings['breadcrumbWrap'] : '/';
1337  $breadcrumbWraps = $GLOBALS['TSFE']->tmpl->splitConfArray(['wrap' => $breadcrumbWrap], $pageCount);
1338  foreach ($rl as $k => $v) {
1339  // Check fe_user
1340  if ($v['fe_group'] && ($v['uid'] == $id || $v['extendToSubpages'])) {
1341  $this->requiredFrontendUsergroups[$id][] = $v['fe_group'];
1342  }
1343  // Check sys_domain
1344  if ($this->settings['detectDomainRcords']) {
1345  $domainName = $this->getFirstSysDomainRecordForPage($v['uid']);
1346  if ($domainName) {
1347  $this->domainRecords[$id][] = $domainName;
1348  // Set path accordingly
1349  $path = $domainName . $path;
1350  break;
1351  }
1352  }
1353  // Stop, if we find that the current id is the current root page.
1354  if ($v['uid'] == $GLOBALS['TSFE']->config['rootLine'][0]['uid']) {
1355  array_pop($breadcrumbWraps);
1356  break;
1357  }
1358  $path = $GLOBALS['TSFE']->cObj->wrap(htmlspecialchars($v['title']), array_pop($breadcrumbWraps)['wrap']) . $path;
1359  }
1360  }
1361  $this->pathCache[$identStr] = $path;
1362  }
1363  return $this->pathCache[$identStr];
1364  }
1365 
1372  protected function getFirstSysDomainRecordForPage($id)
1373  {
1374  $res = $this->getDatabaseConnection()->exec_SELECTquery('domainName', 'sys_domain', 'pid=' . (int)$id . $GLOBALS['TSFE']->cObj->enableFields('sys_domain'), '', 'sorting');
1375  $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
1376  return rtrim($row['domainName'], '/');
1377  }
1378 
1385  protected function initializeExternalParsers()
1386  {
1387  // Initialize external document parsers for icon display and other soft operations
1388  if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'])) {
1389  foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'] as $extension => $_objRef) {
1390  $this->externalParsers[$extension] = GeneralUtility::getUserObj($_objRef);
1391  // Init parser and if it returns FALSE, unset its entry again
1392  if (!$this->externalParsers[$extension]->softInit($extension)) {
1393  unset($this->externalParsers[$extension]);
1394  }
1395  }
1396  }
1397  }
1398 
1405  protected function hookRequest($functionName)
1406  {
1407  // Hook: menuConfig_preProcessModMenu
1408  if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]) {
1409  $hookObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]);
1410  if (method_exists($hookObj, $functionName)) {
1411  $hookObj->pObj = $this;
1412  return $hookObj;
1413  }
1414  }
1415  return null;
1416  }
1417 
1424  protected function multiplePagesType($item_type)
1425  {
1426  return is_object($this->externalParsers[$item_type]) && $this->externalParsers[$item_type]->isMultiplePageExtension($item_type);
1427  }
1428 
1434  protected function getDatabaseConnection()
1435  {
1436  return $GLOBALS['TYPO3_DB'];
1437  }
1438 
1442  protected function loadSettings()
1443  {
1444  if (!is_array($this->settings['results.'])) {
1445  $this->settings['results.'] = [];
1446  }
1447  $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['results']);
1448 
1449  $this->settings['results.']['summaryCropAfter'] = MathUtility::forceIntegerInRange(
1450  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropAfter'], $typoScriptArray['summaryCropAfter.']),
1451  10, 5000, 180
1452  );
1453  $this->settings['results.']['summaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropSignifier'], $typoScriptArray['summaryCropSignifier.']);
1454  $this->settings['results.']['titleCropAfter'] = MathUtility::forceIntegerInRange(
1455  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropAfter'], $typoScriptArray['titleCropAfter.']),
1456  10, 500, 50
1457  );
1458  $this->settings['results.']['titleCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropSignifier'], $typoScriptArray['titleCropSignifier.']);
1459  $this->settings['results.']['markupSW_summaryMax'] = MathUtility::forceIntegerInRange(
1460  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_summaryMax'], $typoScriptArray['markupSW_summaryMax.']),
1461  10, 5000, 300
1462  );
1463  $this->settings['results.']['markupSW_postPreLgd'] = MathUtility::forceIntegerInRange(
1464  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd'], $typoScriptArray['markupSW_postPreLgd.']),
1465  1, 500, 60
1466  );
1467  $this->settings['results.']['markupSW_postPreLgd_offset'] = MathUtility::forceIntegerInRange(
1468  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd_offset'], $typoScriptArray['markupSW_postPreLgd_offset.']),
1469  1, 50, 5
1470  );
1471  $this->settings['results.']['markupSW_divider'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_divider'], $typoScriptArray['markupSW_divider.']);
1472  $this->settings['results.']['hrefInSummaryCropAfter'] = MathUtility::forceIntegerInRange(
1473  $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropAfter'], $typoScriptArray['hrefInSummaryCropAfter.']),
1474  10, 400, 60
1475  );
1476  $this->settings['results.']['hrefInSummaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropSignifier'], $typoScriptArray['hrefInSummaryCropSignifier.']);
1477  }
1478 }
static translate($key, $extensionName, $arguments=null)
makeDescription($row, $noMarkup=false, $length=180)
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
redirect($actionName, $controllerName=null, $extensionName=null, array $arguments=null, $pageUid=null, $delay=0, $statusCode=303)
static trimExplode($delim, $string, $removeEmptyValues=false, $limit=0)
static static static anonymizeIp($address, $mask=null)
static implodeArrayForUrl($name, array $theArray, $str='', $skipBlank=false, $rawurlencodeParamName=false)
injectTypoScriptService(\TYPO3\CMS\Extbase\Service\TypoScriptService $typoScriptService)
static getExplodedSearchString($sword, $defaultOperator, $operatorTranslateTable)
static getFileAbsFileName($filename, $onlyRelative=true, $relToTYPO3_mainDir=false)
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)