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