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