[TASK] Replace csConvObj calls
[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']);
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, 100000, $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 $output = $GLOBALS['TSFE']->csConv($output, 'utf-8');
676 } else {
677 $output = '<span class="noResume">' . LocalizationUtility::translate('result.noResume', 'IndexedSearch') . '</span>';
678 }
679 return $output;
680 }
681
682 /**
683 * Marks up the search words from $this->searchWords in the $str with a color.
684 *
685 * @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.
686 * @return string Processed content
687 */
688 protected function markupSWpartsOfString($str)
689 {
690 $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
691 // Init:
692 $str = str_replace('&nbsp;', ' ', $htmlParser->bidir_htmlspecialchars($str, -1));
693 $str = preg_replace('/\\s\\s+/', ' ', $str);
694 $swForReg = array();
695 // Prepare search words for regex:
696 foreach ($this->searchWords as $d) {
697 $swForReg[] = preg_quote($d['sword'], '/');
698 }
699 $regExString = '(' . implode('|', $swForReg) . ')';
700 // Split and combine:
701 $parts = preg_split('/' . $regExString . '/i', ' ' . $str . ' ', 20000, PREG_SPLIT_DELIM_CAPTURE);
702 // Constants:
703 $summaryMax = $this->settings['results.']['markupSW_summaryMax'];
704 $postPreLgd = $this->settings['results.']['markupSW_postPreLgd'];
705 $postPreLgd_offset = $this->settings['results.']['markupSW_postPreLgd_offset'];
706 $divider = $this->settings['results.']['markupSW_divider'];
707 $occurencies = (count($parts) - 1) / 2;
708 if ($occurencies) {
709 $postPreLgd = MathUtility::forceIntegerInRange($summaryMax / $occurencies, $postPreLgd, $summaryMax / 2);
710 }
711 // Variable:
712 $summaryLgd = 0;
713 $output = array();
714 // Shorten in-between strings:
715 foreach ($parts as $k => $strP) {
716 if ($k % 2 == 0) {
717 // Find length of the summary part:
718 $strLen = $this->charsetConverter->strlen('utf-8', $parts[$k]);
719 $output[$k] = $parts[$k];
720 // Possibly shorten string:
721 if (!$k) {
722 // First entry at all (only cropped on the frontside)
723 if ($strLen > $postPreLgd) {
724 $output[$k] = $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', $this->charsetConverter->crop('utf-8', $parts[$k], -($postPreLgd - $postPreLgd_offset)));
725 }
726 } elseif ($summaryLgd > $summaryMax || !isset($parts[$k + 1])) {
727 // In case summary length is exceed OR if there are no more entries at all:
728 if ($strLen > $postPreLgd) {
729 $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', $this->charsetConverter->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider;
730 }
731 } else {
732 if ($strLen > $postPreLgd * 2) {
733 $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)));
734 }
735 }
736 $summaryLgd += $this->charsetConverter->strlen('utf-8', $output[$k]);
737 // Protect output:
738 $output[$k] = htmlspecialchars($output[$k]);
739 // If summary lgd is exceed, break the process:
740 if ($summaryLgd > $summaryMax) {
741 break;
742 }
743 } else {
744 $summaryLgd += $this->charsetConverter->strlen('utf-8', $strP);
745 $output[$k] = '<strong class="tx-indexedsearch-redMarkup">' . htmlspecialchars($parts[$k]) . '</strong>';
746 }
747 }
748 // Return result:
749 return implode('', $output);
750 }
751
752 /**
753 * Write statistics information to database for the search operation
754 *
755 * @param array $searchParams search params
756 * @param array $searchWords Search Word array
757 * @param int $count Number of hits
758 * @param int $pt Milliseconds the search took
759 * @return void
760 */
761 protected function writeSearchStat($searchParams, $searchWords, $count, $pt)
762 {
763 $insertFields = array(
764 'searchstring' => $this->sword,
765 'searchoptions' => serialize(array($searchParams, $searchWords, $pt)),
766 'feuser_id' => (int)$GLOBALS['TSFE']->fe_user->user['uid'],
767 // cookie as set or retrieved. If people has cookies disabled this will vary all the time
768 'cookie' => $GLOBALS['TSFE']->fe_user->id,
769 // Remote IP address
770 'IP' => GeneralUtility::getIndpEnv('REMOTE_ADDR'),
771 // Number of hits on the search
772 'hits' => (int)$count,
773 // Time stamp
774 'tstamp' => $GLOBALS['EXEC_TIME']
775 );
776 $this->getDatabaseConnection()->exec_INSERTquery('index_stat_search', $insertFields);
777 $newId = $this->getDatabaseConnection()->sql_insert_id();
778 if ($newId) {
779 foreach ($searchWords as $val) {
780 $insertFields = array(
781 'word' => $val['sword'],
782 'index_stat_search_id' => $newId,
783 // Time stamp
784 'tstamp' => $GLOBALS['EXEC_TIME'],
785 // search page id for indexed search stats
786 'pageid' => $GLOBALS['TSFE']->id
787 );
788 $this->getDatabaseConnection()->exec_INSERTquery('index_stat_word', $insertFields);
789 }
790 }
791 }
792
793 /**
794 * Splits the search word input into an array where each word is represented by an array with key "sword"
795 * holding the search word and key "oper" holding the SQL operator (eg. AND, OR)
796 *
797 * Only words with 2 or more characters are accepted
798 * Max 200 chars total
799 * Space is used to split words, "" can be used search for a whole string
800 * AND, OR and NOT are prefix words, overruling the default operator
801 * +/|/- equals AND, OR and NOT as operators.
802 * All search words are converted to lowercase.
803 *
804 * $defOp is the default operator. 1=OR, 0=AND
805 *
806 * @param bool $defaultOperator If TRUE, the default operator will be OR, not AND
807 * @return array Search words if any found
808 */
809 protected function getSearchWords($defaultOperator)
810 {
811 // Shorten search-word string to max 200 bytes (does NOT take multibyte charsets into account - but never mind,
812 // shortening the string here is only a run-away feature!)
813 $searchWords = substr($this->sword, 0, 200);
814 // Convert to UTF-8 + conv. entities (was also converted during indexing!)
815 $searchWords = $this->charsetConverter->conv($searchWords, $GLOBALS['TSFE']->metaCharset, 'utf-8');
816 $searchWords = $this->charsetConverter->entities_to_utf8($searchWords, true);
817 $sWordArray = false;
818 if ($hookObj = $this->hookRequest('getSearchWords')) {
819 $sWordArray = $hookObj->getSearchWords_splitSWords($searchWords, $defaultOperator);
820 } else {
821 // sentence
822 if ($this->searchData['searchType'] == 20) {
823 $sWordArray = array(
824 array(
825 'sword' => trim($searchWords),
826 'oper' => 'AND'
827 )
828 );
829 } else {
830 // case-sensitive. Defines the words, which will be
831 // operators between words
832 $operatorTranslateTable = array(
833 array('+', 'AND'),
834 array('|', 'OR'),
835 array('-', 'AND NOT'),
836 // Add operators for various languages
837 // Converts the operators to UTF-8 and lowercase
838 array($this->charsetConverter->conv_case('utf-8', $this->charsetConverter->conv(LocalizationUtility::translate('localizedOperandAnd', 'IndexedSearch'), $GLOBALS['TSFE']->renderCharset, 'utf-8'), 'toLower'), 'AND'),
839 array($this->charsetConverter->conv_case('utf-8', $this->charsetConverter->conv(LocalizationUtility::translate('localizedOperandOr', 'IndexedSearch'), $GLOBALS['TSFE']->renderCharset, 'utf-8'), 'toLower'), 'OR'),
840 array($this->charsetConverter->conv_case('utf-8', $this->charsetConverter->conv(LocalizationUtility::translate('localizedOperandNot', 'IndexedSearch'), $GLOBALS['TSFE']->renderCharset, 'utf-8'), 'toLower'), 'AND NOT')
841 );
842 $swordArray = \TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::getExplodedSearchString($searchWords, $defaultOperator == 1 ? 'OR' : 'AND', $operatorTranslateTable);
843 if (is_array($swordArray)) {
844 $sWordArray = $this->procSearchWordsByLexer($swordArray);
845 }
846 }
847 }
848 return $sWordArray;
849 }
850
851 /**
852 * Post-process the search word array so it will match the words that was indexed (including case-folding if any)
853 * If any words are splitted into multiple words (eg. CJK will be!) the operator of the main word will remain.
854 *
855 * @param array $searchWords Search word array
856 * @return array Search word array, processed through lexer
857 */
858 protected function procSearchWordsByLexer($searchWords)
859 {
860 $newSearchWords = array();
861 // Init lexer (used to post-processing of search words)
862 $lexerObjRef = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ?: \TYPO3\CMS\IndexedSearch\Lexer::class;
863 $this->lexerObj = GeneralUtility::getUserObj($lexerObjRef);
864 // Traverse the search word array
865 foreach ($searchWords as $wordDef) {
866 // No space in word (otherwise it might be a sentense in quotes like "there is").
867 if (strpos($wordDef['sword'], ' ') === false) {
868 // Split the search word by lexer:
869 $res = $this->lexerObj->split2Words($wordDef['sword']);
870 // Traverse lexer result and add all words again:
871 foreach ($res as $word) {
872 $newSearchWords[] = array(
873 'sword' => $word,
874 'oper' => $wordDef['oper']
875 );
876 }
877 } else {
878 $newSearchWords[] = $wordDef;
879 }
880 }
881 return $newSearchWords;
882 }
883
884 /**
885 * Sort options about the search form
886 *
887 * @param array $search The search data / params
888 * @return void
889 * @ignorevalidation $search
890 */
891 public function formAction($search = array())
892 {
893 $searchData = $this->initialize($search);
894 // Adding search field value
895 $this->view->assign('sword', $this->sword);
896 // Additonal keyword => "Add to current search words"
897 $showAdditionalKeywordSearch = $this->settings['clearSearchBox'] && $this->settings['clearSearchBox']['enableSubSearchCheckBox'];
898 if ($showAdditionalKeywordSearch) {
899 $this->view->assign('previousSearchWord', $this->settings['clearSearchBox'] ? '' : $this->sword);
900 }
901 $this->view->assign('showAdditionalKeywordSearch', $showAdditionalKeywordSearch);
902 // Extended search
903 if ($search['extendedSearch']) {
904 // "Search for"
905 $allSearchTypes = $this->getAllAvailableSearchTypeOptions();
906 $this->view->assign('allSearchTypes', $allSearchTypes);
907 $allDefaultOperands = $this->getAllAvailableOperandsOptions();
908 $this->view->assign('allDefaultOperands', $allDefaultOperands);
909 $showTypeSearch = !empty($allSearchTypes) || !empty($allDefaultOperands);
910 $this->view->assign('showTypeSearch', $showTypeSearch);
911 // "Search in"
912 $allMediaTypes = $this->getAllAvailableMediaTypesOptions();
913 $this->view->assign('allMediaTypes', $allMediaTypes);
914 $allLanguageUids = $this->getAllAvailableLanguageOptions();
915 $this->view->assign('allLanguageUids', $allLanguageUids);
916 $showMediaAndLanguageSearch = !empty($allMediaTypes) || !empty($allLanguageUids);
917 $this->view->assign('showMediaAndLanguageSearch', $showMediaAndLanguageSearch);
918 // Sections
919 $allSections = $this->getAllAvailableSectionsOptions();
920 $this->view->assign('allSections', $allSections);
921 // Free Indexing Configurations
922 $allIndexConfigurations = $this->getAllAvailableIndexConfigurationsOptions();
923 $this->view->assign('allIndexConfigurations', $allIndexConfigurations);
924 // Sorting
925 $allSortOrders = $this->getAllAvailableSortOrderOptions();
926 $this->view->assign('allSortOrders', $allSortOrders);
927 $allSortDescendings = $this->getAllAvailableSortDescendingOptions();
928 $this->view->assign('allSortDescendings', $allSortDescendings);
929 $showSortOrders = !empty($allSortOrders) || !empty($allSortDescendings);
930 $this->view->assign('showSortOrders', $showSortOrders);
931 // Limits
932 $allNumberOfResults = $this->getAllAvailableNumberOfResultsOptions();
933 $this->view->assign('allNumberOfResults', $allNumberOfResults);
934 $allGroups = $this->getAllAvailableGroupOptions();
935 $this->view->assign('allGroups', $allGroups);
936 }
937 $this->view->assign('searchParams', $searchData);
938 }
939
940 /****************************************
941 * building together the available options for every dropdown
942 ***************************************/
943 /**
944 * get the values for the "type" selector
945 *
946 * @return array Associative array with options
947 */
948 protected function getAllAvailableSearchTypeOptions()
949 {
950 $allOptions = array();
951 $types = array(0, 1, 2, 3, 10, 20);
952 $blindSettings = $this->settings['blind'];
953 if (!$blindSettings['searchType']) {
954 foreach ($types as $typeNum) {
955 $allOptions[$typeNum] = LocalizationUtility::translate('searchTypes.' . $typeNum, 'IndexedSearch');
956 }
957 }
958 // Remove this option if metaphone search is disabled)
959 if (!$this->enableMetaphoneSearch) {
960 unset($allOptions[10]);
961 }
962 // disable single entries by TypoScript
963 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['searchType']);
964 return $allOptions;
965 }
966
967 /**
968 * get the values for the "defaultOperand" selector
969 *
970 * @return array Associative array with options
971 */
972 protected function getAllAvailableOperandsOptions()
973 {
974 $allOptions = array();
975 $blindSettings = $this->settings['blind'];
976 if (!$blindSettings['defaultOperand']) {
977 $allOptions = array(
978 0 => LocalizationUtility::translate('defaultOperands.0', 'IndexedSearch'),
979 1 => LocalizationUtility::translate('defaultOperands.1', 'IndexedSearch')
980 );
981 }
982 // disable single entries by TypoScript
983 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['defaultOperand']);
984 return $allOptions;
985 }
986
987 /**
988 * get the values for the "media type" selector
989 *
990 * @return array Associative array with options
991 */
992 protected function getAllAvailableMediaTypesOptions()
993 {
994 $allOptions = array();
995 $mediaTypes = array(-1, 0, -2);
996 $blindSettings = $this->settings['blind'];
997 if (!$blindSettings['mediaType']) {
998 foreach ($mediaTypes as $mediaType) {
999 $allOptions[$mediaType] = LocalizationUtility::translate('mediaTypes.' . $mediaType, 'IndexedSearch');
1000 }
1001 // Add media to search in:
1002 $additionalMedia = trim($this->settings['mediaList']);
1003 if ($additionalMedia !== '') {
1004 $additionalMedia = GeneralUtility::trimExplode(',', $additionalMedia, true);
1005 } else {
1006 $additionalMedia = array();
1007 }
1008 foreach ($this->externalParsers as $extension => $obj) {
1009 // Skip unwanted extensions
1010 if (!empty($additionalMedia) && !in_array($extension, $additionalMedia)) {
1011 continue;
1012 }
1013 if ($name = $obj->searchTypeMediaTitle($extension)) {
1014 $translatedName = LocalizationUtility::translate('mediaTypes.' . $extension, 'IndexedSearch');
1015 $allOptions[$extension] = $translatedName ?: $name;
1016 }
1017 }
1018 }
1019 // disable single entries by TypoScript
1020 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['mediaType']);
1021 return $allOptions;
1022 }
1023
1024 /**
1025 * get the values for the "language" selector
1026 *
1027 * @return array Associative array with options
1028 */
1029 protected function getAllAvailableLanguageOptions()
1030 {
1031 $allOptions = array(
1032 '-1' => LocalizationUtility::translate('languageUids.-1', 'IndexedSearch'),
1033 '0' => LocalizationUtility::translate('languageUids.0', 'IndexedSearch')
1034 );
1035 $blindSettings = $this->settings['blind'];
1036 if (!$blindSettings['languageUid']) {
1037 // Add search languages
1038 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_language', '1=1' . $GLOBALS['TSFE']->cObj->enableFields('sys_language'));
1039 if ($res) {
1040 while ($lang = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
1041 $allOptions[$lang['uid']] = $lang['title'];
1042 }
1043 }
1044 // disable single entries by TypoScript
1045 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['languageUid']);
1046 } else {
1047 $allOptions = array();
1048 }
1049 return $allOptions;
1050 }
1051
1052 /**
1053 * get the values for the "section" selector
1054 * Here values like "rl1_" and "rl2_" + a rootlevel 1/2 id can be added
1055 * to perform searches in rootlevel 1+2 specifically. The id-values can even
1056 * be commaseparated. Eg. "rl1_1,2" would search for stuff inside pages on
1057 * menu-level 1 which has the uid's 1 and 2.
1058 *
1059 * @return array Associative array with options
1060 */
1061 protected function getAllAvailableSectionsOptions()
1062 {
1063 $allOptions = array();
1064 $sections = array(0, -1, -2, -3);
1065 $blindSettings = $this->settings['blind'];
1066 if (!$blindSettings['sections']) {
1067 foreach ($sections as $section) {
1068 $allOptions[$section] = LocalizationUtility::translate('sections.' . $section, 'IndexedSearch');
1069 }
1070 }
1071 // Creating levels for section menu:
1072 // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
1073 if ($this->settings['displayLevel1Sections']) {
1074 $firstLevelMenu = $this->getMenuOfPages($this->searchRootPageIdList);
1075 $labelLevel1 = LocalizationUtility::translate('sections.rootLevel1', 'IndexedSearch');
1076 $labelLevel2 = LocalizationUtility::translate('sections.rootLevel2', 'IndexedSearch');
1077 foreach ($firstLevelMenu as $firstLevelKey => $menuItem) {
1078 if (!$menuItem['nav_hide']) {
1079 $allOptions['rl1_' . $menuItem['uid']] = trim($labelLevel1 . ' ' . $menuItem['title']);
1080 if ($this->settings['displayLevel2Sections']) {
1081 $secondLevelMenu = $this->getMenuOfPages($menuItem['uid']);
1082 foreach ($secondLevelMenu as $secondLevelKey => $menuItemLevel2) {
1083 if (!$menuItemLevel2['nav_hide']) {
1084 $allOptions['rl2_' . $menuItemLevel2['uid']] = trim($labelLevel2 . ' ' . $menuItemLevel2['title']);
1085 } else {
1086 unset($secondLevelMenu[$secondLevelKey]);
1087 }
1088 }
1089 $allOptions['rl2_' . implode(',', array_keys($secondLevelMenu))] = LocalizationUtility::translate('sections.rootLevel2All', 'IndexedSearch');
1090 }
1091 } else {
1092 unset($firstLevelMenu[$firstLevelKey]);
1093 }
1094 }
1095 $allOptions['rl1_' . implode(',', array_keys($firstLevelMenu))] = LocalizationUtility::translate('sections.rootLevel1All', 'IndexedSearch');
1096 }
1097 // disable single entries by TypoScript
1098 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sections']);
1099 return $allOptions;
1100 }
1101
1102 /**
1103 * get the values for the "freeIndexUid" selector
1104 *
1105 * @return array Associative array with options
1106 */
1107 protected function getAllAvailableIndexConfigurationsOptions()
1108 {
1109 $allOptions = array(
1110 '-1' => LocalizationUtility::translate('indexingConfigurations.-1', 'IndexedSearch'),
1111 '-2' => LocalizationUtility::translate('indexingConfigurations.-2', 'IndexedSearch'),
1112 '0' => LocalizationUtility::translate('indexingConfigurations.0', 'IndexedSearch')
1113 );
1114 $blindSettings = $this->settings['blind'];
1115 if (!$blindSettings['indexingConfigurations']) {
1116 // add an additional index configuration
1117 if ($this->settings['defaultFreeIndexUidList']) {
1118 $uidList = GeneralUtility::intExplode(',', $this->settings['defaultFreeIndexUidList']);
1119 $indexCfgRecords = $this->getDatabaseConnection()->exec_SELECTgetRows('uid,title', 'index_config', 'uid IN (' . implode(',', $uidList) . ')' . $GLOBALS['TSFE']->cObj->enableFields('index_config'), '', '', '', 'uid');
1120 foreach ($uidList as $uidValue) {
1121 if (is_array($indexCfgRecords[$uidValue])) {
1122 $allOptions[$uidValue] = $indexCfgRecords[$uidValue]['title'];
1123 }
1124 }
1125 }
1126 // disable single entries by TypoScript
1127 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['indexingConfigurations']);
1128 } else {
1129 $allOptions = array();
1130 }
1131 return $allOptions;
1132 }
1133
1134 /**
1135 * get the values for the "section" selector
1136 * Here values like "rl1_" and "rl2_" + a rootlevel 1/2 id can be added
1137 * to perform searches in rootlevel 1+2 specifically. The id-values can even
1138 * be commaseparated. Eg. "rl1_1,2" would search for stuff inside pages on
1139 * menu-level 1 which has the uid's 1 and 2.
1140 *
1141 * @return array Associative array with options
1142 */
1143 protected function getAllAvailableSortOrderOptions()
1144 {
1145 $allOptions = array();
1146 $sortOrders = array('rank_flag', 'rank_freq', 'rank_first', 'rank_count', 'mtime', 'title', 'crdate');
1147 $blindSettings = $this->settings['blind'];
1148 if (!$blindSettings['sortOrder']) {
1149 foreach ($sortOrders as $order) {
1150 $allOptions[$order] = LocalizationUtility::translate('sortOrders.' . $order, 'IndexedSearch');
1151 }
1152 }
1153 // disable single entries by TypoScript
1154 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sortOrder.']);
1155 return $allOptions;
1156 }
1157
1158 /**
1159 * get the values for the "group" selector
1160 *
1161 * @return array Associative array with options
1162 */
1163 protected function getAllAvailableGroupOptions()
1164 {
1165 $allOptions = array();
1166 $blindSettings = $this->settings['blind'];
1167 if (!$blindSettings['groupBy']) {
1168 $allOptions = array(
1169 'sections' => LocalizationUtility::translate('groupBy.sections', 'IndexedSearch'),
1170 'flat' => LocalizationUtility::translate('groupBy.flat', 'IndexedSearch')
1171 );
1172 }
1173 // disable single entries by TypoScript
1174 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['groupBy.']);
1175 return $allOptions;
1176 }
1177
1178 /**
1179 * get the values for the "sortDescending" selector
1180 *
1181 * @return array Associative array with options
1182 */
1183 protected function getAllAvailableSortDescendingOptions()
1184 {
1185 $allOptions = array();
1186 $blindSettings = $this->settings['blind'];
1187 if (!$blindSettings['descending']) {
1188 $allOptions = array(
1189 0 => LocalizationUtility::translate('sortOrders.descending', 'IndexedSearch'),
1190 1 => LocalizationUtility::translate('sortOrders.ascending', 'IndexedSearch')
1191 );
1192 }
1193 // disable single entries by TypoScript
1194 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['descending.']);
1195 return $allOptions;
1196 }
1197
1198 /**
1199 * get the values for the "results" selector
1200 *
1201 * @return array Associative array with options
1202 */
1203 protected function getAllAvailableNumberOfResultsOptions()
1204 {
1205 $allOptions = array();
1206 $blindSettings = $this->settings['blind'];
1207 if (!$blindSettings['numberOfResults']) {
1208 $allOptions = array(
1209 10 => 10,
1210 25 => 25,
1211 50 => 50,
1212 100 => 100
1213 );
1214 }
1215 // disable single entries by TypoScript
1216 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['numberOfResults']);
1217 return $allOptions;
1218 }
1219
1220 /**
1221 * removes blinding entries from the option list of a selector
1222 *
1223 * @param array $allOptions associative array containing all options
1224 * @param array $blindOptions associative array containing the optionkey as they key and the value = 1 if it should be removed
1225 * @return array Options from $allOptions with some options removed
1226 */
1227 protected function removeOptionsFromOptionList($allOptions, $blindOptions)
1228 {
1229 if (is_array($blindOptions)) {
1230 foreach ($blindOptions as $key => $val) {
1231 if ($val == 1) {
1232 unset($allOptions[$key]);
1233 }
1234 }
1235 }
1236 return $allOptions;
1237 }
1238
1239 /**
1240 * Links the $linkText to page $pageUid
1241 *
1242 * @param int $pageUid Page id
1243 * @param string $linkText Title to link (must already be escaped for HTML output)
1244 * @param array $row Result row
1245 * @param array $markUpSwParams Additional parameters for marking up seach words
1246 * @return string <A> tag wrapped title string.
1247 * @todo make use of the UriBuilder
1248 */
1249 protected function linkPage($pageUid, $linkText, $row = array(), $markUpSwParams = array())
1250 {
1251 // Parameters for link
1252 $urlParameters = (array)unserialize($row['cHashParams']);
1253 // Add &type and &MP variable:
1254 if ($row['data_page_mp']) {
1255 $urlParameters['MP'] = $row['data_page_mp'];
1256 }
1257 if ($row['sys_language_uid']) {
1258 $urlParameters['L'] = $row['sys_language_uid'];
1259 }
1260 // markup-GET vars:
1261 $urlParameters = array_merge($urlParameters, $markUpSwParams);
1262 // This will make sure that the path is retrieved if it hasn't been
1263 // already. Used only for the sake of the domain_record thing.
1264 if (!is_array($this->domainRecords[$pageUid])) {
1265 $this->getPathFromPageId($pageUid);
1266 }
1267 $target = '';
1268 // If external domain, then link to that:
1269 if (!empty($this->domainRecords[$pageUid])) {
1270 $scheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
1271 $firstDomain = reset($this->domainRecords[$pageUid]);
1272 $additionalParams = '';
1273 if (is_array($urlParameters) && !empty($urlParameters)) {
1274 $additionalParams = GeneralUtility::implodeArrayForUrl('', $urlParameters);
1275 }
1276 $uri = $scheme . $firstDomain . '/index.php?id=' . $pageUid . $additionalParams;
1277 if ($target = $this->settings['detectDomainRecords.']['target']) {
1278 $target = ' target="' . $target . '"';
1279 }
1280 } else {
1281 $uriBuilder = $this->controllerContext->getUriBuilder();
1282 $uri = $uriBuilder->setTargetPageUid($pageUid)->setTargetPageType($row['data_page_type'])->setUseCacheHash(true)->setArguments($urlParameters)->build();
1283 }
1284 return '<a href="' . htmlspecialchars($uri) . '"' . $target . '>' . $linkText . '</a>';
1285 }
1286
1287 /**
1288 * Return the menu of pages used for the selector.
1289 *
1290 * @param int $pageUid Page ID for which to return menu
1291 * @return array Menu items (for making the section selector box)
1292 */
1293 protected function getMenuOfPages($pageUid)
1294 {
1295 if ($this->settings['displayLevelxAllTypes']) {
1296 $menu = array();
1297 $res = $this->getDatabaseConnection()->exec_SELECTquery('title,uid', 'pages', 'pid=' . (int)$pageUid . $GLOBALS['TSFE']->cObj->enableFields('pages'), '', 'sorting');
1298 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
1299 $menu[$row['uid']] = $GLOBALS['TSFE']->sys_page->getPageOverlay($row);
1300 }
1301 $this->getDatabaseConnection()->sql_free_result($res);
1302 } else {
1303 $menu = $GLOBALS['TSFE']->sys_page->getMenu($pageUid);
1304 }
1305 return $menu;
1306 }
1307
1308 /**
1309 * Returns the path to the page $id
1310 *
1311 * @param int $id Page ID
1312 * @param string $pathMP Content of the MP (mount point) variable
1313 * @return string Path (HTML-escaped)
1314 */
1315 protected function getPathFromPageId($id, $pathMP = '')
1316 {
1317 $identStr = $id . '|' . $pathMP;
1318 if (!isset($this->pathCache[$identStr])) {
1319 $this->requiredFrontendUsergroups[$id] = array();
1320 $this->domainRecords[$id] = array();
1321 $rl = $GLOBALS['TSFE']->sys_page->getRootLine($id, $pathMP);
1322 $path = '';
1323 $pageCount = count($rl);
1324 if (is_array($rl) && !empty($rl)) {
1325 $breadcrumbWrap = isset($this->settings['breadcrumbWrap']) ? $this->settings['breadcrumbWrap'] : '/';
1326 $breadcrumbWraps = $GLOBALS['TSFE']->tmpl->splitConfArray(array('wrap' => $breadcrumbWrap), $pageCount);
1327 foreach ($rl as $k => $v) {
1328 // Check fe_user
1329 if ($v['fe_group'] && ($v['uid'] == $id || $v['extendToSubpages'])) {
1330 $this->requiredFrontendUsergroups[$id][] = $v['fe_group'];
1331 }
1332 // Check sys_domain
1333 if ($this->settings['detectDomainRcords']) {
1334 $domainName = $this->getFirstSysDomainRecordForPage($v['uid']);
1335 if ($domainName) {
1336 $this->domainRecords[$id][] = $domainName;
1337 // Set path accordingly
1338 $path = $domainName . $path;
1339 break;
1340 }
1341 }
1342 // Stop, if we find that the current id is the current root page.
1343 if ($v['uid'] == $GLOBALS['TSFE']->config['rootLine'][0]['uid']) {
1344 array_pop($breadcrumbWraps);
1345 break;
1346 }
1347 $path = $GLOBALS['TSFE']->cObj->wrap(htmlspecialchars($v['title']), array_pop($breadcrumbWraps)['wrap']) . $path;
1348 }
1349 }
1350 $this->pathCache[$identStr] = $path;
1351 }
1352 return $this->pathCache[$identStr];
1353 }
1354
1355 /**
1356 * Gets the first sys_domain record for the page, $id
1357 *
1358 * @param int $id Page id
1359 * @return string Domain name
1360 */
1361 protected function getFirstSysDomainRecordForPage($id)
1362 {
1363 $res = $this->getDatabaseConnection()->exec_SELECTquery('domainName', 'sys_domain', 'pid=' . (int)$id . $GLOBALS['TSFE']->cObj->enableFields('sys_domain'), '', 'sorting');
1364 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
1365 return rtrim($row['domainName'], '/');
1366 }
1367
1368 /**
1369 * simple function to initialize possible external parsers
1370 * feeds the $this->externalParsers array
1371 *
1372 * @return void
1373 */
1374 protected function initializeExternalParsers()
1375 {
1376 // Initialize external document parsers for icon display and other soft operations
1377 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'])) {
1378 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'] as $extension => $_objRef) {
1379 $this->externalParsers[$extension] = GeneralUtility::getUserObj($_objRef);
1380 // Init parser and if it returns FALSE, unset its entry again
1381 if (!$this->externalParsers[$extension]->softInit($extension)) {
1382 unset($this->externalParsers[$extension]);
1383 }
1384 }
1385 }
1386 }
1387
1388 /**
1389 * Returns an object reference to the hook object if any
1390 *
1391 * @param string $functionName Name of the function you want to call / hook key
1392 * @return object|NULL Hook object, if any. Otherwise NULL.
1393 */
1394 protected function hookRequest($functionName)
1395 {
1396 // Hook: menuConfig_preProcessModMenu
1397 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]) {
1398 $hookObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]);
1399 if (method_exists($hookObj, $functionName)) {
1400 $hookObj->pObj = $this;
1401 return $hookObj;
1402 }
1403 }
1404 return null;
1405 }
1406
1407 /**
1408 * Returns if an item type is a multipage item type
1409 *
1410 * @param string $item_type Item type
1411 * @return bool TRUE if multipage capable
1412 */
1413 protected function multiplePagesType($item_type)
1414 {
1415 return is_object($this->externalParsers[$item_type]) && $this->externalParsers[$item_type]->isMultiplePageExtension($item_type);
1416 }
1417
1418 /**
1419 * Getter for database connection
1420 *
1421 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
1422 */
1423 protected function getDatabaseConnection()
1424 {
1425 return $GLOBALS['TYPO3_DB'];
1426 }
1427
1428 /**
1429 * Load settings and apply stdWrap to them
1430 */
1431 protected function loadSettings()
1432 {
1433 if (!is_array($this->settings['results.'])) {
1434 $this->settings['results.'] = array();
1435 }
1436 $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['results']);
1437
1438 $this->settings['results.']['summaryCropAfter'] = MathUtility::forceIntegerInRange(
1439 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropAfter'], $typoScriptArray['summaryCropAfter.']),
1440 10, 5000, 180
1441 );
1442 $this->settings['results.']['summaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['summaryCropSignifier'], $typoScriptArray['summaryCropSignifier.']);
1443 $this->settings['results.']['titleCropAfter'] = MathUtility::forceIntegerInRange(
1444 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropAfter'], $typoScriptArray['titleCropAfter.']),
1445 10, 500, 50
1446 );
1447 $this->settings['results.']['titleCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['titleCropSignifier'], $typoScriptArray['titleCropSignifier.']);
1448 $this->settings['results.']['markupSW_summaryMax'] = MathUtility::forceIntegerInRange(
1449 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_summaryMax'], $typoScriptArray['markupSW_summaryMax.']),
1450 10, 5000, 300
1451 );
1452 $this->settings['results.']['markupSW_postPreLgd'] = MathUtility::forceIntegerInRange(
1453 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd'], $typoScriptArray['markupSW_postPreLgd.']),
1454 1, 500, 60
1455 );
1456 $this->settings['results.']['markupSW_postPreLgd_offset'] = MathUtility::forceIntegerInRange(
1457 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_postPreLgd_offset'], $typoScriptArray['markupSW_postPreLgd_offset.']),
1458 1, 50, 5
1459 );
1460 $this->settings['results.']['markupSW_divider'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['markupSW_divider'], $typoScriptArray['markupSW_divider.']);
1461 $this->settings['results.']['hrefInSummaryCropAfter'] = MathUtility::forceIntegerInRange(
1462 $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropAfter'], $typoScriptArray['hrefInSummaryCropAfter.']),
1463 10, 400, 60
1464 );
1465 $this->settings['results.']['hrefInSummaryCropSignifier'] = $GLOBALS['TSFE']->cObj->stdWrap($typoScriptArray['hrefInSummaryCropSignifier'], $typoScriptArray['hrefInSummaryCropSignifier.']);
1466 }
1467 }