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