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