bde541f72df174ea69dcde3dbe2a348ef13530cc
[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\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Utility\MathUtility;
24 use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
25
26 /**
27 * Index search frontend
28 *
29 * Creates a search form for indexed search. Indexing must be enabled
30 * for this to make sense.
31 */
32 class SearchController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
33 {
34 /**
35 * previously known as $this->piVars['sword']
36 *
37 * @var string
38 */
39 protected $sword = null;
40
41 /**
42 * @var array
43 */
44 protected $searchWords = [];
45
46 /**
47 * @var array
48 */
49 protected $searchData;
50
51 /**
52 * This is the id of the site root.
53 * This value may be a comma separated list of integer (prepared for this)
54 * Root-page PIDs to search in (rl0 field where clause, see initialize() function)
55 *
56 * If this value is set to less than zero (eg. -1) searching will happen
57 * in ALL of the page tree with no regard to branches at all.
58 * @var int|string
59 */
60 protected $searchRootPageIdList = 0;
61
62 /**
63 * @var int
64 */
65 protected $defaultResultNumber = 10;
66
67 /**
68 * @var int[]
69 */
70 protected $availableResultsNumbers = [];
71
72 /**
73 * Search repository
74 *
75 * @var \TYPO3\CMS\IndexedSearch\Domain\Repository\IndexSearchRepository
76 */
77 protected $searchRepository = null;
78
79 /**
80 * Lexer object
81 *
82 * @var \TYPO3\CMS\IndexedSearch\Lexer
83 */
84 protected $lexerObj;
85
86 /**
87 * External parser objects
88 * @var array
89 */
90 protected $externalParsers = [];
91
92 /**
93 * Will hold the first row in result - used to calculate relative hit-ratings.
94 *
95 * @var array
96 */
97 protected $firstRow = [];
98
99 /**
100 * sys_domain records
101 *
102 * @var array
103 */
104 protected $domainRecords = [];
105
106 /**
107 * Required fe_groups memberships for display of a result.
108 *
109 * @var array
110 */
111 protected $requiredFrontendUsergroups = [];
112
113 /**
114 * Page tree sections for search result.
115 *
116 * @var array
117 */
118 protected $resultSections = [];
119
120 /**
121 * Caching of page path
122 *
123 * @var array
124 */
125 protected $pathCache = [];
126
127 /**
128 * Storage of icons
129 *
130 * @var array
131 */
132 protected $iconFileNameCache = [];
133
134 /**
135 * Indexer configuration, coming from $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search']
136 *
137 * @var array
138 */
139 protected $indexerConfig = [];
140
141 /**
142 * Flag whether metaphone search should be enabled
143 *
144 * @var bool
145 */
146 protected $enableMetaphoneSearch = false;
147
148 /**
149 * @var \TYPO3\CMS\Extbase\Service\TypoScriptService
150 */
151 protected $typoScriptService;
152
153 /**
154 * @var CharsetConverter
155 */
156 protected $charsetConverter;
157
158 /**
159 * @param \TYPO3\CMS\Extbase\Service\TypoScriptService $typoScriptService
160 */
161 public function injectTypoScriptService(\TYPO3\CMS\Extbase\Service\TypoScriptService $typoScriptService)
162 {
163 $this->typoScriptService = $typoScriptService;
164 }
165
166 /**
167 * sets up all necessary object for searching
168 *
169 * @param array $searchData The incoming search parameters
170 * @return array Search parameters
171 */
172 public function initialize($searchData = [])
173 {
174 $this->charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
175 if (!is_array($searchData)) {
176 $searchData = [];
177 }
178
179 // check if TypoScript is loaded
180 if (!isset($this->settings['results'])) {
181 $this->redirect('noTypoScript');
182 }
183
184 // Sets availableResultsNumbers - has to be called before request settings are read to avoid DoS attack
185 $this->availableResultsNumbers = array_filter(GeneralUtility::intExplode(',', $this->settings['blind']['numberOfResults']));
186
187 // Sets default result number if at least one availableResultsNumbers exists
188 if (isset($this->availableResultsNumbers[0])) {
189 $this->defaultResultNumber = $this->availableResultsNumbers[0];
190 }
191
192 $this->loadSettings();
193
194 // setting default values
195 if (is_array($this->settings['defaultOptions'])) {
196 $searchData = array_merge($this->settings['defaultOptions'], $searchData);
197 }
198 // Indexer configuration from Extension Manager interface:
199 $this->indexerConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search'], ['allowed_classes' => false]);
200 $this->enableMetaphoneSearch = (bool)$this->indexerConfig['enableMetaphoneSearch'];
201 $this->initializeExternalParsers();
202 // If "_sections" is set, this value overrides any existing value.
203 if ($searchData['_sections']) {
204 $searchData['sections'] = $searchData['_sections'];
205 }
206 // If "_sections" is set, this value overrides any existing value.
207 if ($searchData['_freeIndexUid'] !== '' && $searchData['_freeIndexUid'] !== '_') {
208 $searchData['freeIndexUid'] = $searchData['_freeIndexUid'];
209 }
210 $searchData['numberOfResults'] = $this->getNumberOfResults($searchData['numberOfResults']);
211 // This gets the search-words into the $searchWordArray
212 $this->setSword($searchData['sword']);
213 // Add previous search words to current
214 if ($searchData['sword_prev_include'] && $searchData['sword_prev']) {
215 $this->setSword(trim($searchData['sword_prev']) . ' ' . $this->getSword());
216 }
217 $this->searchWords = $this->getSearchWords($searchData['defaultOperand']);
218 // This is the id of the site root.
219 // This value may be a commalist of integer (prepared for this)
220 $this->searchRootPageIdList = (int)$GLOBALS['TSFE']->config['rootLine'][0]['uid'];
221 // Setting the list of root PIDs for the search. Notice, these page IDs MUST
222 // have a TypoScript template with root flag on them! Basically this list is used
223 // to select on the "rl0" field and page ids are registered as "rl0" only if
224 // a TypoScript template record with root flag is there.
225 // This happens AFTER the use of $this->searchRootPageIdList above because
226 // the above will then fetch the menu for the CURRENT site - regardless
227 // of this kind of searching here. Thus a general search will lookup in
228 // the WHOLE database while a specific section search will take the current sections.
229 if ($this->settings['rootPidList']) {
230 $this->searchRootPageIdList = implode(',', GeneralUtility::intExplode(',', $this->settings['rootPidList']));
231 }
232 $this->searchRepository = GeneralUtility::makeInstance(\TYPO3\CMS\IndexedSearch\Domain\Repository\IndexSearchRepository::class);
233 $this->searchRepository->initialize($this->settings, $searchData, $this->externalParsers, $this->searchRootPageIdList);
234 $this->searchData = $searchData;
235 // Calling hook for modification of initialized content
236 if ($hookObj = $this->hookRequest('initialize_postProc')) {
237 $hookObj->initialize_postProc();
238 }
239 return $searchData;
240 }
241
242 /**
243 * Performs the search, the display and writing stats
244 *
245 * @param array $search the search parameters, an associative array
246 * @return void
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 = $this->charsetConverter->crop('utf-8', $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 = $this->charsetConverter->crop('utf-8', $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:]]/', '', $this->charsetConverter->crop('utf-8', $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:]]+$/', '', $this->charsetConverter->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider;
773 }
774 } else {
775 if ($strLen > $postPreLgd * 2) {
776 $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', $this->charsetConverter->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', $this->charsetConverter->crop('utf-8', $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
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 * @return void
803 */
804 protected function writeSearchStat($searchParams, $searchWords, $count, $pt)
805 {
806 $insertFields = [
807 'searchstring' => $this->getSword(),
808 'searchoptions' => serialize([$searchParams, $searchWords, $pt]),
809 'feuser_id' => (int)$GLOBALS['TSFE']->fe_user->user['uid'],
810 // cookie as set or retrieved. If people has cookies disabled this will vary all the time
811 'cookie' => $GLOBALS['TSFE']->fe_user->id,
812 // Remote IP address
813 'IP' => GeneralUtility::getIndpEnv('REMOTE_ADDR'),
814 // Number of hits on the search
815 'hits' => (int)$count,
816 // Time stamp
817 'tstamp' => $GLOBALS['EXEC_TIME']
818 ];
819 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_search_stat');
820 $connection->insert(
821 'index_stat_search',
822 $insertFields,
823 ['searchoptions' => Connection::PARAM_LOB]
824 );
825 $newId = $connection->lastInsertId('index_stat_search');
826 if ($newId) {
827 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_stat_word');
828 foreach ($searchWords as $val) {
829 $insertFields = [
830 'word' => $val['sword'],
831 'index_stat_search_id' => $newId,
832 // Time stamp
833 'tstamp' => $GLOBALS['EXEC_TIME'],
834 // search page id for indexed search stats
835 'pageid' => $GLOBALS['TSFE']->id
836 ];
837 $connection->insert('index_stat_word', $insertFields);
838 }
839 }
840 }
841
842 /**
843 * Splits the search word input into an array where each word is represented by an array with key "sword"
844 * holding the search word and key "oper" holding the SQL operator (eg. AND, OR)
845 *
846 * Only words with 2 or more characters are accepted
847 * Max 200 chars total
848 * Space is used to split words, "" can be used search for a whole string
849 * AND, OR and NOT are prefix words, overruling the default operator
850 * +/|/- equals AND, OR and NOT as operators.
851 * All search words are converted to lowercase.
852 *
853 * $defOp is the default operator. 1=OR, 0=AND
854 *
855 * @param bool $defaultOperator If TRUE, the default operator will be OR, not AND
856 * @return array Search words if any found
857 */
858 protected function getSearchWords($defaultOperator)
859 {
860 // Shorten search-word string to max 200 bytes (does NOT take multibyte charsets into account - but never mind,
861 // shortening the string here is only a run-away feature!)
862 $searchWords = substr($this->getSword(), 0, 200);
863 // Convert to UTF-8 + conv. entities (was also converted during indexing!)
864 $searchWords = $this->charsetConverter->conv($searchWords, $GLOBALS['TSFE']->metaCharset, 'utf-8');
865 $searchWords = $this->charsetConverter->entities_to_utf8($searchWords);
866 $sWordArray = false;
867 if ($hookObj = $this->hookRequest('getSearchWords')) {
868 $sWordArray = $hookObj->getSearchWords_splitSWords($searchWords, $defaultOperator);
869 } else {
870 // sentence
871 if ($this->searchData['searchType'] == 20) {
872 $sWordArray = [
873 [
874 'sword' => trim($searchWords),
875 'oper' => 'AND'
876 ]
877 ];
878 } else {
879 // case-sensitive. Defines the words, which will be
880 // operators between words
881 $operatorTranslateTable = [
882 ['+', 'AND'],
883 ['|', 'OR'],
884 ['-', 'AND NOT'],
885 // Add operators for various languages
886 // Converts the operators to lowercase
887 [mb_strtolower(LocalizationUtility::translate('localizedOperandAnd', 'IndexedSearch'), 'utf-8'), 'AND'],
888 [mb_strtolower(LocalizationUtility::translate('localizedOperandOr', 'IndexedSearch'), 'utf-8'), 'OR'],
889 [mb_strtolower(LocalizationUtility::translate('localizedOperandNot', 'IndexedSearch'), 'utf-8'), 'AND NOT']
890 ];
891 $swordArray = \TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::getExplodedSearchString($searchWords, $defaultOperator == 1 ? 'OR' : 'AND', $operatorTranslateTable);
892 if (is_array($swordArray)) {
893 $sWordArray = $this->procSearchWordsByLexer($swordArray);
894 }
895 }
896 }
897 return $sWordArray;
898 }
899
900 /**
901 * Post-process the search word array so it will match the words that was indexed (including case-folding if any)
902 * If any words are splitted into multiple words (eg. CJK will be!) the operator of the main word will remain.
903 *
904 * @param array $searchWords Search word array
905 * @return array Search word array, processed through lexer
906 */
907 protected function procSearchWordsByLexer($searchWords)
908 {
909 $newSearchWords = [];
910 // Init lexer (used to post-processing of search words)
911 $lexerObjRef = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ?: \TYPO3\CMS\IndexedSearch\Lexer::class;
912 $this->lexerObj = GeneralUtility::getUserObj($lexerObjRef);
913 // Traverse the search word array
914 foreach ($searchWords as $wordDef) {
915 // No space in word (otherwise it might be a sentense in quotes like "there is").
916 if (strpos($wordDef['sword'], ' ') === false) {
917 // Split the search word by lexer:
918 $res = $this->lexerObj->split2Words($wordDef['sword']);
919 // Traverse lexer result and add all words again:
920 foreach ($res as $word) {
921 $newSearchWords[] = [
922 'sword' => $word,
923 'oper' => $wordDef['oper']
924 ];
925 }
926 } else {
927 $newSearchWords[] = $wordDef;
928 }
929 }
930 return $newSearchWords;
931 }
932
933 /**
934 * Sort options about the search form
935 *
936 * @param array $search The search data / params
937 * @return void
938 * @ignorevalidation $search
939 */
940 public function formAction($search = [])
941 {
942 $searchData = $this->initialize($search);
943 // Adding search field value
944 $this->view->assign('sword', $this->getSword());
945 // Extended search
946 if ($search['extendedSearch']) {
947 // "Search for"
948 $allSearchTypes = $this->getAllAvailableSearchTypeOptions();
949 $this->view->assign('allSearchTypes', $allSearchTypes);
950 $allDefaultOperands = $this->getAllAvailableOperandsOptions();
951 $this->view->assign('allDefaultOperands', $allDefaultOperands);
952 $showTypeSearch = !empty($allSearchTypes) || !empty($allDefaultOperands);
953 $this->view->assign('showTypeSearch', $showTypeSearch);
954 // "Search in"
955 $allMediaTypes = $this->getAllAvailableMediaTypesOptions();
956 $this->view->assign('allMediaTypes', $allMediaTypes);
957 $allLanguageUids = $this->getAllAvailableLanguageOptions();
958 $this->view->assign('allLanguageUids', $allLanguageUids);
959 $showMediaAndLanguageSearch = !empty($allMediaTypes) || !empty($allLanguageUids);
960 $this->view->assign('showMediaAndLanguageSearch', $showMediaAndLanguageSearch);
961 // Sections
962 $allSections = $this->getAllAvailableSectionsOptions();
963 $this->view->assign('allSections', $allSections);
964 // Free Indexing Configurations
965 $allIndexConfigurations = $this->getAllAvailableIndexConfigurationsOptions();
966 $this->view->assign('allIndexConfigurations', $allIndexConfigurations);
967 // Sorting
968 $allSortOrders = $this->getAllAvailableSortOrderOptions();
969 $this->view->assign('allSortOrders', $allSortOrders);
970 $allSortDescendings = $this->getAllAvailableSortDescendingOptions();
971 $this->view->assign('allSortDescendings', $allSortDescendings);
972 $showSortOrders = !empty($allSortOrders) || !empty($allSortDescendings);
973 $this->view->assign('showSortOrders', $showSortOrders);
974 // Limits
975 $allNumberOfResults = $this->getAllAvailableNumberOfResultsOptions();
976 $this->view->assign('allNumberOfResults', $allNumberOfResults);
977 $allGroups = $this->getAllAvailableGroupOptions();
978 $this->view->assign('allGroups', $allGroups);
979 }
980 $this->view->assign('searchParams', $searchData);
981 }
982
983 /**
984 * TypoScript was not loaded
985 */
986 public function noTypoScriptAction()
987 {
988 }
989
990 /****************************************
991 * building together the available options for every dropdown
992 ***************************************/
993 /**
994 * get the values for the "type" selector
995 *
996 * @return array Associative array with options
997 */
998 protected function getAllAvailableSearchTypeOptions()
999 {
1000 $allOptions = [];
1001 $types = [0, 1, 2, 3, 10, 20];
1002 $blindSettings = $this->settings['blind'];
1003 if (!$blindSettings['searchType']) {
1004 foreach ($types as $typeNum) {
1005 $allOptions[$typeNum] = LocalizationUtility::translate('searchTypes.' . $typeNum, 'IndexedSearch');
1006 }
1007 }
1008 // Remove this option if metaphone search is disabled)
1009 if (!$this->enableMetaphoneSearch) {
1010 unset($allOptions[10]);
1011 }
1012 // disable single entries by TypoScript
1013 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['searchType']);
1014 return $allOptions;
1015 }
1016
1017 /**
1018 * get the values for the "defaultOperand" selector
1019 *
1020 * @return array Associative array with options
1021 */
1022 protected function getAllAvailableOperandsOptions()
1023 {
1024 $allOptions = [];
1025 $blindSettings = $this->settings['blind'];
1026 if (!$blindSettings['defaultOperand']) {
1027 $allOptions = [
1028 0 => LocalizationUtility::translate('defaultOperands.0', 'IndexedSearch'),
1029 1 => LocalizationUtility::translate('defaultOperands.1', 'IndexedSearch')
1030 ];
1031 }
1032 // disable single entries by TypoScript
1033 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['defaultOperand']);
1034 return $allOptions;
1035 }
1036
1037 /**
1038 * get the values for the "media type" selector
1039 *
1040 * @return array Associative array with options
1041 */
1042 protected function getAllAvailableMediaTypesOptions()
1043 {
1044 $allOptions = [];
1045 $mediaTypes = [-1, 0, -2];
1046 $blindSettings = $this->settings['blind'];
1047 if (!$blindSettings['mediaType']) {
1048 foreach ($mediaTypes as $mediaType) {
1049 $allOptions[$mediaType] = LocalizationUtility::translate('mediaTypes.' . $mediaType, 'IndexedSearch');
1050 }
1051 // Add media to search in:
1052 $additionalMedia = trim($this->settings['mediaList']);
1053 if ($additionalMedia !== '') {
1054 $additionalMedia = GeneralUtility::trimExplode(',', $additionalMedia, true);
1055 } else {
1056 $additionalMedia = [];
1057 }
1058 foreach ($this->externalParsers as $extension => $obj) {
1059 // Skip unwanted extensions
1060 if (!empty($additionalMedia) && !in_array($extension, $additionalMedia)) {
1061 continue;
1062 }
1063 if ($name = $obj->searchTypeMediaTitle($extension)) {
1064 $translatedName = LocalizationUtility::translate('mediaTypes.' . $extension, 'IndexedSearch');
1065 $allOptions[$extension] = $translatedName ?: $name;
1066 }
1067 }
1068 }
1069 // disable single entries by TypoScript
1070 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['mediaType']);
1071 return $allOptions;
1072 }
1073
1074 /**
1075 * get the values for the "language" selector
1076 *
1077 * @return array Associative array with options
1078 */
1079 protected function getAllAvailableLanguageOptions()
1080 {
1081 $allOptions = [
1082 '-1' => LocalizationUtility::translate('languageUids.-1', 'IndexedSearch'),
1083 '0' => LocalizationUtility::translate('languageUids.0', 'IndexedSearch')
1084 ];
1085 $blindSettings = $this->settings['blind'];
1086 if (!$blindSettings['languageUid']) {
1087 // Add search languages
1088 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1089 ->getQueryBuilderForTable('sys_language');
1090 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1091 $result = $queryBuilder
1092 ->select('uid', 'title')
1093 ->from('sys_language')
1094 ->execute();
1095
1096 while ($lang = $result->fetch()) {
1097 $allOptions[$lang['uid']] = $lang['title'];
1098 }
1099 // disable single entries by TypoScript
1100 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['languageUid']);
1101 } else {
1102 $allOptions = [];
1103 }
1104 return $allOptions;
1105 }
1106
1107 /**
1108 * get the values for the "section" selector
1109 * Here values like "rl1_" and "rl2_" + a rootlevel 1/2 id can be added
1110 * to perform searches in rootlevel 1+2 specifically. The id-values can even
1111 * be commaseparated. Eg. "rl1_1,2" would search for stuff inside pages on
1112 * menu-level 1 which has the uid's 1 and 2.
1113 *
1114 * @return array Associative array with options
1115 */
1116 protected function getAllAvailableSectionsOptions()
1117 {
1118 $allOptions = [];
1119 $sections = [0, -1, -2, -3];
1120 $blindSettings = $this->settings['blind'];
1121 if (!$blindSettings['sections']) {
1122 foreach ($sections as $section) {
1123 $allOptions[$section] = LocalizationUtility::translate('sections.' . $section, 'IndexedSearch');
1124 }
1125 }
1126 // Creating levels for section menu:
1127 // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
1128 if ($this->settings['displayLevel1Sections']) {
1129 $firstLevelMenu = $this->getMenuOfPages($this->searchRootPageIdList);
1130 $labelLevel1 = LocalizationUtility::translate('sections.rootLevel1', 'IndexedSearch');
1131 $labelLevel2 = LocalizationUtility::translate('sections.rootLevel2', 'IndexedSearch');
1132 foreach ($firstLevelMenu as $firstLevelKey => $menuItem) {
1133 if (!$menuItem['nav_hide']) {
1134 $allOptions['rl1_' . $menuItem['uid']] = trim($labelLevel1 . ' ' . $menuItem['title']);
1135 if ($this->settings['displayLevel2Sections']) {
1136 $secondLevelMenu = $this->getMenuOfPages($menuItem['uid']);
1137 foreach ($secondLevelMenu as $secondLevelKey => $menuItemLevel2) {
1138 if (!$menuItemLevel2['nav_hide']) {
1139 $allOptions['rl2_' . $menuItemLevel2['uid']] = trim($labelLevel2 . ' ' . $menuItemLevel2['title']);
1140 } else {
1141 unset($secondLevelMenu[$secondLevelKey]);
1142 }
1143 }
1144 $allOptions['rl2_' . implode(',', array_keys($secondLevelMenu))] = LocalizationUtility::translate('sections.rootLevel2All', 'IndexedSearch');
1145 }
1146 } else {
1147 unset($firstLevelMenu[$firstLevelKey]);
1148 }
1149 }
1150 $allOptions['rl1_' . implode(',', array_keys($firstLevelMenu))] = LocalizationUtility::translate('sections.rootLevel1All', 'IndexedSearch');
1151 }
1152 // disable single entries by TypoScript
1153 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sections']);
1154 return $allOptions;
1155 }
1156
1157 /**
1158 * get the values for the "freeIndexUid" selector
1159 *
1160 * @return array Associative array with options
1161 */
1162 protected function getAllAvailableIndexConfigurationsOptions()
1163 {
1164 $allOptions = [
1165 '-1' => LocalizationUtility::translate('indexingConfigurations.-1', 'IndexedSearch'),
1166 '-2' => LocalizationUtility::translate('indexingConfigurations.-2', 'IndexedSearch'),
1167 '0' => LocalizationUtility::translate('indexingConfigurations.0', 'IndexedSearch')
1168 ];
1169 $blindSettings = $this->settings['blind'];
1170 if (!$blindSettings['indexingConfigurations']) {
1171 // add an additional index configuration
1172 if ($this->settings['defaultFreeIndexUidList']) {
1173 $uidList = GeneralUtility::intExplode(',', $this->settings['defaultFreeIndexUidList']);
1174 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1175 ->getQueryBuilderForTable('index_config');
1176 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1177 $result = $queryBuilder
1178 ->select('uid', 'title')
1179 ->from('index_config')
1180 ->where(
1181 $queryBuilder->expr()->in(
1182 'uid',
1183 $queryBuilder->createNamedParameter($uidList, Connection::PARAM_INT_ARRAY)
1184 )
1185 )
1186 ->execute();
1187
1188 while ($row = $result->fetch()) {
1189 $allOptions[$row['uid']]= $row['title'];
1190 }
1191 }
1192 // disable single entries by TypoScript
1193 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['indexingConfigurations']);
1194 } else {
1195 $allOptions = [];
1196 }
1197 return $allOptions;
1198 }
1199
1200 /**
1201 * get the values for the "section" selector
1202 * Here values like "rl1_" and "rl2_" + a rootlevel 1/2 id can be added
1203 * to perform searches in rootlevel 1+2 specifically. The id-values can even
1204 * be commaseparated. Eg. "rl1_1,2" would search for stuff inside pages on
1205 * menu-level 1 which has the uid's 1 and 2.
1206 *
1207 * @return array Associative array with options
1208 */
1209 protected function getAllAvailableSortOrderOptions()
1210 {
1211 $allOptions = [];
1212 $sortOrders = ['rank_flag', 'rank_freq', 'rank_first', 'rank_count', 'mtime', 'title', 'crdate'];
1213 $blindSettings = $this->settings['blind'];
1214 if (!$blindSettings['sortOrder']) {
1215 foreach ($sortOrders as $order) {
1216 $allOptions[$order] = LocalizationUtility::translate('sortOrders.' . $order, 'IndexedSearch');
1217 }
1218 }
1219 // disable single entries by TypoScript
1220 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sortOrder.']);
1221 return $allOptions;
1222 }
1223
1224 /**
1225 * get the values for the "group" selector
1226 *
1227 * @return array Associative array with options
1228 */
1229 protected function getAllAvailableGroupOptions()
1230 {
1231 $allOptions = [];
1232 $blindSettings = $this->settings['blind'];
1233 if (!$blindSettings['groupBy']) {
1234 $allOptions = [
1235 'sections' => LocalizationUtility::translate('groupBy.sections', 'IndexedSearch'),
1236 'flat' => LocalizationUtility::translate('groupBy.flat', 'IndexedSearch')
1237 ];
1238 }
1239 // disable single entries by TypoScript
1240 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['groupBy.']);
1241 return $allOptions;
1242 }
1243
1244 /**
1245 * get the values for the "sortDescending" selector
1246 *
1247 * @return array Associative array with options
1248 */
1249 protected function getAllAvailableSortDescendingOptions()
1250 {
1251 $allOptions = [];
1252 $blindSettings = $this->settings['blind'];
1253 if (!$blindSettings['descending']) {
1254 $allOptions = [
1255 0 => LocalizationUtility::translate('sortOrders.descending', 'IndexedSearch'),
1256 1 => LocalizationUtility::translate('sortOrders.ascending', 'IndexedSearch')
1257 ];
1258 }
1259 // disable single entries by TypoScript
1260 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['descending.']);
1261 return $allOptions;
1262 }
1263
1264 /**
1265 * get the values for the "results" selector
1266 *
1267 * @return array Associative array with options
1268 */
1269 protected function getAllAvailableNumberOfResultsOptions()
1270 {
1271 $allOptions = [];
1272 if (count($this->availableResultsNumbers) > 1) {
1273 $allOptions = array_combine($this->availableResultsNumbers, $this->availableResultsNumbers);
1274 }
1275 // disable single entries by TypoScript
1276 $allOptions = $this->removeOptionsFromOptionList($allOptions, $this->settings['blind']['numberOfResults']);
1277 return $allOptions;
1278 }
1279
1280 /**
1281 * removes blinding entries from the option list of a selector
1282 *
1283 * @param array $allOptions associative array containing all options
1284 * @param array $blindOptions associative array containing the optionkey as they key and the value = 1 if it should be removed
1285 * @return array Options from $allOptions with some options removed
1286 */
1287 protected function removeOptionsFromOptionList($allOptions, $blindOptions)
1288 {
1289 if (is_array($blindOptions)) {
1290 foreach ($blindOptions as $key => $val) {
1291 if ($val == 1) {
1292 unset($allOptions[$key]);
1293 }
1294 }
1295 }
1296 return $allOptions;
1297 }
1298
1299 /**
1300 * Links the $linkText to page $pageUid
1301 *
1302 * @param int $pageUid Page id
1303 * @param string $linkText Title to link (must already be escaped for HTML output)
1304 * @param array $row Result row
1305 * @param array $markUpSwParams Additional parameters for marking up seach words
1306 * @return string <A> tag wrapped title string.
1307 * @todo make use of the UriBuilder
1308 */
1309 protected function linkPage($pageUid, $linkText, $row = [], $markUpSwParams = [])
1310 {
1311 // Parameters for link
1312 $urlParameters = (array)unserialize($row['cHashParams']);
1313 // Add &type and &MP variable:
1314 if ($row['data_page_mp']) {
1315 $urlParameters['MP'] = $row['data_page_mp'];
1316 }
1317 $urlParameters['L'] = intval($row['sys_language_uid']);
1318 // markup-GET vars:
1319 $urlParameters = array_merge($urlParameters, $markUpSwParams);
1320 // This will make sure that the path is retrieved if it hasn't been
1321 // already. Used only for the sake of the domain_record thing.
1322 if (!is_array($this->domainRecords[$pageUid])) {
1323 $this->getPathFromPageId($pageUid);
1324 }
1325 $target = '';
1326 // If external domain, then link to that:
1327 if (!empty($this->domainRecords[$pageUid])) {
1328 $scheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
1329 $firstDomain = reset($this->domainRecords[$pageUid]);
1330 $additionalParams = '';
1331 if (is_array($urlParameters) && !empty($urlParameters)) {
1332 $additionalParams = GeneralUtility::implodeArrayForUrl('', $urlParameters);
1333 }
1334 $uri = $scheme . $firstDomain . '/index.php?id=' . $pageUid . $additionalParams;
1335 if ($target = $this->settings['detectDomainRecords.']['target']) {
1336 $target = ' target="' . $target . '"';
1337 }
1338 } else {
1339 $uriBuilder = $this->controllerContext->getUriBuilder();
1340 $uri = $uriBuilder->setTargetPageUid($pageUid)->setTargetPageType($row['data_page_type'])->setUseCacheHash(true)->setArguments($urlParameters)->build();
1341 }
1342 return '<a href="' . htmlspecialchars($uri) . '"' . $target . '>' . $linkText . '</a>';
1343 }
1344
1345 /**
1346 * Return the menu of pages used for the selector.
1347 *
1348 * @param int $pageUid Page ID for which to return menu
1349 * @return array Menu items (for making the section selector box)
1350 */
1351 protected function getMenuOfPages($pageUid)
1352 {
1353 if ($this->settings['displayLevelxAllTypes']) {
1354 $menu = [];
1355 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1356 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1357 $result = $queryBuilder
1358 ->select('uid', 'title')
1359 ->from('pages')
1360 ->where(
1361 $queryBuilder->expr()->eq(
1362 'pid',
1363 $queryBuilder->createNamedParameter($pageUid, \PDO::PARAM_INT)
1364 )
1365 )
1366 ->orderBy('sorting')
1367 ->execute();
1368
1369 while ($row = $result->fetch()) {
1370 $menu[$row['uid']] = $GLOBALS['TSFE']->sys_page->getPageOverlay($row);
1371 }
1372 } else {
1373 $menu = $GLOBALS['TSFE']->sys_page->getMenu($pageUid);
1374 }
1375 return $menu;
1376 }
1377
1378 /**
1379 * Returns the path to the page $id
1380 *
1381 * @param int $id Page ID
1382 * @param string $pathMP Content of the MP (mount point) variable
1383 * @return string Path (HTML-escaped)
1384 */
1385 protected function getPathFromPageId($id, $pathMP = '')
1386 {
1387 $identStr = $id . '|' . $pathMP;
1388 if (!isset($this->pathCache[$identStr])) {
1389 $this->requiredFrontendUsergroups[$id] = [];
1390 $this->domainRecords[$id] = [];
1391 $rl = $GLOBALS['TSFE']->sys_page->getRootLine($id, $pathMP);
1392 $path = '';
1393 $pageCount = count($rl);
1394 if (is_array($rl) && !empty($rl)) {
1395 $breadcrumbWrap = isset($this->settings['breadcrumbWrap']) ? $this->settings['breadcrumbWrap'] : '/';
1396 $breadcrumbWraps = $GLOBALS['TSFE']->tmpl->splitConfArray(['wrap' => $breadcrumbWrap], $pageCount);
1397 foreach ($rl as $k => $v) {
1398 // Check fe_user
1399 if ($v['fe_group'] && ($v['uid'] == $id || $v['extendToSubpages'])) {
1400 $this->requiredFrontendUsergroups[$id][] = $v['fe_group'];
1401 }
1402 // Check sys_domain
1403 if ($this->settings['detectDomainRcords']) {
1404 $domainName = $this->getFirstSysDomainRecordForPage($v['uid']);
1405 if ($domainName) {
1406 $this->domainRecords[$id][] = $domainName;
1407 // Set path accordingly
1408 $path = $domainName . $path;
1409 break;
1410 }
1411 }
1412 // Stop, if we find that the current id is the current root page.
1413 if ($v['uid'] == $GLOBALS['TSFE']->config['rootLine'][0]['uid']) {
1414 array_pop($breadcrumbWraps);
1415 break;
1416 }
1417 $path = $GLOBALS['TSFE']->cObj->wrap(htmlspecialchars($v['title']), array_pop($breadcrumbWraps)['wrap']) . $path;
1418 }
1419 }
1420 $this->pathCache[$identStr] = $path;
1421 }
1422 return $this->pathCache[$identStr];
1423 }
1424
1425 /**
1426 * Gets the first sys_domain record for the page, $id
1427 *
1428 * @param int $id Page id
1429 * @return string Domain name
1430 */
1431 protected function getFirstSysDomainRecordForPage($id)
1432 {
1433 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_domain');
1434 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1435 $row = $queryBuilder
1436 ->select('domainName')
1437 ->from('sys_domain')
1438 ->where(
1439 $queryBuilder->expr()->eq(
1440 'pid',
1441 $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
1442 )
1443 )
1444 ->orderBy('sorting')
1445 ->setMaxResults(1)
1446 ->execute()
1447 ->fetch();
1448
1449 return rtrim($row['domainName'], '/');
1450 }
1451
1452 /**
1453 * simple function to initialize possible external parsers
1454 * feeds the $this->externalParsers array
1455 *
1456 * @return void
1457 */
1458 protected function initializeExternalParsers()
1459 {
1460 // Initialize external document parsers for icon display and other soft operations
1461 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'])) {
1462 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'] as $extension => $_objRef) {
1463 $this->externalParsers[$extension] = GeneralUtility::getUserObj($_objRef);
1464 // Init parser and if it returns FALSE, unset its entry again
1465 if (!$this->externalParsers[$extension]->softInit($extension)) {
1466 unset($this->externalParsers[$extension]);
1467 }
1468 }
1469 }
1470 }
1471
1472 /**
1473 * Returns an object reference to the hook object if any
1474 *
1475 * @param string $functionName Name of the function you want to call / hook key
1476 * @return object|NULL Hook object, if any. Otherwise NULL.
1477 */
1478 protected function hookRequest($functionName)
1479 {
1480 // Hook: menuConfig_preProcessModMenu
1481 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]) {
1482 $hookObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]);
1483 if (method_exists($hookObj, $functionName)) {
1484 $hookObj->pObj = $this;
1485 return $hookObj;
1486 }
1487 }
1488 return null;
1489 }
1490
1491 /**
1492 * Returns if an item type is a multipage item type
1493 *
1494 * @param string $item_type Item type
1495 * @return bool TRUE if multipage capable
1496 */
1497 protected function multiplePagesType($item_type)
1498 {
1499 return is_object($this->externalParsers[$item_type]) && $this->externalParsers[$item_type]->isMultiplePageExtension($item_type);
1500 }
1501
1502 /**
1503 * Load settings and apply stdWrap to them
1504 */
1505 protected function loadSettings()
1506 {
1507 if (!is_array($this->settings['results.'])) {
1508 $this->settings['results.'] = [];
1509 }
1510 $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['results']);
1511
1512 $this->settings['results.']['summaryCropAfter'] = MathUtility::forceIntegerInRange(
1513 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropAfter'], $typoScriptArray['summaryCropAfter.']),
1514 10, 5000, 180
1515 );
1516 $this->settings['results.']['summaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropSignifier'], $typoScriptArray['summaryCropSignifier.']);
1517 $this->settings['results.']['titleCropAfter'] = MathUtility::forceIntegerInRange(
1518 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropAfter'], $typoScriptArray['titleCropAfter.']),
1519 10, 500, 50
1520 );
1521 $this->settings['results.']['titleCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropSignifier'], $typoScriptArray['titleCropSignifier.']);
1522 $this->settings['results.']['markupSW_summaryMax'] = MathUtility::forceIntegerInRange(
1523 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_summaryMax'], $typoScriptArray['markupSW_summaryMax.']),
1524 10, 5000, 300
1525 );
1526 $this->settings['results.']['markupSW_postPreLgd'] = MathUtility::forceIntegerInRange(
1527 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd'], $typoScriptArray['markupSW_postPreLgd.']),
1528 1, 500, 60
1529 );
1530 $this->settings['results.']['markupSW_postPreLgd_offset'] = MathUtility::forceIntegerInRange(
1531 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd_offset'], $typoScriptArray['markupSW_postPreLgd_offset.']),
1532 1, 50, 5
1533 );
1534 $this->settings['results.']['markupSW_divider'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_divider'], $typoScriptArray['markupSW_divider.']);
1535 $this->settings['results.']['hrefInSummaryCropAfter'] = MathUtility::forceIntegerInRange(
1536 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropAfter'], $typoScriptArray['hrefInSummaryCropAfter.']),
1537 10, 400, 60
1538 );
1539 $this->settings['results.']['hrefInSummaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropSignifier'], $typoScriptArray['hrefInSummaryCropSignifier.']);
1540 }
1541
1542 /**
1543 * Returns number of results to display
1544 *
1545 * @param int $numberOfResults Requested number of results
1546 * @return int
1547 */
1548 protected function getNumberOfResults($numberOfResults)
1549 {
1550 $numberOfResults = intval($numberOfResults);
1551
1552 return (in_array($numberOfResults, $this->availableResultsNumbers)) ?
1553 $numberOfResults : $this->defaultResultNumber;
1554 }
1555
1556 /**
1557 * Set the search word
1558 * @param string $sword
1559 */
1560 public function setSword($sword)
1561 {
1562 $this->sword = $sword;
1563 }
1564
1565 /**
1566 * Returns the search word
1567 * @return string
1568 */
1569 public function getSword()
1570 {
1571 return $this->sword;
1572 }
1573 }