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