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