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