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