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