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