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