[CLEANUP] Replace count with empty in 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 * @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 $resultSectionsCount = count($this->resultSections);
276 $result['sectionText'] = sprintf(LocalizationUtility::translate('result.' . ($resultSectionsCount > 1 ? 'inNsections' : 'inNsection'), 'indexed_search'), $resultSectionsCount);
277 }
278 }
279 }
280 // Print a message telling which words in which sections we searched for
281 if (substr($this->searchData['sections'], 0, 2) == 'rl') {
282 $result['searchedInSectionInfo'] = LocalizationUtility::translate('result.inSection', 'indexed_search') . ' "' . substr($this->getPathFromPageId(substr($this->searchData['sections'], 4)), 1) . '"';
283 }
284 return $result;
285 }
286
287 /**
288 * Takes the array with resultrows as input and returns the result-HTML-code
289 * Takes the "group" var into account: Makes a "section" or "flat" display.
290 *
291 * @param array $resultRows Result rows
292 * @param int $freeIndexUid Pointing to which indexing configuration you want to search in. -1 means no filtering. 0 means only regular indexed content.
293 * @return string HTML
294 */
295 protected function compileResultRows($resultRows, $freeIndexUid = -1) {
296 $finalResultRows = array();
297 // Transfer result rows to new variable,
298 // performing some mapping of sub-results etc.
299 $newResultRows = array();
300 foreach ($resultRows as $row) {
301 $id = md5($row['phash_grouping']);
302 if (is_array($newResultRows[$id])) {
303 // swapping:
304 if (!$newResultRows[$id]['show_resume'] && $row['show_resume']) {
305 // Remove old
306 $subrows = $newResultRows[$id]['_sub'];
307 unset($newResultRows[$id]['_sub']);
308 $subrows[] = $newResultRows[$id];
309 // Insert new:
310 $newResultRows[$id] = $row;
311 $newResultRows[$id]['_sub'] = $subrows;
312 } else {
313 $newResultRows[$id]['_sub'][] = $row;
314 }
315 } else {
316 $newResultRows[$id] = $row;
317 }
318 }
319 $resultRows = $newResultRows;
320 $this->resultSections = array();
321 if ($freeIndexUid <= 0 && $this->searchData['group'] == 'sections') {
322 $rl2flag = substr($this->searchData['sections'], 0, 2) == 'rl';
323 $sections = array();
324 foreach ($resultRows as $row) {
325 $id = $row['rl0'] . '-' . $row['rl1'] . ($rl2flag ? '-' . $row['rl2'] : '');
326 $sections[$id][] = $row;
327 }
328 $this->resultSections = array();
329 foreach ($sections as $id => $resultRows) {
330 $rlParts = explode('-', $id);
331 if ($rlParts[2]) {
332 $theId = $rlParts[2];
333 $theRLid = 'rl2_' . $rlParts[2];
334 } elseif ($rlParts[1]) {
335 $theId = $rlParts[1];
336 $theRLid = 'rl1_' . $rlParts[1];
337 } else {
338 $theId = $rlParts[0];
339 $theRLid = '0';
340 }
341 $sectionName = $this->getPathFromPageId($theId);
342 $sectionName = ltrim($sectionName, '/');
343 if (!trim($sectionName)) {
344 $sectionTitleLinked = LocalizationUtility::translate('result.unnamedSection', 'indexed_search') . ':';
345 } else {
346 $onclick = 'document.forms[\'tx_indexedsearch\'][\'tx_indexedsearch_pi2[search][_sections]\'].value=' . GeneralUtility::quoteJSvalue($theRLid) . ';document.forms[\'tx_indexedsearch\'].submit();return false;';
347 $sectionTitleLinked = '<a href="#" onclick="' . htmlspecialchars($onclick) . '">' . htmlspecialchars($sectionName) . ':</a>';
348 }
349 $resultRowsCount = count($resultRows);
350 $this->resultSections[$id] = array($sectionName, $resultRowsCount);
351 // Add section header
352 $finalResultRows[] = array(
353 'isSectionHeader' => TRUE,
354 'numResultRows' => $resultRowsCount,
355 'sectionId' => $id,
356 'sectionTitle' => $sectionTitleLinked
357 );
358 // Render result rows
359 foreach ($resultRows as $row) {
360 $finalResultRows[] = $this->compileSingleResultRow($row);
361 }
362 }
363 } else {
364 // flat mode or no sections at all
365 foreach ($resultRows as $row) {
366 $finalResultRows[] = $this->compileSingleResultRow($row);
367 }
368 }
369 return $finalResultRows;
370 }
371
372 /**
373 * This prints a single result row, including a recursive call for subrows.
374 *
375 * @param array $row Search result row
376 * @param int $headerOnly 1=Display only header (for sub-rows!), 2=nothing at all
377 * @return string HTML code
378 */
379 protected function compileSingleResultRow($row, $headerOnly = 0) {
380 $specRowConf = $this->getSpecialConfigurationForResultRow($row);
381 $resultData = $row;
382 $resultData['headerOnly'] = $headerOnly;
383 $resultData['CSSsuffix'] = $specRowConf['CSSsuffix'] ? '-' . $specRowConf['CSSsuffix'] : '';
384 if ($this->multiplePagesType($row['item_type'])) {
385 $dat = unserialize($row['cHashParams']);
386 $pp = explode('-', $dat['key']);
387 if ($pp[0] != $pp[1]) {
388 $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.page', 'indexed_search') . ' ' . $dat['key'];
389 } else {
390 $resultData['titleaddition'] = ', ' . LocalizationUtility::translate('result.pages', 'indexed_search') . ' ' . $pp[0];
391 }
392 }
393 $title = $resultData['item_title'] . $resultData['titleaddition'];
394 // If external media, link to the media-file instead.
395 if ($row['item_type']) {
396 if ($row['show_resume']) {
397 // Can link directly.
398 $targetAttribute = '';
399 if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
400 $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
401 }
402 $title = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($title) . '</a>';
403 } else {
404 // Suspicious, so linking to page instead...
405 $copiedRow = $row;
406 unset($copiedRow['cHashParams']);
407 $title = $this->linkPage($row['page_id'], $title, $copiedRow);
408 }
409 } else {
410 // Else the page:
411 // Prepare search words for markup in content:
412 if ($this->settings['forwardSearchWordsInResultLink']) {
413 $markUpSwParams = array('no_cache' => 1);
414 foreach ($this->searchWords as $d) {
415 $markUpSwParams['sword_list'][] = $d['sword'];
416 }
417 } else {
418 $markUpSwParams = array();
419 }
420 $title = $this->linkPage($row['data_page_id'], $title, $row, $markUpSwParams);
421 }
422 $resultData['title'] = $title;
423 $resultData['icon'] = $this->makeItemTypeIcon($row['item_type'], '', $specRowConf);
424 $resultData['rating'] = $this->makeRating($row);
425 $resultData['description'] = $this->makeDescription($row, $this->searchData['extResume'] && !$headerOnly ? 0 : 1);
426 $resultData['language'] = $this->makeLanguageIndication($row);
427 $resultData['size'] = GeneralUtility::formatSize($row['item_size']);
428 $resultData['created'] = $row['item_crdate'];
429 $resultData['modified'] = $row['item_mtime'];
430 $pI = parse_url($row['data_filename']);
431 if ($pI['scheme']) {
432 $targetAttribute = '';
433 if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
434 $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
435 }
436 $resultData['path'] = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($row['data_filename']) . '</a>';
437 } else {
438 $pathId = $row['data_page_id'] ?: $row['page_id'];
439 $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
440 $pathStr = htmlspecialchars($this->getPathFromPageId($pathId, $pathMP));
441 $resultData['path'] = $this->linkPage($pathId, $pathStr, array(
442 'cHashParams' => $row['cHashParams'],
443 'data_page_type' => $row['data_page_type'],
444 'data_page_mp' => $pathMP,
445 'sys_language_uid' => $row['sys_language_uid']
446 ));
447 // check if the access is restricted
448 if (is_array($this->requiredFrontendUsergroups[$pathId]) && !empty($this->requiredFrontendUsergroups[$pathId])) {
449 $resultData['access'] = '<img src="' . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath('indexed_search')
450 . 'pi/res/locked.gif" width="12" height="15" vspace="5" title="'
451 . sprintf(LocalizationUtility::translate('result.memberGroups', 'indexed_search'), implode(',', array_unique($this->requiredFrontendUsergroups[$pathId])))
452 . '" alt="" />';
453 }
454 }
455 // If there are subrows (eg. subpages in a PDF-file or if a duplicate page
456 // is selected due to user-login (phash_grouping))
457 if (is_array($row['_sub'])) {
458 $resultData['subresults'] = array();
459 if ($this->multiplePagesType($row['item_type'])) {
460 $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'indexed_search');
461 foreach ($row['_sub'] as $subRow) {
462 $resultData['subresults']['items'][] = $this->compileSingleResultRow($subRow, 1);
463 }
464 } else {
465 $resultData['subresults']['header'] = LocalizationUtility::translate('result.otherMatching', 'indexed_search');
466 $resultData['subresults']['info'] = LocalizationUtility::translate('result.otherPageAsWell', 'indexed_search');
467 }
468 }
469 return $resultData;
470 }
471
472 /**
473 * Returns configuration from TypoScript for result row based
474 * on ID / location in page tree!
475 *
476 * @param array $row Result row
477 * @return array Configuration array
478 */
479 protected function getSpecialConfigurationForResultRow($row) {
480 $pathId = $row['data_page_id'] ?: $row['page_id'];
481 $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
482 $rl = $GLOBALS['TSFE']->sys_page->getRootLine($pathId, $pathMP);
483 $specConf = $this->settings['specialConfiguration']['0'];
484 if (is_array($rl)) {
485 foreach ($rl as $dat) {
486 if (is_array($this->settings['specialConfiguration'][$dat['uid']])) {
487 $specConf = $this->settings['specialConfiguration'][$dat['uid']];
488 $specConf['_pid'] = $dat['uid'];
489 break;
490 }
491 }
492 }
493 return $specConf;
494 }
495
496 /**
497 * Return the rating-HTML code for the result row. This makes use of the $this->firstRow
498 *
499 * @param array $row Result row array
500 * @return string String showing ranking value
501 * @todo can this be a ViewHelper?
502 */
503 protected function makeRating($row) {
504 switch ((string)$this->searchData['sortOrder']) {
505 case 'rank_count':
506 return $row['order_val'] . ' ' . LocalizationUtility::translate('result.ratingMatches', 'indexed_search');
507 break;
508 case 'rank_first':
509 return ceil(MathUtility::forceIntegerInRange((255 - $row['order_val']), 1, 255) / 255 * 100) . '%';
510 break;
511 case 'rank_flag':
512 if ($this->firstRow['order_val2']) {
513 // (3 MSB bit, 224 is highest value of order_val1 currently)
514 $base = $row['order_val1'] * 256;
515 // 15-3 MSB = 12
516 $freqNumber = $row['order_val2'] / $this->firstRow['order_val2'] * pow(2, 12);
517 $total = MathUtility::forceIntegerInRange($base + $freqNumber, 0, 32767);
518 return ceil(log($total) / log(32767) * 100) . '%';
519 }
520 break;
521 case 'rank_freq':
522 $max = 10000;
523 $total = MathUtility::forceIntegerInRange($row['order_val'], 0, $max);
524 return ceil(log($total) / log($max) * 100) . '%';
525 break;
526 case 'crdate':
527 return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_crdate'], 0);
528 break;
529 case 'mtime':
530 return $GLOBALS['TSFE']->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_mtime'], 0);
531 break;
532 default:
533 return ' ';
534 }
535 }
536
537 /**
538 * Returns the HTML code for language indication.
539 *
540 * @param array $row Result row
541 * @return string HTML code for result row.
542 */
543 protected function makeLanguageIndication($row) {
544 $output = '&nbsp;';
545 // If search result is a TYPO3 page:
546 if ((string)$row['item_type'] === '0') {
547 // If TypoScript is used to render the flag:
548 if (is_array($this->settings['flagRendering'])) {
549 /** @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $cObj */
550 $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
551 $cObj->setCurrentVal($row['sys_language_uid']);
552 $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['flagRendering']);
553 $output = $cObj->cObjGetSingle($this->settings['flagRendering']['_typoScriptNodeValue'], $typoScriptArray);
554 }
555 }
556 return $output;
557 }
558
559 /**
560 * Return icon for file extension
561 *
562 * @param string $imageType File extension / item type
563 * @param string $alt Title attribute value in icon.
564 * @param array $specRowConf TypoScript configuration specifically for search result.
565 * @return string <img> tag for icon
566 */
567 public function makeItemTypeIcon($imageType, $alt, $specRowConf) {
568 // Build compound key if item type is 0, iconRendering is not used
569 // and specialConfiguration.[pid].pageIcon was set in TS
570 if ($imageType === '0' && $specRowConf['_pid'] && is_array($specRowConf['pageIcon']) && !is_array($this->settings['iconRendering'])) {
571 $imageType .= ':' . $specRowConf['_pid'];
572 }
573 if (!isset($this->iconFileNameCache[$imageType])) {
574 $this->iconFileNameCache[$imageType] = '';
575 // If TypoScript is used to render the icon:
576 if (is_array($this->settings['iconRendering'])) {
577 /** @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $cObj */
578 $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
579 $cObj->setCurrentVal($imageType);
580 $typoScriptArray = $this->typoScriptService->convertPlainArrayToTypoScriptArray($this->settings['iconRendering']);
581 $this->iconFileNameCache[$imageType] = $cObj->cObjGetSingle($this->settings['iconRendering']['_typoScriptNodeValue'], $typoScriptArray);
582 } else {
583 // Default creation / finding of icon:
584 $icon = '';
585 if ($imageType === '0' || substr($imageType, 0, 2) == '0:') {
586 if (is_array($specRowConf['pageIcon'])) {
587 $this->iconFileNameCache[$imageType] = $GLOBALS['TSFE']->cObj->cObjGetSingle('IMAGE', $specRowConf['pageIcon']);
588 } else {
589 $icon = 'EXT:indexed_search/pi/res/pages.gif';
590 }
591 } elseif ($this->externalParsers[$imageType]) {
592 $icon = $this->externalParsers[$imageType]->getIcon($imageType);
593 }
594 if ($icon) {
595 $fullPath = GeneralUtility::getFileAbsFileName($icon);
596 if ($fullPath) {
597 $info = @getimagesize($fullPath);
598 $iconPath = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($fullPath);
599 $this->iconFileNameCache[$imageType] = is_array($info) ? '<img src="' . $iconPath . '" ' . $info[3] . ' title="' . htmlspecialchars($alt) . '" alt="" />' : '';
600 }
601 }
602 }
603 }
604 return $this->iconFileNameCache[$imageType];
605 }
606
607 /**
608 * Returns the resume for the search-result.
609 *
610 * @param array $row Search result row
611 * @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.
612 * @param int $length String length
613 * @return string HTML string
614 * @todo overwork this
615 */
616 protected function makeDescription($row, $noMarkup = FALSE, $length = 180) {
617 if ($row['show_resume']) {
618 if (!$noMarkup) {
619 $markedSW = '';
620 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'index_fulltext', 'phash=' . (int)$row['phash']);
621 if ($ftdrow = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
622 // Cut HTTP references after some length
623 $content = preg_replace('/(http:\\/\\/[^ ]{60})([^ ]+)/i', '$1...', $ftdrow['fulltextdata']);
624 $markedSW = $this->markupSWpartsOfString($content);
625 }
626 $this->getDatabaseConnection()->sql_free_result($res);
627 }
628 if (!trim($markedSW)) {
629 $outputStr = $GLOBALS['TSFE']->csConvObj->crop('utf-8', $row['item_description'], $length);
630 $outputStr = htmlspecialchars($outputStr);
631 }
632 $output = $outputStr ?: $markedSW;
633 $output = $GLOBALS['TSFE']->csConv($output, 'utf-8');
634 } else {
635 $output = '<span class="noResume">' . LocalizationUtility::translate('result.noResume', 'indexed_search') . '</span>';
636 }
637 return $output;
638 }
639
640 /**
641 * Marks up the search words from $this->searchWords in the $str with a color.
642 *
643 * @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.
644 * @return string Processed content
645 */
646 protected function markupSWpartsOfString($str) {
647 $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
648 // Init:
649 $str = str_replace('&nbsp;', ' ', $htmlParser->bidir_htmlspecialchars($str, -1));
650 $str = preg_replace('/\\s\\s+/', ' ', $str);
651 $swForReg = array();
652 // Prepare search words for regex:
653 foreach ($this->searchWords as $d) {
654 $swForReg[] = preg_quote($d['sword'], '/');
655 }
656 $regExString = '(' . implode('|', $swForReg) . ')';
657 // Split and combine:
658 $parts = preg_split('/' . $regExString . '/i', ' ' . $str . ' ', 20000, PREG_SPLIT_DELIM_CAPTURE);
659 // Constants:
660 $summaryMax = 300;
661 $postPreLgd = 60;
662 $postPreLgd_offset = 5;
663 $divider = ' ... ';
664 $occurencies = (count($parts) - 1) / 2;
665 if ($occurencies) {
666 $postPreLgd = MathUtility::forceIntegerInRange($summaryMax / $occurencies, $postPreLgd, $summaryMax / 2);
667 }
668 // Variable:
669 $summaryLgd = 0;
670 $output = array();
671 // Shorten in-between strings:
672 foreach ($parts as $k => $strP) {
673 if ($k % 2 == 0) {
674 // Find length of the summary part:
675 $strLen = $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $parts[$k]);
676 $output[$k] = $parts[$k];
677 // Possibly shorten string:
678 if (!$k) {
679 // First entry at all (only cropped on the frontside)
680 if ($strLen > $postPreLgd) {
681 $output[$k] = $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', $GLOBALS['TSFE']->csConvObj->crop('utf-8', $parts[$k], -($postPreLgd - $postPreLgd_offset)));
682 }
683 } elseif ($summaryLgd > $summaryMax || !isset($parts[($k + 1)])) {
684 // In case summary length is exceed OR if there are no more entries at all:
685 if ($strLen > $postPreLgd) {
686 $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', $GLOBALS['TSFE']->csConvObj->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider;
687 }
688 } else {
689 if ($strLen > $postPreLgd * 2) {
690 $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)));
691 }
692 }
693 $summaryLgd += $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $output[$k]);
694 // Protect output:
695 $output[$k] = htmlspecialchars($output[$k]);
696 // If summary lgd is exceed, break the process:
697 if ($summaryLgd > $summaryMax) {
698 break;
699 }
700 } else {
701 $summaryLgd += $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $strP);
702 $output[$k] = '<strong class="tx-indexedsearch-redMarkup">' . htmlspecialchars($parts[$k]) . '</strong>';
703 }
704 }
705 // Return result:
706 return implode('', $output);
707 }
708
709 /**
710 * Write statistics information to database for the search operation
711 *
712 * @param array $searchParams search params
713 * @param array $searchWords Search Word array
714 * @param int $count Number of hits
715 * @param int $pt Milliseconds the search took
716 * @return void
717 */
718 protected function writeSearchStat($searchParams, $searchWords, $count, $pt) {
719 $insertFields = array(
720 'searchstring' => $this->sword,
721 'searchoptions' => serialize(array($searchParams, $searchWords, $pt)),
722 'feuser_id' => (int)$GLOBALS['TSFE']->fe_user->user['uid'],
723 // cookie as set or retrieved. If people has cookies disabled this will vary all the time
724 'cookie' => $GLOBALS['TSFE']->fe_user->id,
725 // Remote IP address
726 'IP' => GeneralUtility::getIndpEnv('REMOTE_ADDR'),
727 // Number of hits on the search
728 'hits' => (int)$count,
729 // Time stamp
730 'tstamp' => $GLOBALS['EXEC_TIME']
731 );
732 $this->getDatabaseConnection()->exec_INSERTquery('index_stat_search', $insertFields);
733 $newId = $this->getDatabaseConnection()->sql_insert_id();
734 if ($newId) {
735 foreach ($searchWords as $val) {
736 $insertFields = array(
737 'word' => $val['sword'],
738 'index_stat_search_id' => $newId,
739 // Time stamp
740 'tstamp' => $GLOBALS['EXEC_TIME'],
741 // search page id for indexed search stats
742 'pageid' => $GLOBALS['TSFE']->id
743 );
744 $this->getDatabaseConnection()->exec_INSERTquery('index_stat_word', $insertFields);
745 }
746 }
747 }
748
749 /**
750 * Splits the search word input into an array where each word is represented by an array with key "sword"
751 * holding the search word and key "oper" holding the SQL operator (eg. AND, OR)
752 *
753 * Only words with 2 or more characters are accepted
754 * Max 200 chars total
755 * Space is used to split words, "" can be used search for a whole string
756 * AND, OR and NOT are prefix words, overruling the default operator
757 * +/|/- equals AND, OR and NOT as operators.
758 * All search words are converted to lowercase.
759 *
760 * $defOp is the default operator. 1=OR, 0=AND
761 *
762 * @param bool $defaultOperator If TRUE, the default operator will be OR, not AND
763 * @return array Search words if any found
764 */
765 protected function getSearchWords($defaultOperator) {
766 // Shorten search-word string to max 200 bytes (does NOT take multibyte charsets into account - but never mind,
767 // shortening the string here is only a run-away feature!)
768 $searchWords = substr($this->sword, 0, 200);
769 // Convert to UTF-8 + conv. entities (was also converted during indexing!)
770 $searchWords = $GLOBALS['TSFE']->csConvObj->utf8_encode($searchWords, $GLOBALS['TSFE']->metaCharset);
771 $searchWords = $GLOBALS['TSFE']->csConvObj->entities_to_utf8($searchWords, TRUE);
772 $sWordArray = FALSE;
773 if ($hookObj = $this->hookRequest('getSearchWords')) {
774 $sWordArray = $hookObj->getSearchWords_splitSWords($searchWords, $defaultOperator);
775 } else {
776 // sentence
777 if ($this->searchData['searchType'] == 20) {
778 $sWordArray = array(
779 array(
780 'sword' => trim($searchWords),
781 'oper' => 'AND'
782 )
783 );
784 } else {
785 // case-sensitive. Defines the words, which will be
786 // operators between words
787 $operatorTranslateTable = array(
788 array('+', 'AND'),
789 array('|', 'OR'),
790 array('-', 'AND NOT'),
791 // Add operators for various languages
792 // Converts the operators to UTF-8 and lowercase
793 array($GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode(LocalizationUtility::translate('localizedOperandAnd', 'indexed_search'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'AND'),
794 array($GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode(LocalizationUtility::translate('localizedOperandOr', 'indexed_search'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'OR'),
795 array($GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode(LocalizationUtility::translate('localizedOperandNot', 'indexed_search'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'AND NOT')
796 );
797 $swordArray = \TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::getExplodedSearchString($searchWords, $defaultOperator == 1 ? 'OR' : 'AND', $operatorTranslateTable);
798 if (is_array($swordArray)) {
799 $sWordArray = $this->procSearchWordsByLexer($swordArray);
800 }
801 }
802 }
803 return $sWordArray;
804 }
805
806 /**
807 * Post-process the search word array so it will match the words that was indexed (including case-folding if any)
808 * If any words are splitted into multiple words (eg. CJK will be!) the operator of the main word will remain.
809 *
810 * @param array $searchWords Search word array
811 * @return array Search word array, processed through lexer
812 */
813 protected function procSearchWordsByLexer($searchWords) {
814 $newSearchWords = array();
815 // Init lexer (used to post-processing of search words)
816 $lexerObjRef = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ?: \TYPO3\CMS\IndexedSearch\Lexer::class;
817 $this->lexerObj = GeneralUtility::getUserObj($lexerObjRef);
818 // Traverse the search word array
819 foreach ($searchWords as $wordDef) {
820 // No space in word (otherwise it might be a sentense in quotes like "there is").
821 if (strpos($wordDef['sword'], ' ') === FALSE) {
822 // Split the search word by lexer:
823 $res = $this->lexerObj->split2Words($wordDef['sword']);
824 // Traverse lexer result and add all words again:
825 foreach ($res as $word) {
826 $newSearchWords[] = array(
827 'sword' => $word,
828 'oper' => $wordDef['oper']
829 );
830 }
831 } else {
832 $newSearchWords[] = $wordDef;
833 }
834 }
835 return $newSearchWords;
836 }
837
838 /**
839 * Sort options about the search form
840 *
841 * @param array $search The search data / params
842 * @return void
843 * @dontvalidate $search
844 */
845 public function formAction($search = array()) {
846 $searchData = $this->initialize($search);
847 // Adding search field value
848 $this->view->assign('sword', $this->sword);
849 // Additonal keyword => "Add to current search words"
850 $showAdditionalKeywordSearch = $this->settings['clearSearchBox'] && $this->settings['clearSearchBox']['enableSubSearchCheckBox'];
851 if ($showAdditionalKeywordSearch) {
852 $this->view->assign('previousSearchWord', $this->settings['clearSearchBox'] ? '' : $this->sword);
853 }
854 $this->view->assign('showAdditionalKeywordSearch', $showAdditionalKeywordSearch);
855 // Extended search
856 if ($search['extendedSearch']) {
857 // "Search for"
858 $allSearchTypes = $this->getAllAvailableSearchTypeOptions();
859 $this->view->assign('allSearchTypes', $allSearchTypes);
860 $allDefaultOperands = $this->getAllAvailableOperandsOptions();
861 $this->view->assign('allDefaultOperands', $allDefaultOperands);
862 $showTypeSearch = !empty($allSearchTypes) || !empty($allDefaultOperands);
863 $this->view->assign('showTypeSearch', $showTypeSearch);
864 // "Search in"
865 $allMediaTypes = $this->getAllAvailableMediaTypesOptions();
866 $this->view->assign('allMediaTypes', $allMediaTypes);
867 $allLanguageUids = $this->getAllAvailableLanguageOptions();
868 $this->view->assign('allLanguageUids', $allLanguageUids);
869 $showMediaAndLanguageSearch = !empty($allMediaTypes) || !empty($allLanguageUids);
870 $this->view->assign('showMediaAndLanguageSearch', $showMediaAndLanguageSearch);
871 // Sections
872 $allSections = $this->getAllAvailableSectionsOptions();
873 $this->view->assign('allSections', $allSections);
874 // Free Indexing Configurations
875 $allIndexConfigurations = $this->getAllAvailableIndexConfigurationsOptions();
876 $this->view->assign('allIndexConfigurations', $allIndexConfigurations);
877 // Sorting
878 $allSortOrders = $this->getAllAvailableSortOrderOptions();
879 $this->view->assign('allSortOrders', $allSortOrders);
880 $allSortDescendings = $this->getAllAvailableSortDescendingOptions();
881 $this->view->assign('allSortDescendings', $allSortDescendings);
882 $showSortOrders = !empty($allSortOrders) || !empty($allSortDescendings);
883 $this->view->assign('showSortOrders', $showSortOrders);
884 // Limits
885 $allNumberOfResults = $this->getAllAvailableNumberOfResultsOptions();
886 $this->view->assign('allNumberOfResults', $allNumberOfResults);
887 $allGroups = $this->getAllAvailableGroupOptions();
888 $this->view->assign('allGroups', $allGroups);
889 }
890 $this->view->assign('searchParams', $searchData);
891 }
892
893 /****************************************
894 * building together the available options for every dropdown
895 ***************************************/
896 /**
897 * get the values for the "type" selector
898 *
899 * @return array Associative array with options
900 */
901 protected function getAllAvailableSearchTypeOptions() {
902 $allOptions = array();
903 $types = array(0, 1, 2, 3, 10, 20);
904 $blindSettings = $this->settings['blind'];
905 if (!$blindSettings['searchType']) {
906 foreach ($types as $typeNum) {
907 $allOptions[$typeNum] = LocalizationUtility::translate('searchTypes.' . $typeNum, 'indexed_search');
908 }
909 }
910 // Remove this option if metaphone search is disabled)
911 if (!$this->enableMetaphoneSearch) {
912 unset($allOptions[10]);
913 }
914 // disable single entries by TypoScript
915 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['searchType']);
916 return $allOptions;
917 }
918
919 /**
920 * get the values for the "defaultOperand" selector
921 *
922 * @return array Associative array with options
923 */
924 protected function getAllAvailableOperandsOptions() {
925 $allOptions = array();
926 $blindSettings = $this->settings['blind'];
927 if (!$blindSettings['defaultOperand']) {
928 $allOptions = array(
929 0 => LocalizationUtility::translate('defaultOperands.0', 'indexed_search'),
930 1 => LocalizationUtility::translate('defaultOperands.1', 'indexed_search')
931 );
932 }
933 // disable single entries by TypoScript
934 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['defaultOperand']);
935 return $allOptions;
936 }
937
938 /**
939 * get the values for the "media type" selector
940 *
941 * @return array Associative array with options
942 */
943 protected function getAllAvailableMediaTypesOptions() {
944 $allOptions = array();
945 $mediaTypes = array(-1, 0, -2);
946 $blindSettings = $this->settings['blind'];
947 if (!$blindSettings['mediaType']) {
948 foreach ($mediaTypes as $mediaType) {
949 $allOptions[$mediaType] = LocalizationUtility::translate('mediaTypes.' . $mediaType, 'indexed_search');
950 }
951 // Add media to search in:
952 $additionalMedia = trim($this->settings['mediaList']);
953 if ($additionalMedia !== '') {
954 $additionalMedia = GeneralUtility::trimExplode(',', $additionalMedia, TRUE);
955 } else {
956 $additionalMedia = array();
957 }
958 foreach ($this->externalParsers as $extension => $obj) {
959 // Skip unwanted extensions
960 if (!empty($additionalMedia) && !in_array($extension, $additionalMedia)) {
961 continue;
962 }
963 if ($name = $obj->searchTypeMediaTitle($extension)) {
964 $translatedName = LocalizationUtility::translate('mediaTypes.' . $extension, 'indexed_search');
965 $allOptions[$extension] = $translatedName ?: $name;
966 }
967 }
968 }
969 // disable single entries by TypoScript
970 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['mediaType']);
971 return $allOptions;
972 }
973
974 /**
975 * get the values for the "language" selector
976 *
977 * @return array Associative array with options
978 */
979 protected function getAllAvailableLanguageOptions() {
980 $allOptions = array(
981 '-1' => LocalizationUtility::translate('languageUids.-1', 'indexed_search'),
982 '0' => LocalizationUtility::translate('languageUids.0', 'indexed_search')
983 );
984 $blindSettings = $this->settings['blind'];
985 if (!$blindSettings['languageUid']) {
986 // Add search languages
987 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_language', '1=1' . $GLOBALS['TSFE']->cObj->enableFields('sys_language'));
988 if ($res) {
989 while ($lang = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
990 $allOptions[$lang['uid']] = $lang['title'];
991 }
992 }
993 // disable single entries by TypoScript
994 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['languageUid']);
995 } else {
996 $allOptions = array();
997 }
998 return $allOptions;
999 }
1000
1001 /**
1002 * get the values for the "section" selector
1003 * Here values like "rl1_" and "rl2_" + a rootlevel 1/2 id can be added
1004 * to perform searches in rootlevel 1+2 specifically. The id-values can even
1005 * be commaseparated. Eg. "rl1_1,2" would search for stuff inside pages on
1006 * menu-level 1 which has the uid's 1 and 2.
1007 *
1008 * @return array Associative array with options
1009 */
1010 protected function getAllAvailableSectionsOptions() {
1011 $allOptions = array();
1012 $sections = array(0, -1, -2, -3);
1013 $blindSettings = $this->settings['blind'];
1014 if (!$blindSettings['sections']) {
1015 foreach ($sections as $section) {
1016 $allOptions[$section] = LocalizationUtility::translate('sections.' . $section, 'indexed_search');
1017 }
1018 }
1019 // Creating levels for section menu:
1020 // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
1021 if ($this->settings['displayLevel1Sections']) {
1022 $firstLevelMenu = $this->getMenuOfPages($this->searchRootPageIdList);
1023 $labelLevel1 = LocalizationUtility::translate('sections.rootLevel1', 'indexed_search');
1024 $labelLevel2 = LocalizationUtility::translate('sections.rootLevel2', 'indexed_search');
1025 foreach ($firstLevelMenu as $firstLevelKey => $menuItem) {
1026 if (!$menuItem['nav_hide']) {
1027 $allOptions['rl1_' . $menuItem['uid']] = trim($labelLevel1 . ' ' . $menuItem['title']);
1028 if ($this->settings['displayLevel2Sections']) {
1029 $secondLevelMenu = $this->getMenuOfPages($menuItem['uid']);
1030 foreach ($secondLevelMenu as $secondLevelKey => $menuItemLevel2) {
1031 if (!$menuItemLevel2['nav_hide']) {
1032 $allOptions['rl2_' . $menuItemLevel2['uid']] = trim($labelLevel2 . ' ' . $menuItemLevel2['title']);
1033 } else {
1034 unset($secondLevelMenu[$secondLevelKey]);
1035 }
1036 }
1037 $allOptions['rl2_' . implode(',', array_keys($secondLevelMenu))] = LocalizationUtility::translate('sections.rootLevel2All', 'indexed_search');
1038 }
1039 } else {
1040 unset($firstLevelMenu[$firstLevelKey]);
1041 }
1042 }
1043 $allOptions['rl1_' . implode(',', array_keys($firstLevelMenu))] = LocalizationUtility::translate('sections.rootLevel1All', 'indexed_search');
1044 }
1045 // disable single entries by TypoScript
1046 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sections']);
1047 return $allOptions;
1048 }
1049
1050 /**
1051 * get the values for the "freeIndexUid" selector
1052 *
1053 * @return array Associative array with options
1054 */
1055 protected function getAllAvailableIndexConfigurationsOptions() {
1056 $allOptions = array(
1057 '-1' => LocalizationUtility::translate('indexingConfigurations.-1', 'indexed_search'),
1058 '-2' => LocalizationUtility::translate('indexingConfigurations.-2', 'indexed_search'),
1059 '0' => LocalizationUtility::translate('indexingConfigurations.0', 'indexed_search')
1060 );
1061 $blindSettings = $this->settings['blind'];
1062 if (!$blindSettings['indexingConfigurations']) {
1063 // add an additional index configuration
1064 if ($this->settings['defaultFreeIndexUidList']) {
1065 $uidList = GeneralUtility::intExplode(',', $this->settings['defaultFreeIndexUidList']);
1066 $indexCfgRecords = $this->getDatabaseConnection()->exec_SELECTgetRows('uid,title', 'index_config', 'uid IN (' . implode(',', $uidList) . ')' . $GLOBALS['TSFE']->cObj->enableFields('index_config'), '', '', '', 'uid');
1067 foreach ($uidList as $uidValue) {
1068 if (is_array($indexCfgRecords[$uidValue])) {
1069 $allOptions[$uidValue] = $indexCfgRecords[$uidValue]['title'];
1070 }
1071 }
1072 }
1073 // disable single entries by TypoScript
1074 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['indexingConfigurations']);
1075 } else {
1076 $allOptions = array();
1077 }
1078 return $allOptions;
1079 }
1080
1081 /**
1082 * get the values for the "section" selector
1083 * Here values like "rl1_" and "rl2_" + a rootlevel 1/2 id can be added
1084 * to perform searches in rootlevel 1+2 specifically. The id-values can even
1085 * be commaseparated. Eg. "rl1_1,2" would search for stuff inside pages on
1086 * menu-level 1 which has the uid's 1 and 2.
1087 *
1088 * @return array Associative array with options
1089 */
1090 protected function getAllAvailableSortOrderOptions() {
1091 $allOptions = array();
1092 $sortOrders = array('rank_flag', 'rank_freq', 'rank_first', 'rank_count', 'mtime', 'title', 'crdate');
1093 $blindSettings = $this->settings['blind'];
1094 if (!$blindSettings['sortOrder']) {
1095 foreach ($sortOrders as $order) {
1096 $allOptions[$order] = LocalizationUtility::translate('sortOrders.' . $order, 'indexed_search');
1097 }
1098 }
1099 // disable single entries by TypoScript
1100 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['sortOrder.']);
1101 return $allOptions;
1102 }
1103
1104 /**
1105 * get the values for the "group" selector
1106 *
1107 * @return array Associative array with options
1108 */
1109 protected function getAllAvailableGroupOptions() {
1110 $allOptions = array();
1111 $blindSettings = $this->settings['blind'];
1112 if (!$blindSettings['groupBy']) {
1113 $allOptions = array(
1114 'sections' => LocalizationUtility::translate('groupBy.sections', 'indexed_search'),
1115 'flat' => LocalizationUtility::translate('groupBy.flat', 'indexed_search')
1116 );
1117 }
1118 // disable single entries by TypoScript
1119 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['groupBy.']);
1120 return $allOptions;
1121 }
1122
1123 /**
1124 * get the values for the "sortDescending" selector
1125 *
1126 * @return array Associative array with options
1127 */
1128 protected function getAllAvailableSortDescendingOptions() {
1129 $allOptions = array();
1130 $blindSettings = $this->settings['blind'];
1131 if (!$blindSettings['descending']) {
1132 $allOptions = array(
1133 0 => LocalizationUtility::translate('sortOrders.descending', 'indexed_search'),
1134 1 => LocalizationUtility::translate('sortOrders.ascending', 'indexed_search')
1135 );
1136 }
1137 // disable single entries by TypoScript
1138 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['descending.']);
1139 return $allOptions;
1140 }
1141
1142 /**
1143 * get the values for the "results" selector
1144 *
1145 * @return array Associative array with options
1146 */
1147 protected function getAllAvailableNumberOfResultsOptions() {
1148 $allOptions = array();
1149 $blindSettings = $this->settings['blind'];
1150 if (!$blindSettings['numberOfResults']) {
1151 $allOptions = array(
1152 10 => 10,
1153 25 => 25,
1154 50 => 50,
1155 100 => 100
1156 );
1157 }
1158 // disable single entries by TypoScript
1159 $allOptions = $this->removeOptionsFromOptionList($allOptions, $blindSettings['numberOfResults']);
1160 return $allOptions;
1161 }
1162
1163 /**
1164 * removes blinding entries from the option list of a selector
1165 *
1166 * @param array $allOptions associative array containing all options
1167 * @param array $blindOptions associative array containing the optionkey as they key and the value = 1 if it should be removed
1168 * @return array Options from $allOptions with some options removed
1169 */
1170 protected function removeOptionsFromOptionList($allOptions, $blindOptions) {
1171 if (is_array($blindOptions)) {
1172 foreach ($blindOptions as $key => $val) {
1173 if ($val == 1) {
1174 unset($allOptions[$key]);
1175 }
1176 }
1177 }
1178 return $allOptions;
1179 }
1180
1181 /**
1182 * Links the $linkText to page $pageUid
1183 *
1184 * @param int $pageUid Page id
1185 * @param string $linkText Title String to link
1186 * @param array $row Result row
1187 * @param array $markUpSwParams Additional parameters for marking up seach words
1188 * @return string <A> tag wrapped title string.
1189 * @todo make use of the UriBuilder
1190 */
1191 protected function linkPage($pageUid, $linkText, $row = array(), $markUpSwParams = array()) {
1192 // Parameters for link
1193 $urlParameters = (array)unserialize($row['cHashParams']);
1194 // Add &type and &MP variable:
1195 if ($row['data_page_mp']) {
1196 $urlParameters['MP'] = $row['data_page_mp'];
1197 }
1198 if ($row['sys_language_uid']) {
1199 $urlParameters['L'] = $row['sys_language_uid'];
1200 }
1201 // markup-GET vars:
1202 $urlParameters = array_merge($urlParameters, $markUpSwParams);
1203 // This will make sure that the path is retrieved if it hasn't been
1204 // already. Used only for the sake of the domain_record thing.
1205 if (!is_array($this->domainRecords[$pageUid])) {
1206 $this->getPathFromPageId($pageUid);
1207 }
1208 $target = '';
1209 // If external domain, then link to that:
1210 if (!empty($this->domainRecords[$pageUid])) {
1211 $scheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
1212 $firstDomain = reset($this->domainRecords[$pageUid]);
1213 $additionalParams = '';
1214 if (is_array($urlParameters) && !empty($urlParameters)) {
1215 $additionalParams = GeneralUtility::implodeArrayForUrl('', $urlParameters);
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) && !empty($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 }