[BUGFIX] Remove hardcoded index.php indexed search links
[Packages/TYPO3.CMS.git] / typo3 / sysext / indexed_search / Classes / Controller / SearchController.php
1 <?php
2 namespace TYPO3\CMS\IndexedSearch\Controller;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
18 use TYPO3\CMS\Core\Context\Context;
19 use TYPO3\CMS\Core\Database\Connection;
20 use TYPO3\CMS\Core\Database\ConnectionPool;
21 use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
22 use TYPO3\CMS\Core\Exception\Page\RootLineException;
23 use TYPO3\CMS\Core\Exception\SiteNotFoundException;
24 use TYPO3\CMS\Core\Html\HtmlParser;
25 use TYPO3\CMS\Core\Site\PseudoSiteFinder;
26 use TYPO3\CMS\Core\Site\SiteFinder;
27 use TYPO3\CMS\Core\Type\File\ImageInfo;
28 use TYPO3\CMS\Core\TypoScript\TypoScriptService;
29 use TYPO3\CMS\Core\Utility\GeneralUtility;
30 use TYPO3\CMS\Core\Utility\IpAnonymizationUtility;
31 use TYPO3\CMS\Core\Utility\MathUtility;
32 use TYPO3\CMS\Core\Utility\PathUtility;
33 use TYPO3\CMS\Core\Utility\RootlineUtility;
34 use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
35 use TYPO3\CMS\Frontend\Page\PageRepository;
36
37 /**
38 * Index search frontend
39 *
40 * Creates a search form for indexed search. Indexing must be enabled
41 * for this to make sense.
42 */
43 class SearchController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
44 {
45 /**
46 * previously known as $this->piVars['sword']
47 *
48 * @var string
49 */
50 protected $sword = '';
51
52 /**
53 * @var array
54 */
55 protected $searchWords = [];
56
57 /**
58 * @var array
59 */
60 protected $searchData;
61
62 /**
63 * This is the id of the site root.
64 * This value may be a comma separated list of integer (prepared for this)
65 * Root-page PIDs to search in (rl0 field where clause, see initialize() function)
66 *
67 * If this value is set to less than zero (eg. -1) searching will happen
68 * in ALL of the page tree with no regard to branches at all.
69 * @var int|string
70 */
71 protected $searchRootPageIdList = 0;
72
73 /**
74 * @var int
75 */
76 protected $defaultResultNumber = 10;
77
78 /**
79 * @var int[]
80 */
81 protected $availableResultsNumbers = [];
82
83 /**
84 * Search repository
85 *
86 * @var \TYPO3\CMS\IndexedSearch\Domain\Repository\IndexSearchRepository
87 */
88 protected $searchRepository;
89
90 /**
91 * Lexer object
92 *
93 * @var \TYPO3\CMS\IndexedSearch\Lexer
94 */
95 protected $lexerObj;
96
97 /**
98 * External parser objects
99 * @var array
100 */
101 protected $externalParsers = [];
102
103 /**
104 * Will hold the first row in result - used to calculate relative hit-ratings.
105 *
106 * @var array
107 */
108 protected $firstRow = [];
109
110 /**
111 * sys_domain records
112 *
113 * @var array
114 */
115 protected $domainRecords = [];
116
117 /**
118 * Required fe_groups memberships for display of a result.
119 *
120 * @var array
121 */
122 protected $requiredFrontendUsergroups = [];
123
124 /**
125 * Page tree sections for search result.
126 *
127 * @var array
128 */
129 protected $resultSections = [];
130
131 /**
132 * Caching of page path
133 *
134 * @var array
135 */
136 protected $pathCache = [];
137
138 /**
139 * Storage of icons
140 *
141 * @var array
142 */
143 protected $iconFileNameCache = [];
144
145 /**
146 * Indexer configuration, coming from TYPO3's system configuration for EXT:indexed_search
147 *
148 * @var array
149 */
150 protected $indexerConfig = [];
151
152 /**
153 * Flag whether metaphone search should be enabled
154 *
155 * @var bool
156 */
157 protected $enableMetaphoneSearch = false;
158
159 /**
160 * @var \TYPO3\CMS\Core\TypoScript\TypoScriptService
161 */
162 protected $typoScriptService;
163
164 /**
165 * @param \TYPO3\CMS\Core\TypoScript\TypoScriptService $typoScriptService
166 */
167 public function injectTypoScriptService(\TYPO3\CMS\Core\TypoScript\TypoScriptService $typoScriptService)
168 {
169 $this->typoScriptService = $typoScriptService;
170 }
171
172 /**
173 * sets up all necessary object for searching
174 *
175 * @param array $searchData The incoming search parameters
176 * @return array Search parameters
177 */
178 public function initialize($searchData = [])
179 {
180 if (!is_array($searchData)) {
181 $searchData = [];
182 }
183
184 // check if TypoScript is loaded
185 if (!isset($this->settings['results'])) {
186 $this->redirect('noTypoScript');
187 }
188
189 // Sets availableResultsNumbers - has to be called before request settings are read to avoid DoS attack
190 $this->availableResultsNumbers = array_filter(GeneralUtility::intExplode(',', $this->settings['blind']['numberOfResults']));
191
192 // Sets default result number if at least one availableResultsNumbers exists
193 if (isset($this->availableResultsNumbers[0])) {
194 $this->defaultResultNumber = $this->availableResultsNumbers[0];
195 }
196
197 $this->loadSettings();
198
199 // setting default values
200 if (is_array($this->settings['defaultOptions'])) {
201 $searchData = array_merge($this->settings['defaultOptions'], $searchData);
202 }
203 // Indexer configuration from Extension Manager interface:
204 $this->indexerConfig = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('indexed_search');
205 $this->enableMetaphoneSearch = (bool)$this->indexerConfig['enableMetaphoneSearch'];
206 $this->initializeExternalParsers();
207 // If "_sections" is set, this value overrides any existing value.
208 if ($searchData['_sections']) {
209 $searchData['sections'] = $searchData['_sections'];
210 }
211 // If "_sections" is set, this value overrides any existing value.
212 if ($searchData['_freeIndexUid'] !== '' && $searchData['_freeIndexUid'] !== '_') {
213 $searchData['freeIndexUid'] = $searchData['_freeIndexUid'];
214 }
215 $searchData['numberOfResults'] = $this->getNumberOfResults($searchData['numberOfResults']);
216 // This gets the search-words into the $searchWordArray
217 $this->setSword($searchData['sword']);
218 // Add previous search words to current
219 if ($searchData['sword_prev_include'] && $searchData['sword_prev']) {
220 $this->setSword(trim($searchData['sword_prev']) . ' ' . $this->getSword());
221 }
222 $this->searchWords = $this->getSearchWords($searchData['defaultOperand']);
223 // This is the id of the site root.
224 // This value may be a commalist of integer (prepared for this)
225 $this->searchRootPageIdList = (int)$GLOBALS['TSFE']->config['rootLine'][0]['uid'];
226 // Setting the list of root PIDs for the search. Notice, these page IDs MUST
227 // have a TypoScript template with root flag on them! Basically this list is used
228 // to select on the "rl0" field and page ids are registered as "rl0" only if
229 // a TypoScript template record with root flag is there.
230 // This happens AFTER the use of $this->searchRootPageIdList above because
231 // the above will then fetch the menu for the CURRENT site - regardless
232 // of this kind of searching here. Thus a general search will lookup in
233 // the WHOLE database while a specific section search will take the current sections.
234 if ($this->settings['rootPidList']) {
235 $this->searchRootPageIdList = implode(',', GeneralUtility::intExplode(',', $this->settings['rootPidList']));
236 }
237 $this->searchRepository = GeneralUtility::makeInstance(\TYPO3\CMS\IndexedSearch\Domain\Repository\IndexSearchRepository::class);
238 $this->searchRepository->initialize($this->settings, $searchData, $this->externalParsers, $this->searchRootPageIdList);
239 $this->searchData = $searchData;
240 // Calling hook for modification of initialized content
241 if ($hookObj = $this->hookRequest('initialize_postProc')) {
242 $hookObj->initialize_postProc();
243 }
244 return $searchData;
245 }
246
247 /**
248 * Performs the search, the display and writing stats
249 *
250 * @param array $search the search parameters, an associative array
251 * @ignorevalidation $search
252 */
253 public function searchAction($search = [])
254 {
255 $searchData = $this->initialize($search);
256 // Find free index uid:
257 $freeIndexUid = $searchData['freeIndexUid'];
258 if ($freeIndexUid == -2) {
259 $freeIndexUid = $this->settings['defaultFreeIndexUidList'];
260 } elseif (!isset($searchData['freeIndexUid'])) {
261 // index configuration is disabled
262 $freeIndexUid = -1;
263 }
264
265 if (!empty($searchData['extendedSearch'])) {
266 $this->view->assignMultiple($this->processExtendedSearchParameters());
267 }
268
269 $indexCfgs = GeneralUtility::intExplode(',', $freeIndexUid);
270 $resultsets = [];
271 foreach ($indexCfgs as $freeIndexUid) {
272 // Get result rows
273 $tstamp1 = GeneralUtility::milliseconds();
274 if ($hookObj = $this->hookRequest('getResultRows')) {
275 $resultData = $hookObj->getResultRows($this->searchWords, $freeIndexUid);
276 } else {
277 $resultData = $this->searchRepository->doSearch($this->searchWords, $freeIndexUid);
278 }
279 // Display search results
280 $tstamp2 = GeneralUtility::milliseconds();
281 if ($hookObj = $this->hookRequest('getDisplayResults')) {
282 $resultsets[$freeIndexUid] = $hookObj->getDisplayResults($this->searchWords, $resultData, $freeIndexUid);
283 } else {
284 $resultsets[$freeIndexUid] = $this->getDisplayResults($this->searchWords, $resultData, $freeIndexUid);
285 }
286 $tstamp3 = GeneralUtility::milliseconds();
287 // Create header if we are searching more than one indexing configuration
288 if (count($indexCfgs) > 1) {
289 if ($freeIndexUid > 0) {
290 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
291 ->getQueryBuilderForTable('index_config');
292 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
293 $indexCfgRec = $queryBuilder
294 ->select('*')
295 ->from('index_config')
296 ->where(
297 $queryBuilder->expr()->eq(
298 'uid',
299 $queryBuilder->createNamedParameter($freeIndexUid, \PDO::PARAM_INT)
300 )
301 )
302 ->execute()
303 ->fetch();
304 $categoryTitle = $indexCfgRec['title'];
305 } else {
306 $categoryTitle = LocalizationUtility::translate('indexingConfigurationHeader.' . $freeIndexUid, 'IndexedSearch');
307 }
308 $resultsets[$freeIndexUid]['categoryTitle'] = $categoryTitle;
309 }
310 // Write search statistics
311 $this->writeSearchStat($searchData, $this->searchWords, $resultData['count'], [$tstamp1, $tstamp2, $tstamp3]);
312 }
313 $this->view->assign('resultsets', $resultsets);
314 $this->view->assign('searchParams', $searchData);
315 $this->view->assign('searchWords', $this->searchWords);
316 }
317
318 /****************************************
319 * functions to make the result rows and result sets
320 * ready for the output
321 ***************************************/
322 /**
323 * Compiles the HTML display of the incoming array of result rows.
324 *
325 * @param array $searchWords Search words array (for display of text describing what was searched for)
326 * @param array $resultData Array with result rows, count, first row.
327 * @param int $freeIndexUid Pointing to which indexing configuration you want to search in. -1 means no filtering. 0 means only regular indexed content.
328 * @return array
329 */
330 protected function getDisplayResults($searchWords, $resultData, $freeIndexUid = -1)
331 {
332 $result = [
333 'count' => $resultData['count'],
334 'searchWords' => $searchWords
335 ];
336 // Perform display of result rows array
337 if ($resultData) {
338 // Set first selected row (for calculation of ranking later)
339 $this->firstRow = $resultData['firstRow'];
340 // Result display here
341 $result['rows'] = $this->compileResultRows($resultData['resultRows'], $freeIndexUid);
342 $result['affectedSections'] = $this->resultSections;
343 // Browsing box
344 if ($resultData['count']) {
345 // could we get this in the view?
346 if ($this->searchData['group'] === 'sections' && $freeIndexUid <= 0) {
347 $resultSectionsCount = count($this->resultSections);
348 $result['sectionText'] = sprintf(LocalizationUtility::translate('result.' . ($resultSectionsCount > 1 ? 'inNsections' : 'inNsection'), 'IndexedSearch'), $resultSectionsCount);
349 }
350 }
351 }
352 // Print a message telling which words in which sections we searched for
353 if (strpos($this->searchData['sections'], 'rl') === 0) {
354 $result['searchedInSectionInfo'] = LocalizationUtility::translate('result.inSection', 'IndexedSearch') . ' "' . $this->getPathFromPageId(substr($this->searchData['sections'], 4)) . '"';
355 }
356
357 if ($hookObj = $this->hookRequest('getDisplayResults_postProc')) {
358 $result = $hookObj->getDisplayResults_postProc($result);
359 }
360
361 return $result;
362 }
363
364 /**
365 * Takes the array with resultrows as input and returns the result-HTML-code
366 * Takes the "group" var into account: Makes a "section" or "flat" display.
367 *
368 * @param array $resultRows Result rows
369 * @param int $freeIndexUid Pointing to which indexing configuration you want to search in. -1 means no filtering. 0 means only regular indexed content.
370 * @return array the result rows with additional information
371 */
372 protected function compileResultRows($resultRows, $freeIndexUid = -1)
373 {
374 $finalResultRows = [];
375 // Transfer result rows to new variable,
376 // performing some mapping of sub-results etc.
377 $newResultRows = [];
378 foreach ($resultRows as $row) {
379 $id = md5($row['phash_grouping']);
380 if (is_array($newResultRows[$id])) {
381 // swapping:
382 if (!$newResultRows[$id]['show_resume'] && $row['show_resume']) {
383 // Remove old
384 $subrows = $newResultRows[$id]['_sub'];
385 unset($newResultRows[$id]['_sub']);
386 $subrows[] = $newResultRows[$id];
387 // Insert new:
388 $newResultRows[$id] = $row;
389 $newResultRows[$id]['_sub'] = $subrows;
390 } else {
391 $newResultRows[$id]['_sub'][] = $row;
392 }
393 } else {
394 $newResultRows[$id] = $row;
395 }
396 }
397 $resultRows = $newResultRows;
398 $this->resultSections = [];
399 if ($freeIndexUid <= 0 && $this->searchData['group'] === 'sections') {
400 $rl2flag = strpos($this->searchData['sections'], 'rl') === 0;
401 $sections = [];
402 foreach ($resultRows as $row) {
403 $id = $row['rl0'] . '-' . $row['rl1'] . ($rl2flag ? '-' . $row['rl2'] : '');
404 $sections[$id][] = $row;
405 }
406 $this->resultSections = [];
407 foreach ($sections as $id => $resultRows) {
408 $rlParts = explode('-', $id);
409 if ($rlParts[2]) {
410 $theId = $rlParts[2];
411 $theRLid = 'rl2_' . $rlParts[2];
412 } elseif ($rlParts[1]) {
413 $theId = $rlParts[1];
414 $theRLid = 'rl1_' . $rlParts[1];
415 } else {
416 $theId = $rlParts[0];
417 $theRLid = '0';
418 }
419 $sectionName = $this->getPathFromPageId($theId);
420 $sectionName = ltrim($sectionName, '/');
421 if (!trim($sectionName)) {
422 $sectionTitleLinked = LocalizationUtility::translate('result.unnamedSection', 'IndexedSearch') . ':';
423 } else {
424 $onclick = 'document.forms[\'tx_indexedsearch\'][\'tx_indexedsearch_pi2[search][_sections]\'].value=' . GeneralUtility::quoteJSvalue($theRLid) . ';document.forms[\'tx_indexedsearch\'].submit();return false;';
425 $sectionTitleLinked = '<a href="#" onclick="' . htmlspecialchars($onclick) . '">' . $sectionName . ':</a>';
426 }
427 $resultRowsCount = count($resultRows);
428 $this->resultSections[$id] = [$sectionName, $resultRowsCount];
429 // Add section header
430 $finalResultRows[] = [
431 'isSectionHeader' => true,
432 'numResultRows' => $resultRowsCount,
433 'sectionId' => $id,
434 'sectionTitle' => $sectionTitleLinked
435 ];
436 // Render result rows
437 foreach ($resultRows as $row) {
438 $finalResultRows[] = $this->compileSingleResultRow($row);
439 }
440 }
441 } else {
442 // flat mode or no sections at all
443 foreach ($resultRows as $row) {
444 $finalResultRows[] = $this->compileSingleResultRow($row);
445 }
446 }
447 return $finalResultRows;
448 }
449
450 /**
451 * This prints a single result row, including a recursive call for subrows.
452 *
453 * @param array $row Search result row
454 * @param int $headerOnly 1=Display only header (for sub-rows!), 2=nothing at all
455 * @return array the result row with additional information
456 */
457 protected function compileSingleResultRow($row, $headerOnly = 0)
458 {
459 $specRowConf = $this->getSpecialConfigurationForResultRow($row);
460 $resultData = $row;
461 $resultData['headerOnly'] = $headerOnly;
462 $resultData['CSSsuffix'] = $specRowConf['CSSsuffix'] ? '-' . $specRowConf['CSSsuffix'] : '';
463 if ($this->multiplePagesType($row['item_type'])) {
464 $dat = unserialize($row['cHashParams']);
465 $pp = explode('-', $dat['key']);
466 if ($pp[0] != $pp[1]) {
467 $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.page', 'IndexedSearch') . ' ' . $dat['key'];
468 } else {
469 $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.pages', 'IndexedSearch') . ' ' . $pp[0];
470 }
471 }
472 $title = $resultData['item_title'] . $resultData['titleaddition'];
473 $title = GeneralUtility::fixed_lgd_cs($title, $this->settings['results.']['titleCropAfter'], $this->settings['results.']['titleCropSignifier']);
474 // If external media, link to the media-file instead.
475 if ($row['item_type']) {
476 if ($row['show_resume']) {
477 // Can link directly.
478 $targetAttribute = '';
479 if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
480 $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
481 }
482 $title = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($title) . '</a>';
483 } else {
484 // Suspicious, so linking to page instead...
485 $copiedRow = $row;
486 unset($copiedRow['cHashParams']);
487 $title = $this->linkPageATagWrap(
488 htmlspecialchars($title),
489 $this->linkPage($row['page_id'], $copiedRow)
490 );
491 }
492 } else {
493 // Else the page:
494 // Prepare search words for markup in content:
495 $markUpSwParams = [];
496 if ($this->settings['forwardSearchWordsInResultLink']['_typoScriptNodeValue']) {
497 if ($this->settings['forwardSearchWordsInResultLink']['no_cache']) {
498 $markUpSwParams = ['no_cache' => 1];
499 }
500 foreach ($this->searchWords as $d) {
501 $markUpSwParams['sword_list'][] = $d['sword'];
502 }
503 }
504 $title = $this->linkPageATagWrap(
505 htmlspecialchars($title),
506 $this->linkPage($row['data_page_id'], $row, $markUpSwParams)
507 );
508 }
509 $resultData['title'] = $title;
510 $resultData['icon'] = $this->makeItemTypeIcon($row['item_type'], '', $specRowConf);
511 $resultData['rating'] = $this->makeRating($row);
512 $resultData['description'] = $this->makeDescription(
513 $row,
514 (bool)!($this->searchData['extResume'] && !$headerOnly),
515 $this->settings['results.']['summaryCropAfter']
516 );
517 $resultData['language'] = $this->makeLanguageIndication($row);
518 $resultData['size'] = GeneralUtility::formatSize($row['item_size']);
519 $resultData['created'] = $row['item_crdate'];
520 $resultData['modified'] = $row['item_mtime'];
521 $pI = parse_url($row['data_filename']);
522 if ($pI['scheme']) {
523 $targetAttribute = '';
524 if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
525 $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
526 }
527 $resultData['pathTitle'] = $row['data_filename'];
528 $resultData['pathUri'] = $row['data_filename'];
529 $resultData['path'] = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($row['data_filename']) . '</a>';
530 } else {
531 $pathId = $row['data_page_id'] ?: $row['page_id'];
532 $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
533 $pathStr = $this->getPathFromPageId($pathId, $pathMP);
534 $pathLinkData = $this->linkPage(
535 $pathId,
536 [
537 'cHashParams' => $row['cHashParams'],
538 'data_page_type' => $row['data_page_type'],
539 'data_page_mp' => $pathMP,
540 'sys_language_uid' => $row['sys_language_uid']
541 ]
542 );
543
544 $resultData['pathTitle'] = $pathStr;
545 $resultData['pathUri'] = $pathLinkData['uri'];
546 $resultData['path'] = $this->linkPageATagWrap($pathStr, $pathLinkData);
547
548 // check if the access is restricted
549 if (is_array($this->requiredFrontendUsergroups[$pathId]) && !empty($this->requiredFrontendUsergroups[$pathId])) {
550 $lockedIcon = GeneralUtility::getFileAbsFileName('EXT:indexed_search/Resources/Public/Icons/FileTypes/locked.gif');
551 $lockedIcon = PathUtility::getAbsoluteWebPath($lockedIcon);
552 $resultData['access'] = '<img src="' . htmlspecialchars($lockedIcon) . '"'
553 . ' width="12" height="15" vspace="5" title="'
554 . sprintf(LocalizationUtility::translate('result.memberGroups', 'IndexedSearch'), implode(',', array_unique($this->requiredFrontendUsergroups[$pathId])))
555 . '" alt="" />';
556 }
557 }
558 // If there are subrows (eg. subpages in a PDF-file or if a duplicate page
559 // is selected due to user-login (phash_grouping))
560 if (is_array($row['_sub'])) {
561 $resultData['subresults'] = [];
562 if ($this->multiplePagesType($row['item_type'])) {
563 $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'IndexedSearch');
564 foreach ($row['_sub'] as $subRow) {
565 $resultData['subresults']['items'][] = $this->compileSingleResultRow($subRow, 1);
566 }
567 } else {
568 $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'IndexedSearch');
569 $resultData['subresults']['info'] = LocalizationUtility::translate('result.otherPageAsWell', 'IndexedSearch');
570 }
571 }
572 return $resultData;
573 }
574
575 /**
576 * Returns configuration from TypoScript for result row based
577 * on ID / location in page tree!
578 *
579 * @param array $row Result row
580 * @return array Configuration array
581 */
582 protected function getSpecialConfigurationForResultRow($row)
583 {
584 $pathId = $row['data_page_id'] ?: $row['page_id'];
585 $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
586 $specConf = $this->settings['specialConfiguration']['0'];
587 try {
588 $rl = GeneralUtility::makeInstance(RootlineUtility::class, $pathId, $pathMP)->get();
589 foreach ($rl as $dat) {
590 if (is_array($this->settings['specialConfiguration'][$dat['uid']])) {
591 $specConf = $this->settings['specialConfiguration'][$dat['uid']];
592 $specConf['_pid'] = $dat['uid'];
593 break;
594 }
595 }
596 } catch (RootLineException $e) {
597 // do nothing
598 }
599 return $specConf;
600 }
601
602 /**
603 * Return the rating-HTML code for the result row. This makes use of the $this->firstRow
604 *
605 * @param array $row Result row array
606 * @return string String showing ranking value
607 * @todo can this be a ViewHelper?
608 */
609 protected function makeRating($row)
610 {
611 switch ((string)$this->searchData['sortOrder']) {
612 case 'rank_count':
613 return $row['order_val'] . ' ' . LocalizationUtility::translate('result.ratingMatches', 'IndexedSearch');
614 case 'rank_first':
615 return ceil(MathUtility::forceIntegerInRange(255 - $row['order_val'], 1, 255) / 255 * 100) . '%';
616 case 'rank_flag':
617 if ($this->firstRow['order_val2']) {
618 // (3 MSB bit, 224 is highest value of order_val1 currently)
619 $base = $row['order_val1'] * 256;
620 // 15-3 MSB = 12
621 $freqNumber = $row['order_val2'] / $this->firstRow['order_val2'] * pow(2, 12);
622 $total = MathUtility::forceIntegerInRange($base + $freqNumber, 0, 32767);
623 return ceil(log($total) / log(32767) * 100) . '%';
624 }
625 break;
626 case 'rank_freq':
627 $max = 10000;
628 $total = MathUtility::forceIntegerInRange($row['order_val'], 0, $max);
629 return ceil(log($total) / log($max) * 100) . '%';
630 case 'crdate':
631 return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_crdate'], 0);
632 case 'mtime':
633 return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_mtime'], 0);
634 default:
635 return ' ';
636 }
637 }
638
639 /**
640 * Returns the HTML code for language indication.
641 *
642 * @param array $row Result row
643 * @return string HTML code for result row.
644 */
645 protected function makeLanguageIndication($row)
646 {
647 $output = '&nbsp;';
648 // If search result is a TYPO3 page:
649 if ((string)$row['item_type'] === '0') {
650 // If TypoScript is used to render the flag:
651 if (is_array($this->settings['flagRendering'])) {
652 /** @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $cObj */
653 $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
654 $cObj->setCurrentVal($row['sys_language_uid']);
655 $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['flagRendering']);
656 $output = $cObj->cObjGetSingle($this->settings['flagRendering']['_typoScriptNodeValue'], $typoScriptArray);
657 }
658 }
659 return $output;
660 }
661
662 /**
663 * Return icon for file extension
664 *
665 * @param string $imageType File extension / item type
666 * @param string $alt Title attribute value in icon.
667 * @param array $specRowConf TypoScript configuration specifically for search result.
668 * @return string <img> tag for icon
669 */
670 public function makeItemTypeIcon($imageType, $alt, $specRowConf)
671 {
672 // Build compound key if item type is 0, iconRendering is not used
673 // and specialConfiguration.[pid].pageIcon was set in TS
674 if ($imageType === '0' && $specRowConf['_pid'] && is_array($specRowConf['pageIcon']) && !is_array($this->settings['iconRendering'])) {
675 $imageType .= ':' . $specRowConf['_pid'];
676 }
677 if (!isset($this->iconFileNameCache[$imageType])) {
678 $this->iconFileNameCache[$imageType] = '';
679 // If TypoScript is used to render the icon:
680 if (is_array($this->settings['iconRendering'])) {
681 /** @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $cObj */
682 $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
683 $cObj->setCurrentVal($imageType);
684 $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['iconRendering']);
685 $this->iconFileNameCache[$imageType] = $cObj->cObjGetSingle($this->settings['iconRendering']['_typoScriptNodeValue'], $typoScriptArray);
686 } else {
687 // Default creation / finding of icon:
688 $icon = '';
689 if ($imageType === '0' || strpos($imageType, '0:') === 0) {
690 if (is_array($specRowConf['pageIcon'])) {
691 $this->iconFileNameCache[$imageType] = $GLOBALS['TSFE']->cObj->cObjGetSingle('IMAGE', $specRowConf['pageIcon']);
692 } else {
693 $icon = 'EXT:indexed_search/Resources/Public/Icons/FileTypes/pages.gif';
694 }
695 } elseif ($this->externalParsers[$imageType]) {
696 $icon = $this->externalParsers[$imageType]->getIcon($imageType);
697 }
698 if ($icon) {
699 $fullPath = GeneralUtility::getFileAbsFileName($icon);
700 if ($fullPath) {
701 $imageInfo = GeneralUtility::makeInstance(ImageInfo::class, $fullPath);
702 $iconPath = PathUtility::stripPathSitePrefix($fullPath);
703 $this->iconFileNameCache[$imageType] = $imageInfo->getWidth()
704 ? '<img src="' . $iconPath
705 . '" width="' . $imageInfo->getWidth()
706 . '" height="' . $imageInfo->getHeight()
707 . '" title="' . htmlspecialchars($alt) . '" alt="" />'
708 : '';
709 }
710 }
711 }
712 }
713 return $this->iconFileNameCache[$imageType];
714 }
715
716 /**
717 * Returns the resume for the search-result.
718 *
719 * @param array $row Search result row
720 * @param bool $noMarkup If noMarkup is FALSE, then the index_fulltext table is used to select the content of the page, split it with regex to display the search words in the text.
721 * @param int $length String length
722 * @return string HTML string
723 * @todo overwork this
724 */
725 protected function makeDescription($row, $noMarkup = false, $length = 180)
726 {
727 if ($row['show_resume']) {
728 if (!$noMarkup) {
729 $markedSW = '';
730 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('index_fulltext');
731 $ftdrow = $queryBuilder
732 ->select('*')
733 ->from('index_fulltext')
734 ->where(
735 $queryBuilder->expr()->eq(
736 'phash',
737 $queryBuilder->createNamedParameter($row['phash'], \PDO::PARAM_INT)
738 )
739 )
740 ->execute()
741 ->fetch();
742 if ($ftdrow !== false) {
743 // Cut HTTP references after some length
744 $content = preg_replace('/(http:\\/\\/[^ ]{' . $this->settings['results.']['hrefInSummaryCropAfter'] . '})([^ ]+)/i', '$1...', $ftdrow['fulltextdata']);
745 $markedSW = $this->markupSWpartsOfString($content);
746 }
747 }
748 if (!trim($markedSW)) {
749 $outputStr = GeneralUtility::fixed_lgd_cs($row['item_description'], $length, $this->settings['results.']['summaryCropSignifier']);
750 $outputStr = htmlspecialchars($outputStr);
751 }
752 $output = $outputStr ?: $markedSW;
753 } else {
754 $output = '<span class="noResume">' . LocalizationUtility::translate('result.noResume', 'IndexedSearch') . '</span>';
755 }
756 return $output;
757 }
758
759 /**
760 * Marks up the search words from $this->searchWords in the $str with a color.
761 *
762 * @param string $str Text in which to find and mark up search words. This text is assumed to be UTF-8 like the search words internally is.
763 * @return string Processed content
764 */
765 protected function markupSWpartsOfString($str)
766 {
767 $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
768 // Init:
769 $str = str_replace('&nbsp;', ' ', $htmlParser->bidir_htmlspecialchars($str, -1));
770 $str = preg_replace('/\\s\\s+/', ' ', $str);
771 $swForReg = [];
772 // Prepare search words for regex:
773 foreach ($this->searchWords as $d) {
774 $swForReg[] = preg_quote($d['sword'], '/');
775 }
776 $regExString = '(' . implode('|', $swForReg) . ')';
777 // Split and combine:
778 $parts = preg_split('/' . $regExString . '/i', ' ' . $str . ' ', 20000, PREG_SPLIT_DELIM_CAPTURE);
779 // Constants:
780 $summaryMax = $this->settings['results.']['markupSW_summaryMax'];
781 $postPreLgd = $this->settings['results.']['markupSW_postPreLgd'];
782 $postPreLgd_offset = $this->settings['results.']['markupSW_postPreLgd_offset'];
783 $divider = $this->settings['results.']['markupSW_divider'];
784 $occurencies = (count($parts) - 1) / 2;
785 if ($occurencies) {
786 $postPreLgd = MathUtility::forceIntegerInRange($summaryMax / $occurencies, $postPreLgd, $summaryMax / 2);
787 }
788 // Variable:
789 $summaryLgd = 0;
790 $output = [];
791 // Shorten in-between strings:
792 foreach ($parts as $k => $strP) {
793 if ($k % 2 == 0) {
794 // Find length of the summary part:
795 $strLen = mb_strlen($parts[$k], 'utf-8');
796 $output[$k] = $parts[$k];
797 // Possibly shorten string:
798 if (!$k) {
799 // First entry at all (only cropped on the frontside)
800 if ($strLen > $postPreLgd) {
801 $output[$k] = $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', GeneralUtility::fixed_lgd_cs($parts[$k], -($postPreLgd - $postPreLgd_offset)));
802 }
803 } elseif ($summaryLgd > $summaryMax || !isset($parts[$k + 1])) {
804 // In case summary length is exceed OR if there are no more entries at all:
805 if ($strLen > $postPreLgd) {
806 $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', GeneralUtility::fixed_lgd_cs(
807 $parts[$k],
808 $postPreLgd - $postPreLgd_offset
809 )) . $divider;
810 }
811 } else {
812 if ($strLen > $postPreLgd * 2) {
813 $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', GeneralUtility::fixed_lgd_cs(
814 $parts[$k],
815 $postPreLgd - $postPreLgd_offset
816 )) . $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', GeneralUtility::fixed_lgd_cs($parts[$k], -($postPreLgd - $postPreLgd_offset)));
817 }
818 }
819 $summaryLgd += mb_strlen($output[$k], 'utf-8');
820 // Protect output:
821 $output[$k] = htmlspecialchars($output[$k]);
822 // If summary lgd is exceed, break the process:
823 if ($summaryLgd > $summaryMax) {
824 break;
825 }
826 } else {
827 $summaryLgd += mb_strlen($strP, 'utf-8');
828 $output[$k] = '<strong class="tx-indexedsearch-redMarkup">' . htmlspecialchars($parts[$k]) . '</strong>';
829 }
830 }
831 // Return result:
832 return implode('', $output);
833 }
834
835 /**
836 * Write statistics information to database for the search operation if there was at least one search word.
837 *
838 * @param array $searchParams search params
839 * @param array $searchWords Search Word array
840 * @param int $count Number of hits
841 * @param array $pt Milliseconds the search took (start time DB query + end time DB query + end time to compile results)
842 */
843 protected function writeSearchStat($searchParams, $searchWords, $count, $pt)
844 {
845 $searchWord = $this->getSword();
846 if (empty($searchWord) && empty($searchWords)) {
847 return;
848 }
849
850 $ipAddress = '';
851 try {
852 $ipMask = isset($this->indexerConfig['trackIpInStatistic']) ? (int)$this->indexerConfig['trackIpInStatistic'] : 2;
853 $ipAddress = IpAnonymizationUtility::anonymizeIp(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $ipMask);
854 } catch (\Exception $e) {
855 }
856 $insertFields = [
857 'searchstring' => $searchWord,
858 'searchoptions' => serialize([$searchParams, $searchWords, $pt]),
859 'feuser_id' => (int)$GLOBALS['TSFE']->fe_user->user['uid'],
860 // cookie as set or retrieved. If people has cookies disabled this will vary all the time
861 'cookie' => $GLOBALS['TSFE']->fe_user->id,
862 // Remote IP address
863 'IP' => $ipAddress,
864 // Number of hits on the search
865 'hits' => (int)$count,
866 // Time stamp
867 'tstamp' => $GLOBALS['EXEC_TIME']
868 ];
869 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_search_stat');
870 $connection->insert(
871 'index_stat_search',
872 $insertFields,
873 ['searchoptions' => Connection::PARAM_LOB]
874 );
875 $newId = $connection->lastInsertId('index_stat_search');
876 if ($newId) {
877 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_stat_word');
878 foreach ($searchWords as $val) {
879 $insertFields = [
880 'word' => $val['sword'],
881 'index_stat_search_id' => $newId,
882 // Time stamp
883 'tstamp' => $GLOBALS['EXEC_TIME'],
884 // search page id for indexed search stats
885 'pageid' => $GLOBALS['TSFE']->id
886 ];
887 $connection->insert('index_stat_word', $insertFields);
888 }
889 }
890 }
891
892 /**
893 * Splits the search word input into an array where each word is represented by an array with key "sword"
894 * holding the search word and key "oper" holding the SQL operator (eg. AND, OR)
895 *
896 * Only words with 2 or more characters are accepted
897 * Max 200 chars total
898 * Space is used to split words, "" can be used search for a whole string
899 * AND, OR and NOT are prefix words, overruling the default operator
900 * +/|/- equals AND, OR and NOT as operators.
901 * All search words are converted to lowercase.
902 *
903 * $defOp is the default operator. 1=OR, 0=AND
904 *
905 * @param bool $defaultOperator If TRUE, the default operator will be OR, not AND
906 * @return array Search words if any found
907 */
908 protected function getSearchWords($defaultOperator)
909 {
910 // Shorten search-word string to max 200 bytes - shortening the string here is only a run-away feature!
911 $searchWords = mb_substr($this->getSword(), 0, 200);
912 // Convert to UTF-8 + conv. entities (was also converted during indexing!)
913 if ($GLOBALS['TSFE']->metaCharset && $GLOBALS['TSFE']->metaCharset !== 'utf-8') {
914 $searchWords = mb_convert_encoding($searchWords, 'utf-8', $GLOBALS['TSFE']->metaCharset);
915 $searchWords = html_entity_decode($searchWords);
916 }
917 $sWordArray = false;
918 if ($hookObj = $this->hookRequest('getSearchWords')) {
919 $sWordArray = $hookObj->getSearchWords_splitSWords($searchWords, $defaultOperator);
920 } else {
921 // sentence
922 if ($this->searchData['searchType'] == 20) {
923 $sWordArray = [
924 [
925 'sword' => trim($searchWords),
926 'oper' => 'AND'
927 ]
928 ];
929 } else {
930 // case-sensitive. Defines the words, which will be
931 // operators between words
932 $operatorTranslateTable = [
933 ['+', 'AND'],
934 ['|', 'OR'],
935 ['-', 'AND NOT'],
936 // Add operators for various languages
937 // Converts the operators to lowercase
938 [mb_strtolower(LocalizationUtility::translate('localizedOperandAnd', 'IndexedSearch'), 'utf-8'), 'AND'],
939 [mb_strtolower(LocalizationUtility::translate('localizedOperandOr', 'IndexedSearch'), 'utf-8'), 'OR'],
940 [mb_strtolower(LocalizationUtility::translate('localizedOperandNot', 'IndexedSearch'), 'utf-8'), 'AND NOT']
941 ];
942 $swordArray = \TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::getExplodedSearchString($searchWords, $defaultOperator == 1 ? 'OR' : 'AND', $operatorTranslateTable);
943 if (is_array($swordArray)) {
944 $sWordArray = $this->procSearchWordsByLexer($swordArray);
945 }
946 }
947 }
948 return $sWordArray;
949 }
950
951 /**
952 * Post-process the search word array so it will match the words that was indexed (including case-folding if any)
953 * If any words are splitted into multiple words (eg. CJK will be!) the operator of the main word will remain.
954 *
955 * @param array $searchWords Search word array
956 * @return array Search word array, processed through lexer
957 */
958 protected function procSearchWordsByLexer($searchWords)
959 {
960 $newSearchWords = [];
961 // Init lexer (used to post-processing of search words)
962 $lexerObjectClassName = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ?: \TYPO3\CMS\IndexedSearch\Lexer::class;
963 $this->lexerObj = GeneralUtility::makeInstance($lexerObjectClassName);
964 // Traverse the search word array
965 foreach ($searchWords as $wordDef) {
966 // No space in word (otherwise it might be a sentense in quotes like "there is").
967 if (strpos($wordDef['sword'], ' ') === false) {
968 // Split the search word by lexer:
969 $res = $this->lexerObj->split2Words($wordDef['sword']);
970 // Traverse lexer result and add all words again:
971 foreach ($res as $word) {
972 $newSearchWords[] = [
973 'sword' => $word,
974 'oper' => $wordDef['oper']
975 ];
976 }
977 } else {
978 $newSearchWords[] = $wordDef;
979 }
980 }
981 return $newSearchWords;
982 }
983
984 /**
985 * Sort options about the search form
986 *
987 * @param array $search The search data / params
988 * @ignorevalidation $search
989 */
990 public function formAction($search = [])
991 {
992 $searchData = $this->initialize($search);
993 // Adding search field value
994 $this->view->assign('sword', $this->getSword());
995 // Extended search
996 if (!empty($searchData['extendedSearch'])) {
997 $this->view->assignMultiple($this->processExtendedSearchParameters());
998 }
999 $this->view->assign('searchParams', $searchData);
1000 }
1001
1002 /**
1003 * TypoScript was not loaded
1004 */
1005 public function noTypoScriptAction()
1006 {
1007 }
1008
1009 /****************************************
1010 * building together the available options for every dropdown
1011 ***************************************/
1012 /**
1013 * get the values for the "type" selector
1014 *
1015 * @return array Associative array with options
1016 */
1017 protected function getAllAvailableSearchTypeOptions()
1018 {
1019 $allOptions = [];
1020 $types = [0, 1, 2, 3, 10, 20];
1021 $blindSettings = $this->settings['blind'];
1022 if (!$blindSettings['searchType']) {
1023 foreach ($types as $typeNum) {
1024 $allOptions[$typeNum] = LocalizationUtility::translate('searchTypes.' . $typeNum, 'IndexedSearch');
1025 }
1026 }
1027 // Remove this option if metaphone search is disabled)
1028 if (!$this->enableMetaphoneSearch) {
1029 unset($allOptions[10]);
1030 }
1031 // disable single entries by TypoScript
1032 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['searchType']);
1033 return $allOptions;
1034 }
1035
1036 /**
1037 * get the values for the "defaultOperand" selector
1038 *
1039 * @return array Associative array with options
1040 */
1041 protected function getAllAvailableOperandsOptions()
1042 {
1043 $allOptions = [];
1044 $blindSettings = $this->settings['blind'];
1045 if (!$blindSettings['defaultOperand']) {
1046 $allOptions = [
1047 0 => LocalizationUtility::translate('defaultOperands.0', 'IndexedSearch'),
1048 1 => LocalizationUtility::translate('defaultOperands.1', 'IndexedSearch')
1049 ];
1050 }
1051 // disable single entries by TypoScript
1052 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['defaultOperand']);
1053 return $allOptions;
1054 }
1055
1056 /**
1057 * get the values for the "media type" selector
1058 *
1059 * @return array Associative array with options
1060 */
1061 protected function getAllAvailableMediaTypesOptions()
1062 {
1063 $allOptions = [];
1064 $mediaTypes = [-1, 0, -2];
1065 $blindSettings = $this->settings['blind'];
1066 if (!$blindSettings['mediaType']) {
1067 foreach ($mediaTypes as $mediaType) {
1068 $allOptions[$mediaType] = LocalizationUtility::translate('mediaTypes.' . $mediaType, 'IndexedSearch');
1069 }
1070 // Add media to search in:
1071 $additionalMedia = trim($this->settings['mediaList']);
1072 if ($additionalMedia !== '') {
1073 $additionalMedia = GeneralUtility::trimExplode(',', $additionalMedia, true);
1074 } else {
1075 $additionalMedia = [];
1076 }
1077 foreach ($this->externalParsers as $extension => $obj) {
1078 // Skip unwanted extensions
1079 if (!empty($additionalMedia) && !in_array($extension, $additionalMedia)) {
1080 continue;
1081 }
1082 if ($name = $obj->searchTypeMediaTitle($extension)) {
1083 $translatedName = LocalizationUtility::translate('mediaTypes.' . $extension, 'IndexedSearch');
1084 $allOptions[$extension] = $translatedName ?: $name;
1085 }
1086 }
1087 }
1088 // disable single entries by TypoScript
1089 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['mediaType']);
1090 return $allOptions;
1091 }
1092
1093 /**
1094 * get the values for the "language" selector
1095 *
1096 * @return array Associative array with options
1097 */
1098 protected function getAllAvailableLanguageOptions()
1099 {
1100 $allOptions = [
1101 '-1' => LocalizationUtility::translate('languageUids.-1', 'IndexedSearch'),
1102 '0' => LocalizationUtility::translate('languageUids.0', 'IndexedSearch')
1103 ];
1104 $blindSettings = $this->settings['blind'];
1105 if (!$blindSettings['languageUid']) {
1106 // Add search languages
1107 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1108 ->getQueryBuilderForTable('sys_language');
1109 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1110 $result = $queryBuilder
1111 ->select('uid', 'title')
1112 ->from('sys_language')
1113 ->execute();
1114
1115 while ($lang = $result->fetch()) {
1116 $allOptions[$lang['uid']] = $lang['title'];
1117 }
1118 // disable single entries by TypoScript
1119 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['languageUid']);
1120 } else {
1121 $allOptions = [];
1122 }
1123 return $allOptions;
1124 }
1125
1126 /**
1127 * get the values for the "section" selector
1128 * Here values like "rl1_" and "rl2_" + a rootlevel 1/2 id can be added
1129 * to perform searches in rootlevel 1+2 specifically. The id-values can even
1130 * be commaseparated. Eg. "rl1_1,2" would search for stuff inside pages on
1131 * menu-level 1 which has the uid's 1 and 2.
1132 *
1133 * @return array Associative array with options
1134 */
1135 protected function getAllAvailableSectionsOptions()
1136 {
1137 $allOptions = [];
1138 $sections = [0, -1, -2, -3];
1139 $blindSettings = $this->settings['blind'];
1140 if (!$blindSettings['sections']) {
1141 foreach ($sections as $section) {
1142 $allOptions[$section] = LocalizationUtility::translate('sections.' . $section, 'IndexedSearch');
1143 }
1144 }
1145 // Creating levels for section menu:
1146 // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
1147 if ($this->settings['displayLevel1Sections']) {
1148 $firstLevelMenu = $this->getMenuOfPages($this->searchRootPageIdList);
1149 $labelLevel1 = LocalizationUtility::translate('sections.rootLevel1', 'IndexedSearch');
1150 $labelLevel2 = LocalizationUtility::translate('sections.rootLevel2', 'IndexedSearch');
1151 foreach ($firstLevelMenu as $firstLevelKey => $menuItem) {
1152 if (!$menuItem['nav_hide']) {
1153 $allOptions['rl1_' . $menuItem['uid']] = trim($labelLevel1 . ' ' . $menuItem['title']);
1154 if ($this->settings['displayLevel2Sections']) {
1155 $secondLevelMenu = $this->getMenuOfPages($menuItem['uid']);
1156 foreach ($secondLevelMenu as $secondLevelKey => $menuItemLevel2) {
1157 if (!$menuItemLevel2['nav_hide']) {
1158 $allOptions['rl2_' . $menuItemLevel2['uid']] = trim($labelLevel2 . ' ' . $menuItemLevel2['title']);
1159 } else {
1160 unset($secondLevelMenu[$secondLevelKey]);
1161 }
1162 }
1163 $allOptions['rl2_' . implode(',', array_keys($secondLevelMenu))] = LocalizationUtility::translate('sections.rootLevel2All', 'IndexedSearch');
1164 }
1165 } else {
1166 unset($firstLevelMenu[$firstLevelKey]);
1167 }
1168 }
1169 $allOptions['rl1_' . implode(',', array_keys($firstLevelMenu))] = LocalizationUtility::translate('sections.rootLevel1All', 'IndexedSearch');
1170 }
1171 // disable single entries by TypoScript
1172 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sections']);
1173 return $allOptions;
1174 }
1175
1176 /**
1177 * get the values for the "freeIndexUid" selector
1178 *
1179 * @return array Associative array with options
1180 */
1181 protected function getAllAvailableIndexConfigurationsOptions()
1182 {
1183 $allOptions = [
1184 '-1' => LocalizationUtility::translate('indexingConfigurations.-1', 'IndexedSearch'),
1185 '-2' => LocalizationUtility::translate('indexingConfigurations.-2', 'IndexedSearch'),
1186 '0' => LocalizationUtility::translate('indexingConfigurations.0', 'IndexedSearch')
1187 ];
1188 $blindSettings = $this->settings['blind'];
1189 if (!$blindSettings['indexingConfigurations']) {
1190 // add an additional index configuration
1191 if ($this->settings['defaultFreeIndexUidList']) {
1192 $uidList = GeneralUtility::intExplode(',', $this->settings['defaultFreeIndexUidList']);
1193 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1194 ->getQueryBuilderForTable('index_config');
1195 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1196 $result = $queryBuilder
1197 ->select('uid', 'title')
1198 ->from('index_config')
1199 ->where(
1200 $queryBuilder->expr()->in(
1201 'uid',
1202 $queryBuilder->createNamedParameter($uidList, Connection::PARAM_INT_ARRAY)
1203 )
1204 )
1205 ->execute();
1206
1207 while ($row = $result->fetch()) {
1208 $allOptions[$row['uid']] = $row['title'];
1209 }
1210 }
1211 // disable single entries by TypoScript
1212 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['indexingConfigurations']);
1213 } else {
1214 $allOptions = [];
1215 }
1216 return $allOptions;
1217 }
1218
1219 /**
1220 * get the values for the "section" selector
1221 * Here values like "rl1_" and "rl2_" + a rootlevel 1/2 id can be added
1222 * to perform searches in rootlevel 1+2 specifically. The id-values can even
1223 * be commaseparated. Eg. "rl1_1,2" would search for stuff inside pages on
1224 * menu-level 1 which has the uid's 1 and 2.
1225 *
1226 * @return array Associative array with options
1227 */
1228 protected function getAllAvailableSortOrderOptions()
1229 {
1230 $allOptions = [];
1231 $sortOrders = ['rank_flag', 'rank_freq', 'rank_first', 'rank_count', 'mtime', 'title', 'crdate'];
1232 $blindSettings = $this->settings['blind'];
1233 if (!$blindSettings['sortOrder']) {
1234 foreach ($sortOrders as $order) {
1235 $allOptions[$order] = LocalizationUtility::translate('sortOrders.' . $order, 'IndexedSearch');
1236 }
1237 }
1238 // disable single entries by TypoScript
1239 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sortOrder.']);
1240 return $allOptions;
1241 }
1242
1243 /**
1244 * get the values for the "group" selector
1245 *
1246 * @return array Associative array with options
1247 */
1248 protected function getAllAvailableGroupOptions()
1249 {
1250 $allOptions = [];
1251 $blindSettings = $this->settings['blind'];
1252 if (!$blindSettings['groupBy']) {
1253 $allOptions = [
1254 'sections' => LocalizationUtility::translate('groupBy.sections', 'IndexedSearch'),
1255 'flat' => LocalizationUtility::translate('groupBy.flat', 'IndexedSearch')
1256 ];
1257 }
1258 // disable single entries by TypoScript
1259 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['groupBy.']);
1260 return $allOptions;
1261 }
1262
1263 /**
1264 * get the values for the "sortDescending" selector
1265 *
1266 * @return array Associative array with options
1267 */
1268 protected function getAllAvailableSortDescendingOptions()
1269 {
1270 $allOptions = [];
1271 $blindSettings = $this->settings['blind'];
1272 if (!$blindSettings['descending']) {
1273 $allOptions = [
1274 0 => LocalizationUtility::translate('sortOrders.descending', 'IndexedSearch'),
1275 1 => LocalizationUtility::translate('sortOrders.ascending', 'IndexedSearch')
1276 ];
1277 }
1278 // disable single entries by TypoScript
1279 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['descending.']);
1280 return $allOptions;
1281 }
1282
1283 /**
1284 * get the values for the "results" selector
1285 *
1286 * @return array Associative array with options
1287 */
1288 protected function getAllAvailableNumberOfResultsOptions()
1289 {
1290 $allOptions = [];
1291 if (count($this->availableResultsNumbers) > 1) {
1292 $allOptions = array_combine($this->availableResultsNumbers, $this->availableResultsNumbers);
1293 }
1294 // disable single entries by TypoScript
1295 $allOptions = $this->removeOptionsFromOptionList($allOptions, $this->settings['blind']['numberOfResults']);
1296 return $allOptions;
1297 }
1298
1299 /**
1300 * removes blinding entries from the option list of a selector
1301 *
1302 * @param array $allOptions associative array containing all options
1303 * @param array $blindOptions associative array containing the optionkey as they key and the value = 1 if it should be removed
1304 * @return array Options from $allOptions with some options removed
1305 */
1306 protected function removeOptionsFromOptionList($allOptions, $blindOptions)
1307 {
1308 if (is_array($blindOptions)) {
1309 foreach ($blindOptions as $key => $val) {
1310 if ($val == 1) {
1311 unset($allOptions[$key]);
1312 }
1313 }
1314 }
1315 return $allOptions;
1316 }
1317
1318 /**
1319 * Links the $linkText to page $pageUid
1320 *
1321 * @param int $pageUid Page id
1322 * @param array $row Result row
1323 * @param array $markUpSwParams Additional parameters for marking up search words
1324 * @return array
1325 */
1326 protected function linkPage($pageUid, $row = [], $markUpSwParams = [])
1327 {
1328 $pageLanguage = GeneralUtility::makeInstance(Context::class)->getPropertyFromAspect('language', 'contentId', 0);
1329 // Parameters for link
1330 $urlParameters = (array)unserialize($row['cHashParams']);
1331 // Add &type and &MP variable:
1332 if ($row['data_page_mp']) {
1333 $urlParameters['MP'] = $row['data_page_mp'];
1334 }
1335 if (($pageLanguage === 0 && $row['sys_language_uid'] > 0) || $pageLanguage > 0) {
1336 $urlParameters['L'] = (int)$row['sys_language_uid'];
1337 }
1338 // markup-GET vars:
1339 $urlParameters = array_merge($urlParameters, $markUpSwParams);
1340 // This will make sure that the path is retrieved if it hasn't been
1341 // already. Used only for the sake of the domain_record thing.
1342 if (!is_array($this->domainRecords[$pageUid])) {
1343 $this->getPathFromPageId($pageUid);
1344 }
1345
1346 return $this->preparePageLink($pageUid, $row, $urlParameters);
1347 }
1348
1349 /**
1350 * Return the menu of pages used for the selector.
1351 *
1352 * @param int $pageUid Page ID for which to return menu
1353 * @return array Menu items (for making the section selector box)
1354 */
1355 protected function getMenuOfPages($pageUid)
1356 {
1357 $pageRepository = GeneralUtility::makeInstance(PageRepository::class);
1358 if ($this->settings['displayLevelxAllTypes']) {
1359 return $pageRepository->getMenuForPages([$pageUid]);
1360 }
1361 return $pageRepository->getMenu($pageUid);
1362 }
1363
1364 /**
1365 * Returns the path to the page $id
1366 *
1367 * @param int $id Page ID
1368 * @param string $pathMP Content of the MP (mount point) variable
1369 * @return string Path (HTML-escaped)
1370 */
1371 protected function getPathFromPageId($id, $pathMP = '')
1372 {
1373 $identStr = $id . '|' . $pathMP;
1374 if (!isset($this->pathCache[$identStr])) {
1375 $this->requiredFrontendUsergroups[$id] = [];
1376 $this->domainRecords[$id] = [];
1377 try {
1378 $rl = GeneralUtility::makeInstance(RootlineUtility::class, $id, $pathMP)->get();
1379 $path = '';
1380 $pageCount = count($rl);
1381 if (!empty($rl)) {
1382 $excludeDoktypesFromPath = GeneralUtility::trimExplode(
1383 ',',
1384 $this->settings['results']['pathExcludeDoktypes'] ?? '',
1385 true
1386 );
1387 $breadcrumbWrap = $this->settings['breadcrumbWrap'] ?? '/';
1388 $breadcrumbWraps = GeneralUtility::makeInstance(TypoScriptService::class)
1389 ->explodeConfigurationForOptionSplit(['wrap' => $breadcrumbWrap], $pageCount);
1390 foreach ($rl as $k => $v) {
1391 if (in_array($v['doktype'], $excludeDoktypesFromPath, false)) {
1392 continue;
1393 }
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->getFirstDomainForPage((int)$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 } catch (RootLineException $e) {
1417 $path = '';
1418 }
1419 $this->pathCache[$identStr] = $path;
1420 }
1421 return $this->pathCache[$identStr];
1422 }
1423
1424 /**
1425 * Gets the first domain for the page
1426 *
1427 * @param int $id Page id
1428 * @return string Domain name
1429 */
1430 protected function getFirstDomainForPage(int $id): string
1431 {
1432 $domain = '';
1433 try {
1434 $domain = GeneralUtility::makeInstance(SiteFinder::class)
1435 ->getSiteByRootPageId($id)
1436 ->getBase()
1437 ->getHost();
1438 } catch (SiteNotFoundException $e) {
1439 $pseudoSiteFinder = GeneralUtility::makeInstance(PseudoSiteFinder::class);
1440 try {
1441 $domain = trim((string)$pseudoSiteFinder->getSiteByPageId($id)->getBase(), '/');
1442 } catch (SiteNotFoundException $e) {
1443 // site was not found, we return an empty string as default
1444 }
1445 }
1446 return $domain;
1447 }
1448
1449 /**
1450 * simple function to initialize possible external parsers
1451 * feeds the $this->externalParsers array
1452 */
1453 protected function initializeExternalParsers()
1454 {
1455 // Initialize external document parsers for icon display and other soft operations
1456 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'] ?? [] as $extension => $className) {
1457 $this->externalParsers[$extension] = GeneralUtility::makeInstance($className);
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 /**
1466 * Returns an object reference to the hook object if any
1467 *
1468 * @param string $functionName Name of the function you want to call / hook key
1469 * @return object|null Hook object, if any. Otherwise NULL.
1470 */
1471 protected function hookRequest($functionName)
1472 {
1473 // Hook: menuConfig_preProcessModMenu
1474 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]) {
1475 $hookObj = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]);
1476 if (method_exists($hookObj, $functionName)) {
1477 $hookObj->pObj = $this;
1478 return $hookObj;
1479 }
1480 }
1481 return null;
1482 }
1483
1484 /**
1485 * Returns if an item type is a multipage item type
1486 *
1487 * @param string $item_type Item type
1488 * @return bool TRUE if multipage capable
1489 */
1490 protected function multiplePagesType($item_type)
1491 {
1492 return is_object($this->externalParsers[$item_type]) && $this->externalParsers[$item_type]->isMultiplePageExtension($item_type);
1493 }
1494
1495 /**
1496 * Process variables related to indexed_search extendedSearch needed by frontend view.
1497 * Populate select boxes and setting some flags.
1498 * The returned data can be passed directly into the view by assignMultiple()
1499 *
1500 * @return array Variables to pass into the view so they can be used in fluid template
1501 */
1502 protected function processExtendedSearchParameters()
1503 {
1504 $allSearchTypes = $this->getAllAvailableSearchTypeOptions();
1505 $allDefaultOperands = $this->getAllAvailableOperandsOptions();
1506 $allMediaTypes = $this->getAllAvailableMediaTypesOptions();
1507 $allLanguageUids = $this->getAllAvailableLanguageOptions();
1508 $allSortOrders = $this->getAllAvailableSortOrderOptions();
1509 $allSortDescendings = $this->getAllAvailableSortDescendingOptions();
1510
1511 return [
1512 'allSearchTypes' => $allSearchTypes,
1513 'allDefaultOperands' => $allDefaultOperands,
1514 'showTypeSearch' => !empty($allSearchTypes) || !empty($allDefaultOperands),
1515 'allMediaTypes' => $allMediaTypes,
1516 'allLanguageUids' => $allLanguageUids,
1517 'showMediaAndLanguageSearch' => !empty($allMediaTypes) || !empty($allLanguageUids),
1518 'allSections' => $this->getAllAvailableSectionsOptions(),
1519 'allIndexConfigurations' => $this->getAllAvailableIndexConfigurationsOptions(),
1520 'allSortOrders' => $allSortOrders,
1521 'allSortDescendings' => $allSortDescendings,
1522 'showSortOrders' => !empty($allSortOrders) || !empty($allSortDescendings),
1523 'allNumberOfResults' => $this->getAllAvailableNumberOfResultsOptions(),
1524 'allGroups' => $this->getAllAvailableGroupOptions()
1525 ];
1526 }
1527
1528 /**
1529 * Load settings and apply stdWrap to them
1530 */
1531 protected function loadSettings()
1532 {
1533 if (!is_array($this->settings['results.'])) {
1534 $this->settings['results.'] = [];
1535 }
1536 $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['results']);
1537
1538 $this->settings['results.']['summaryCropAfter'] = MathUtility::forceIntegerInRange(
1539 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropAfter'], $typoScriptArray['summaryCropAfter.']),
1540 10,
1541 5000,
1542 180
1543 );
1544 $this->settings['results.']['summaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropSignifier'], $typoScriptArray['summaryCropSignifier.']);
1545 $this->settings['results.']['titleCropAfter'] = MathUtility::forceIntegerInRange(
1546 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropAfter'], $typoScriptArray['titleCropAfter.']),
1547 10,
1548 500,
1549 50
1550 );
1551 $this->settings['results.']['titleCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropSignifier'], $typoScriptArray['titleCropSignifier.']);
1552 $this->settings['results.']['markupSW_summaryMax'] = MathUtility::forceIntegerInRange(
1553 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_summaryMax'], $typoScriptArray['markupSW_summaryMax.']),
1554 10,
1555 5000,
1556 300
1557 );
1558 $this->settings['results.']['markupSW_postPreLgd'] = MathUtility::forceIntegerInRange(
1559 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd'], $typoScriptArray['markupSW_postPreLgd.']),
1560 1,
1561 500,
1562 60
1563 );
1564 $this->settings['results.']['markupSW_postPreLgd_offset'] = MathUtility::forceIntegerInRange(
1565 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd_offset'], $typoScriptArray['markupSW_postPreLgd_offset.']),
1566 1,
1567 50,
1568 5
1569 );
1570 $this->settings['results.']['markupSW_divider'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_divider'], $typoScriptArray['markupSW_divider.']);
1571 $this->settings['results.']['hrefInSummaryCropAfter'] = MathUtility::forceIntegerInRange(
1572 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropAfter'], $typoScriptArray['hrefInSummaryCropAfter.']),
1573 10,
1574 400,
1575 60
1576 );
1577 $this->settings['results.']['hrefInSummaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropSignifier'], $typoScriptArray['hrefInSummaryCropSignifier.']);
1578 }
1579
1580 /**
1581 * Returns number of results to display
1582 *
1583 * @param int $numberOfResults Requested number of results
1584 * @return int
1585 */
1586 protected function getNumberOfResults($numberOfResults)
1587 {
1588 $numberOfResults = (int)$numberOfResults;
1589
1590 return in_array($numberOfResults, $this->availableResultsNumbers) ?
1591 $numberOfResults : $this->defaultResultNumber;
1592 }
1593
1594 /**
1595 * Internal method to build the page uri and link target.
1596 * @todo make use of the UriBuilder
1597 *
1598 * @param int $pageUid
1599 * @param array $row
1600 * @param array $urlParameters
1601 * @return array
1602 */
1603 protected function preparePageLink(int $pageUid, array $row, array $urlParameters): array
1604 {
1605 $target = '';
1606 $uri = $this->controllerContext->getUriBuilder()
1607 ->setTargetPageUid($pageUid)
1608 ->setTargetPageType($row['data_page_type'])
1609 ->setUseCacheHash(true)
1610 ->setArguments($urlParameters)
1611 ->build();
1612
1613 // If external domain, then link to that:
1614 if (!empty($this->domainRecords[$pageUid])) {
1615 $scheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
1616 $firstDomain = reset($this->domainRecords[$pageUid]);
1617 $uri = $scheme . $firstDomain . $uri;
1618 $target = $this->settings['detectDomainRecords.']['target'];
1619 }
1620
1621 return ['uri' => $uri, 'target' => $target];
1622 }
1623
1624 /**
1625 * Create a tag for "path" key in search result
1626 *
1627 * @param string $linkText Link text (nodeValue)
1628 * @param array $linkData
1629 * @return string <A> tag wrapped title string.
1630 */
1631 protected function linkPageATagWrap(string $linkText, array $linkData): string
1632 {
1633 $target = !empty($linkData['target']) ? 'target="' . htmlspecialchars($linkData['target']) . '"' : '';
1634
1635 return '<a href="' . htmlspecialchars($linkData['uri']) . '" ' . $target . '>'
1636 . htmlspecialchars($linkText)
1637 . '</a>';
1638 }
1639
1640 /**
1641 * Set the search word
1642 * @param string $sword
1643 */
1644 public function setSword($sword)
1645 {
1646 $this->sword = (string)$sword;
1647 }
1648
1649 /**
1650 * Returns the search word
1651 * @return string
1652 */
1653 public function getSword()
1654 {
1655 return (string)$this->sword;
1656 }
1657 }