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