45b29df51509679e80aa5265ff8cf95b61bb2693
[Packages/TYPO3.CMS.git] / typo3 / sysext / indexed_search / Classes / Controller / SearchFormController.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\Utility\GeneralUtility;
18
19 /**
20 * Index search frontend
21 *
22 * Creates a searchform for indexed search. Indexing must be enabled
23 * for this to make sense.
24 *
25 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
26 */
27 class SearchFormController extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin {
28
29 public $prefixId = 'tx_indexedsearch';
30
31 // Same as class name
32 public $scriptRelPath = 'Classes/Controller/SearchFormController.php';
33
34 // Path to this script relative to the extension dir.
35 public $extKey = 'indexed_search';
36
37 // The extension key.
38 public $join_pages = 0;
39
40 // See document for info about this flag...
41 public $defaultResultNumber = 10;
42
43 public $operator_translate_table = array(array('+', 'AND'), array('|', 'OR'), array('-', 'AND NOT'));
44
45 // Internal variable
46 public $wholeSiteIdList = 0;
47
48 // Root-page PIDs to search in (rl0 field where clause, see initialize() function)
49 // Internals:
50 public $sWArr = array();
51
52 // Search Words and operators
53 public $optValues = array();
54
55 // Selector box values for search configuration form
56 public $firstRow = array();
57
58 // Will hold the first row in result - used to calculate relative hit-ratings.
59 public $cache_path = array();
60
61 // Caching of page path
62 public $cache_rl = array();
63
64 // Caching of root line data
65 public $fe_groups_required = array();
66
67 // Required fe_groups memberships for display of a result.
68 public $domain_records = array();
69
70 // Select clauses for individual words
71 public $wSelClauses = array();
72
73 // Domain records (?)
74 public $resultSections = array();
75
76 // Page tree sections for search result.
77 public $external_parsers = array();
78
79 // External parser objects
80 public $iconFileNameCache = array();
81
82 // Storage of icons....
83 public $templateCode;
84
85 // Will hold the content of $conf['templateFile']
86 public $hiddenFieldList = 'ext, type, defOp, media, order, group, lang, desc, results';
87
88 public $indexerConfig = array();
89
90 // Indexer configuration, coming from $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search']
91 public $enableMetaphoneSearch = FALSE;
92
93 public $storeMetaphoneInfoAsWords;
94
95 /**
96 * Lexer object
97 *
98 * @var \TYPO3\CMS\IndexedSearch\Lexer
99 */
100 public $lexerObj;
101
102 const WILDCARD_LEFT = 1;
103 const WILDCARD_RIGHT = 2;
104 /**
105 * Main function, called from TypoScript as a USER_INT object.
106 *
107 * @param string Content input, ignore (just put blank string)
108 * @param array TypoScript configuration of the plugin!
109 * @return string HTML code for the search form / result display.
110 */
111 public function main($content, $conf) {
112 // Initialize:
113 $this->conf = $conf;
114 $this->pi_loadLL();
115 $this->pi_setPiVarDefaults();
116 // Initialize:
117 $this->initialize();
118 // Do search:
119 // If there were any search words entered...
120 if (is_array($this->sWArr)) {
121 $content = $this->doSearch($this->sWArr);
122 }
123 // Finally compile all the content, form, messages and results:
124 $content = $this->makeSearchForm($this->optValues) . $this->printRules() . $content;
125 return $this->pi_wrapInBaseClass($content);
126 }
127
128 /**
129 * Initialize internal variables, especially selector box values for the search form and search words
130 *
131 * @return void
132 */
133 public function initialize() {
134 // Indexer configuration from Extension Manager interface:
135 $this->indexerConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search']);
136 $this->enableMetaphoneSearch = $this->indexerConfig['enableMetaphoneSearch'] ? TRUE : FALSE;
137 $this->storeMetaphoneInfoAsWords = !\TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::isTableUsed('index_words');
138 // Initialize external document parsers for icon display and other soft operations
139 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'])) {
140 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'] as $extension => $_objRef) {
141 $this->external_parsers[$extension] = GeneralUtility::getUserObj($_objRef);
142 // Init parser and if it returns FALSE, unset its entry again:
143 if (!$this->external_parsers[$extension]->softInit($extension)) {
144 unset($this->external_parsers[$extension]);
145 }
146 }
147 }
148 // Init lexer (used to post-processing of search words)
149 $lexerObjRef = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ? $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] : 'EXT:indexed_search/Classes/Lexer.php:&TYPO3\\CMS\\IndexedSearch\\Lexer';
150 $this->lexerObj = GeneralUtility::getUserObj($lexerObjRef);
151 // If "_sections" is set, this value overrides any existing value.
152 if ($this->piVars['_sections']) {
153 $this->piVars['sections'] = $this->piVars['_sections'];
154 }
155 // If "_sections" is set, this value overrides any existing value.
156 if ($this->piVars['_freeIndexUid'] !== '_') {
157 $this->piVars['freeIndexUid'] = $this->piVars['_freeIndexUid'];
158 }
159 // Add previous search words to current
160 if ($this->piVars['sword_prev_include'] && $this->piVars['sword_prev']) {
161 $this->piVars['sword'] = trim($this->piVars['sword_prev']) . ' ' . $this->piVars['sword'];
162 }
163 $this->piVars['results'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['results'], 1, 100000, $this->defaultResultNumber);
164 // Selector-box values defined here:
165 $this->optValues = array(
166 'type' => array(
167 '0' => $this->pi_getLL('opt_type_0'),
168 '1' => $this->pi_getLL('opt_type_1'),
169 '2' => $this->pi_getLL('opt_type_2'),
170 '3' => $this->pi_getLL('opt_type_3'),
171 '10' => $this->pi_getLL('opt_type_10'),
172 '20' => $this->pi_getLL('opt_type_20')
173 ),
174 'defOp' => array(
175 '0' => $this->pi_getLL('opt_defOp_0'),
176 '1' => $this->pi_getLL('opt_defOp_1')
177 ),
178 'sections' => array(
179 '0' => $this->pi_getLL('opt_sections_0'),
180 '-1' => $this->pi_getLL('opt_sections_-1'),
181 '-2' => $this->pi_getLL('opt_sections_-2'),
182 '-3' => $this->pi_getLL('opt_sections_-3')
183 ),
184 'freeIndexUid' => array(
185 '-1' => $this->pi_getLL('opt_freeIndexUid_-1'),
186 '-2' => $this->pi_getLL('opt_freeIndexUid_-2'),
187 '0' => $this->pi_getLL('opt_freeIndexUid_0')
188 ),
189 'media' => array(
190 '-1' => $this->pi_getLL('opt_media_-1'),
191 '0' => $this->pi_getLL('opt_media_0'),
192 '-2' => $this->pi_getLL('opt_media_-2')
193 ),
194 'order' => array(
195 'rank_flag' => $this->pi_getLL('opt_order_rank_flag'),
196 'rank_freq' => $this->pi_getLL('opt_order_rank_freq'),
197 'rank_first' => $this->pi_getLL('opt_order_rank_first'),
198 'rank_count' => $this->pi_getLL('opt_order_rank_count'),
199 'mtime' => $this->pi_getLL('opt_order_mtime'),
200 'title' => $this->pi_getLL('opt_order_title'),
201 'crdate' => $this->pi_getLL('opt_order_crdate')
202 ),
203 'group' => array(
204 'sections' => $this->pi_getLL('opt_group_sections'),
205 'flat' => $this->pi_getLL('opt_group_flat')
206 ),
207 'lang' => array(
208 -1 => $this->pi_getLL('opt_lang_-1'),
209 0 => $this->pi_getLL('opt_lang_0')
210 ),
211 'desc' => array(
212 '0' => $this->pi_getLL('opt_desc_0'),
213 '1' => $this->pi_getLL('opt_desc_1')
214 ),
215 'results' => array(
216 '10' => '10',
217 '20' => '20',
218 '50' => '50',
219 '100' => '100'
220 )
221 );
222 // Remove this option if metaphone search is disabled)
223 if (!$this->enableMetaphoneSearch) {
224 unset($this->optValues['type']['10']);
225 }
226 // Free Index Uid:
227 if ($this->conf['search.']['defaultFreeIndexUidList']) {
228 $uidList = GeneralUtility::intExplode(',', $this->conf['search.']['defaultFreeIndexUidList']);
229 $indexCfgRecords = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,title', 'index_config', 'uid IN (' . implode(',', $uidList) . ')' . $this->cObj->enableFields('index_config'), '', '', '', 'uid');
230 foreach ($uidList as $uidValue) {
231 if (is_array($indexCfgRecords[$uidValue])) {
232 $this->optValues['freeIndexUid'][$uidValue] = $indexCfgRecords[$uidValue]['title'];
233 }
234 }
235 }
236 // Should we use join_pages instead of long lists of uids?
237 if ($this->conf['search.']['skipExtendToSubpagesChecking']) {
238 $this->join_pages = 1;
239 }
240 // Add media to search in:
241 if (strlen(trim($this->conf['search.']['mediaList']))) {
242 $mediaList = implode(',', GeneralUtility::trimExplode(',', $this->conf['search.']['mediaList'], TRUE));
243 }
244 foreach ($this->external_parsers as $extension => $obj) {
245 // Skip unwanted extensions
246 if ($mediaList && !GeneralUtility::inList($mediaList, $extension)) {
247 continue;
248 }
249 if ($name = $obj->searchTypeMediaTitle($extension)) {
250 $this->optValues['media'][$extension] = $this->pi_getLL('opt_sections_' . $extension, $name);
251 }
252 }
253 // Add operators for various languages
254 // Converts the operators to UTF-8 and lowercase
255 $this->operator_translate_table[] = array($GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode($this->pi_getLL('local_operator_AND'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'AND');
256 $this->operator_translate_table[] = array($GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode($this->pi_getLL('local_operator_OR'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'OR');
257 $this->operator_translate_table[] = array($GLOBALS['TSFE']->csConvObj->conv_case('utf-8', $GLOBALS['TSFE']->csConvObj->utf8_encode($this->pi_getLL('local_operator_NOT'), $GLOBALS['TSFE']->renderCharset), 'toLower'), 'AND NOT');
258 // This is the id of the site root. This value may be a commalist of integer (prepared for this)
259 $this->wholeSiteIdList = (int)$GLOBALS['TSFE']->config['rootLine'][0]['uid'];
260 // Creating levels for section menu:
261 // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
262 if ($this->conf['show.']['L1sections']) {
263 $firstLevelMenu = $this->getMenu($this->wholeSiteIdList);
264 foreach ($firstLevelMenu as $optionName => $mR) {
265 if (!$mR['nav_hide']) {
266 $this->optValues['sections']['rl1_' . $mR['uid']] = trim($this->pi_getLL('opt_RL1') . ' ' . $mR['title']);
267 if ($this->conf['show.']['L2sections']) {
268 $secondLevelMenu = $this->getMenu($mR['uid']);
269 foreach ($secondLevelMenu as $kk2 => $mR2) {
270 if (!$mR2['nav_hide']) {
271 $this->optValues['sections']['rl2_' . $mR2['uid']] = trim($this->pi_getLL('opt_RL2') . ' ' . $mR2['title']);
272 } else {
273 unset($secondLevelMenu[$kk2]);
274 }
275 }
276 $this->optValues['sections']['rl2_' . implode(',', array_keys($secondLevelMenu))] = $this->pi_getLL('opt_RL2ALL');
277 }
278 } else {
279 unset($firstLevelMenu[$optionName]);
280 }
281 }
282 $this->optValues['sections']['rl1_' . implode(',', array_keys($firstLevelMenu))] = $this->pi_getLL('opt_RL1ALL');
283 }
284 // Setting the list of root PIDs for the search. Notice, these page IDs MUST have a TypoScript template with root flag on them! Basically this list is used to select on the "rl0" field and page ids are registered as "rl0" only if a TypoScript template record with root flag is there.
285 // This happens AFTER the use of $this->wholeSiteIdList above because the above will then fetch the menu for the CURRENT site - regardless of this kind of searching here. Thus a general search will lookup in the WHOLE database while a specific section search will take the current sections...
286 if ($this->conf['search.']['rootPidList']) {
287 $this->wholeSiteIdList = implode(',', GeneralUtility::intExplode(',', $this->conf['search.']['rootPidList']));
288 }
289 // Load the template
290 $this->templateCode = $this->cObj->fileResource($this->conf['templateFile']);
291 // Add search languages:
292 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_language', '1=1' . $this->cObj->enableFields('sys_language'));
293 while (FALSE !== ($data = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {
294 $this->optValues['lang'][$data['uid']] = $data['title'];
295 }
296 $GLOBALS['TYPO3_DB']->sql_free_result($res);
297 // Calling hook for modification of initialized content
298 if ($hookObj = $this->hookRequest('initialize_postProc')) {
299 $hookObj->initialize_postProc();
300 }
301 // Default values set:
302 // Setting first values in optValues as default values IF there is not corresponding piVar value set already.
303 foreach ($this->optValues as $optionName => $optionValue) {
304 if (!isset($this->piVars[$optionName])) {
305 reset($optionValue);
306 $this->piVars[$optionName] = key($optionValue);
307 }
308 }
309 // Blind selectors:
310 if (is_array($this->conf['blind.'])) {
311 foreach ($this->conf['blind.'] as $optionName => $optionValue) {
312 if (is_array($optionValue)) {
313 foreach ($optionValue as $optionValueSubKey => $optionValueSubValue) {
314 if (!is_array($optionValueSubValue) && $optionValueSubValue && is_array($this->optValues[substr($optionName, 0, -1)])) {
315 unset($this->optValues[substr($optionName, 0, -1)][$optionValueSubKey]);
316 }
317 }
318 } elseif ($optionValue) {
319 // If value is not set, unset the option array
320 unset($this->optValues[$optionName]);
321 }
322 }
323 }
324 // This gets the search-words into the $sWArr:
325 $this->sWArr = $this->getSearchWords($this->piVars['defOp']);
326 }
327
328 /**
329 * Splits the search word input into an array where each word is represented by an array with key "sword" holding the search word and key "oper" holding the SQL operator (eg. AND, OR)
330 *
331 * Only words with 2 or more characters are accepted
332 * Max 200 chars total
333 * Space is used to split words, "" can be used search for a whole string
334 * AND, OR and NOT are prefix words, overruling the default operator
335 * +/|/- equals AND, OR and NOT as operators.
336 * All search words are converted to lowercase.
337 *
338 * $defOp is the default operator. 1=OR, 0=AND
339 *
340 * @param bool If TRUE, the default operator will be OR, not AND
341 * @return array Returns array with search words if any found
342 */
343 public function getSearchWords($defOp) {
344 // Shorten search-word string to max 200 bytes (does NOT take multibyte charsets into account - but never mind, shortening the string here is only a run-away feature!)
345 $inSW = substr($this->piVars['sword'], 0, 200);
346 // Convert to UTF-8 + conv. entities (was also converted during indexing!)
347 $inSW = $GLOBALS['TSFE']->csConvObj->utf8_encode($inSW, $GLOBALS['TSFE']->metaCharset);
348 $inSW = $GLOBALS['TSFE']->csConvObj->entities_to_utf8($inSW, TRUE);
349 $sWordArray = FALSE;
350 if ($hookObj = $this->hookRequest('getSearchWords')) {
351 $sWordArray = $hookObj->getSearchWords_splitSWords($inSW, $defOp);
352 } else {
353 if ($this->piVars['type'] == 20) {
354 // type = Sentence
355 $sWordArray = array(array('sword' => trim($inSW), 'oper' => 'AND'));
356 } else {
357 $search = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\SearchResultContentObject::class);
358 $search->default_operator = $defOp == 1 ? 'OR' : 'AND';
359 $search->operator_translate_table = $this->operator_translate_table;
360 $search->register_and_explode_search_string($inSW);
361 if (is_array($search->sword_array)) {
362 $sWordArray = $this->procSearchWordsByLexer($search->sword_array);
363 }
364 }
365 }
366 return $sWordArray;
367 }
368
369 /**
370 * Post-process the search word array so it will match the words that was indexed (including case-folding if any)
371 * If any words are splitted into multiple words (eg. CJK will be!) the operator of the main word will remain.
372 *
373 * @param array Search word array
374 * @return array Search word array, processed through lexer
375 */
376 public function procSearchWordsByLexer($SWArr) {
377 // Init output variable:
378 $newSWArr = array();
379 // Traverse the search word array:
380 foreach ($SWArr as $wordDef) {
381 if (!strstr($wordDef['sword'], ' ')) {
382 // No space in word (otherwise it might be a sentense in quotes like "there is").
383 // Split the search word by lexer:
384 $res = $this->lexerObj->split2Words($wordDef['sword']);
385 // Traverse lexer result and add all words again:
386 foreach ($res as $word) {
387 $newSWArr[] = array('sword' => $word, 'oper' => $wordDef['oper']);
388 }
389 } else {
390 $newSWArr[] = $wordDef;
391 }
392 }
393 // Return result:
394 return $newSWArr;
395 }
396
397 /*****************************
398 *
399 * Main functions
400 *
401 *****************************/
402 /**
403 * Performs the search, the display and writing stats
404 *
405 * @param array Search words in array, see ->getSearchWords() for details
406 * @return string HTML for result display.
407 */
408 public function doSearch($sWArr) {
409 // Find free index uid:
410 $freeIndexUid = $this->piVars['freeIndexUid'];
411 if ($freeIndexUid == -2) {
412 $freeIndexUid = $this->conf['search.']['defaultFreeIndexUidList'];
413 }
414 $indexCfgs = GeneralUtility::intExplode(',', $freeIndexUid);
415 $accumulatedContent = '';
416 foreach ($indexCfgs as $freeIndexUid) {
417 // Get result rows:
418 $pt1 = GeneralUtility::milliseconds();
419 if ($hookObj = $this->hookRequest('getResultRows')) {
420 $resData = $hookObj->getResultRows($sWArr, $freeIndexUid);
421 } else {
422 $resData = $this->getResultRows($sWArr, $freeIndexUid);
423 }
424 // Display search results:
425 $pt2 = GeneralUtility::milliseconds();
426 if ($hookObj = $this->hookRequest('getDisplayResults')) {
427 $content = $hookObj->getDisplayResults($sWArr, $resData, $freeIndexUid);
428 } else {
429 $content = $this->getDisplayResults($sWArr, $resData, $freeIndexUid);
430 }
431 $pt3 = GeneralUtility::milliseconds();
432 // Create header if we are searching more than one indexing configuration:
433 if (count($indexCfgs) > 1) {
434 if ($freeIndexUid > 0) {
435 $indexCfgRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('title', 'index_config', 'uid=' . (int)$freeIndexUid . $this->cObj->enableFields('index_config'));
436 $titleString = $indexCfgRec['title'];
437 } else {
438 $titleString = $this->pi_getLL('opt_freeIndexUid_header_' . $freeIndexUid);
439 }
440 $content = '<h1 class="tx-indexedsearch-category">' . htmlspecialchars($titleString) . '</h1>' . $content;
441 }
442 $accumulatedContent .= $content;
443 }
444 // Write search statistics
445 $this->writeSearchStat($sWArr, $resData['count'], array($pt1, $pt2, $pt3));
446 // Return content:
447 return $accumulatedContent;
448 }
449
450 /**
451 * Get search result rows / data from database. Returned as data in array.
452 *
453 * @param array $searchWordArray Search word array
454 * @param int Pointer to which indexing configuration you want to search in. -1 means no filtering. 0 means only regular indexed content.
455 * @return array False if no result, otherwise an array with keys for first row, result rows and total number of results found.
456 */
457 public function getResultRows($searchWordArray, $freeIndexUid = -1) {
458 // Getting SQL result pointer. This fetches ALL results (1,000,000 if found)
459 $GLOBALS['TT']->push('Searching result');
460 if ($hookObj = &$this->hookRequest('getResultRows_SQLpointer')) {
461 $res = $hookObj->getResultRows_SQLpointer($searchWordArray, $freeIndexUid);
462 } else {
463 $res = $this->getResultRows_SQLpointer($searchWordArray, $freeIndexUid);
464 }
465 $GLOBALS['TT']->pull();
466 // Organize and process result:
467 $result = FALSE;
468 if ($res) {
469 $totalSearchResultCount = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
470 // Total search-result count
471 $currentPageNumber = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['pointer'], 0, floor($totalSearchResultCount / $this->piVars['results']));
472 // The pointer is set to the result page that is currently being viewed
473 // Initialize result accumulation variables:
474 $positionInSearchResults = 0;
475 $groupingPhashes = array();
476 // Used for filtering out duplicates
477 $groupingChashes = array();
478 // Used for filtering out duplicates BASED ON cHash
479 $firstRow = array();
480 // Will hold the first row in result - used to calculate relative hit-ratings.
481 $resultRows = array();
482 // Will hold the results rows for display.
483 // Should we continue counting and checking of results even if
484 // we are sure they are not displayed in this request?
485 // This will slow down your page rendering, but it allows
486 // precise search result counters.
487 $calculateExactCount = (bool)$this->conf['search.']['exactCount'];
488 $lastResultNumberOnPreviousPage = $currentPageNumber * $this->piVars['results'];
489 $firstResultNumberOnNextPage = ($currentPageNumber + 1) * $this->piVars['results'];
490 $lastResultNumberToAnalyze = ($currentPageNumber + 1) * $this->piVars['results'] + $this->piVars['results'];
491 // Now, traverse result and put the rows to be displayed into an array
492 // Each row should contain the fields from 'ISEC.*, IP.*' combined + artificial fields "show_resume" (bool) and "result_number" (counter)
493 while (FALSE !== ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {
494 if (!$this->checkExistance($row)) {
495 // Check if the record is still available or if it has been deleted meanwhile.
496 // Currently this works for files only, since extending it to content elements would cause a lot of overhead...
497 // Otherwise, skip the row.
498 $totalSearchResultCount--;
499 continue;
500 }
501 // Set first row:
502 if ($positionInSearchResults === 0) {
503 $firstRow = $row;
504 }
505 $row['show_resume'] = $this->checkResume($row);
506 // Tells whether we can link directly to a document or not (depends on possible right problems)
507 $phashGr = !in_array($row['phash_grouping'], $groupingPhashes);
508 $chashGr = !in_array(($row['contentHash'] . '.' . $row['data_page_id']), $groupingChashes);
509 if ($phashGr && $chashGr) {
510 if ($row['show_resume'] || $this->conf['show.']['forbiddenRecords']) {
511 // Only if the resume may be shown are we going to filter out duplicates...
512 if (!$this->multiplePagesType($row['item_type'])) {
513 // Only on documents which are not multiple pages documents
514 $groupingPhashes[] = $row['phash_grouping'];
515 }
516 $groupingChashes[] = $row['contentHash'] . '.' . $row['data_page_id'];
517 $positionInSearchResults++;
518 // Check if we are inside result range for current page
519 if ($positionInSearchResults > $lastResultNumberOnPreviousPage && $positionInSearchResults <= $lastResultNumberToAnalyze) {
520 // Collect results to display
521 $row['result_number'] = $positionInSearchResults;
522 $resultRows[] = $row;
523 // This may lead to a problem: If the result
524 // check is not stopped here, the search will
525 // take longer. However the result counter
526 // will not filter out grouped cHashes/pHashes
527 // that were not processed yet. You can change
528 // this behavior using the "search.exactCount"
529 // property (see above).
530 $nextResultPosition = $positionInSearchResults + 1;
531 if (!$calculateExactCount && $nextResultPosition > $firstResultNumberOnNextPage) {
532 break;
533 }
534 }
535 } else {
536 // Skip this row if the user cannot view it (missing permission)
537 $totalSearchResultCount--;
538 }
539 } else {
540 // For each time a phash_grouping document is found
541 // (which is thus not displayed) the search-result count
542 // is reduced, so that it matches the number of rows displayed.
543 $totalSearchResultCount--;
544 }
545 }
546 $GLOBALS['TYPO3_DB']->sql_free_result($res);
547 $result = array(
548 'resultRows' => $resultRows,
549 'firstRow' => $firstRow,
550 'count' => $totalSearchResultCount
551 );
552 }
553 return $result;
554 }
555
556 /**
557 * Gets a SQL result pointer to traverse for the search records.
558 *
559 * @param array Search words
560 * @param int Pointer to which indexing configuration you want to search in. -1 means no filtering. 0 means only regular indexed content.
561 * @return pointer
562 */
563 public function getResultRows_SQLpointer($sWArr, $freeIndexUid = -1) {
564 // This SEARCHES for the searchwords in $sWArr AND returns a COMPLETE list of phash-integers of the matches.
565 $list = $this->getPhashList($sWArr);
566 // Perform SQL Search / collection of result rows array:
567 if ($list) {
568 // Do the search:
569 $GLOBALS['TT']->push('execFinalQuery');
570 $res = $this->execFinalQuery($list, $freeIndexUid);
571 $GLOBALS['TT']->pull();
572 return $res;
573 } else {
574 return FALSE;
575 }
576 }
577
578 /**
579 * Compiles the HTML display of the incoming array of result rows.
580 *
581 * @param array Search words array (for display of text describing what was searched for)
582 * @param array Array with result rows, count, first row.
583 * @param int Pointer to which indexing configuration you want to search in. -1 means no filtering. 0 means only regular indexed content.
584 * @return string HTML content to display result.
585 */
586 public function getDisplayResults($sWArr, $resData, $freeIndexUid = -1) {
587 // Perform display of result rows array:
588 if ($resData) {
589 $GLOBALS['TT']->push('Display Final result');
590 // Set first selected row (for calculation of ranking later)
591 $this->firstRow = $resData['firstRow'];
592 // Result display here:
593 $rowcontent = '';
594 $rowcontent .= $this->compileResult($resData['resultRows'], $freeIndexUid);
595 // Browsing box:
596 if ($resData['count']) {
597 $this->internal['res_count'] = $resData['count'];
598 $this->internal['results_at_a_time'] = $this->piVars['results'];
599 $this->internal['maxPages'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->conf['search.']['page_links'], 1, 100, 10);
600 $addString = $resData['count'] && $this->piVars['group'] == 'sections' && $freeIndexUid <= 0 ? ' ' . sprintf($this->pi_getLL((count($this->resultSections) > 1 ? 'inNsections' : 'inNsection')), count($this->resultSections)) : '';
601 $browseBox1 = $this->pi_list_browseresults(1, $addString, $this->printResultSectionLinks(), $freeIndexUid);
602 $browseBox2 = $this->pi_list_browseresults(0, '', '', $freeIndexUid);
603 }
604 // Browsing nav, bottom.
605 if ($resData['count']) {
606 $content = $browseBox1 . $rowcontent . $browseBox2;
607 } else {
608 $content = '<p' . $this->pi_classParam('noresults') . '>' . $this->pi_getLL('noResults', '', TRUE) . '</p>';
609 }
610 $GLOBALS['TT']->pull();
611 } else {
612 $content .= '<p' . $this->pi_classParam('noresults') . '>' . $this->pi_getLL('noResults', '', TRUE) . '</p>';
613 }
614 // Print a message telling which words we searched for, and in which sections etc.
615 $what = $this->tellUsWhatIsSeachedFor($sWArr) . (substr($this->piVars['sections'], 0, 2) == 'rl' ? ' ' . $this->pi_getLL('inSection', '', TRUE) . ' "' . substr($this->getPathFromPageId(substr($this->piVars['sections'], 4)), 1) . '"' : '');
616 $what = '<div' . $this->pi_classParam('whatis') . '>' . $this->cObj->stdWrap($what, $this->conf['whatis_stdWrap.']) . '</div>';
617 $content = $what . $content;
618 // Return content:
619 return $content;
620 }
621
622 /**
623 * Takes the array with resultrows as input and returns the result-HTML-code
624 * Takes the "group" var into account: Makes a "section" or "flat" display.
625 *
626 * @param array Result rows
627 * @param int Pointer to which indexing configuration you want to search in. -1 means no filtering. 0 means only regular indexed content.
628 * @return string HTML
629 */
630 public function compileResult($resultRows, $freeIndexUid = -1) {
631 $content = '';
632 // Transfer result rows to new variable, performing some mapping of sub-results etc.
633 $newResultRows = array();
634 foreach ($resultRows as $row) {
635 $id = md5($row['phash_grouping']);
636 if (is_array($newResultRows[$id])) {
637 if (!$newResultRows[$id]['show_resume'] && $row['show_resume']) {
638 // swapping:
639 // Remove old
640 $subrows = $newResultRows[$id]['_sub'];
641 unset($newResultRows[$id]['_sub']);
642 $subrows[] = $newResultRows[$id];
643 // Insert new:
644 $newResultRows[$id] = $row;
645 $newResultRows[$id]['_sub'] = $subrows;
646 } else {
647 $newResultRows[$id]['_sub'][] = $row;
648 }
649 } else {
650 $newResultRows[$id] = $row;
651 }
652 }
653 $resultRows = $newResultRows;
654 $this->resultSections = array();
655 if ($freeIndexUid <= 0) {
656 switch ($this->piVars['group']) {
657 case 'sections':
658 $rl2flag = substr($this->piVars['sections'], 0, 2) == 'rl';
659 $sections = array();
660 foreach ($resultRows as $row) {
661 $id = $row['rl0'] . '-' . $row['rl1'] . ($rl2flag ? '-' . $row['rl2'] : '');
662 $sections[$id][] = $row;
663 }
664 $this->resultSections = array();
665 foreach ($sections as $id => $resultRows) {
666 $rlParts = explode('-', $id);
667 $theId = $rlParts[2] ? $rlParts[2] : ($rlParts[1] ? $rlParts[1] : $rlParts[0]);
668 $theRLid = $rlParts[2] ? 'rl2_' . $rlParts[2] : ($rlParts[1] ? 'rl1_' . $rlParts[1] : '0');
669 $sectionName = $this->getPathFromPageId($theId);
670 if ($sectionName[0] == '/') {
671 $sectionName = substr($sectionName, 1);
672 }
673 if (!trim($sectionName)) {
674 $sectionTitleLinked = $this->pi_getLL('unnamedSection', '', TRUE) . ':';
675 } else {
676 $onclick = 'document.' . $this->prefixId . '[\'' . $this->prefixId . '[_sections]\'].value=\'' . $theRLid . '\';document.' . $this->prefixId . '.submit();return false;';
677 $sectionTitleLinked = '<a href="#" onclick="' . htmlspecialchars($onclick) . '">' . htmlspecialchars($sectionName) . ':</a>';
678 }
679 $this->resultSections[$id] = array($sectionName, count($resultRows));
680 // Add content header:
681 $content .= $this->makeSectionHeader($id, $sectionTitleLinked, count($resultRows));
682 // Render result rows:
683 $resultlist = '';
684 foreach ($resultRows as $row) {
685 $resultlist .= $this->printResultRow($row);
686 }
687 $content .= $this->cObj->stdWrap($resultlist, $this->conf['resultlist_stdWrap.']);
688 }
689 break;
690 default:
691 // flat:
692 $resultlist = '';
693 foreach ($resultRows as $row) {
694 $resultlist .= $this->printResultRow($row);
695 }
696 $content .= $this->cObj->stdWrap($resultlist, $this->conf['resultlist_stdWrap.']);
697 }
698 } else {
699 $resultlist = '';
700 foreach ($resultRows as $row) {
701 $resultlist .= $this->printResultRow($row);
702 }
703 $content .= $this->cObj->stdWrap($resultlist, $this->conf['resultlist_stdWrap.']);
704 }
705 return '<div' . $this->pi_classParam('res') . '>' . $content . '</div>';
706 }
707
708 /***********************************
709 *
710 * Searching functions (SQL)
711 *
712 ***********************************/
713 /**
714 * Returns a COMPLETE list of phash-integers matching the search-result composed of the search-words in the sWArr array.
715 * The list of phash integers are unsorted and should be used for subsequent selection of index_phash records for display of the result.
716 *
717 * @param array Search word array
718 * @return string List of integers
719 */
720 public function getPhashList($sWArr) {
721 // Initialize variables:
722 $c = 0;
723 $totalHashList = array();
724 // This array accumulates the phash-values
725 // Traverse searchwords; for each, select all phash integers and merge/diff/intersect them with previous word (based on operator)
726 foreach ($sWArr as $k => $v) {
727 // Making the query for a single search word based on the search-type
728 $sWord = $v['sword'];
729 $theType = (string)$this->piVars['type'];
730 if (strstr($sWord, ' ')) {
731 // If there are spaces in the search-word, make a full text search instead.
732 $theType = 20;
733 }
734 $GLOBALS['TT']->push('SearchWord "' . $sWord . '" - $theType=' . $theType);
735 // Perform search for word:
736 switch ($theType) {
737 case '1':
738 // Part of word
739 $res = $this->searchWord($sWord, self::WILDCARD_LEFT | self::WILDCARD_RIGHT);
740 break;
741 case '2':
742 // First part of word
743 $res = $this->searchWord($sWord, self::WILDCARD_RIGHT);
744 break;
745 case '3':
746 // Last part of word
747 $res = $this->searchWord($sWord, self::WILDCARD_LEFT);
748 break;
749 case '10':
750 // Sounds like
751 /**
752 * Indexer object
753 *
754 * @var \TYPO3\CMS\IndexedSearch\Indexer
755 */
756 // Initialize the indexer-class
757 $indexerObj = GeneralUtility::makeInstance(\TYPO3\CMS\IndexedSearch\Indexer::class);
758 // Perform metaphone search
759 $res = $this->searchMetaphone($indexerObj->metaphone($sWord, $this->storeMetaphoneInfoAsWords));
760 unset($indexerObj);
761 break;
762 case '20':
763 // Sentence
764 $res = $this->searchSentence($sWord);
765 $this->piVars['order'] = 'mtime';
766 // If there is a fulltext search for a sentence there is a likeliness that sorting cannot be done by the rankings from the rel-table (because no relations will exist for the sentence in the word-table). So therefore mtime is used instead. It is not required, but otherwise some hits may be left out.
767 break;
768 default:
769 // Distinct word
770 $res = $this->searchDistinct($sWord);
771 }
772 // If there was a query to do, then select all phash-integers which resulted from this.
773 if ($res) {
774 // Get phash list by searching for it:
775 $phashList = array();
776 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
777 $phashList[] = $row['phash'];
778 }
779 $GLOBALS['TYPO3_DB']->sql_free_result($res);
780 // Here the phash list are merged with the existing result based on whether we are dealing with OR, NOT or AND operations.
781 if ($c) {
782 switch ($v['oper']) {
783 case 'OR':
784 $totalHashList = array_unique(array_merge($phashList, $totalHashList));
785 break;
786 case 'AND NOT':
787 $totalHashList = array_diff($totalHashList, $phashList);
788 break;
789 default:
790 // AND...
791 $totalHashList = array_intersect($totalHashList, $phashList);
792 }
793 } else {
794 $totalHashList = $phashList;
795 }
796 }
797 $GLOBALS['TT']->pull();
798 $c++;
799 }
800 return implode(',', $totalHashList);
801 }
802
803 /**
804 * Returns a query which selects the search-word from the word/rel tables.
805 *
806 * @param string WHERE clause selecting the word from phash
807 * @param string Additional AND clause in the end of the query.
808 * @return pointer SQL result pointer
809 */
810 public function execPHashListQuery($wordSel, $plusQ = '') {
811 return $GLOBALS['TYPO3_DB']->exec_SELECTquery('IR.phash', 'index_words IW,
812 index_rel IR,
813 index_section ISEC', $wordSel . '
814 AND IW.wid=IR.wid
815 AND ISEC.phash = IR.phash
816 ' . $this->sectionTableWhere() . '
817 ' . $plusQ, 'IR.phash');
818 }
819
820 /**
821 * Search for a word
822 *
823 * @param string $sWord Word to search for
824 * @param int $mode Bit-field which can contain WILDCARD_LEFT and/or WILDCARD_RIGHT
825 * @return pointer SQL result pointer
826 */
827 public function searchWord($sWord, $mode) {
828 $wildcard_left = $mode & self::WILDCARD_LEFT ? '%' : '';
829 $wildcard_right = $mode & self::WILDCARD_RIGHT ? '%' : '';
830 $wSel = 'IW.baseword LIKE \'' . $wildcard_left . $GLOBALS['TYPO3_DB']->quoteStr($sWord, 'index_words') . $wildcard_right . '\'';
831 $this->wSelClauses[] = $wSel;
832 $res = $this->execPHashListQuery($wSel, ' AND is_stopword=0');
833 return $res;
834 }
835
836 /**
837 * Search for one distinct word
838 *
839 * @param string $sWord Word to search for
840 * @return pointer SQL result pointer
841 */
842 public function searchDistinct($sWord) {
843 $wSel = 'IW.wid=' . \TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::md5inthash($sWord);
844 $this->wSelClauses[] = $wSel;
845 $res = $this->execPHashListQuery($wSel, ' AND is_stopword=0');
846 return $res;
847 }
848
849 /**
850 * Search for a sentence
851 *
852 * @param string $sSentence Sentence to search for
853 * @return pointer SQL result pointer
854 */
855 public function searchSentence($sSentence) {
856 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('ISEC.phash', 'index_section ISEC, index_fulltext IFT', 'IFT.fulltextdata LIKE \'%' . $GLOBALS['TYPO3_DB']->quoteStr($sSentence, 'index_fulltext') . '%\' AND
857 ISEC.phash = IFT.phash
858 ' . $this->sectionTableWhere(), 'ISEC.phash');
859 $this->wSelClauses[] = '1=1';
860 return $res;
861 }
862
863 /**
864 * Search for a metaphone word
865 *
866 * @param string $sWord Word to search for
867 * @return \mysqli_result SQL result pointer
868 */
869 public function searchMetaphone($sWord) {
870 $wSel = 'IW.metaphone=' . $sWord;
871 $this->wSelClauses[] = $wSel;
872 return $this->execPHashListQuery($wSel, ' AND is_stopword=0');
873 }
874
875 /**
876 * Returns AND statement for selection of section in database. (rootlevel 0-2 + page_id)
877 *
878 * @return string AND clause for selection of section in database.
879 */
880 public function sectionTableWhere() {
881 $out = $this->wholeSiteIdList < 0 ? '' : ' AND ISEC.rl0 IN (' . $this->wholeSiteIdList . ')';
882 $match = '';
883 if (substr($this->piVars['sections'], 0, 4) == 'rl1_') {
884 $list = implode(',', GeneralUtility::intExplode(',', substr($this->piVars['sections'], 4)));
885 $out .= ' AND ISEC.rl1 IN (' . $list . ')';
886 $match = TRUE;
887 } elseif (substr($this->piVars['sections'], 0, 4) == 'rl2_') {
888 $list = implode(',', GeneralUtility::intExplode(',', substr($this->piVars['sections'], 4)));
889 $out .= ' AND ISEC.rl2 IN (' . $list . ')';
890 $match = TRUE;
891 } elseif (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['addRootLineFields'])) {
892 // Traversing user configured fields to see if any of those are used to limit search to a section:
893 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['addRootLineFields'] as $fieldName => $rootLineLevel) {
894 if (substr($this->piVars['sections'], 0, strlen($fieldName) + 1) == $fieldName . '_') {
895 $list = implode(',', GeneralUtility::intExplode(',', substr($this->piVars['sections'], strlen($fieldName) + 1)));
896 $out .= ' AND ISEC.' . $fieldName . ' IN (' . $list . ')';
897 $match = TRUE;
898 break;
899 }
900 }
901 }
902 // If no match above, test the static types:
903 if (!$match) {
904 switch ((string)$this->piVars['sections']) {
905 case '-1':
906 // '-1' => 'Only this page',
907 $out .= ' AND ISEC.page_id=' . $GLOBALS['TSFE']->id;
908 break;
909 case '-2':
910 // '-2' => 'Top + level 1',
911 $out .= ' AND ISEC.rl2=0';
912 break;
913 case '-3':
914 // '-3' => 'Level 2 and out',
915 $out .= ' AND ISEC.rl2>0';
916 break;
917 }
918 }
919 return $out;
920 }
921
922 /**
923 * Returns AND statement for selection of media type
924 *
925 * @return string AND statement for selection of media type
926 */
927 public function mediaTypeWhere() {
928 switch ((string)$this->piVars['media']) {
929 case '0':
930 // '0' => 'Kun TYPO3 sider',
931 $out = ' AND IP.item_type=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('0', 'index_phash');
932 break;
933 case '-2':
934 // All external documents
935 $out = ' AND IP.item_type<>' . $GLOBALS['TYPO3_DB']->fullQuoteStr('0', 'index_phash');
936 break;
937 case '-1':
938 // All content
939 $out = '';
940 break;
941 default:
942 $out = ' AND IP.item_type=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->piVars['media'], 'index_phash');
943 }
944 return $out;
945 }
946
947 /**
948 * Returns AND statement for selection of langauge
949 *
950 * @return string AND statement for selection of langauge
951 */
952 public function languageWhere() {
953 if ($this->piVars['lang'] >= 0) {
954 // -1 is the same as ALL language.
955 return 'AND IP.sys_language_uid=' . (int)$this->piVars['lang'];
956 }
957 }
958
959 /**
960 * Where-clause for free index-uid value.
961 *
962 * @param int Free Index UID value to limit search to.
963 * @return string WHERE SQL clause part.
964 */
965 public function freeIndexUidWhere($freeIndexUid) {
966 if ($freeIndexUid >= 0) {
967 // First, look if the freeIndexUid is a meta configuration:
968 $indexCfgRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('indexcfgs', 'index_config', 'type=5 AND uid=' . (int)$freeIndexUid . $this->cObj->enableFields('index_config'));
969 if (is_array($indexCfgRec)) {
970 $refs = GeneralUtility::trimExplode(',', $indexCfgRec['indexcfgs']);
971 $list = array(-99);
972 // Default value to protect against empty array.
973 foreach ($refs as $ref) {
974 list($table, $uid) = GeneralUtility::revExplode('_', $ref, 2);
975 switch ($table) {
976 case 'index_config':
977 $idxRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('uid', 'index_config', 'uid=' . (int)$uid . $this->cObj->enableFields('index_config'));
978 if ($idxRec) {
979 $list[] = $uid;
980 }
981 break;
982 case 'pages':
983 $indexCfgRecordsFromPid = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', 'index_config', 'pid=' . (int)$uid . $this->cObj->enableFields('index_config'));
984 foreach ($indexCfgRecordsFromPid as $idxRec) {
985 $list[] = $idxRec['uid'];
986 }
987 break;
988 }
989 }
990 $list = array_unique($list);
991 } else {
992 $list = array((int)$freeIndexUid);
993 }
994 return ' AND IP.freeIndexUid IN (' . implode(',', $list) . ')';
995 }
996 }
997
998 /**
999 * Execute final query, based on phash integer list. The main point is sorting the result in the right order.
1000 *
1001 * @param string List of phash integers which match the search.
1002 * @param int Pointer to which indexing configuration you want to search in. -1 means no filtering. 0 means only regular indexed content.
1003 * @return pointer Query result pointer
1004 */
1005 public function execFinalQuery($list, $freeIndexUid = -1) {
1006 // Setting up methods of filtering results based on page types, access, etc.
1007 $page_join = '';
1008 $page_where = '';
1009 // Indexing configuration clause:
1010 $freeIndexUidClause = $this->freeIndexUidWhere($freeIndexUid);
1011 // Calling hook for alternative creation of page ID list
1012 if ($hookObj = $this->hookRequest('execFinalQuery_idList')) {
1013 $page_where = $hookObj->execFinalQuery_idList($list);
1014 } elseif ($this->join_pages) {
1015 // Alternative to getting all page ids by ->getTreeList() where "excludeSubpages" is NOT respected.
1016 $page_join = ',
1017 pages';
1018 $page_where = 'pages.uid = ISEC.page_id
1019 ' . $this->cObj->enableFields('pages') . '
1020 AND pages.no_search=0
1021 AND pages.doktype<200
1022 ';
1023 } elseif ($this->wholeSiteIdList >= 0) {
1024 // Collecting all pages IDs in which to search; filtering out ALL pages that are not accessible due to enableFields. Does NOT look for "no_search" field!
1025 $siteIdNumbers = GeneralUtility::intExplode(',', $this->wholeSiteIdList);
1026 $id_list = array();
1027 foreach ($siteIdNumbers as $rootId) {
1028 $id_list[] = $this->cObj->getTreeList(-1 * $rootId, 9999);
1029 }
1030 $page_where = ' ISEC.page_id IN (' . implode(',', $id_list) . ')';
1031 } else {
1032 // Disable everything... (select all)
1033 $page_where = ' 1=1 ';
1034 }
1035 // If any of the ranking sortings are selected, we must make a join with the word/rel-table again, because we need to calculate ranking based on all search-words found.
1036 if (substr($this->piVars['order'], 0, 5) == 'rank_') {
1037 switch ($this->piVars['order']) {
1038 case 'rank_flag':
1039 // This gives priority to word-position (max-value) so that words in title, keywords, description counts more than in content.
1040 // The ordering is refined with the frequency sum as well.
1041 $grsel = 'MAX(IR.flags) AS order_val1, SUM(IR.freq) AS order_val2';
1042 $orderBy = 'order_val1' . $this->isDescending() . ',order_val2' . $this->isDescending();
1043 break;
1044 case 'rank_first':
1045 // Results in average position of search words on page. Must be inversely sorted (low numbers are closer to top)
1046 $grsel = 'AVG(IR.first) AS order_val';
1047 $orderBy = 'order_val' . $this->isDescending(1);
1048 break;
1049 case 'rank_count':
1050 // Number of words found
1051 $grsel = 'SUM(IR.count) AS order_val';
1052 $orderBy = 'order_val' . $this->isDescending();
1053 break;
1054 default:
1055 // Frequency sum. I'm not sure if this is the best way to do it (make a sum...). Or should it be the average?
1056 $grsel = 'SUM(IR.freq) AS order_val';
1057 $orderBy = 'order_val' . $this->isDescending();
1058 }
1059
1060 // So, words are imploded into an OR statement (no "sentence search" should be done here - may deselect results)
1061 $wordSel = '(' . implode(' OR ', $this->wSelClauses) . ') AND ';
1062
1063 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1064 'ISEC.*, IP.*, ' . $grsel,
1065 'index_words IW,
1066 index_rel IR,
1067 index_section ISEC,
1068 index_phash IP' . $page_join,
1069 $wordSel .
1070 'IP.phash IN (' . $list . ') ' .
1071 $this->mediaTypeWhere() . ' ' . $this->languageWhere() . $freeIndexUidClause . '
1072 AND IW.wid=IR.wid
1073 AND ISEC.phash = IR.phash
1074 AND IP.phash = IR.phash
1075 AND ' . $page_where,
1076 'IP.phash,ISEC.phash,ISEC.phash_t3,ISEC.rl0,ISEC.rl1,ISEC.rl2 ,ISEC.page_id,ISEC.uniqid,IP.phash_grouping,IP.data_filename ,IP.data_page_id ,IP.data_page_reg1,IP.data_page_type,IP.data_page_mp,IP.gr_list,IP.item_type,IP.item_title,IP.item_description,IP.item_mtime,IP.tstamp,IP.item_size,IP.contentHash,IP.crdate,IP.parsetime,IP.sys_language_uid,IP.item_crdate,IP.cHashParams,IP.externalUrl,IP.recordUid,IP.freeIndexUid,IP.freeIndexSetId',
1077 $orderBy
1078 );
1079 } else {
1080 // Otherwise, if sorting are done with the pages table or other fields, there is no need for joining with the rel/word tables:
1081 $orderBy = '';
1082 switch ((string)$this->piVars['order']) {
1083 case 'title':
1084 $orderBy = 'IP.item_title' . $this->isDescending();
1085 break;
1086 case 'crdate':
1087 $orderBy = 'IP.item_crdate' . $this->isDescending();
1088 break;
1089 case 'mtime':
1090 $orderBy = 'IP.item_mtime' . $this->isDescending();
1091 break;
1092 }
1093 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('ISEC.*, IP.*', 'index_phash IP,index_section ISEC' . $page_join, 'IP.phash IN (' . $list . ') ' . $this->mediaTypeWhere() . ' ' . $this->languageWhere() . $freeIndexUidClause . '
1094 AND IP.phash = ISEC.phash
1095 AND ' . $page_where, 'IP.phash,ISEC.phash,ISEC.phash_t3,ISEC.rl0,ISEC.rl1,ISEC.rl2 ,ISEC.page_id,ISEC.uniqid,IP.phash_grouping,IP.data_filename ,IP.data_page_id ,IP.data_page_reg1,IP.data_page_type,IP.data_page_mp,IP.gr_list,IP.item_type,IP.item_title,IP.item_description,IP.item_mtime,IP.tstamp,IP.item_size,IP.contentHash,IP.crdate,IP.parsetime,IP.sys_language_uid,IP.item_crdate,IP.cHashParams,IP.externalUrl,IP.recordUid,IP.freeIndexUid,IP.freeIndexSetId', $orderBy);
1096 }
1097 return $res;
1098 }
1099
1100 /**
1101 * Checking if the resume can be shown for the search result (depending on whether the rights are OK)
1102 * ? Should it also check for gr_list "0,-1"?
1103 *
1104 * @param array Result row array.
1105 * @return bool Returns TRUE if resume can safely be shown
1106 */
1107 public function checkResume($row) {
1108 // If the record is indexed by an indexing configuration, just show it.
1109 // At least this is needed for external URLs and files.
1110 // For records we might need to extend this - for instance block display if record is access restricted.
1111 if ($row['freeIndexUid']) {
1112 return TRUE;
1113 }
1114 // Evaluate regularly indexed pages based on item_type:
1115 if ($row['item_type']) {
1116 // External media:
1117 // For external media we will check the access of the parent page on which the media was linked from.
1118 // "phash_t3" is the phash of the parent TYPO3 page row which initiated the indexing of the documents in this section.
1119 // So, selecting for the grlist records belonging to the parent phash-row where the current users gr_list exists will help us to know.
1120 // If this is NOT found, there is still a theoretical possibility that another user accessible page would display a link, so maybe the resume of such a document here may be unjustified hidden. But better safe than sorry.
1121 if (\TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::isTableUsed('index_grlist')) {
1122 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('phash', 'index_grlist', 'phash=' . (int)$row['phash_t3'] . ' AND gr_list=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($GLOBALS['TSFE']->gr_list, 'index_grlist'));
1123 } else {
1124 $res = FALSE;
1125 }
1126 if ($res && $GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1127 return TRUE;
1128 } else {
1129 return FALSE;
1130 }
1131 } else {
1132 // Ordinary TYPO3 pages:
1133 if ((string)$row['gr_list'] !== (string)$GLOBALS['TSFE']->gr_list) {
1134 // Selecting for the grlist records belonging to the phash-row where the current users gr_list exists. If it is found it is proof that this user has direct access to the phash-rows content although he did not himself initiate the indexing...
1135 if (\TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::isTableUsed('index_grlist')) {
1136 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('phash', 'index_grlist', 'phash=' . (int)$row['phash'] . ' AND gr_list=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($GLOBALS['TSFE']->gr_list, 'index_grlist'));
1137 } else {
1138 $res = FALSE;
1139 }
1140 if ($res && $GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1141 return TRUE;
1142 } else {
1143 return FALSE;
1144 }
1145 } else {
1146 return TRUE;
1147 }
1148 }
1149 }
1150
1151 /**
1152 * Check if the record is still available or if it has been deleted meanwhile.
1153 * Currently this works for files only, since extending it to page content would cause a lot of overhead.
1154 *
1155 * @param array Result row array
1156 * @return bool Returns TRUE if record is still available
1157 */
1158 public function checkExistance($row) {
1159 $recordExists = TRUE;
1160 // Always expect that page content exists
1161 if ($row['item_type']) {
1162 // External media:
1163 if (!is_file($row['data_filename']) || !file_exists($row['data_filename'])) {
1164 $recordExists = FALSE;
1165 }
1166 }
1167 return $recordExists;
1168 }
1169
1170 /**
1171 * Returns "DESC" or "" depending on the settings of the incoming highest/lowest result order (piVars['desc']
1172 *
1173 * @param bool If TRUE, inverse the order which is defined by piVars['desc']
1174 * @return string " DESC" or
1175 */
1176 public function isDescending($inverse = FALSE) {
1177 $desc = $this->piVars['desc'];
1178 if ($inverse) {
1179 $desc = !$desc;
1180 }
1181 return !$desc ? ' DESC' : '';
1182 }
1183
1184 /**
1185 * Write statistics information to database for the search operation
1186 *
1187 * @param array Search Word array
1188 * @param int Number of hits
1189 * @param int Milliseconds the search took
1190 * @return void
1191 */
1192 public function writeSearchStat($sWArr, $count, $pt) {
1193 $insertFields = array(
1194 'searchstring' => $this->piVars['sword'],
1195 'searchoptions' => serialize(array($this->piVars, $sWArr, $pt)),
1196 'feuser_id' => (int)$this->fe_user->user['uid'],
1197 // fe_user id, integer
1198 'cookie' => (string)$this->fe_user->id,
1199 // cookie as set or retrieve. If people has cookies disabled this will vary all the time...
1200 'IP' => GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1201 // Remote IP address
1202 'hits' => (int)$count,
1203 // Number of hits on the search.
1204 'tstamp' => $GLOBALS['EXEC_TIME']
1205 );
1206 $GLOBALS['TYPO3_DB']->exec_INSERTquery('index_stat_search', $insertFields);
1207 $newId = $GLOBALS['TYPO3_DB']->sql_insert_id();
1208 if ($newId) {
1209 foreach ($sWArr as $val) {
1210 $insertFields = array(
1211 'word' => $val['sword'],
1212 'index_stat_search_id' => $newId,
1213 'tstamp' => $GLOBALS['EXEC_TIME'],
1214 // Time stamp
1215 'pageid' => $GLOBALS['TSFE']->id
1216 );
1217 $GLOBALS['TYPO3_DB']->exec_INSERTquery('index_stat_word', $insertFields);
1218 }
1219 }
1220 }
1221
1222 /***********************************
1223 *
1224 * HTML output functions
1225 *
1226 ***********************************/
1227 /**
1228 * Make search form HTML
1229 *
1230 * @param array Value/Labels pairs for search form selector boxes.
1231 * @return string Search form HTML
1232 */
1233 public function makeSearchForm($optValues) {
1234 $html = $this->cObj->getSubpart($this->templateCode, '###SEARCH_FORM###');
1235 // Multilangual text
1236 $substituteArray = array('legend', 'searchFor', 'extResume', 'atATime', 'orderBy', 'fromSection', 'searchIn', 'match', 'style', 'freeIndexUid');
1237 foreach ($substituteArray as $marker) {
1238 $markerArray['###FORM_' . GeneralUtility::strtoupper($marker) . '###'] = $this->pi_getLL('form_' . $marker, '', TRUE);
1239 }
1240 $markerArray['###FORM_SUBMIT###'] = $this->pi_getLL('submit_button_label', '', TRUE);
1241 // Adding search field value
1242 $markerArray['###SWORD_VALUE###'] = htmlspecialchars($this->piVars['sword']);
1243 // Additonal keyword => "Add to current search words"
1244 if ($this->conf['show.']['clearSearchBox'] && $this->conf['show.']['clearSearchBox.']['enableSubSearchCheckBox']) {
1245 $markerArray['###SWORD_PREV_VALUE###'] = htmlspecialchars($this->conf['show.']['clearSearchBox'] ? '' : $this->piVars['sword']);
1246 $markerArray['###SWORD_PREV_INCLUDE_CHECKED###'] = $this->piVars['sword_prev_include'] ? ' checked="checked"' : '';
1247 $markerArray['###ADD_TO_CURRENT_SEARCH###'] = $this->pi_getLL('makerating_addToCurrentSearch', '', TRUE);
1248 } else {
1249 $html = $this->cObj->substituteSubpart($html, '###ADDITONAL_KEYWORD###', '');
1250 }
1251 $markerArray['###ACTION_URL###'] = htmlspecialchars($this->getSearchFormActionURL());
1252 $hiddenFieldCode = $this->cObj->getSubpart($this->templateCode, '###HIDDEN_FIELDS###');
1253 $hiddenFieldCode = preg_replace('/^\\n\\t(.+)/ms', '$1', $hiddenFieldCode);
1254 // Remove first newline and tab (cosmetical issue)
1255 $hiddenFieldArr = array();
1256 foreach (GeneralUtility::trimExplode(',', $this->hiddenFieldList) as $fieldName) {
1257 $hiddenFieldMarkerArray = array();
1258 $hiddenFieldMarkerArray['###HIDDEN_FIELDNAME###'] = $this->prefixId . '[' . $fieldName . ']';
1259 $hiddenFieldMarkerArray['###HIDDEN_VALUE###'] = htmlspecialchars((string)$this->piVars[$fieldName]);
1260 $hiddenFieldArr[$fieldName] = $this->cObj->substituteMarkerArrayCached($hiddenFieldCode, $hiddenFieldMarkerArray, array(), array());
1261 }
1262 // Extended search
1263 if ($this->piVars['ext']) {
1264 // Search for
1265 if (!is_array($optValues['type']) && !is_array($optValues['defOp']) || $this->conf['blind.']['type'] && $this->conf['blind.']['defOp']) {
1266 $html = $this->cObj->substituteSubpart($html, '###SELECT_SEARCH_FOR###', '');
1267 } else {
1268 if (is_array($optValues['type']) && !$this->conf['blind.']['type']) {
1269 unset($hiddenFieldArr['type']);
1270 $markerArray['###SELECTBOX_TYPE_VALUES###'] = $this->renderSelectBoxValues($this->piVars['type'], $optValues['type']);
1271 } else {
1272 $html = $this->cObj->substituteSubpart($html, '###SELECT_SEARCH_TYPE###', '');
1273 }
1274 if (is_array($optValues['defOp']) || !$this->conf['blind.']['defOp']) {
1275 $markerArray['###SELECTBOX_DEFOP_VALUES###'] = $this->renderSelectBoxValues($this->piVars['defOp'], $optValues['defOp']);
1276 } else {
1277 $html = $this->cObj->substituteSubpart($html, '###SELECT_SEARCH_DEFOP###', '');
1278 }
1279 }
1280 // Search in
1281 if (!is_array($optValues['media']) && !is_array($optValues['lang']) || $this->conf['blind.']['media'] && $this->conf['blind.']['lang']) {
1282 $html = $this->cObj->substituteSubpart($html, '###SELECT_SEARCH_IN###', '');
1283 } else {
1284 if (is_array($optValues['media']) && !$this->conf['blind.']['media']) {
1285 unset($hiddenFieldArr['media']);
1286 $markerArray['###SELECTBOX_MEDIA_VALUES###'] = $this->renderSelectBoxValues($this->piVars['media'], $optValues['media']);
1287 } else {
1288 $html = $this->cObj->substituteSubpart($html, '###SELECT_SEARCH_MEDIA###', '');
1289 }
1290 if (is_array($optValues['lang']) || !$this->conf['blind.']['lang']) {
1291 unset($hiddenFieldArr['lang']);
1292 $markerArray['###SELECTBOX_LANG_VALUES###'] = $this->renderSelectBoxValues($this->piVars['lang'], $optValues['lang']);
1293 } else {
1294 $html = $this->cObj->substituteSubpart($html, '###SELECT_SEARCH_LANG###', '');
1295 }
1296 }
1297 // Sections
1298 if (!is_array($optValues['sections']) || $this->conf['blind.']['sections']) {
1299 $html = $this->cObj->substituteSubpart($html, '###SELECT_SECTION###', '');
1300 } else {
1301 $markerArray['###SELECTBOX_SECTIONS_VALUES###'] = $this->renderSelectBoxValues($this->piVars['sections'], $optValues['sections']);
1302 }
1303 // Free Indexing Configurations:
1304 if (!is_array($optValues['freeIndexUid']) || $this->conf['blind.']['freeIndexUid']) {
1305 $html = $this->cObj->substituteSubpart($html, '###SELECT_FREEINDEXUID###', '');
1306 } else {
1307 $markerArray['###SELECTBOX_FREEINDEXUIDS_VALUES###'] = $this->renderSelectBoxValues($this->piVars['freeIndexUid'], $optValues['freeIndexUid']);
1308 }
1309 // Sorting
1310 if (!is_array($optValues['order']) || !is_array($optValues['desc']) || $this->conf['blind.']['order']) {
1311 $html = $this->cObj->substituteSubpart($html, '###SELECT_ORDER###', '');
1312 } else {
1313 unset($hiddenFieldArr['order']);
1314 unset($hiddenFieldArr['desc']);
1315 unset($hiddenFieldArr['results']);
1316 $markerArray['###SELECTBOX_ORDER_VALUES###'] = $this->renderSelectBoxValues($this->piVars['order'], $optValues['order']);
1317 $markerArray['###SELECTBOX_DESC_VALUES###'] = $this->renderSelectBoxValues($this->piVars['desc'], $optValues['desc']);
1318 $markerArray['###SELECTBOX_RESULTS_VALUES###'] = $this->renderSelectBoxValues($this->piVars['results'], $optValues['results']);
1319 }
1320 // Limits
1321 if (!is_array($optValues['results']) || !is_array($optValues['results']) || $this->conf['blind.']['results']) {
1322 $html = $this->cObj->substituteSubpart($html, '###SELECT_RESULTS###', '');
1323 } else {
1324 $markerArray['###SELECTBOX_RESULTS_VALUES###'] = $this->renderSelectBoxValues($this->piVars['results'], $optValues['results']);
1325 }
1326 // Grouping
1327 if (!is_array($optValues['group']) || $this->conf['blind.']['group']) {
1328 $html = $this->cObj->substituteSubpart($html, '###SELECT_GROUP###', '');
1329 } else {
1330 unset($hiddenFieldArr['group']);
1331 $markerArray['###SELECTBOX_GROUP_VALUES###'] = $this->renderSelectBoxValues($this->piVars['group'], $optValues['group']);
1332 }
1333 if ($this->conf['blind.']['extResume']) {
1334 $html = $this->cObj->substituteSubpart($html, '###SELECT_EXTRESUME###', '');
1335 } else {
1336 $markerArray['###EXT_RESUME_CHECKED###'] = $this->piVars['extResume'] ? ' checked="checked"' : '';
1337 }
1338 } else {
1339 // Extended search
1340 $html = $this->cObj->substituteSubpart($html, '###SEARCH_FORM_EXTENDED###', '');
1341 }
1342 if ($this->conf['show.']['advancedSearchLink']) {
1343 $linkToOtherMode = $this->piVars['ext'] ? $this->pi_getPageLink($GLOBALS['TSFE']->id, $GLOBALS['TSFE']->sPre) : $this->pi_getPageLink($GLOBALS['TSFE']->id, $GLOBALS['TSFE']->sPre, array($this->prefixId . '[ext]' => 1));
1344 $markerArray['###LINKTOOTHERMODE###'] = '<a href="' . htmlspecialchars($linkToOtherMode) . '">' . $this->pi_getLL(($this->piVars['ext'] ? 'link_regularSearch' : 'link_advancedSearch'), '', TRUE) . '</a>';
1345 } else {
1346 $markerArray['###LINKTOOTHERMODE###'] = '';
1347 }
1348 // Write all hidden fields
1349 $html = $this->cObj->substituteSubpart($html, '###HIDDEN_FIELDS###', implode('', $hiddenFieldArr));
1350 $substitutedContent = $this->cObj->substituteMarkerArrayCached($html, $markerArray, array(), array());
1351 return $substitutedContent;
1352 }
1353
1354 /**
1355 * Function, rendering selector box values.
1356 *
1357 * @param string Current value
1358 * @param array Array with the options as key=>value pairs
1359 * @return string <options> imploded.
1360 */
1361 public function renderSelectBoxValues($value, $optValues) {
1362 if (is_array($optValues)) {
1363 $opt = array();
1364 $isSelFlag = 0;
1365 foreach ($optValues as $k => $v) {
1366 $sel = (string)$k === (string)$value ? ' selected="selected"' : '';
1367 if ($sel) {
1368 $isSelFlag++;
1369 }
1370 $opt[] = '<option value="' . htmlspecialchars($k) . '"' . $sel . '>' . htmlspecialchars($v) . '</option>';
1371 }
1372 return implode('', $opt);
1373 }
1374 }
1375
1376 /**
1377 * Print the searching rules
1378 *
1379 * @return string Rules for the search
1380 */
1381 public function printRules() {
1382 if ($this->conf['show.']['rules']) {
1383 $html = $this->cObj->getSubpart($this->templateCode, '###RULES###');
1384 $markerArray['###RULES_HEADER###'] = $this->pi_getLL('rules_header', '', TRUE);
1385 $markerArray['###RULES_TEXT###'] = nl2br(trim($this->pi_getLL('rules_text', '', TRUE)));
1386 $substitutedContent = $this->cObj->substituteMarkerArrayCached($html, $markerArray, array(), array());
1387 return $this->cObj->stdWrap($substitutedContent, $this->conf['rules_stdWrap.']);
1388 }
1389 }
1390
1391 /**
1392 * Returns the anchor-links to the sections inside the displayed result rows.
1393 *
1394 * @return string
1395 */
1396 public function printResultSectionLinks() {
1397 if (count($this->resultSections)) {
1398 $lines = array();
1399 $html = $this->cObj->getSubpart($this->templateCode, '###RESULT_SECTION_LINKS###');
1400 $item = $this->cObj->getSubpart($this->templateCode, '###RESULT_SECTION_LINKS_LINK###');
1401 foreach ($this->resultSections as $id => $dat) {
1402 $markerArray = array();
1403 $aBegin = '<a href="' . htmlspecialchars(($GLOBALS['TSFE']->anchorPrefix . '#anchor_' . md5($id))) . '">';
1404 $aContent = htmlspecialchars((trim($dat[0]) ? trim($dat[0]) : $this->pi_getLL('unnamedSection'))) . ' (' . $dat[1] . ' ' . $this->pi_getLL(($dat[1] > 1 ? 'word_pages' : 'word_page'), '', TRUE) . ')';
1405 $aEnd = '</a>';
1406 $markerArray['###LINK###'] = $aBegin . $aContent . $aEnd;
1407 $links[] = $this->cObj->substituteMarkerArrayCached($item, $markerArray, array(), array());
1408 }
1409 $html = $this->cObj->substituteMarkerArrayCached($html, array('###LINKS###' => implode('', $links)), array(), array());
1410 return '<div' . $this->pi_classParam('sectionlinks') . '>' . $this->cObj->stdWrap($html, $this->conf['sectionlinks_stdWrap.']) . '</div>';
1411 }
1412 }
1413
1414 /**
1415 * Returns the section header of the search result.
1416 *
1417 * @param string ID for the section (used for anchor link)
1418 * @param string Section title with linked wrapped around
1419 * @param int Number of results in section
1420 * @return string HTML output
1421 */
1422 public function makeSectionHeader($id, $sectionTitleLinked, $countResultRows) {
1423 $html = $this->cObj->getSubpart($this->templateCode, '###SECTION_HEADER###');
1424 $markerArray['###ANCHOR_URL###'] = 'anchor_' . md5($id);
1425 $markerArray['###SECTION_TITLE###'] = $sectionTitleLinked;
1426 $markerArray['###RESULT_COUNT###'] = $countResultRows;
1427 $markerArray['###RESULT_NAME###'] = $this->pi_getLL('word_page' . ($countResultRows > 1 ? 's' : ''));
1428 $substitutedContent = $this->cObj->substituteMarkerArrayCached($html, $markerArray, array(), array());
1429 return $substitutedContent;
1430 }
1431
1432 /**
1433 * This prints a single result row, including a recursive call for subrows.
1434 *
1435 * @param array Search result row
1436 * @param int 1=Display only header (for sub-rows!), 2=nothing at all
1437 * @return string HTML code
1438 */
1439 public function printResultRow($row, $headerOnly = 0) {
1440 // Get template content:
1441 $tmplContent = $this->prepareResultRowTemplateData($row, $headerOnly);
1442 if ($hookObj = $this->hookRequest('printResultRow')) {
1443 return $hookObj->printResultRow($row, $headerOnly, $tmplContent);
1444 } else {
1445 $html = $this->cObj->getSubpart($this->templateCode, '###RESULT_OUTPUT###');
1446 if (!is_array($row['_sub'])) {
1447 $html = $this->cObj->substituteSubpart($html, '###ROW_SUB###', '');
1448 }
1449 if (!$headerOnly) {
1450 $html = $this->cObj->substituteSubpart($html, '###ROW_SHORT###', '');
1451 } elseif ($headerOnly == 1) {
1452 $html = $this->cObj->substituteSubpart($html, '###ROW_LONG###', '');
1453 } elseif ($headerOnly == 2) {
1454 $html = $this->cObj->substituteSubpart($html, '###ROW_SHORT###', '');
1455 $html = $this->cObj->substituteSubpart($html, '###ROW_LONG###', '');
1456 }
1457 if (is_array($tmplContent)) {
1458 foreach ($tmplContent as $k => $v) {
1459 $markerArray['###' . GeneralUtility::strtoupper($k) . '###'] = $v;
1460 }
1461 }
1462 // Description text
1463 $markerArray['###TEXT_ITEM_SIZE###'] = $this->pi_getLL('res_size', '', TRUE);
1464 $markerArray['###TEXT_ITEM_CRDATE###'] = $this->pi_getLL('res_created', '', TRUE);
1465 $markerArray['###TEXT_ITEM_MTIME###'] = $this->pi_getLL('res_modified', '', TRUE);
1466 $markerArray['###TEXT_ITEM_PATH###'] = $this->pi_getLL('res_path', '', TRUE);
1467 $html = $this->cObj->substituteMarkerArrayCached($html, $markerArray, array(), array());
1468 // If there are subrows (eg. subpages in a PDF-file or if a duplicate page is selected due to user-login (phash_grouping))
1469 if (is_array($row['_sub'])) {
1470 if ($this->multiplePagesType($row['item_type'])) {
1471 $html = str_replace('###TEXT_ROW_SUB###', $this->pi_getLL('res_otherMatching', '', TRUE), $html);
1472 foreach ($row['_sub'] as $subRow) {
1473 $html .= $this->printResultRow($subRow, 1);
1474 }
1475 } else {
1476 $markerArray['###TEXT_ROW_SUB###'] = $this->pi_getLL('res_otherMatching', '', TRUE);
1477 $html = str_replace('###TEXT_ROW_SUB###', $this->pi_getLL('res_otherPageAsWell', '', TRUE), $html);
1478 }
1479 }
1480 return $html;
1481 }
1482 }
1483
1484 /**
1485 * Returns a results browser
1486 *
1487 * @param bool $showResultCount Show result count
1488 * @param string $addString String appended to "displaying results..." notice.
1489 * @param string $addPart String appended after section "displaying results...
1490 * @param string $freeIndexUid List of integers pointing to free indexing configurations to search. -1 represents no filtering, 0 represents TYPO3 pages only, any number above zero is a uid of an indexing configuration!
1491 * @return string HTML output
1492 */
1493 public function pi_list_browseresults($showResultCount = TRUE, $addString = '', $addPart = '', $freeIndexUid = -1) {
1494 // Initializing variables:
1495 $pointer = (int)$this->piVars['pointer'];
1496 $count = (int)$this->internal['res_count'];
1497 $results_at_a_time = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->internal['results_at_a_time'], 1, 1000);
1498 $pageCount = (int)ceil($count / $results_at_a_time);
1499
1500 $links = array();
1501 // only show the result browser if more than one page is needed
1502 if ($pageCount > 1) {
1503 $maxPages = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->internal['maxPages'], 1, $pageCount);
1504
1505 // Make browse-table/links:
1506 if ($pointer > 0) {
1507 // all pages after the 1st one
1508 $links[] = '<li>' . $this->makePointerSelector_link($this->pi_getLL('pi_list_browseresults_prev', '< Previous', TRUE), $pointer - 1, $freeIndexUid) . '</li>';
1509 }
1510 $minPage = $pointer - (int)floor($maxPages / 2);
1511 $maxPage = $minPage + $maxPages - 1;
1512 // Check if the indexes are within the page limits
1513 if ($minPage < 0) {
1514 $maxPage -= $minPage;
1515 $minPage = 0;
1516 } elseif ($maxPage >= $pageCount) {
1517 $minPage -= $maxPage - $pageCount + 1;
1518 $maxPage = $pageCount - 1;
1519 }
1520 $pageLabel = $this->pi_getLL('pi_list_browseresults_page', 'Page', TRUE);
1521 for ($a = $minPage; $a <= $maxPage; $a++) {
1522 $label = trim($pageLabel . ' ' . ($a + 1));
1523 $link = $this->makePointerSelector_link($label, $a, $freeIndexUid);
1524 if ($a === $pointer) {
1525 $links[] = '<li' . $this->pi_classParam('browselist-currentPage') . '><strong>' . $link . '</strong></li>';
1526 } else {
1527 $links[] = '<li>' . $link . '</li>';
1528 }
1529 }
1530 if ($pointer + 1 < $pageCount) {
1531 $links[] = '<li>' . $this->makePointerSelector_link($this->pi_getLL('pi_list_browseresults_next', 'Next >', TRUE), $pointer + 1, $freeIndexUid) . '</li>';
1532 }
1533 }
1534 if (!empty($links)) {
1535 $addPart .= '
1536 <ul class="browsebox">
1537 ' . implode('', $links) . '
1538 </ul>';
1539 }
1540 $label = str_replace(
1541 array('###TAG_BEGIN###', '###TAG_END###'),
1542 array('<strong>', '</strong>'),
1543 $this->pi_getLL('pi_list_browseresults_display', 'Displaying results ###TAG_BEGIN###%1$s to %2$s###TAG_END### out of ###TAG_BEGIN###%3$s###TAG_END###')
1544 );
1545 $resultsFrom = $pointer * $results_at_a_time + 1;
1546 $resultsTo = min($resultsFrom + $results_at_a_time - 1, $count);
1547 $resultCountText = '';
1548 if ($showResultCount) {
1549 $resultCountText = '<p>' . sprintf($label, $resultsFrom, $resultsTo, $count) . $addString . '</p>';
1550 }
1551 $sTables = '<div' . $this->pi_classParam('browsebox') . '>'
1552 . $resultCountText
1553 . $addPart . '</div>';
1554 return $sTables;
1555 }
1556
1557 /***********************************
1558 *
1559 * Support functions for HTML output (with a minimum of fixed markup)
1560 *
1561 ***********************************/
1562 /**
1563 * Preparing template data for the result row output
1564 *
1565 * @param array Result row
1566 * @param bool If set, display only header of result (for sub-results)
1567 * @return array Array with data to insert in result row template
1568 */
1569 public function prepareResultRowTemplateData($row, $headerOnly) {
1570 // Initialize:
1571 $specRowConf = $this->getSpecialConfigForRow($row);
1572 $CSSsuffix = $specRowConf['CSSsuffix'] ? '-' . $specRowConf['CSSsuffix'] : '';
1573 // If external media, link to the media-file instead.
1574 if ($row['item_type']) {
1575 // External media
1576 if ($row['show_resume']) {
1577 // Can link directly.
1578 $targetAttribute = '';
1579 if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
1580 $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
1581 }
1582 $title = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($this->makeTitle($row)) . '</a>';
1583 } else {
1584 // Suspicious, so linking to page instead...
1585 $copy_row = $row;
1586 unset($copy_row['cHashParams']);
1587 $title = $this->linkPage($row['page_id'], htmlspecialchars($this->makeTitle($row)), $copy_row);
1588 }
1589 } else {
1590 // Else the page:
1591 // Prepare search words for markup in content:
1592 if ($this->conf['forwardSearchWordsInResultLink']) {
1593 $markUpSwParams = array('no_cache' => 1);
1594 foreach ($this->sWArr as $d) {
1595 $markUpSwParams['sword_list'][] = $d['sword'];
1596 }
1597 } else {
1598 $markUpSwParams = array();
1599 }
1600 $title = $this->linkPage($row['data_page_id'], htmlspecialchars($this->makeTitle($row)), $row, $markUpSwParams);
1601 }
1602 $tmplContent = array();
1603 $tmplContent['title'] = $title;
1604 $tmplContent['result_number'] = $this->conf['show.']['resultNumber'] ? $row['result_number'] . ': ' : '&nbsp;';
1605 $tmplContent['icon'] = $this->makeItemTypeIcon($row['item_type'], '', $specRowConf);
1606 $tmplContent['rating'] = $this->makeRating($row);
1607 $tmplContent['description'] = $this->makeDescription($row, $this->piVars['extResume'] && !$headerOnly ? 0 : 1);
1608 $tmplContent = $this->makeInfo($row, $tmplContent);
1609 $tmplContent['access'] = $this->makeAccessIndication($row['page_id']);
1610 $tmplContent['language'] = $this->makeLanguageIndication($row);
1611 $tmplContent['CSSsuffix'] = $CSSsuffix;
1612 // Post processing with hook.
1613 if ($hookObj = $this->hookRequest('prepareResultRowTemplateData_postProc')) {
1614 $tmplContent = $hookObj->prepareResultRowTemplateData_postProc($tmplContent, $row, $headerOnly);
1615 }
1616 return $tmplContent;
1617 }
1618
1619 /**
1620 * Returns a string that tells which search words are searched for.
1621 *
1622 * @param array Array of search words
1623 * @return string HTML telling what is searched for.
1624 */
1625 public function tellUsWhatIsSeachedFor($sWArr) {
1626 // Init:
1627 $searchingFor = '';
1628 $c = 0;
1629 // Traverse search words:
1630 foreach ($sWArr as $k => $v) {
1631 if ($c) {
1632 switch ($v['oper']) {
1633 case 'OR':
1634 $searchingFor .= ' ' . $this->pi_getLL('searchFor_or', '', TRUE) . ' ' . $this->wrapSW($this->utf8_to_currentCharset($v['sword']));
1635 break;
1636 case 'AND NOT':
1637 $searchingFor .= ' ' . $this->pi_getLL('searchFor_butNot', '', TRUE) . ' ' . $this->wrapSW($this->utf8_to_currentCharset($v['sword']));
1638 break;
1639 default:
1640 // AND...
1641 $searchingFor .= ' ' . $this->pi_getLL('searchFor_and', '', TRUE) . ' ' . $this->wrapSW($this->utf8_to_currentCharset($v['sword']));
1642 }
1643 } else {
1644 $searchingFor = $this->pi_getLL('searchFor', '', TRUE) . ' ' . $this->wrapSW($this->utf8_to_currentCharset($v['sword']));
1645 }
1646 $c++;
1647 }
1648 return $searchingFor;
1649 }
1650
1651 /**
1652 * Wraps the search words in the search-word list display (from ->tellUsWhatIsSeachedFor())
1653 *
1654 * @param string search word to wrap (in local charset!)
1655 * @return string Search word wrapped in <span> tag.
1656 */
1657 public function wrapSW($str) {
1658 return '"<span' . $this->pi_classParam('sw') . '>' . htmlspecialchars($str) . '</span>"';
1659 }
1660
1661 /**
1662 * Makes a selector box
1663 *
1664 * @param string Name of selector box
1665 * @param string Current value
1666 * @param array Array of options in the selector box (value => label pairs)
1667 * @return string HTML of selector box
1668 */
1669 public function renderSelectBox($name, $value, $optValues) {
1670 if (is_array($optValues)) {
1671 $opt = array();
1672 $isSelFlag = 0;
1673 foreach ($optValues as $k => $v) {
1674 $sel = (string)$k === (string)$value ? ' selected="selected"' : '';
1675 if ($sel) {
1676 $isSelFlag++;
1677 }
1678 $opt[] = '<option value="' . htmlspecialchars($k) . '"' . $sel . '>' . htmlspecialchars($v) . '</option>';
1679 }
1680 return '<select name="' . $name . '">' . implode('', $opt) . '</select>';
1681 }
1682 }
1683
1684 /**
1685 * Used to make the link for the result-browser.
1686 * Notice how the links must resubmit the form after setting the new pointer-value in a hidden formfield.
1687 *
1688 * @param string String to wrap in <a> tag
1689 * @param int Pointer value
1690 * @param string List of integers pointing to free indexing configurations to search. -1 represents no filtering, 0 represents TYPO3 pages only, any number above zero is a uid of an indexing configuration!
1691 * @return string Input string wrapped in <a> tag with onclick event attribute set.
1692 */
1693 public function makePointerSelector_link($str, $p, $freeIndexUid) {
1694 $onclick = 'document.getElementById(\'' . $this->prefixId . '_pointer\').value=\'' . $p . '\';' . 'document.getElementById(\'' . $this->prefixId . '_freeIndexUid\').value=\'' . rawurlencode($freeIndexUid) . '\';' . 'document.getElementById(\'' . $this->prefixId . '\').submit();return false;';
1695 return '<a href="#" onclick="' . htmlspecialchars($onclick) . '">' . $str . '</a>';
1696 }
1697
1698 /**
1699 * Return icon for file extension
1700 *
1701 * @param string File extension / item type
1702 * @param string Title attribute value in icon.
1703 * @param array TypoScript configuration specifically for search result.
1704 * @return string <img> tag for icon
1705 */
1706 public function makeItemTypeIcon($it, $alt = '', $specRowConf) {
1707 // Build compound key if item type is 0, iconRendering is not used
1708 // and specConfs.[pid].pageIcon was set in TS
1709 if ($it === '0' && $specRowConf['_pid'] && is_array($specRowConf['pageIcon.']) && !is_array($this->conf['iconRendering.'])) {
1710 $it .= ':' . $specRowConf['_pid'];
1711 }
1712 if (!isset($this->iconFileNameCache[$it])) {
1713 $this->iconFileNameCache[$it] = '';
1714 // If TypoScript is used to render the icon:
1715 if (is_array($this->conf['iconRendering.'])) {
1716 $this->cObj->setCurrentVal($it);
1717 $this->iconFileNameCache[$it] = $this->cObj->cObjGetSingle($this->conf['iconRendering'], $this->conf['iconRendering.']);
1718 } else {
1719 // Default creation / finding of icon:
1720 $icon = '';
1721 if ($it === '0' || substr($it, 0, 2) == '0:') {
1722 if (is_array($specRowConf['pageIcon.'])) {
1723 $this->iconFileNameCache[$it] = $this->cObj->IMAGE($specRowConf['pageIcon.']);
1724 } else {
1725 $icon = 'EXT:indexed_search/pi/res/pages.gif';
1726 }
1727 } elseif ($this->external_parsers[$it]) {
1728 $icon = $this->external_parsers[$it]->getIcon($it);
1729 }
1730 if ($icon) {
1731 $fullPath = GeneralUtility::getFileAbsFileName($icon);
1732 if ($fullPath) {
1733 $info = @getimagesize($fullPath);
1734 $iconPath = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($fullPath);
1735 $this->iconFileNameCache[$it] = is_array($info) ? '<img src="' . $iconPath . '" ' . $info[3] . ' title="' . htmlspecialchars($alt) . '" alt="" />' : '';
1736 }
1737 }
1738 }
1739 }
1740 return $this->iconFileNameCache[$it];
1741 }
1742
1743 /**
1744 * Return the rating-HTML code for the result row. This makes use of the $this->firstRow
1745 *
1746 * @param array Result row array
1747 * @return string String showing ranking value
1748 */
1749 public function makeRating($row) {
1750 switch ((string)$this->piVars['order']) {
1751 case 'rank_count':
1752 // Number of occurencies on page
1753 return $row['order_val'] . ' ' . $this->pi_getLL('maketitle_matches');
1754 break;
1755 case 'rank_first':
1756 // Close to top of page
1757 return ceil(\TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((255 - $row['order_val']), 1, 255) / 255 * 100) . '%';
1758 break;
1759 case 'rank_flag':
1760 // Based on priority assigned to <title> / <meta-keywords> / <meta-description> / <body>
1761 if ($this->firstRow['order_val2']) {
1762 $base = $row['order_val1'] * 256;
1763 // (3 MSB bit, 224 is highest value of order_val1 currently)
1764 $freqNumber = $row['order_val2'] / $this->firstRow['order_val2'] * pow(2, 12);
1765 // 15-3 MSB = 12
1766 $total = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($base + $freqNumber, 0, 32767);
1767 return ceil(log($total) / log(32767) * 100) . '%';
1768 }
1769 break;
1770 case 'rank_freq':
1771 // Based on frequency
1772 $max = 10000;
1773 $total = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($row['order_val'], 0, $max);
1774 return ceil(log($total) / log($max) * 100) . '%';
1775 break;
1776 case 'crdate':
1777 // Based on creation date
1778 return $this->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_crdate'], 0);
1779 break;
1780 case 'mtime':
1781 // Based on modification time
1782 return $this->cObj->calcAge($GLOBALS['EXEC_TIME'] - $row['item_mtime'], 0);
1783 break;
1784 default:
1785 // fx. title
1786 return '&nbsp;';
1787 }
1788 }
1789
1790 /**
1791 * Returns the resume for the search-result.
1792 *
1793 * @param array Search result row
1794 * @param bool 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.
1795 * @param int String length
1796 * @return string HTML string ...
1797 */
1798 public function makeDescription($row, $noMarkup = 0, $lgd = 180) {
1799 if ($row['show_resume']) {
1800 if (!$noMarkup) {
1801 $markedSW = '';
1802 if (\TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility::isTableUsed('index_fulltext')) {
1803 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'index_fulltext', 'phash=' . (int)$row['phash']);
1804 } else {
1805 $res = FALSE;
1806 }
1807 if ($res) {
1808 if ($ftdrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1809 // Cut HTTP references after some length
1810 $content = preg_replace('/(http:\\/\\/[^ ]{60})([^ ]+)/i', '$1...', $ftdrow['fulltextdata']);
1811 $markedSW = $this->markupSWpartsOfString($content);
1812 }
1813 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1814 }
1815 }
1816 if (!trim($markedSW)) {
1817 $outputStr = $GLOBALS['TSFE']->csConvObj->crop('utf-8', $row['item_description'], $lgd);
1818 $outputStr = htmlspecialchars($outputStr);
1819 }
1820 $output = $this->utf8_to_currentCharset($outputStr ?: $markedSW);
1821 } else {
1822 $output = '<span class="noResume">' . $this->pi_getLL('res_noResume', '', TRUE) . '</span>';
1823 }
1824 return $output;
1825 }
1826
1827 /**
1828 * Marks up the search words from $this->sWarr in the $str with a color.
1829 *
1830 * @param string Text in which to find and mark up search words. This text is assumed to be UTF-8 like the search words internally is.
1831 * @return string Processed content.
1832 */
1833 public function markupSWpartsOfString($str) {
1834 // Init:
1835 $str = str_replace('&nbsp;', ' ', \TYPO3\CMS\Core\Html\HtmlParser::bidir_htmlspecialchars($str, -1));
1836 $str = preg_replace('/\\s\\s+/', ' ', $str);
1837 $swForReg = array();
1838 // Prepare search words for regex:
1839 foreach ($this->sWArr as $d) {
1840 $swForReg[] = preg_quote($d['sword'], '/');
1841 }
1842 $regExString = '(' . implode('|', $swForReg) . ')';
1843 // Split and combine:
1844 $parts = preg_split('/' . $regExString . '/ui', ' ' . $str . ' ', 20000, PREG_SPLIT_DELIM_CAPTURE);
1845 // Constants:
1846 $summaryMax = 300;
1847 $postPreLgd = 60;
1848 $postPreLgd_offset = 5;
1849 $divider = ' ... ';
1850 $occurencies = (count($parts) - 1) / 2;
1851 if ($occurencies) {
1852 $postPreLgd = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($summaryMax / $occurencies, $postPreLgd, $summaryMax / 2);
1853 }
1854 // Variable:
1855 $summaryLgd = 0;
1856 $output = array();
1857 // Shorten in-between strings:
1858 foreach ($parts as $k => $strP) {
1859 if ($k % 2 == 0) {
1860 // Find length of the summary part:
1861 $strLen = $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $parts[$k]);
1862 $output[$k] = $parts[$k];
1863 // Possibly shorten string:
1864 if (!$k) {
1865 // First entry at all (only cropped on the frontside)
1866 if ($strLen > $postPreLgd) {
1867 $output[$k] = $divider . preg_replace('/^[^[:space:]]+[[:space:]]/', '', $GLOBALS['TSFE']->csConvObj->crop('utf-8', $parts[$k], -($postPreLgd - $postPreLgd_offset)));
1868 }
1869 } elseif ($summaryLgd > $summaryMax || !isset($parts[($k + 1)])) {
1870 // In case summary length is exceed OR if there are no more entries at all:
1871 if ($strLen > $postPreLgd) {
1872 $output[$k] = preg_replace('/[[:space:]][^[:space:]]+$/', '', $GLOBALS['TSFE']->csConvObj->crop('utf-8', $parts[$k], ($postPreLgd - $postPreLgd_offset))) . $divider;
1873 }
1874 } else {
1875 // In-between search words:
1876 if ($strLen > $postPreLgd * 2) {
1877 $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)));
1878 }
1879 }
1880 $summaryLgd += $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $output[$k]);
1881 // Protect output:
1882 $output[$k] = htmlspecialchars($output[$k]);
1883 // If summary lgd is exceed, break the process:
1884 if ($summaryLgd > $summaryMax) {
1885 break;
1886 }
1887 } else {
1888 $summaryLgd += $GLOBALS['TSFE']->csConvObj->strlen('utf-8', $strP);
1889 $output[$k] = '<strong class="tx-indexedsearch-redMarkup">' . htmlspecialchars($parts[$k]) . '</strong>';
1890 }
1891 }
1892 // Return result:
1893 return implode('', $output);
1894 }
1895
1896 /**
1897 * Returns the title of the search result row
1898 *
1899 * @param array Result row
1900 * @return string Title from row
1901 */
1902 public function makeTitle($row) {
1903 $add = '';
1904 if ($this->multiplePagesType($row['item_type'])) {
1905 $dat = unserialize($row['cHashParams']);
1906 $pp = explode('-', $dat['key']);
1907 if ($pp[0] != $pp[1]) {
1908 $add = ', ' . $this->pi_getLL('word_pages') . ' ' . $dat['key'];
1909 } else {
1910 $add = ', ' . $this->pi_getLL('word_page') . ' ' . $pp[0];
1911 }
1912 }
1913 $outputString = $GLOBALS['TSFE']->csConvObj->crop('utf-8', $row['item_title'], 50, '...');
1914 return $this->utf8_to_currentCharset($outputString) . $add;
1915 }
1916
1917 /**
1918 * Returns the info-string in the bottom of the result-row display (size, dates, path)
1919 *
1920 * @param array Result row
1921 * @param array Template array to modify
1922 * @return array Modified template array
1923 */
1924 public function makeInfo($row, $tmplArray) {
1925 $tmplArray['size'] = GeneralUtility::formatSize($row['item_size']);
1926 $tmplArray['created'] = $this->formatCreatedDate($row['item_crdate']);
1927 $tmplArray['modified'] = $this->formatModifiedDate($row['item_mtime']);
1928 $pathId = $row['data_page_id'] ?: $row['page_id'];
1929 $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
1930 $pI = parse_url($row['data_filename']);
1931 if ($pI['scheme']) {
1932 $targetAttribute = '';
1933 if ($GLOBALS['TSFE']->config['config']['fileTarget']) {
1934 $targetAttribute = ' target="' . htmlspecialchars($GLOBALS['TSFE']->config['config']['fileTarget']) . '"';
1935 }
1936 $tmplArray['path'] = '<a href="' . htmlspecialchars($row['data_filename']) . '"' . $targetAttribute . '>' . htmlspecialchars($row['data_filename']) . '</a>';
1937 } else {
1938 $pathStr = htmlspecialchars($this->getPathFromPageId($pathId, $pathMP));
1939 $tmplArray['path'] = $this->linkPage($pathId, $pathStr, array(
1940 'cHashParams' => $row['cHashParams'],
1941 'data_page_type' => $row['data_page_type'],
1942 'data_page_mp' => $pathMP,
1943 'sys_language_uid' => $row['sys_language_uid']
1944 ));
1945 }
1946 return $tmplArray;
1947 }
1948
1949 /**
1950 * Returns configuration from TypoScript for result row based on ID / location in page tree!
1951 *
1952 * @param array Result row
1953 * @return array Configuration array
1954 */
1955 public function getSpecialConfigForRow($row) {
1956 $pathId = $row['data_page_id'] ?: $row['page_id'];
1957 $pathMP = $row['data_page_id'] ? $row['data_page_mp'] : '';
1958 $rl = $this->getRootLine($pathId, $pathMP);
1959 $specConf = $this->conf['specConfs.']['0.'];
1960 if (is_array($rl)) {
1961 foreach ($rl as $dat) {
1962 if (is_array($this->conf['specConfs.'][$dat['uid'] . '.'])) {
1963 $specConf = $this->conf['specConfs.'][$dat['uid'] . '.'];
1964 $specConf['_pid'] = $dat['uid'];
1965 break;
1966 }
1967 }
1968 }
1969 return $specConf;
1970 }
1971
1972 /**
1973 * Returns the HTML code for language indication.
1974 *
1975 * @param array Result row
1976 * @return string HTML code for result row.
1977 */
1978 public function makeLanguageIndication($row) {
1979 // If search result is a TYPO3 page:
1980 if ((string)$row['item_type'] === '0') {
1981 // If TypoScript is used to render the flag:
1982 if (is_array($this->conf['flagRendering.'])) {
1983 $this->cObj->setCurrentVal($row['sys_language_uid']);
1984 return $this->cObj->cObjGetSingle($this->conf['flagRendering'], $this->conf['flagRendering.']);
1985 }
1986 }
1987 return '&nbsp;';
1988 }
1989
1990 /**
1991 * Returns the HTML code for the locking symbol.
1992 * NOTICE: Requires a call to ->getPathFromPageId() first in order to work (done in ->makeInfo() by calling that first)
1993 *
1994 * @param int Page id for which to find answer
1995 * @return string <img> tag if access is limited.
1996 */
1997 public function makeAccessIndication($id) {
1998 if (is_array($this->fe_groups_required[$id]) && count($this->fe_groups_required[$id])) {
1999 return '<img src="' . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath('indexed_search') . 'pi/res/locked.gif" width="12" height="15" vspace="5" title="' . sprintf($this->pi_getLL('res_memberGroups', '', TRUE), implode(',', array_unique($this->fe_groups_required[$id]))) . '" alt="" />';
2000 }
2001 }
2002
2003 /**
2004 * Links the $str to page $id
2005 *
2006 * @param int Page id
2007 * @param string Title String to link
2008 * @param array Result row
2009 * @param array Additional parameters for marking up seach words
2010 * @return string <A> tag wrapped title string.
2011 */
2012 public function linkPage($id, $str, $row = array(), $markUpSwParams = array()) {
2013 // Parameters for link:
2014 $urlParameters = (array)unserialize($row['cHashParams']);
2015 // Add &type and &MP variable:
2016 if ($row['data_page_type']) {
2017 $urlParameters['type'] = $row['data_page_type'];
2018 }
2019 if ($row['data_page_mp']) {
2020 $urlParameters['MP'] = $row['data_page_mp'];
2021 }
2022 if ($row['sys_language_uid']) {
2023 $urlParameters['L'] = $row['sys_language_uid'];
2024 }
2025 // markup-GET vars:
2026 $urlParameters = array_merge($urlParameters, $markUpSwParams);
2027 // This will make sure that the path is retrieved if it hasn't been already. Used only for the sake of the domain_record thing...
2028 if (!is_array($this->domain_records[$id])) {
2029 $this->getPathFromPageId($id);
2030 }
2031 // If external domain, then link to that:
2032 if (count($this->domain_records[$id])) {
2033 reset($this->domain_records[$id]);
2034 $firstDom = current($this->domain_records[$id]);
2035 $scheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
2036 $addParams = '';
2037 if (is_array($urlParameters)) {
2038 if (count($urlParameters)) {
2039 $addParams .= GeneralUtility::implodeArrayForUrl('', $urlParameters);
2040 }
2041 }
2042 if ($target = $this->conf['search.']['detect_sys_domain_records.']['target']) {
2043 $target = ' target="' . $target . '"';
2044 }
2045 return '<a href="' . htmlspecialchars(($scheme . $firstDom . '/index.php?id=' . $id . $addParams)) . '"' . $target . '>' . htmlspecialchars($str) . '</a>';
2046 } else {
2047 return $this->pi_linkToPage($str, $id, $this->conf['result_link_target'], $urlParameters);
2048 }
2049 }
2050
2051 /**
2052 * Returns the path to the page $id
2053 *
2054 * @param int Page ID
2055 * @param string MP variable content.
2056 * @return string Root line for result.
2057 */
2058 public function getRootLine($id, $pathMP = '') {
2059 $identStr = $id . '|' . $pathMP;
2060 if (!isset($this->cache_path[$identStr])) {
2061 $this->cache_rl[$identStr] = $GLOBALS['TSFE']->sys_page->getRootLine($id, $pathMP);
2062 }
2063 return $this->cache_rl[$identStr];
2064 }
2065
2066 /**
2067 * Gets the first sys_domain record for the page, $id
2068 *
2069 * @param int Page id
2070 * @return string Domain name
2071 */
2072 public function getFirstSysDomainRecordForPage($id) {
2073 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('domainName', 'sys_domain', 'pid=' . (int)$id . $this->cObj->enableFields('sys_domain'), '', 'sorting');
2074 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
2075 return rtrim($row['domainName'], '/');
2076 }
2077
2078 /**
2079 * Returns the path to the page $id
2080 *
2081 * @param int Page ID
2082 * @param string MP variable content
2083 * @return string Path
2084 */
2085 public function getPathFromPageId($id, $pathMP = '') {
2086 $identStr = $id . '|' . $pathMP;
2087 if (!isset($this->cache_path[$identStr])) {
2088 $this->fe_groups_required[$id] = array();
2089 $this->domain_records[$id] = array();
2090 $rl = $this->getRootLine($id, $pathMP);
2091 $hitRoot = 0;
2092 $path = '';
2093 if (is_array($rl) && count($rl)) {
2094 foreach ($rl as $k => $v) {
2095 // Check fe_user
2096 if ($v['fe_group'] && ($v['uid'] == $id || $v['extendToSubpages'])) {
2097 $this->fe_groups_required[$id][] = $v['fe_group'];
2098 }
2099 // Check sys_domain.
2100 if ($this->conf['search.']['detect_sys_domain_records']) {
2101 $sysDName = $this->getFirstSysDomainRecordForPage($v['uid']);
2102 if ($sysDName) {
2103 $this->domain_records[$id][] = $sysDName;
2104 // Set path accordingly:
2105 $path = $sysDName . $path;
2106 break;
2107 }
2108 }
2109 // Stop, if we find that the current id is the current root page.
2110 if ($v['uid'] == $GLOBALS['TSFE']->config['rootLine'][0]['uid']) {
2111 break;
2112 }
2113 $path = '/' . $v['title'] . $path;
2114 }
2115 }
2116 $this->cache_path[$identStr] = $path;
2117 if (is_array($this->conf['path_stdWrap.'])) {
2118 $this->cache_path[$identStr] = $this->cObj->stdWrap($this->cache_path[$identStr], $this->conf['path_stdWrap.']);
2119 }
2120 }
2121 return $this->cache_path[$identStr];
2122 }
2123
2124 /**
2125 * Return the menu of pages used for the selector.
2126 *
2127 * @param int Page ID for which to return menu
2128 * @return array Menu items (for making the section selector box)
2129 */
2130 public function getMenu($id) {
2131 if ($this->conf['show.']['LxALLtypes']) {
2132 $output = array();
2133 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('title,uid', 'pages', 'pid=' . (int)$id . $this->cObj->enableFields('pages'), '', 'sorting');
2134 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2135 $output[$row['uid']] = $GLOBALS['TSFE']->sys_page->getPageOverlay($row);
2136 }
2137 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2138 return $output;
2139 } else {
2140 return $GLOBALS['TSFE']->sys_page->getMenu($id);
2141 }
2142 }
2143
2144 /**
2145 * Returns if an item type is a multipage item type
2146 *
2147 * @param string Item type
2148 * @return bool TRUE if multipage capable
2149 */
2150 public function multiplePagesType($item_type) {
2151 return is_object($this->external_parsers[$item_type]) && $this->external_parsers[$item_type]->isMultiplePageExtension($item_type);
2152 }
2153
2154 /**
2155 * Converts the input string from utf-8 to the backend charset.
2156 *
2157 * @param string String to convert (utf-8)
2158 * @return string Converted string (backend charset if different from utf-8)
2159 */
2160 public function utf8_to_currentCharset($str) {
2161 return $GLOBALS['TSFE']->csConv($str, 'utf-8');
2162 }
2163
2164 /**
2165 * Returns an object reference to the hook object if any
2166 *
2167 * @param string Name of the function you want to call / hook key
2168 * @return object Hook object, if any. Otherwise NULL.
2169 */
2170 public function hookRequest($functionName) {
2171 // Hook: menuConfig_preProcessModMenu
2172 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]) {
2173 $hookObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['pi1_hooks'][$functionName]);
2174 if (method_exists($hookObj, $functionName)) {
2175 $hookObj->pObj = $this;
2176 return $hookObj;
2177 }
2178 }
2179 }
2180
2181 /**
2182 * Obtains the URL of the search target page
2183 *
2184 * @return string
2185 */
2186 protected function getSearchFormActionURL() {
2187 $targetUrlPid = $this->getSearchFormActionPidFromTS();
2188 if ($targetUrlPid == 0) {
2189 $targetUrlPid = $GLOBALS['TSFE']->id;
2190 }
2191 return $this->pi_getPageLink($targetUrlPid, $GLOBALS['TSFE']->sPre);
2192 }
2193
2194 /**
2195 * Obtains search form target pid from the TypoScript configuration
2196 *
2197 * @return int
2198 */
2199 protected function getSearchFormActionPidFromTS() {
2200 $result = 0;
2201 if (isset($this->conf['search.']['targetPid']) || isset($this->conf['search.']['targetPid.'])) {
2202 if (is_array($this->conf['search.']['targetPid.'])) {
2203 $result = $this->cObj->stdWrap($this->conf['search.']['targetPid'], $this->conf['search.']['targetPid.']);
2204 } else {
2205 $result = $this->conf['search.']['targetPid'];
2206 }
2207 $result = (int)$result;
2208 }
2209 return $result;
2210 }
2211
2212 /**
2213 * Formats date as 'created' date
2214 *
2215 * @param int $date
2216 * @return string
2217 */
2218 protected function formatCreatedDate($date) {
2219 $defaultFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2220 return $this->formatDate($date, 'created', $defaultFormat);
2221 }
2222
2223 /**
2224 * Formats date as 'modified' date
2225 *
2226 * @param int $date
2227 * @return string
2228 */
2229 protected function formatModifiedDate($date) {
2230 $defaultFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2231 return $this->formatDate($date, 'modified', $defaultFormat);
2232 }
2233
2234 /**
2235 * Formats the date using format string from TypoScript or default format
2236 * if TypoScript format is not set
2237 *
2238 * @param int $date
2239 * @param string $tsKey
2240 * @param string $defaultFormat
2241 * @return string
2242 */
2243 protected function formatDate($date, $tsKey, $defaultFormat) {
2244 $strftimeFormat = $this->conf['dateFormat.'][$tsKey];
2245 if ($strftimeFormat) {
2246 $result = strftime($strftimeFormat, $date);
2247 } else {
2248 $result = date($defaultFormat, $date);
2249 }
2250 return $result;
2251 }
2252
2253 }