[TASK] Update php-cs-fixer to 2.5.0
[Packages/TYPO3.CMS.git] / typo3 / sysext / indexed_search / Classes / Indexer.php
1 <?php
2 namespace TYPO3\CMS\IndexedSearch;
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\Database\Connection;
18 use TYPO3\CMS\Core\Database\ConnectionPool;
19 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21 use TYPO3\CMS\Core\Utility\MathUtility;
22 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
23 use TYPO3\CMS\IndexedSearch\Utility\IndexedSearchUtility;
24
25 /**
26 * Indexing class for TYPO3 frontend
27 */
28 class Indexer
29 {
30 /**
31 * @var array
32 */
33 public $reasons = [
34 -1 => 'mtime matched the document, so no changes detected and no content updated',
35 -2 => 'The minimum age was not exceeded',
36 1 => 'The configured max-age was exceeded for the document and thus it\'s indexed.',
37 2 => 'The minimum age was exceed and mtime was set and the mtime was different, so the page was indexed.',
38 3 => 'The minimum age was exceed, but mtime was not set, so the page was indexed.',
39 4 => 'Page has never been indexed (is not represented in the index_phash table).'
40 ];
41
42 /**
43 * HTML code blocks to exclude from indexing
44 *
45 * @var string
46 */
47 public $excludeSections = 'script,style';
48
49 /**
50 * Supported Extensions for external files
51 *
52 * @var array
53 */
54 public $external_parsers = [];
55
56 /**
57 * External parser objects, keys are file extension names. Values are objects with certain methods.
58 * Fe-group list (pages might be indexed separately for each usergroup combination to support search
59 * in access limited pages!)
60 *
61 * @var string
62 */
63 public $defaultGrList = '0,-1';
64
65 /**
66 * Min/Max times
67 *
68 * @var int
69 */
70 public $tstamp_maxAge = 0;
71
72 /**
73 * If set, this tells a number of seconds that is the maximum age of an indexed document.
74 * Regardless of mtime the document will be re-indexed if this limit is exceeded.
75 *
76 * @var int
77 */
78 public $tstamp_minAge = 0;
79
80 /**
81 * If set, this tells a minimum limit before a document can be indexed again. This is regardless of mtime.
82 *
83 * @var int
84 */
85 public $maxExternalFiles = 0;
86
87 /**
88 * Max number of external files to index.
89 *
90 * @var bool
91 */
92 public $forceIndexing = false;
93
94 /**
95 * If TRUE, indexing is forced despite of hashes etc.
96 *
97 * @var bool
98 */
99 public $crawlerActive = false;
100
101 /**
102 * Set when crawler is detected (internal)
103 *
104 * @var array
105 */
106 public $defaultContentArray = [
107 'title' => '',
108 'description' => '',
109 'keywords' => '',
110 'body' => ''
111 ];
112
113 /**
114 * @var int
115 */
116 public $wordcount = 0;
117
118 /**
119 * @var int
120 */
121 public $externalFileCounter = 0;
122
123 /**
124 * @var array
125 */
126 public $conf = [];
127
128 /**
129 * Configuration set internally (see init functions for required keys and their meaning)
130 *
131 * @var array
132 */
133 public $indexerConfig = [];
134
135 /**
136 * Indexer configuration, coming from $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search']
137 *
138 * @var array
139 */
140 public $hash = [];
141
142 /**
143 * Hash array, contains phash and phash_grouping
144 *
145 * @var array
146 */
147 public $file_phash_arr = [];
148
149 /**
150 * Hash array for files
151 *
152 * @var array
153 */
154 public $contentParts = [];
155
156 /**
157 * Content of TYPO3 page
158 *
159 * @var string
160 */
161 public $content_md5h = '';
162
163 /**
164 * @var array
165 */
166 public $internal_log = [];
167
168 /**
169 * Internal log
170 *
171 * @var string
172 */
173 public $indexExternalUrl_content = '';
174
175 /**
176 * @var array
177 */
178 public $cHashParams = [];
179
180 /**
181 * cHashparams array
182 *
183 * @var int
184 */
185 public $freqRange = 32000;
186
187 /**
188 * @var float
189 */
190 public $freqMax = 0.1;
191
192 /**
193 * @var bool
194 */
195 public $enableMetaphoneSearch = false;
196
197 /**
198 * @var bool
199 */
200 public $storeMetaphoneInfoAsWords;
201
202 /**
203 * @var string
204 */
205 public $metaphoneContent = '';
206
207 /**
208 * Charset class object
209 *
210 * @var \TYPO3\CMS\Core\Charset\CharsetConverter
211 */
212 public $csObj;
213
214 /**
215 * Metaphone object, if any
216 *
217 * @var \TYPO3\CMS\IndexedSearch\Utility\DoubleMetaPhoneUtility
218 */
219 public $metaphoneObj;
220
221 /**
222 * Lexer object for word splitting
223 *
224 * @var \TYPO3\CMS\IndexedSearch\Lexer
225 */
226 public $lexerObj;
227
228 /**
229 * @var bool
230 */
231 public $flagBitMask;
232
233 /**
234 * @var TimeTracker
235 */
236 protected $timeTracker;
237
238 /**
239 * Indexer constructor.
240 */
241 public function __construct()
242 {
243 $this->timeTracker = GeneralUtility::makeInstance(TimeTracker::class);
244 }
245
246 /**
247 * Parent Object (TSFE) Initialization
248 *
249 * @param TypoScriptFrontendController $pObj Parent Object, passed by reference
250 */
251 public function hook_indexContent(&$pObj)
252 {
253 // Indexer configuration from Extension Manager interface:
254 $indexerConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search'], ['allowed_classes' => false]);
255 // Crawler activation:
256 // Requirements are that the crawler is loaded, a crawler session is running and re-indexing requested as processing instruction:
257 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('crawler') && $pObj->applicationData['tx_crawler']['running'] && in_array('tx_indexedsearch_reindex', $pObj->applicationData['tx_crawler']['parameters']['procInstructions'])) {
258 // Setting simple log message:
259 $pObj->applicationData['tx_crawler']['log'][] = 'Forced Re-indexing enabled';
260 // Setting variables:
261 $this->crawlerActive = true;
262 // Crawler active flag
263 $this->forceIndexing = true;
264 }
265 // Determine if page should be indexed, and if so, configure and initialize indexer
266 if ($pObj->config['config']['index_enable']) {
267 $this->log_push('Index page', '');
268 if (!$indexerConfig['disableFrontendIndexing'] || $this->crawlerActive) {
269 if (!$pObj->page['no_search']) {
270 if (!$pObj->no_cache) {
271 if ((int)$pObj->sys_language_uid === (int)$pObj->sys_language_content) {
272 // Setting up internal configuration from config array:
273 $this->conf = [];
274 // Information about page for which the indexing takes place
275 $this->conf['id'] = $pObj->id;
276 // Page id
277 $this->conf['type'] = $pObj->type;
278 // Page type
279 $this->conf['sys_language_uid'] = $pObj->sys_language_uid;
280 // sys_language UID of the language of the indexing.
281 $this->conf['MP'] = $pObj->MP;
282 // MP variable, if any (Mount Points)
283 $this->conf['gr_list'] = $pObj->gr_list;
284 // Group list
285 $this->conf['cHash'] = $pObj->cHash;
286 // cHash string for additional parameters
287 $this->conf['cHash_array'] = $pObj->cHash_array;
288 // Array of the additional parameters
289 $this->conf['crdate'] = $pObj->page['crdate'];
290 // The creation date of the TYPO3 page
291 $this->conf['page_cache_reg1'] = $pObj->page_cache_reg1;
292 // reg1 of the caching table. Not known what practical use this has.
293 // Root line uids
294 $this->conf['rootline_uids'] = [];
295 foreach ($pObj->config['rootLine'] as $rlkey => $rldat) {
296 $this->conf['rootline_uids'][$rlkey] = $rldat['uid'];
297 }
298 // Content of page:
299 $this->conf['content'] = $pObj->content;
300 // Content string (HTML of TYPO3 page)
301 $this->conf['indexedDocTitle'] = $pObj->convOutputCharset($pObj->indexedDocTitle);
302 // Alternative title for indexing
303 $this->conf['metaCharset'] = $pObj->metaCharset;
304 // Character set of content (will be converted to utf-8 during indexing)
305 $this->conf['mtime'] = isset($pObj->register['SYS_LASTCHANGED']) ? $pObj->register['SYS_LASTCHANGED'] : $pObj->page['SYS_LASTCHANGED'];
306 // Most recent modification time (seconds) of the content on the page. Used to evaluate whether it should be re-indexed.
307 // Configuration of behavior:
308 $this->conf['index_externals'] = $pObj->config['config']['index_externals'];
309 // Whether to index external documents like PDF, DOC etc. (if possible)
310 $this->conf['index_descrLgd'] = $pObj->config['config']['index_descrLgd'];
311 // Length of description text (max 250, default 200)
312 $this->conf['index_metatags'] = isset($pObj->config['config']['index_metatags']) ? $pObj->config['config']['index_metatags'] : true;
313 // Set to zero:
314 $this->conf['recordUid'] = 0;
315 $this->conf['freeIndexUid'] = 0;
316 $this->conf['freeIndexSetId'] = 0;
317 // Init and start indexing:
318 $this->init();
319 $this->indexTypo3PageContent();
320 } else {
321 $this->log_setTSlogMessage('Index page? No, ->sys_language_uid was different from sys_language_content which indicates that the page contains fall-back content and that would be falsely indexed as localized content.');
322 }
323 } else {
324 $this->log_setTSlogMessage('Index page? No, page was set to "no_cache" and so cannot be indexed.');
325 }
326 } else {
327 $this->log_setTSlogMessage('Index page? No, The "No Search" flag has been set in the page properties!');
328 }
329 } else {
330 $this->log_setTSlogMessage('Index page? No, Ordinary Frontend indexing during rendering is disabled.');
331 }
332 $this->log_pull();
333 }
334 }
335
336 /****************************
337 *
338 * Backend API
339 *
340 ****************************/
341 /**
342 * Initializing the "combined ID" of the page (phash) being indexed (or for which external media is attached)
343 *
344 * @param int $id The page uid, &id=
345 * @param int $type The page type, &type=
346 * @param int $sys_language_uid sys_language uid, typically &L=
347 * @param string $MP The MP variable (Mount Points), &MP=
348 * @param array $uidRL Rootline array of only UIDs.
349 * @param array $cHash_array Array of GET variables to register with this indexing
350 * @param bool $createCHash If set, calculates a cHash value from the $cHash_array. Probably you will not do that since such cases are indexed through the frontend and the idea of this interface is to index non-cacheable pages from the backend!
351 */
352 public function backend_initIndexer($id, $type, $sys_language_uid, $MP, $uidRL, $cHash_array = [], $createCHash = false)
353 {
354 // Setting up internal configuration from config array:
355 $this->conf = [];
356 // Information about page for which the indexing takes place
357 $this->conf['id'] = $id;
358 // Page id (int)
359 $this->conf['type'] = $type;
360 // Page type (int)
361 $this->conf['sys_language_uid'] = $sys_language_uid;
362 // sys_language UID of the language of the indexing (int)
363 $this->conf['MP'] = $MP;
364 // MP variable, if any (Mount Points) (string)
365 $this->conf['gr_list'] = '0,-1';
366 // Group list (hardcoded for now...)
367 // cHash values:
368 if ($createCHash) {
369 /* @var $cacheHash \TYPO3\CMS\Frontend\Page\CacheHashCalculator */
370 $cacheHash = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Page\CacheHashCalculator::class);
371 $this->conf['cHash'] = $cacheHash->generateForParameters(GeneralUtility::implodeArrayForUrl('', $cHash_array));
372 } else {
373 $this->conf['cHash'] = '';
374 }
375 // cHash string for additional parameters
376 $this->conf['cHash_array'] = $cHash_array;
377 // Array of the additional parameters
378 // Set to defaults
379 $this->conf['freeIndexUid'] = 0;
380 $this->conf['freeIndexSetId'] = 0;
381 $this->conf['page_cache_reg1'] = '';
382 // Root line uids
383 $this->conf['rootline_uids'] = $uidRL;
384 // Configuration of behavior:
385 $this->conf['index_externals'] = 1;
386 // Whether to index external documents like PDF, DOC etc. (if possible)
387 $this->conf['index_descrLgd'] = 200;
388 // Length of description text (max 250, default 200)
389 $this->conf['index_metatags'] = true;
390 // Whether to index document keywords and description (if present)
391 // Init and start indexing:
392 $this->init();
393 }
394
395 /**
396 * Sets the free-index uid. Can be called right after backend_initIndexer()
397 *
398 * @param int $freeIndexUid Free index UID
399 * @param int $freeIndexSetId Set id - an integer identifying the "set" of indexing operations.
400 */
401 public function backend_setFreeIndexUid($freeIndexUid, $freeIndexSetId = 0)
402 {
403 $this->conf['freeIndexUid'] = $freeIndexUid;
404 $this->conf['freeIndexSetId'] = $freeIndexSetId;
405 }
406
407 /**
408 * Indexing records as the content of a TYPO3 page.
409 *
410 * @param string $title Title equivalent
411 * @param string $keywords Keywords equivalent
412 * @param string $description Description equivalent
413 * @param string $content The main content to index
414 * @param string $charset The charset of the title, keyword, description and body-content. MUST BE VALID, otherwise nothing is indexed!
415 * @param int $mtime Last modification time, in seconds
416 * @param int $crdate The creation date of the content, in seconds
417 * @param int $recordUid The record UID that the content comes from (for registration with the indexed rows)
418 */
419 public function backend_indexAsTYPO3Page($title, $keywords, $description, $content, $charset, $mtime, $crdate = 0, $recordUid = 0)
420 {
421 // Content of page:
422 $this->conf['mtime'] = $mtime;
423 // Most recent modification time (seconds) of the content
424 $this->conf['crdate'] = $crdate;
425 // The creation date of the TYPO3 content
426 $this->conf['recordUid'] = $recordUid;
427 // UID of the record, if applicable
428 // Construct fake HTML for parsing:
429 $this->conf['content'] = '
430 <html>
431 <head>
432 <title>' . htmlspecialchars($title) . '</title>
433 <meta name="keywords" content="' . htmlspecialchars($keywords) . '" />
434 <meta name="description" content="' . htmlspecialchars($description) . '" />
435 </head>
436 <body>
437 ' . htmlspecialchars($content) . '
438 </body>
439 </html>';
440 // Content string (HTML of TYPO3 page)
441 // Initializing charset:
442 $this->conf['metaCharset'] = $charset;
443 // Character set of content (will be converted to utf-8 during indexing)
444 $this->conf['indexedDocTitle'] = '';
445 // Alternative title for indexing
446 // Index content as if it was a TYPO3 page:
447 $this->indexTypo3PageContent();
448 }
449
450 /********************************
451 *
452 * Initialization
453 *
454 *******************************/
455 /**
456 * Initializes the object. $this->conf MUST be set with proper values prior to this call!!!
457 */
458 public function init()
459 {
460 // Initializing:
461 $this->cHashParams = $this->conf['cHash_array'];
462 if (is_array($this->cHashParams) && !empty($this->cHashParams)) {
463 if ($this->conf['cHash']) {
464 // Add this so that URL's come out right...
465 $this->cHashParams['cHash'] = $this->conf['cHash'];
466 }
467 unset($this->cHashParams['encryptionKey']);
468 }
469 // Setting phash / phash_grouping which identifies the indexed page based on some of these variables:
470 $this->setT3Hashes();
471 // Indexer configuration from Extension Manager interface:
472 $this->indexerConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['indexed_search'], ['allowed_classes' => false]);
473 $this->tstamp_minAge = MathUtility::forceIntegerInRange($this->indexerConfig['minAge'] * 3600, 0);
474 $this->tstamp_maxAge = MathUtility::forceIntegerInRange($this->indexerConfig['maxAge'] * 3600, 0);
475 $this->maxExternalFiles = MathUtility::forceIntegerInRange($this->indexerConfig['maxExternalFiles'], 0, 1000, 5);
476 $this->flagBitMask = MathUtility::forceIntegerInRange($this->indexerConfig['flagBitMask'], 0, 255);
477 // Workaround: If the extension configuration was not updated yet, the value is not existing
478 $this->enableMetaphoneSearch = !isset($this->indexerConfig['enableMetaphoneSearch']) || $this->indexerConfig['enableMetaphoneSearch'];
479 $this->storeMetaphoneInfoAsWords = !IndexedSearchUtility::isTableUsed('index_words') && $this->enableMetaphoneSearch;
480 // Initialize external document parsers:
481 // Example configuration, see ext_localconf.php of this file!
482 if ($this->conf['index_externals']) {
483 $this->initializeExternalParsers();
484 }
485 // Initialize lexer (class that deconstructs the text into words):
486 $lexerObjectClassName = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['lexer'] ?: Lexer::class;
487 $this->lexerObj = GeneralUtility::makeInstance($lexerObjectClassName);
488 $this->lexerObj->debug = $this->indexerConfig['debugMode'];
489 // Initialize metaphone hook:
490 // Make sure that the hook is loaded _after_ indexed_search as this may overwrite the hook depending on the configuration.
491 if ($this->enableMetaphoneSearch && $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['metaphone']) {
492 $this->metaphoneObj = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['metaphone']);
493 $this->metaphoneObj->pObj = $this;
494 }
495 // Init charset class:
496 $this->csObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
497 }
498
499 /**
500 * Initialize external parsers
501 *
502 * @access private
503 * @see init()
504 */
505 public function initializeExternalParsers()
506 {
507 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'])) {
508 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['external_parsers'] as $extension => $className) {
509 $this->external_parsers[$extension] = GeneralUtility::makeInstance($className);
510 $this->external_parsers[$extension]->pObj = $this;
511 // Init parser and if it returns FALSE, unset its entry again:
512 if (!$this->external_parsers[$extension]->initParser($extension)) {
513 unset($this->external_parsers[$extension]);
514 }
515 }
516 }
517 }
518
519 /********************************
520 *
521 * Indexing; TYPO3 pages (HTML content)
522 *
523 *******************************/
524 /**
525 * Start indexing of the TYPO3 page
526 */
527 public function indexTypo3PageContent()
528 {
529 $check = $this->checkMtimeTstamp($this->conf['mtime'], $this->hash['phash']);
530 $is_grlist = $this->is_grlist_set($this->hash['phash']);
531 if ($check > 0 || !$is_grlist || $this->forceIndexing) {
532 // Setting message:
533 if ($this->forceIndexing) {
534 $this->log_setTSlogMessage('Indexing needed, reason: Forced', 1);
535 } elseif ($check > 0) {
536 $this->log_setTSlogMessage('Indexing needed, reason: ' . $this->reasons[$check], 1);
537 } else {
538 $this->log_setTSlogMessage('Indexing needed, reason: Updates gr_list!', 1);
539 }
540 // Divide into title,keywords,description and body:
541 $this->log_push('Split content', '');
542 $this->contentParts = $this->splitHTMLContent($this->conf['content']);
543 if ($this->conf['indexedDocTitle']) {
544 $this->contentParts['title'] = $this->conf['indexedDocTitle'];
545 }
546 $this->log_pull();
547 // Calculating a hash over what is to be the actual page content. Maybe this hash should not include title,description and keywords? The bodytext is the primary concern. (on the other hand a changed page-title would make no difference then, so don't!)
548 $this->content_md5h = IndexedSearchUtility::md5inthash(implode('', $this->contentParts));
549 // This function checks if there is already a page (with gr_list = 0,-1) indexed and if that page has the very same contentHash.
550 // If the contentHash is the same, then we can rest assured that this page is already indexed and regardless of mtime and origContent we don't need to do anything more.
551 // This will also prevent pages from being indexed if a fe_users has logged in and it turns out that the page content is not changed anyway. fe_users logged in should always search with hash_gr_list = "0,-1" OR "[their_group_list]". This situation will be prevented only if the page has been indexed with no user login on before hand. Else the page will be indexed by users until that event. However that does not present a serious problem.
552 $checkCHash = $this->checkContentHash();
553 if (!is_array($checkCHash) || $check === 1) {
554 $Pstart = GeneralUtility::milliseconds();
555 $this->log_push('Converting charset of content (' . $this->conf['metaCharset'] . ') to utf-8', '');
556 $this->charsetEntity2utf8($this->contentParts, $this->conf['metaCharset']);
557 $this->log_pull();
558 // Splitting words
559 $this->log_push('Extract words from content', '');
560 $splitInWords = $this->processWordsInArrays($this->contentParts);
561 $this->log_pull();
562 // Analyse the indexed words.
563 $this->log_push('Analyse the extracted words', '');
564 $indexArr = $this->indexAnalyze($splitInWords);
565 $this->log_pull();
566 // Submitting page (phash) record
567 $this->log_push('Submitting page', '');
568 $this->submitPage();
569 $this->log_pull();
570 // Check words and submit to word list if not there
571 $this->log_push('Check word list and submit words', '');
572 if (IndexedSearchUtility::isTableUsed('index_words')) {
573 $this->checkWordList($indexArr);
574 $this->submitWords($indexArr, $this->hash['phash']);
575 }
576 $this->log_pull();
577 // Set parsetime
578 $this->updateParsetime($this->hash['phash'], GeneralUtility::milliseconds() - $Pstart);
579 // Checking external files if configured for.
580 $this->log_push('Checking external files', '');
581 if ($this->conf['index_externals']) {
582 $this->extractLinks($this->conf['content']);
583 }
584 $this->log_pull();
585 } else {
586 // Update the timestamp
587 $this->updateTstamp($this->hash['phash'], $this->conf['mtime']);
588 $this->updateSetId($this->hash['phash']);
589 // $checkCHash['phash'] is the phash of the result row that is similar to the current phash regarding the content hash.
590 $this->update_grlist($checkCHash['phash'], $this->hash['phash']);
591 $this->updateRootline();
592 $this->log_setTSlogMessage('Indexing not needed, the contentHash, ' . $this->content_md5h . ', has not changed. Timestamp, grlist and rootline updated if necessary.');
593 }
594 } else {
595 $this->log_setTSlogMessage('Indexing not needed, reason: ' . $this->reasons[$check]);
596 }
597 }
598
599 /**
600 * Splits HTML content and returns an associative array, with title, a list of metatags, and a list of words in the body.
601 *
602 * @param string $content HTML content to index. To some degree expected to be made by TYPO3 (ei. splitting the header by ":")
603 * @return array Array of content, having keys "title", "body", "keywords" and "description" set.
604 * @see splitRegularContent()
605 */
606 public function splitHTMLContent($content)
607 {
608 // divide head from body ( u-ouh :) )
609 $contentArr = $this->defaultContentArray;
610 $contentArr['body'] = stristr($content, '<body');
611 $headPart = substr($content, 0, -strlen($contentArr['body']));
612 // get title
613 $this->embracingTags($headPart, 'TITLE', $contentArr['title'], $dummy2, $dummy);
614 $titleParts = explode(':', $contentArr['title'], 2);
615 $contentArr['title'] = trim(isset($titleParts[1]) ? $titleParts[1] : $titleParts[0]);
616 // get keywords and description metatags
617 if ($this->conf['index_metatags']) {
618 $meta = [];
619 $i = 0;
620 while ($this->embracingTags($headPart, 'meta', $dummy, $headPart, $meta[$i])) {
621 $i++;
622 }
623 // @todo The code below stops at first unset tag. Is that correct?
624 for ($i = 0; isset($meta[$i]); $i++) {
625 $meta[$i] = GeneralUtility::get_tag_attributes($meta[$i]);
626 if (stristr($meta[$i]['name'], 'keywords')) {
627 $contentArr['keywords'] .= ',' . $this->addSpacesToKeywordList($meta[$i]['content']);
628 }
629 if (stristr($meta[$i]['name'], 'description')) {
630 $contentArr['description'] .= ',' . $meta[$i]['content'];
631 }
632 }
633 }
634 // Process <!--TYPO3SEARCH_begin--> or <!--TYPO3SEARCH_end--> tags:
635 $this->typoSearchTags($contentArr['body']);
636 // Get rid of unwanted sections (ie. scripting and style stuff) in body
637 $tagList = explode(',', $this->excludeSections);
638 foreach ($tagList as $tag) {
639 while ($this->embracingTags($contentArr['body'], $tag, $dummy, $contentArr['body'], $dummy2)) {
640 }
641 }
642 // remove tags, but first make sure we don't concatenate words by doing it
643 $contentArr['body'] = str_replace('<', ' <', $contentArr['body']);
644 $contentArr['body'] = trim(strip_tags($contentArr['body']));
645 $contentArr['keywords'] = trim($contentArr['keywords']);
646 $contentArr['description'] = trim($contentArr['description']);
647 // Return array
648 return $contentArr;
649 }
650
651 /**
652 * Extract the charset value from HTML meta tag.
653 *
654 * @param string $content HTML content
655 * @return string The charset value if found.
656 */
657 public function getHTMLcharset($content)
658 {
659 if (preg_match('/<meta[[:space:]]+[^>]*http-equiv[[:space:]]*=[[:space:]]*["\']CONTENT-TYPE["\'][^>]*>/i', $content, $reg)) {
660 if (preg_match('/charset[[:space:]]*=[[:space:]]*([[:alnum:]-]+)/i', $reg[0], $reg2)) {
661 return $reg2[1];
662 }
663 }
664 }
665
666 /**
667 * Converts a HTML document to utf-8
668 *
669 * @param string $content HTML content, any charset
670 * @param string $charset Optional charset (otherwise extracted from HTML)
671 * @return string Converted HTML
672 */
673 public function convertHTMLToUtf8($content, $charset = '')
674 {
675 // Find charset:
676 $charset = $charset ?: $this->getHTMLcharset($content);
677 $charset = trim(strtolower($charset));
678 // Convert charset:
679 if ($charset && $charset !== 'utf-8') {
680 $content = mb_convert_encoding($content, 'utf-8', $charset);
681 }
682 // Convert entities, assuming document is now UTF-8:
683 return html_entity_decode($content);
684 }
685
686 /**
687 * Finds first occurrence of embracing tags and returns the embraced content and the original string with
688 * the tag removed in the two passed variables. Returns FALSE if no match found. ie. useful for finding
689 * <title> of document or removing <script>-sections
690 *
691 * @param string $string String to search in
692 * @param string $tagName Tag name, eg. "script
693 * @param string $tagContent Passed by reference: Content inside found tag
694 * @param string $stringAfter Passed by reference: Content after found tag
695 * @param string $paramList Passed by reference: Attributes of the found tag.
696 * @return bool Returns FALSE if tag was not found, otherwise TRUE.
697 */
698 public function embracingTags($string, $tagName, &$tagContent, &$stringAfter, &$paramList)
699 {
700 $endTag = '</' . $tagName . '>';
701 $startTag = '<' . $tagName;
702 // stristr used because we want a case-insensitive search for the tag.
703 $isTagInText = stristr($string, $startTag);
704 // if the tag was not found, return FALSE
705 if (!$isTagInText) {
706 return false;
707 }
708 list($paramList, $isTagInText) = explode('>', substr($isTagInText, strlen($startTag)), 2);
709 $afterTagInText = stristr($isTagInText, $endTag);
710 if ($afterTagInText) {
711 $stringBefore = substr($string, 0, strpos(strtolower($string), strtolower($startTag)));
712 $tagContent = substr($isTagInText, 0, strlen($isTagInText) - strlen($afterTagInText));
713 $stringAfter = $stringBefore . substr($afterTagInText, strlen($endTag));
714 } else {
715 $tagContent = '';
716 $stringAfter = $isTagInText;
717 }
718 return true;
719 }
720
721 /**
722 * Removes content that shouldn't be indexed according to TYPO3SEARCH-tags.
723 *
724 * @param string $body HTML Content, passed by reference
725 * @return bool Returns TRUE if a TYPOSEARCH_ tag was found, otherwise FALSE.
726 */
727 public function typoSearchTags(&$body)
728 {
729 $expBody = preg_split('/\\<\\!\\-\\-[\\s]?TYPO3SEARCH_/', $body);
730 if (count($expBody) > 1) {
731 $body = '';
732 foreach ($expBody as $val) {
733 $part = explode('-->', $val, 2);
734 if (trim($part[0]) === 'begin') {
735 $body .= $part[1];
736 $prev = '';
737 } elseif (trim($part[0]) === 'end') {
738 $body .= $prev;
739 } else {
740 $prev = $val;
741 }
742 }
743 return true;
744 }
745 return false;
746 }
747
748 /**
749 * Extract links (hrefs) from HTML content and if indexable media is found, it is indexed.
750 *
751 * @param string $content HTML content
752 */
753 public function extractLinks($content)
754 {
755 // Get links:
756 $list = $this->extractHyperLinks($content);
757 if ($this->indexerConfig['useCrawlerForExternalFiles'] && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('crawler')) {
758 $crawler = GeneralUtility::makeInstance(\tx_crawler_lib::class);
759 }
760 // Traverse links:
761 foreach ($list as $linkInfo) {
762 // Decode entities:
763 if ($linkInfo['localPath']) {
764 // localPath means: This file is sent by a download script. While the indexed URL has to point to $linkInfo['href'], the absolute path to the file is specified here!
765 $linkSource = htmlspecialchars_decode($linkInfo['localPath']);
766 } else {
767 $linkSource = htmlspecialchars_decode($linkInfo['href']);
768 }
769 // Parse URL:
770 $qParts = parse_url($linkSource);
771 // Check for jumpurl (TYPO3 specific thing...)
772 if ($qParts['query'] && strstr($qParts['query'], 'jumpurl=')) {
773 parse_str($qParts['query'], $getP);
774 $linkSource = $getP['jumpurl'];
775 $qParts = parse_url($linkSource);
776 }
777 if (!$linkInfo['localPath'] && $qParts['scheme']) {
778 if ($this->indexerConfig['indexExternalURLs']) {
779 // Index external URL (http or otherwise)
780 $this->indexExternalUrl($linkSource);
781 }
782 } elseif (!$qParts['query']) {
783 $linkSource = urldecode($linkSource);
784 if (GeneralUtility::isAllowedAbsPath($linkSource)) {
785 $localFile = $linkSource;
786 } else {
787 $localFile = GeneralUtility::getFileAbsFileName(PATH_site . $linkSource);
788 }
789 if ($localFile && @is_file($localFile)) {
790 // Index local file:
791 if ($linkInfo['localPath']) {
792 $fI = pathinfo($linkSource);
793 $ext = strtolower($fI['extension']);
794 if (is_object($crawler)) {
795 $params = [
796 'document' => $linkSource,
797 'alturl' => $linkInfo['href'],
798 'conf' => $this->conf
799 ];
800 unset($params['conf']['content']);
801 $crawler->addQueueEntry_callBack(0, $params, Hook\CrawlerFilesHook::class, $this->conf['id']);
802 $this->log_setTSlogMessage('media "' . $params['document'] . '" added to "crawler" queue.', 1);
803 } else {
804 $this->indexRegularDocument($linkInfo['href'], false, $linkSource, $ext);
805 }
806 } else {
807 if (is_object($crawler)) {
808 $params = [
809 'document' => $linkSource,
810 'conf' => $this->conf
811 ];
812 unset($params['conf']['content']);
813 $crawler->addQueueEntry_callBack(0, $params, Hook\CrawlerFilesHook::class, $this->conf['id']);
814 $this->log_setTSlogMessage('media "' . $params['document'] . '" added to "crawler" queue.', 1);
815 } else {
816 $this->indexRegularDocument($linkSource);
817 }
818 }
819 }
820 }
821 }
822 }
823
824 /**
825 * Extracts all links to external documents from the HTML content string
826 *
827 * @param string $html
828 * @return array Array of hyperlinks (keys: tag, href, localPath (empty if not local))
829 * @see extractLinks()
830 */
831 public function extractHyperLinks($html)
832 {
833 $htmlParser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Html\HtmlParser::class);
834 $htmlParts = $htmlParser->splitTags('a', $html);
835 $hyperLinksData = [];
836 foreach ($htmlParts as $index => $tagData) {
837 if ($index % 2 !== 0) {
838 $tagAttributes = $htmlParser->get_tag_attributes($tagData, true);
839 $firstTagName = $htmlParser->getFirstTagName($tagData);
840 if (strtolower($firstTagName) === 'a') {
841 if ($tagAttributes[0]['href'] && $tagAttributes[0]['href'][0] !== '#') {
842 $hyperLinksData[] = [
843 'tag' => $tagData,
844 'href' => $tagAttributes[0]['href'],
845 'localPath' => $this->createLocalPath($tagAttributes[0]['href'])
846 ];
847 }
848 }
849 }
850 }
851 return $hyperLinksData;
852 }
853
854 /**
855 * Extracts the "base href" from content string.
856 *
857 * @param string $html Content to analyze
858 * @return string The base href or an empty string if not found
859 */
860 public function extractBaseHref($html)
861 {
862 $href = '';
863 $htmlParser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Html\HtmlParser::class);
864 $htmlParts = $htmlParser->splitTags('base', $html);
865 foreach ($htmlParts as $index => $tagData) {
866 if ($index % 2 !== 0) {
867 $tagAttributes = $htmlParser->get_tag_attributes($tagData, true);
868 $firstTagName = $htmlParser->getFirstTagName($tagData);
869 if (strtolower($firstTagName) === 'base') {
870 $href = $tagAttributes[0]['href'];
871 if ($href) {
872 break;
873 }
874 }
875 }
876 }
877 return $href;
878 }
879
880 /******************************************
881 *
882 * Indexing; external URL
883 *
884 ******************************************/
885 /**
886 * Index External URLs HTML content
887 *
888 * @param string $externalUrl URL, eg. "http://typo3.org/
889 * @see indexRegularDocument()
890 */
891 public function indexExternalUrl($externalUrl)
892 {
893 // Get headers:
894 $urlHeaders = $this->getUrlHeaders($externalUrl);
895 if (stristr($urlHeaders['Content-Type'], 'text/html')) {
896 $content = ($this->indexExternalUrl_content = GeneralUtility::getUrl($externalUrl));
897 if ((string)$content !== '') {
898 // Create temporary file:
899 $tmpFile = GeneralUtility::tempnam('EXTERNAL_URL');
900 if ($tmpFile) {
901 GeneralUtility::writeFile($tmpFile, $content);
902 // Index that file:
903 $this->indexRegularDocument($externalUrl, true, $tmpFile, 'html');
904 // Using "TRUE" for second parameter to force indexing of external URLs (mtime doesn't make sense, does it?)
905 unlink($tmpFile);
906 }
907 }
908 }
909 }
910
911 /**
912 * Getting HTTP request headers of URL
913 *
914 * @param string $url The URL
915 * @return mixed If no answer, returns FALSE. Otherwise an array where HTTP headers are keys
916 */
917 public function getUrlHeaders($url)
918 {
919 // Try to get the headers only
920 $content = GeneralUtility::getUrl($url, 2);
921 if ((string)$content !== '') {
922 // Compile headers:
923 $headers = GeneralUtility::trimExplode(LF, $content, true);
924 $retVal = [];
925 foreach ($headers as $line) {
926 if (trim($line) === '') {
927 break;
928 }
929 list($headKey, $headValue) = explode(':', $line, 2);
930 $retVal[$headKey] = $headValue;
931 }
932 return $retVal;
933 }
934 }
935
936 /**
937 * Checks if the file is local
938 *
939 * @param string $sourcePath
940 * @return string Absolute path to file if file is local, else empty string
941 */
942 protected function createLocalPath($sourcePath)
943 {
944 $localPath = '';
945 static $pathFunctions = [
946 'createLocalPathFromT3vars',
947 'createLocalPathUsingAbsRefPrefix',
948 'createLocalPathUsingDomainURL',
949 'createLocalPathFromAbsoluteURL',
950 'createLocalPathFromRelativeURL'
951 ];
952 foreach ($pathFunctions as $functionName) {
953 $localPath = $this->{$functionName}($sourcePath);
954 if ($localPath != '') {
955 break;
956 }
957 }
958 return $localPath;
959 }
960
961 /**
962 * Attempts to create a local file path from T3VARs. This is useful for
963 * various download extensions that hide actual file name but still want the
964 * file to be indexed.
965 *
966 * @param string $sourcePath
967 * @return string
968 */
969 protected function createLocalPathFromT3vars($sourcePath)
970 {
971 $localPath = '';
972 $indexLocalFiles = $GLOBALS['T3_VAR']['ext']['indexed_search']['indexLocalFiles'];
973 if (is_array($indexLocalFiles)) {
974 $md5 = GeneralUtility::shortMD5($sourcePath);
975 // Note: not using self::isAllowedLocalFile here because this method
976 // is allowed to index files outside of the web site (for example,
977 // protected downloads)
978 if (isset($indexLocalFiles[$md5]) && is_file($indexLocalFiles[$md5])) {
979 $localPath = $indexLocalFiles[$md5];
980 }
981 }
982 return $localPath;
983 }
984
985 /**
986 * Attempts to create a local file path by matching a current request URL.
987 *
988 * @param string $sourcePath
989 * @return string
990 */
991 protected function createLocalPathUsingDomainURL($sourcePath)
992 {
993 $localPath = '';
994 $baseURL = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
995 $baseURLLength = strlen($baseURL);
996 if (substr($sourcePath, 0, $baseURLLength) == $baseURL) {
997 $sourcePath = substr($sourcePath, $baseURLLength);
998 $localPath = PATH_site . $sourcePath;
999 if (!self::isAllowedLocalFile($localPath)) {
1000 $localPath = '';
1001 }
1002 }
1003 return $localPath;
1004 }
1005
1006 /**
1007 * Attempts to create a local file path by matching absRefPrefix. This
1008 * requires TSFE. If TSFE is missing, this function does nothing.
1009 *
1010 * @param string $sourcePath
1011 * @return string
1012 */
1013 protected function createLocalPathUsingAbsRefPrefix($sourcePath)
1014 {
1015 $localPath = '';
1016 if ($GLOBALS['TSFE'] instanceof \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController) {
1017 $absRefPrefix = $GLOBALS['TSFE']->config['config']['absRefPrefix'];
1018 $absRefPrefixLength = strlen($absRefPrefix);
1019 if ($absRefPrefixLength > 0 && substr($sourcePath, 0, $absRefPrefixLength) == $absRefPrefix) {
1020 $sourcePath = substr($sourcePath, $absRefPrefixLength);
1021 $localPath = PATH_site . $sourcePath;
1022 if (!self::isAllowedLocalFile($localPath)) {
1023 $localPath = '';
1024 }
1025 }
1026 }
1027 return $localPath;
1028 }
1029
1030 /**
1031 * Attempts to create a local file path from the absolute URL without
1032 * schema.
1033 *
1034 * @param string $sourcePath
1035 * @return string
1036 */
1037 protected function createLocalPathFromAbsoluteURL($sourcePath)
1038 {
1039 $localPath = '';
1040 if ($sourcePath[0] === '/') {
1041 $sourcePath = substr($sourcePath, 1);
1042 $localPath = PATH_site . $sourcePath;
1043 if (!self::isAllowedLocalFile($localPath)) {
1044 $localPath = '';
1045 }
1046 }
1047 return $localPath;
1048 }
1049
1050 /**
1051 * Attempts to create a local file path from the relative URL.
1052 *
1053 * @param string $sourcePath
1054 * @return string
1055 */
1056 protected function createLocalPathFromRelativeURL($sourcePath)
1057 {
1058 $localPath = '';
1059 if (self::isRelativeURL($sourcePath)) {
1060 $localPath = PATH_site . $sourcePath;
1061 if (!self::isAllowedLocalFile($localPath)) {
1062 $localPath = '';
1063 }
1064 }
1065 return $localPath;
1066 }
1067
1068 /**
1069 * Checks if URL is relative.
1070 *
1071 * @param string $url
1072 * @return bool
1073 */
1074 protected static function isRelativeURL($url)
1075 {
1076 $urlParts = @parse_url($url);
1077 return $urlParts['scheme'] == '' && $urlParts['path'][0] !== '/';
1078 }
1079
1080 /**
1081 * Checks if the path points to the file inside the web site
1082 *
1083 * @param string $filePath
1084 * @return bool
1085 */
1086 protected static function isAllowedLocalFile($filePath)
1087 {
1088 $filePath = GeneralUtility::resolveBackPath($filePath);
1089 $insideWebPath = substr($filePath, 0, strlen(PATH_site)) == PATH_site;
1090 $isFile = is_file($filePath);
1091 return $insideWebPath && $isFile;
1092 }
1093
1094 /******************************************
1095 *
1096 * Indexing; external files (PDF, DOC, etc)
1097 *
1098 ******************************************/
1099 /**
1100 * Indexing a regular document given as $file (relative to PATH_site, local file)
1101 *
1102 * @param string $file Relative Filename, relative to PATH_site. It can also be an absolute path as long as it is inside the lockRootPath (validated with \TYPO3\CMS\Core\Utility\GeneralUtility::isAbsPath()). Finally, if $contentTmpFile is set, this value can be anything, most likely a URL
1103 * @param bool $force If set, indexing is forced (despite content hashes, mtime etc).
1104 * @param string $contentTmpFile Temporary file with the content to read it from (instead of $file). Used when the $file is a URL.
1105 * @param string $altExtension File extension for temporary file.
1106 */
1107 public function indexRegularDocument($file, $force = false, $contentTmpFile = '', $altExtension = '')
1108 {
1109 // Init
1110 $fI = pathinfo($file);
1111 $ext = $altExtension ?: strtolower($fI['extension']);
1112 // Create abs-path:
1113 if (!$contentTmpFile) {
1114 if (!GeneralUtility::isAbsPath($file)) {
1115 // Relative, prepend PATH_site:
1116 $absFile = GeneralUtility::getFileAbsFileName(PATH_site . $file);
1117 } else {
1118 // Absolute, pass-through:
1119 $absFile = $file;
1120 }
1121 $absFile = GeneralUtility::isAllowedAbsPath($absFile) ? $absFile : '';
1122 } else {
1123 $absFile = $contentTmpFile;
1124 }
1125 // Indexing the document:
1126 if ($absFile && @is_file($absFile)) {
1127 if ($this->external_parsers[$ext]) {
1128 $fileInfo = stat($absFile);
1129 $cParts = $this->fileContentParts($ext, $absFile);
1130 foreach ($cParts as $cPKey) {
1131 $this->internal_log = [];
1132 $this->log_push('Index: ' . str_replace('.', '_', basename($file)) . ($cPKey ? '#' . $cPKey : ''), '');
1133 $Pstart = GeneralUtility::milliseconds();
1134 $subinfo = ['key' => $cPKey];
1135 // Setting page range. This is "0" (zero) when no division is made, otherwise a range like "1-3"
1136 $phash_arr = ($this->file_phash_arr = $this->setExtHashes($file, $subinfo));
1137 $check = $this->checkMtimeTstamp($fileInfo['mtime'], $phash_arr['phash']);
1138 if ($check > 0 || $force) {
1139 if ($check > 0) {
1140 $this->log_setTSlogMessage('Indexing needed, reason: ' . $this->reasons[$check], 1);
1141 } else {
1142 $this->log_setTSlogMessage('Indexing forced by flag', 1);
1143 }
1144 // Check external file counter:
1145 if ($this->externalFileCounter < $this->maxExternalFiles || $force) {
1146 // Divide into title,keywords,description and body:
1147 $this->log_push('Split content', '');
1148 $contentParts = $this->readFileContent($ext, $absFile, $cPKey);
1149 $this->log_pull();
1150 if (is_array($contentParts)) {
1151 // Calculating a hash over what is to be the actual content. (see indexTypo3PageContent())
1152 $content_md5h = IndexedSearchUtility::md5inthash(implode($contentParts, ''));
1153 if ($this->checkExternalDocContentHash($phash_arr['phash_grouping'], $content_md5h) || $force) {
1154 // Increment counter:
1155 $this->externalFileCounter++;
1156 // Splitting words
1157 $this->log_push('Extract words from content', '');
1158 $splitInWords = $this->processWordsInArrays($contentParts);
1159 $this->log_pull();
1160 // Analyse the indexed words.
1161 $this->log_push('Analyse the extracted words', '');
1162 $indexArr = $this->indexAnalyze($splitInWords);
1163 $this->log_pull();
1164 // Submitting page (phash) record
1165 $this->log_push('Submitting page', '');
1166 // Unfortunately I cannot determine WHEN a file is originally made - so I must return the modification time...
1167 $this->submitFilePage($phash_arr, $file, $subinfo, $ext, $fileInfo['mtime'], $fileInfo['ctime'], $fileInfo['size'], $content_md5h, $contentParts);
1168 $this->log_pull();
1169 // Check words and submit to word list if not there
1170 $this->log_push('Check word list and submit words', '');
1171 if (IndexedSearchUtility::isTableUsed('index_words')) {
1172 $this->checkWordList($indexArr);
1173 $this->submitWords($indexArr, $phash_arr['phash']);
1174 }
1175 $this->log_pull();
1176 // Set parsetime
1177 $this->updateParsetime($phash_arr['phash'], GeneralUtility::milliseconds() - $Pstart);
1178 } else {
1179 // Update the timestamp
1180 $this->updateTstamp($phash_arr['phash'], $fileInfo['mtime']);
1181 $this->log_setTSlogMessage('Indexing not needed, the contentHash, ' . $content_md5h . ', has not changed. Timestamp updated.');
1182 }
1183 } else {
1184 $this->log_setTSlogMessage('Could not index file! Unsupported extension.');
1185 }
1186 } else {
1187 $this->log_setTSlogMessage('The limit of ' . $this->maxExternalFiles . ' has already been exceeded, so no indexing will take place this time.');
1188 }
1189 } else {
1190 $this->log_setTSlogMessage('Indexing not needed, reason: ' . $this->reasons[$check]);
1191 }
1192 // Checking and setting sections:
1193 $this->submitFile_section($phash_arr['phash']);
1194 // Setting a section-record for the file. This is done also if the file is not indexed. Notice that section records are deleted when the page is indexed.
1195 $this->log_pull();
1196 }
1197 } else {
1198 $this->log_setTSlogMessage('Indexing not possible; The extension "' . $ext . '" was not supported.');
1199 }
1200 } else {
1201 $this->log_setTSlogMessage('Indexing not possible; File "' . $absFile . '" not found or valid.');
1202 }
1203 }
1204
1205 /**
1206 * Reads the content of an external file being indexed.
1207 * The content from the external parser MUST be returned in utf-8!
1208 *
1209 * @param string $fileExtension File extension, eg. "pdf", "doc" etc.
1210 * @param string $absoluteFileName Absolute filename of file (must exist and be validated OK before calling function)
1211 * @param string $sectionPointer Pointer to section (zero for all other than PDF which will have an indication of pages into which the document should be splitted.)
1212 * @return array Standard content array (title, description, keywords, body keys)
1213 */
1214 public function readFileContent($fileExtension, $absoluteFileName, $sectionPointer)
1215 {
1216 $contentArray = null;
1217 // Consult relevant external document parser:
1218 if (is_object($this->external_parsers[$fileExtension])) {
1219 $contentArray = $this->external_parsers[$fileExtension]->readFileContent($fileExtension, $absoluteFileName, $sectionPointer);
1220 }
1221 return $contentArray;
1222 }
1223
1224 /**
1225 * Creates an array with pointers to divisions of document.
1226 *
1227 * @param string $ext File extension
1228 * @param string $absFile Absolute filename (must exist and be validated OK before calling function)
1229 * @return array Array of pointers to sections that the document should be divided into
1230 */
1231 public function fileContentParts($ext, $absFile)
1232 {
1233 $cParts = [0];
1234 // Consult relevant external document parser:
1235 if (is_object($this->external_parsers[$ext])) {
1236 $cParts = $this->external_parsers[$ext]->fileContentParts($ext, $absFile);
1237 }
1238 return $cParts;
1239 }
1240
1241 /**
1242 * Splits non-HTML content (from external files for instance)
1243 *
1244 * @param string $content Input content (non-HTML) to index.
1245 * @return array Array of content, having the key "body" set (plus "title", "description" and "keywords", but empty)
1246 * @see splitHTMLContent()
1247 */
1248 public function splitRegularContent($content)
1249 {
1250 $contentArr = $this->defaultContentArray;
1251 $contentArr['body'] = $content;
1252 return $contentArr;
1253 }
1254
1255 /**********************************
1256 *
1257 * Analysing content, Extracting words
1258 *
1259 **********************************/
1260 /**
1261 * Convert character set and HTML entities in the value of input content array keys
1262 *
1263 * @param array $contentArr Standard content array
1264 * @param string $charset Charset of the input content (converted to utf-8)
1265 */
1266 public function charsetEntity2utf8(&$contentArr, $charset)
1267 {
1268 // Convert charset if necessary
1269 foreach ($contentArr as $key => $value) {
1270 if ((string)$contentArr[$key] !== '') {
1271 if ($charset !== 'utf-8') {
1272 $contentArr[$key] = mb_convert_encoding($contentArr[$key], 'utf-8', $charset);
1273 }
1274 // decode all numeric / html-entities in the string to real characters:
1275 $contentArr[$key] = html_entity_decode($contentArr[$key]);
1276 }
1277 }
1278 }
1279
1280 /**
1281 * Processing words in the array from split*Content -functions
1282 *
1283 * @param array $contentArr Array of content to index, see splitHTMLContent() and splitRegularContent()
1284 * @return array Content input array modified so each key is not a unique array of words
1285 */
1286 public function processWordsInArrays($contentArr)
1287 {
1288 // split all parts to words
1289 foreach ($contentArr as $key => $value) {
1290 $contentArr[$key] = $this->lexerObj->split2Words($contentArr[$key]);
1291 }
1292 // For title, keywords, and description we don't want duplicates:
1293 $contentArr['title'] = array_unique($contentArr['title']);
1294 $contentArr['keywords'] = array_unique($contentArr['keywords']);
1295 $contentArr['description'] = array_unique($contentArr['description']);
1296 // Return modified array:
1297 return $contentArr;
1298 }
1299
1300 /**
1301 * Extracts the sample description text from the content array.
1302 *
1303 * @param array $contentArr Content array
1304 * @return string Description string
1305 */
1306 public function bodyDescription($contentArr)
1307 {
1308 // Setting description
1309 $maxL = MathUtility::forceIntegerInRange($this->conf['index_descrLgd'], 0, 255, 200);
1310 if ($maxL) {
1311 $bodyDescription = preg_replace('/\s+/u', ' ', $contentArr['body']);
1312 // Shorten the string:
1313 $bodyDescription = mb_strcut($bodyDescription, 0, $maxL, 'utf-8');
1314 }
1315 return $bodyDescription;
1316 }
1317
1318 /**
1319 * Analyzes content to use for indexing,
1320 *
1321 * @param array $content Standard content array: an array with the keys title,keywords,description and body, which all contain an array of words.
1322 * @return array Index Array (whatever that is...)
1323 */
1324 public function indexAnalyze($content)
1325 {
1326 $indexArr = [];
1327 $this->analyzeHeaderinfo($indexArr, $content, 'title', 7);
1328 $this->analyzeHeaderinfo($indexArr, $content, 'keywords', 6);
1329 $this->analyzeHeaderinfo($indexArr, $content, 'description', 5);
1330 $this->analyzeBody($indexArr, $content);
1331 return $indexArr;
1332 }
1333
1334 /**
1335 * Calculates relevant information for headercontent
1336 *
1337 * @param array $retArr Index array, passed by reference
1338 * @param array $content Standard content array
1339 * @param string $key Key from standard content array
1340 * @param int $offset Bit-wise priority to type
1341 */
1342 public function analyzeHeaderinfo(&$retArr, $content, $key, $offset)
1343 {
1344 foreach ($content[$key] as $val) {
1345 $val = substr($val, 0, 60);
1346 // Cut after 60 chars because the index_words.baseword varchar field has this length. This MUST be the same.
1347 if (!isset($retArr[$val])) {
1348 // Word ID (wid)
1349 $retArr[$val]['hash'] = IndexedSearchUtility::md5inthash($val);
1350 // Metaphone value is also 60 only chars long
1351 $metaphone = $this->enableMetaphoneSearch ? substr($this->metaphone($val, $this->storeMetaphoneInfoAsWords), 0, 60) : '';
1352 $retArr[$val]['metaphone'] = $metaphone;
1353 }
1354 // Build metaphone fulltext string (can be used for fulltext indexing)
1355 if ($this->storeMetaphoneInfoAsWords) {
1356 $this->metaphoneContent .= ' ' . $retArr[$val]['metaphone'];
1357 }
1358 // Priority used for flagBitMask feature (see extension configuration)
1359 $retArr[$val]['cmp'] = $retArr[$val]['cmp'] | pow(2, $offset);
1360 // Increase number of occurrences
1361 $retArr[$val]['count']++;
1362 $this->wordcount++;
1363 }
1364 }
1365
1366 /**
1367 * Calculates relevant information for bodycontent
1368 *
1369 * @param array $retArr Index array, passed by reference
1370 * @param array $content Standard content array
1371 */
1372 public function analyzeBody(&$retArr, $content)
1373 {
1374 foreach ($content['body'] as $key => $val) {
1375 $val = substr($val, 0, 60);
1376 // Cut after 60 chars because the index_words.baseword varchar field has this length. This MUST be the same.
1377 if (!isset($retArr[$val])) {
1378 // First occurrence (used for ranking results)
1379 $retArr[$val]['first'] = $key;
1380 // Word ID (wid)
1381 $retArr[$val]['hash'] = IndexedSearchUtility::md5inthash($val);
1382 // Metaphone value is also only 60 chars long
1383 $metaphone = $this->enableMetaphoneSearch ? substr($this->metaphone($val, $this->storeMetaphoneInfoAsWords), 0, 60) : '';
1384 $retArr[$val]['metaphone'] = $metaphone;
1385 }
1386 // Build metaphone fulltext string (can be used for fulltext indexing)
1387 if ($this->storeMetaphoneInfoAsWords) {
1388 $this->metaphoneContent .= ' ' . $retArr[$val]['metaphone'];
1389 }
1390 // Increase number of occurrences
1391 $retArr[$val]['count']++;
1392 $this->wordcount++;
1393 }
1394 }
1395
1396 /**
1397 * Creating metaphone based hash from input word
1398 *
1399 * @param string $word Word to convert
1400 * @param bool $returnRawMetaphoneValue If set, returns the raw metaphone value (not hashed)
1401 * @return mixed Metaphone hash integer (or raw value, string)
1402 */
1403 public function metaphone($word, $returnRawMetaphoneValue = false)
1404 {
1405 if (is_object($this->metaphoneObj)) {
1406 $metaphoneRawValue = $this->metaphoneObj->metaphone($word, $this->conf['sys_language_uid']);
1407 } else {
1408 // Use native PHP function instead of advanced doubleMetaphone class
1409 $metaphoneRawValue = metaphone($word);
1410 }
1411 if ($returnRawMetaphoneValue) {
1412 $result = $metaphoneRawValue;
1413 } elseif ($metaphoneRawValue !== '') {
1414 // Create hash and return integer
1415 $result = IndexedSearchUtility::md5inthash($metaphoneRawValue);
1416 } else {
1417 $result = 0;
1418 }
1419 return $result;
1420 }
1421
1422 /********************************
1423 *
1424 * SQL; TYPO3 Pages
1425 *
1426 *******************************/
1427 /**
1428 * Updates db with information about the page (TYPO3 page, not external media)
1429 */
1430 public function submitPage()
1431 {
1432 // Remove any current data for this phash:
1433 $this->removeOldIndexedPages($this->hash['phash']);
1434 // setting new phash_row
1435 $fields = [
1436 'phash' => $this->hash['phash'],
1437 'phash_grouping' => $this->hash['phash_grouping'],
1438 'cHashParams' => serialize($this->cHashParams),
1439 'contentHash' => $this->content_md5h,
1440 'data_page_id' => $this->conf['id'],
1441 'data_page_reg1' => $this->conf['page_cache_reg1'],
1442 'data_page_type' => $this->conf['type'],
1443 'data_page_mp' => $this->conf['MP'],
1444 'gr_list' => $this->conf['gr_list'],
1445 'item_type' => 0,
1446 // TYPO3 page
1447 'item_title' => $this->contentParts['title'],
1448 'item_description' => $this->bodyDescription($this->contentParts),
1449 'item_mtime' => (int)$this->conf['mtime'],
1450 'item_size' => strlen($this->conf['content']),
1451 'tstamp' => $GLOBALS['EXEC_TIME'],
1452 'crdate' => $GLOBALS['EXEC_TIME'],
1453 'item_crdate' => $this->conf['crdate'],
1454 // Creation date of page
1455 'sys_language_uid' => $this->conf['sys_language_uid'],
1456 // Sys language uid of the page. Should reflect which language it DOES actually display!
1457 'externalUrl' => 0,
1458 'recordUid' => (int)$this->conf['recordUid'],
1459 'freeIndexUid' => (int)$this->conf['freeIndexUid'],
1460 'freeIndexSetId' => (int)$this->conf['freeIndexSetId']
1461 ];
1462 if (IndexedSearchUtility::isTableUsed('index_phash')) {
1463 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1464 ->getConnectionForTable('index_phash');
1465 $connection->insert(
1466 'index_phash',
1467 $fields,
1468 ['cHashParams' => Connection::PARAM_LOB]
1469 );
1470 }
1471 // PROCESSING index_section
1472 $this->submit_section($this->hash['phash'], $this->hash['phash']);
1473 // PROCESSING index_grlist
1474 $this->submit_grlist($this->hash['phash'], $this->hash['phash']);
1475 // PROCESSING index_fulltext
1476 $fields = [
1477 'phash' => $this->hash['phash'],
1478 'fulltextdata' => implode(' ', $this->contentParts),
1479 'metaphonedata' => $this->metaphoneContent
1480 ];
1481 if ($this->indexerConfig['fullTextDataLength'] > 0) {
1482 $fields['fulltextdata'] = substr($fields['fulltextdata'], 0, $this->indexerConfig['fullTextDataLength']);
1483 }
1484 if (IndexedSearchUtility::isTableUsed('index_fulltext')) {
1485 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1486 ->getConnectionForTable('index_fulltext');
1487 $connection->insert('index_fulltext', $fields);
1488 }
1489 // PROCESSING index_debug
1490 if ($this->indexerConfig['debugMode']) {
1491 $fields = [
1492 'phash' => $this->hash['phash'],
1493 'debuginfo' => serialize([
1494 'cHashParams' => $this->cHashParams,
1495 'external_parsers initialized' => array_keys($this->external_parsers),
1496 'conf' => array_merge($this->conf, ['content' => substr($this->conf['content'], 0, 1000)]),
1497 'contentParts' => array_merge($this->contentParts, ['body' => substr($this->contentParts['body'], 0, 1000)]),
1498 'logs' => $this->internal_log,
1499 'lexer' => $this->lexerObj->debugString
1500 ])
1501 ];
1502 if (IndexedSearchUtility::isTableUsed('index_debug')) {
1503 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1504 ->getConnectionForTable('index_debug');
1505 $connection->insert('index_debug', $fields);
1506 }
1507 }
1508 }
1509
1510 /**
1511 * Stores gr_list in the database.
1512 *
1513 * @param int $hash Search result record phash
1514 * @param int $phash_x Actual phash of current content
1515 * @see update_grlist()
1516 */
1517 public function submit_grlist($hash, $phash_x)
1518 {
1519 // Setting the gr_list record
1520 $fields = [
1521 'phash' => $hash,
1522 'phash_x' => $phash_x,
1523 'hash_gr_list' => IndexedSearchUtility::md5inthash($this->conf['gr_list']),
1524 'gr_list' => $this->conf['gr_list']
1525 ];
1526 if (IndexedSearchUtility::isTableUsed('index_grlist')) {
1527 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1528 ->getConnectionForTable('index_grlist');
1529 $connection->insert('index_grlist', $fields);
1530 }
1531 }
1532
1533 /**
1534 * Stores section
1535 * $hash and $hash_t3 are the same for TYPO3 pages, but different when it is external files.
1536 *
1537 * @param int $hash phash of TYPO3 parent search result record
1538 * @param int $hash_t3 phash of the file indexation search record
1539 */
1540 public function submit_section($hash, $hash_t3)
1541 {
1542 $fields = [
1543 'phash' => $hash,
1544 'phash_t3' => $hash_t3,
1545 'page_id' => (int)$this->conf['id']
1546 ];
1547 $this->getRootLineFields($fields);
1548 if (IndexedSearchUtility::isTableUsed('index_section')) {
1549 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1550 ->getConnectionForTable('index_section');
1551 $connection->insert('index_section', $fields);
1552 }
1553 }
1554
1555 /**
1556 * Removes records for the indexed page, $phash
1557 *
1558 * @param int $phash phash value to flush
1559 */
1560 public function removeOldIndexedPages($phash)
1561 {
1562 // Removing old registrations for all tables. Because the pages are TYPO3 pages
1563 // there can be nothing else than 1-1 relations here.
1564 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1565 $tableArray = ['index_phash', 'index_section', 'index_grlist', 'index_fulltext', 'index_debug'];
1566 foreach ($tableArray as $table) {
1567 if (IndexedSearchUtility::isTableUsed($table)) {
1568 $connectionPool->getConnectionForTable($table)->delete($table, ['phash' => (int)$phash]);
1569 }
1570 }
1571
1572 // Removing all index_section records with hash_t3 set to this hash (this includes such
1573 // records set for external media on the page as well!). The re-insert of these records
1574 // are done in indexRegularDocument($file).
1575 if (IndexedSearchUtility::isTableUsed('index_section')) {
1576 $connectionPool->getConnectionForTable('index_section')
1577 ->delete('index_section', ['phash_t3' => (int)$phash]);
1578 }
1579 }
1580
1581 /********************************
1582 *
1583 * SQL; External media
1584 *
1585 *******************************/
1586 /**
1587 * Updates db with information about the file
1588 *
1589 * @param array $hash Array with phash and phash_grouping keys for file
1590 * @param string $file File name
1591 * @param array $subinfo Array of "cHashParams" for files: This is for instance the page index for a PDF file (other document types it will be a zero)
1592 * @param string $ext File extension determining the type of media.
1593 * @param int $mtime Modification time of file.
1594 * @param int $ctime Creation time of file.
1595 * @param int $size Size of file in bytes
1596 * @param int $content_md5h Content HASH value.
1597 * @param array $contentParts Standard content array (using only title and body for a file)
1598 */
1599 public function submitFilePage($hash, $file, $subinfo, $ext, $mtime, $ctime, $size, $content_md5h, $contentParts)
1600 {
1601 // Find item Type:
1602 $storeItemType = $this->external_parsers[$ext]->ext2itemtype_map[$ext];
1603 $storeItemType = $storeItemType ?: $ext;
1604 // Remove any current data for this phash:
1605 $this->removeOldIndexedFiles($hash['phash']);
1606 // Split filename:
1607 $fileParts = parse_url($file);
1608 // Setting new
1609 $fields = [
1610 'phash' => $hash['phash'],
1611 'phash_grouping' => $hash['phash_grouping'],
1612 'cHashParams' => serialize($subinfo),
1613 'contentHash' => $content_md5h,
1614 'data_filename' => $file,
1615 'item_type' => $storeItemType,
1616 'item_title' => trim($contentParts['title']) ?: basename($file),
1617 'item_description' => $this->bodyDescription($contentParts),
1618 'item_mtime' => $mtime,
1619 'item_size' => $size,
1620 'item_crdate' => $ctime,
1621 'tstamp' => $GLOBALS['EXEC_TIME'],
1622 'crdate' => $GLOBALS['EXEC_TIME'],
1623 'gr_list' => $this->conf['gr_list'],
1624 'externalUrl' => $fileParts['scheme'] ? 1 : 0,
1625 'recordUid' => (int)$this->conf['recordUid'],
1626 'freeIndexUid' => (int)$this->conf['freeIndexUid'],
1627 'freeIndexSetId' => (int)$this->conf['freeIndexSetId'],
1628 'sys_language_uid' => (int)$this->conf['sys_language_uid']
1629 ];
1630 if (IndexedSearchUtility::isTableUsed('index_phash')) {
1631 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1632 ->getConnectionForTable('index_phash');
1633 $connection->insert(
1634 'index_phash',
1635 $fields,
1636 ['cHashParams' => Connection::PARAM_LOB]
1637 );
1638 }
1639 // PROCESSING index_fulltext
1640 $fields = [
1641 'phash' => $hash['phash'],
1642 'fulltextdata' => implode(' ', $contentParts),
1643 'metaphonedata' => $this->metaphoneContent
1644 ];
1645 if ($this->indexerConfig['fullTextDataLength'] > 0) {
1646 $fields['fulltextdata'] = substr($fields['fulltextdata'], 0, $this->indexerConfig['fullTextDataLength']);
1647 }
1648 if (IndexedSearchUtility::isTableUsed('index_fulltext')) {
1649 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1650 ->getConnectionForTable('index_fulltext');
1651 $connection->insert('index_fulltext', $fields);
1652 }
1653 // PROCESSING index_debug
1654 if ($this->indexerConfig['debugMode']) {
1655 $fields = [
1656 'phash' => $hash['phash'],
1657 'debuginfo' => serialize([
1658 'cHashParams' => $subinfo,
1659 'contentParts' => array_merge($contentParts, ['body' => substr($contentParts['body'], 0, 1000)]),
1660 'logs' => $this->internal_log,
1661 'lexer' => $this->lexerObj->debugString
1662 ])
1663 ];
1664 if (IndexedSearchUtility::isTableUsed('index_debug')) {
1665 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1666 ->getConnectionForTable('index_debug');
1667 $connection->insert('index_debug', $fields);
1668 }
1669 }
1670 }
1671
1672 /**
1673 * Stores file gr_list for a file IF it does not exist already
1674 *
1675 * @param int $hash phash value of file
1676 */
1677 public function submitFile_grlist($hash)
1678 {
1679 // Testing if there is a gr_list record for a non-logged in user and if so, there is no need to place another one.
1680 if (!IndexedSearchUtility::isTableUsed('index_grlist')) {
1681 return;
1682 }
1683
1684 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1685 ->getQueryBuilderForTable('index_grlist');
1686 $count = (int)$queryBuilder->count('*')
1687 ->from('index_grlist')
1688 ->where(
1689 $queryBuilder->expr()->eq(
1690 'phash',
1691 $queryBuilder->createNamedParameter($hash, \PDO::PARAM_INT)
1692 ),
1693 $queryBuilder->expr()->orX(
1694 $queryBuilder->expr()->eq(
1695 'hash_gr_list',
1696 $queryBuilder->createNamedParameter(
1697 IndexedSearchUtility::md5inthash($this->defaultGrList),
1698 \PDO::PARAM_INT
1699 )
1700 ),
1701 $queryBuilder->expr()->eq(
1702 'hash_gr_list',
1703 $queryBuilder->createNamedParameter(
1704 IndexedSearchUtility::md5inthash($this->conf['gr_list']),
1705 \PDO::PARAM_INT
1706 )
1707 )
1708 )
1709 )
1710 ->execute()
1711 ->fetchColumn();
1712
1713 if ($count === 0) {
1714 $this->submit_grlist($hash, $hash);
1715 }
1716 }
1717
1718 /**
1719 * Stores file section for a file IF it does not exist
1720 *
1721 * @param int $hash phash value of file
1722 */
1723 public function submitFile_section($hash)
1724 {
1725 // Testing if there is already a section
1726 if (!IndexedSearchUtility::isTableUsed('index_section')) {
1727 return;
1728 }
1729
1730 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1731 ->getQueryBuilderForTable('index_section');
1732 $count = (int)$queryBuilder->count('phash')
1733 ->from('index_section')
1734 ->where(
1735 $queryBuilder->expr()->eq(
1736 'phash',
1737 $queryBuilder->createNamedParameter($hash, \PDO::PARAM_INT)
1738 ),
1739 $queryBuilder->expr()->eq(
1740 'page_id',
1741 $queryBuilder->createNamedParameter($this->conf['id'], \PDO::PARAM_INT)
1742 )
1743 )
1744 ->execute()
1745 ->fetchColumn();
1746
1747 if ($count === 0) {
1748 $this->submit_section($hash, $this->hash['phash']);
1749 }
1750 }
1751
1752 /**
1753 * Removes records for the indexed page, $phash
1754 *
1755 * @param int $phash phash value to flush
1756 */
1757 public function removeOldIndexedFiles($phash)
1758 {
1759 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1760 // Removing old registrations for tables.
1761 $tableArray = ['index_phash', 'index_grlist', 'index_fulltext', 'index_debug'];
1762 foreach ($tableArray as $table) {
1763 if (!IndexedSearchUtility::isTableUsed($table)) {
1764 continue;
1765 }
1766 $connectionPool->getConnectionForTable($table)->delete($table, ['phash' => (int)$phash]);
1767 }
1768 }
1769
1770 /********************************
1771 *
1772 * SQL Helper functions
1773 *
1774 *******************************/
1775 /**
1776 * Check the mtime / tstamp of the currently indexed page/file (based on phash)
1777 * Return positive integer if the page needs to be indexed
1778 *
1779 * @param int $mtime mtime value to test against limits and indexed page (usually this is the mtime of the cached document)
1780 * @param int $phash "phash" used to select any already indexed page to see what its mtime is.
1781 * @return int Result integer: Generally: <0 = No indexing, >0 = Do indexing (see $this->reasons): -2) Min age was NOT exceeded and so indexing cannot occur. -1) mtime matched so no need to reindex page. 0) N/A 1) Max age exceeded, page must be indexed again. 2) mtime of indexed page doesn't match mtime given for current content and we must index page. 3) No mtime was set, so we will index... 4) No indexed page found, so of course we will index.
1782 */
1783 public function checkMtimeTstamp($mtime, $phash)
1784 {
1785 if (!IndexedSearchUtility::isTableUsed('index_phash')) {
1786 // Not indexed (not in index_phash)
1787 $result = 4;
1788 } else {
1789 $row = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_phash')
1790 ->select(
1791 ['item_mtime', 'tstamp'],
1792 'index_phash',
1793 ['phash' => (int)$phash],
1794 [],
1795 [],
1796 1
1797 )
1798 ->fetch();
1799 // If there was an indexing of the page...:
1800 if (!empty($row)) {
1801 if ($this->tstamp_maxAge && $row['tstamp'] + $this->tstamp_maxAge < $GLOBALS['EXEC_TIME']) {
1802 // If max age is exceeded, index the page
1803 // The configured max-age was exceeded for the document and thus it's indexed.
1804 $result = 1;
1805 } else {
1806 if (!$this->tstamp_minAge || $row['tstamp'] + $this->tstamp_minAge < $GLOBALS['EXEC_TIME']) {
1807 // if minAge is not set or if minAge is exceeded, consider at mtime
1808 if ($mtime) {
1809 // It mtime is set, then it's tested. If not, the page must clearly be indexed.
1810 if ($row['item_mtime'] != $mtime) {
1811 // And if mtime is different from the index_phash mtime, it's about time to re-index.
1812 // The minimum age was exceed and mtime was set and the mtime was different, so the page was indexed.
1813 $result = 2;
1814 } else {
1815 // mtime matched the document, so no changes detected and no content updated
1816 $result = -1;
1817 if ($this->tstamp_maxAge) {
1818 $this->log_setTSlogMessage('mtime matched, timestamp NOT updated because a maxAge is set (' . ($row['tstamp'] + $this->tstamp_maxAge - $GLOBALS['EXEC_TIME']) . ' seconds to expire time).', 1);
1819 } else {
1820 $this->updateTstamp($phash);
1821 $this->log_setTSlogMessage('mtime matched, timestamp updated.', 1);
1822 }
1823 }
1824 } else {
1825 // The minimum age was exceed, but mtime was not set, so the page was indexed.
1826 $result = 3;
1827 }
1828 } else {
1829 // The minimum age was not exceeded
1830 $result = -2;
1831 }
1832 }
1833 } else {
1834 // Page has never been indexed (is not represented in the index_phash table).
1835 $result = 4;
1836 }
1837 }
1838 return $result;
1839 }
1840
1841 /**
1842 * Check content hash in phash table
1843 *
1844 * @return mixed Returns TRUE if the page needs to be indexed (that is, there was no result), otherwise the phash value (in an array) of the phash record to which the grlist_record should be related!
1845 */
1846 public function checkContentHash()
1847 {
1848 // With this query the page will only be indexed if it's content is different from the same "phash_grouping" -page.
1849 $result = true;
1850 if (IndexedSearchUtility::isTableUsed('index_phash')) {
1851 $row = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_phash')
1852 ->select(
1853 ['phash'],
1854 'index_phash',
1855 [
1856 'phash_grouping' => (int)$this->hash['phash_grouping'],
1857 'contentHash' => (int)$this->content_md5h
1858 ],
1859 [],
1860 [],
1861 1
1862 )
1863 ->fetch();
1864
1865 if (!empty($row)) {
1866 $result = $row;
1867 }
1868 }
1869 return $result;
1870 }
1871
1872 /**
1873 * Check content hash for external documents
1874 * Returns TRUE if the document needs to be indexed (that is, there was no result)
1875 *
1876 * @param int $hashGr phash value to check (phash_grouping)
1877 * @param int $content_md5h Content hash to check
1878 * @return bool Returns TRUE if the document needs to be indexed (that is, there was no result)
1879 */
1880 public function checkExternalDocContentHash($hashGr, $content_md5h)
1881 {
1882 $result = true;
1883 if (IndexedSearchUtility::isTableUsed('index_phash')) {
1884 $count = (int)GeneralUtility::makeInstance(ConnectionPool::class)
1885 ->getConnectionForTable('index_phash')
1886 ->count(
1887 '*',
1888 'index_phash',
1889 [
1890 'phash_grouping' => (int)$hashGr,
1891 'contentHash' => (int)$content_md5h
1892 ]
1893 );
1894
1895 $result = $count === 0;
1896 }
1897 return $result;
1898 }
1899
1900 /**
1901 * Checks if a grlist record has been set for the phash value input (looking at the "real" phash of the current content, not the linked-to phash of the common search result page)
1902 *
1903 * @param int $phash_x Phash integer to test.
1904 * @return bool
1905 */
1906 public function is_grlist_set($phash_x)
1907 {
1908 $result = false;
1909 if (IndexedSearchUtility::isTableUsed('index_grlist')) {
1910 $count = (int)GeneralUtility::makeInstance(ConnectionPool::class)
1911 ->getConnectionForTable('index_grlist')
1912 ->count(
1913 'phash_x',
1914 'index_grlist',
1915 ['phash_x' => (int)$phash_x]
1916 );
1917
1918 $result = $count > 0;
1919 }
1920 return $result;
1921 }
1922
1923 /**
1924 * Check if an grlist-entry for this hash exists and if not so, write one.
1925 *
1926 * @param int $phash phash of the search result that should be found
1927 * @param int $phash_x The real phash of the current content. The two values are different when a page with userlogin turns out to contain the exact same content as another already indexed version of the page; This is the whole reason for the grlist table in fact...
1928 * @see submit_grlist()
1929 */
1930 public function update_grlist($phash, $phash_x)
1931 {
1932 if (IndexedSearchUtility::isTableUsed('index_grlist')) {
1933 $count = (int)GeneralUtility::makeInstance(ConnectionPool::class)
1934 ->getConnectionForTable('index_grlist')
1935 ->count(
1936 'phash',
1937 'index_grlist',
1938 [
1939 'phash' => (int)$phash,
1940 'hash_gr_list' => IndexedSearchUtility::md5inthash($this->conf['gr_list'])
1941 ]
1942 );
1943
1944 if ($count === 0) {
1945 $this->submit_grlist($phash, $phash_x);
1946 $this->log_setTSlogMessage('Inserted gr_list \'' . $this->conf['gr_list'] . '\' for phash \'' . $phash . '\'', 1);
1947 }
1948 }
1949 }
1950
1951 /**
1952 * Update tstamp for a phash row.
1953 *
1954 * @param int $phash phash value
1955 * @param int $mtime If set, update the mtime field to this value.
1956 */
1957 public function updateTstamp($phash, $mtime = 0)
1958 {
1959 if (!IndexedSearchUtility::isTableUsed('index_phash')) {
1960 return;
1961 }
1962
1963 $updateFields = [
1964 'tstamp' => $GLOBALS['EXEC_TIME']
1965 ];
1966
1967 if ($mtime) {
1968 $updateFields['item_mtime'] = (int)$mtime;
1969 }
1970
1971 GeneralUtility::makeInstance(ConnectionPool::class)
1972 ->getConnectionForTable('index_phash')
1973 ->update(
1974 'index_phash',
1975 $updateFields,
1976 [
1977 'phash' => (int)$phash
1978 ]
1979 );
1980 }
1981
1982 /**
1983 * Update SetID of the index_phash record.
1984 *
1985 * @param int $phash phash value
1986 */
1987 public function updateSetId($phash)
1988 {
1989 if (!IndexedSearchUtility::isTableUsed('index_phash')) {
1990 return;
1991 }
1992
1993 GeneralUtility::makeInstance(ConnectionPool::class)
1994 ->getConnectionForTable('index_phash')
1995 ->update(
1996 'index_phash',
1997 [
1998 'freeIndexSetId' => (int)$this->conf['freeIndexSetId']
1999 ],
2000 [
2001 'phash' => (int)$phash
2002 ]
2003 );
2004 }
2005
2006 /**
2007 * Update parsetime for phash row.
2008 *
2009 * @param int $phash phash value.
2010 * @param int $parsetime Parsetime value to set.
2011 */
2012 public function updateParsetime($phash, $parsetime)
2013 {
2014 if (!IndexedSearchUtility::isTableUsed('index_phash')) {
2015 return;
2016 }
2017
2018 GeneralUtility::makeInstance(ConnectionPool::class)
2019 ->getConnectionForTable('index_phash')
2020 ->update(
2021 'index_phash',
2022 [
2023 'parsetime' => (int)$parsetime
2024 ],
2025 [
2026 'phash' => (int)$phash
2027 ]
2028 );
2029 }
2030
2031 /**
2032 * Update section rootline for the page
2033 */
2034 public function updateRootline()
2035 {
2036 if (!IndexedSearchUtility::isTableUsed('index_section')) {
2037 return;
2038 }
2039
2040 $updateFields = [];
2041 $this->getRootLineFields($updateFields);
2042
2043 GeneralUtility::makeInstance(ConnectionPool::class)
2044 ->getConnectionForTable('index_section')
2045 ->update(
2046 'index_section',
2047 $updateFields,
2048 [
2049 'page_id' => (int)$this->conf['id']
2050 ]
2051 );
2052 }
2053
2054 /**
2055 * Adding values for root-line fields.
2056 * rl0, rl1 and rl2 are standard. A hook might add more.
2057 *
2058 * @param array $fieldArray Field array, passed by reference
2059 */
2060 public function getRootLineFields(array &$fieldArray)
2061 {
2062 $fieldArray['rl0'] = (int)$this->conf['rootline_uids'][0];
2063 $fieldArray['rl1'] = (int)$this->conf['rootline_uids'][1];
2064 $fieldArray['rl2'] = (int)$this->conf['rootline_uids'][2];
2065 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['addRootLineFields'])) {
2066 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['addRootLineFields'] as $fieldName => $rootLineLevel) {
2067 $fieldArray[$fieldName] = (int)$this->conf['rootline_uids'][$rootLineLevel];
2068 }
2069 }
2070 }
2071
2072 /********************************
2073 *
2074 * SQL; Submitting words
2075 *
2076 *******************************/
2077 /**
2078 * Adds new words to db
2079 *
2080 * @param array $wordListArray Word List array (where each word has information about position etc).
2081 */
2082 public function checkWordList($wordListArray)
2083 {
2084 if (!IndexedSearchUtility::isTableUsed('index_words') || empty($wordListArray)) {
2085 return;
2086 }
2087
2088 $wordListArrayCount = count($wordListArray);
2089 $phashArray = array_map('intval', array_column($wordListArray, 'hash'));
2090
2091 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('index_words');
2092 $count = (int)$queryBuilder->count('baseword')
2093 ->from('index_words')
2094 ->where(
2095 $queryBuilder->expr()->in(
2096 'wid',
2097 $queryBuilder->createNamedParameter($phashArray, Connection::PARAM_INT_ARRAY)
2098 )
2099 )
2100 ->execute()
2101 ->fetchColumn();
2102
2103 if ($count !== $wordListArrayCount) {
2104 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_words');
2105 $queryBuilder = $connection->createQueryBuilder();
2106
2107 $result = $queryBuilder->select('baseword')
2108 ->from('index_words')
2109 ->where(
2110 $queryBuilder->expr()->in(
2111 'wid',
2112 $queryBuilder->createNamedParameter($phashArray, Connection::PARAM_INT_ARRAY)
2113 )
2114 )
2115 ->execute();
2116
2117 $this->log_setTSlogMessage('Inserting words: ' . ($wordListArrayCount - $count), 1);
2118 while ($row = $result->fetch()) {
2119 unset($wordListArray[$row['baseword']]);
2120 }
2121
2122 foreach ($wordListArray as $key => $val) {
2123 // A duplicate-key error will occur here if a word is NOT unset in the unset() line. However as
2124 // long as the words in $wl are NOT longer as 60 chars (the baseword varchar is 60 characters...)
2125 // this is not a problem.
2126 $connection->insert(
2127 'index_words',
2128 [
2129 'wid' => $val['hash'],
2130 'baseword' => $key,
2131 'metaphone' => $val['metaphone']
2132 ]
2133 );
2134 }
2135 }
2136 }
2137
2138 /**
2139 * Submits RELATIONS between words and phash
2140 *
2141 * @param array $wordList Word list array
2142 * @param int $phash phash value
2143 */
2144 public function submitWords($wordList, $phash)
2145 {
2146 if (!IndexedSearchUtility::isTableUsed('index_rel')) {
2147 return;
2148 }
2149 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
2150 $queryBuilder = $connectionPool->getQueryBuilderForTable('index_words');
2151 $result = $queryBuilder->select('wid')
2152 ->from('index_words')
2153 ->where(
2154 $queryBuilder->expr()->neq('is_stopword', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
2155 )
2156 ->groupBy('wid')
2157 ->execute();
2158
2159 $stopWords = [];
2160 while ($row = $result->fetch()) {
2161 $stopWords[$row['wid']] = $row;
2162 }
2163
2164 $connectionPool->getConnectionForTable('index_rel')->delete('index_rel', ['phash' => (int)$phash]);
2165
2166 $fields = ['phash', 'wid', 'count', 'first', 'freq', 'flags'];
2167 $rows = [];
2168 foreach ($wordList as $val) {
2169 if (isset($stopWords[$val['hash']])) {
2170 continue;
2171 }
2172 $rows[] = [
2173 (int)$phash,
2174 (int)$val['hash'],
2175 (int)$val['count'],
2176 (int)$val['first'],
2177 $this->freqMap($val['count'] / $this->wordcount),
2178 $val['cmp'] & $this->flagBitMask
2179 ];
2180 }
2181
2182 if (!empty($rows)) {
2183 $connectionPool->getConnectionForTable('index_rel')->bulkInsert('index_rel', $rows, $fields);
2184 }
2185 }
2186
2187 /**
2188 * maps frequency from a real number in [0;1] to an integer in [0;$this->freqRange] with anything above $this->freqMax as 1
2189 * and back.
2190 *
2191 * @param float $freq Frequency
2192 * @return int Frequency in range.
2193 */
2194 public function freqMap($freq)
2195 {
2196 $mapFactor = $this->freqMax * 100 * $this->freqRange;
2197 if ($freq <= 1) {
2198 $newFreq = $freq * $mapFactor;
2199 $newFreq = $newFreq > $this->freqRange ? $this->freqRange : $newFreq;
2200 } else {
2201 $newFreq = $freq / $mapFactor;
2202 }
2203 return $newFreq;
2204 }
2205
2206 /********************************
2207 *
2208 * Hashing
2209 *
2210 *******************************/
2211 /**
2212 * Get search hash, T3 pages
2213 */
2214 public function setT3Hashes()
2215 {
2216 // Set main array:
2217 $hArray = [
2218 'id' => (int)$this->conf['id'],
2219 'type' => (int)$this->conf['type'],
2220 'sys_lang' => (int)$this->conf['sys_language_uid'],
2221 'MP' => (string)$this->conf['MP'],
2222 'cHash' => $this->cHashParams
2223 ];
2224 // Set grouping hash (Identifies a "page" combined of id, type, language, mountpoint and cHash parameters):
2225 $this->hash['phash_grouping'] = IndexedSearchUtility::md5inthash(serialize($hArray));
2226 // Add gr_list and set plain phash (Subdivision where special page composition based on login is taken into account as well. It is expected that such pages are normally similar regardless of the login.)
2227 $hArray['gr_list'] = (string)$this->conf['gr_list'];
2228 $this->hash['phash'] = IndexedSearchUtility::md5inthash(serialize($hArray));
2229 }
2230
2231 /**
2232 * Get search hash, external files
2233 *
2234 * @param string $file File name / path which identifies it on the server
2235 * @param array $subinfo Additional content identifying the (subpart of) content. For instance; PDF files are divided into groups of pages for indexing.
2236 * @return array Array with "phash_grouping" and "phash" inside.
2237 */
2238 public function setExtHashes($file, $subinfo = [])
2239 {
2240 // Set main array:
2241 $hash = [];
2242 $hArray = [
2243 'file' => $file
2244 ];
2245 // Set grouping hash:
2246 $hash['phash_grouping'] = IndexedSearchUtility::md5inthash(serialize($hArray));
2247 // Add subinfo
2248 $hArray['subinfo'] = $subinfo;
2249 $hash['phash'] = IndexedSearchUtility::md5inthash(serialize($hArray));
2250 return $hash;
2251 }
2252
2253 /*********************************
2254 *
2255 * Internal logging functions
2256 *
2257 *********************************/
2258 /**
2259 * Push function wrapper for TT logging
2260 *
2261 * @param string $msg Title to set
2262 * @param string $key Key (?)
2263 */
2264 public function log_push($msg, $key)
2265 {
2266 $this->timeTracker->push($msg, $key);
2267 }
2268
2269 /**
2270 * Pull function wrapper for TT logging
2271 */
2272 public function log_pull()
2273 {
2274 $this->timeTracker->pull();
2275 }
2276
2277 /**
2278 * Set log message function wrapper for TT logging
2279 *
2280 * @param string $msg Message to set
2281 * @param int $errorNum Error number
2282 */
2283 public function log_setTSlogMessage($msg, $errorNum = 0)
2284 {
2285 $this->timeTracker->setTSlogMessage($msg, $errorNum);
2286 $this->internal_log[] = $msg;
2287 }
2288
2289 /**
2290 * Makes sure that keywords are space-separated. This is impotant for their
2291 * proper displaying as a part of fulltext index.
2292 *
2293 * @param string $keywordList
2294 * @return string
2295 * @see http://forge.typo3.org/issues/14959
2296 */
2297 protected function addSpacesToKeywordList($keywordList)
2298 {
2299 $keywords = GeneralUtility::trimExplode(',', $keywordList);
2300 return ' ' . implode(', ', $keywords) . ' ';
2301 }
2302 }