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