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