[BUGFIX] Fix checking config.metaCharset with uppercase letters
[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 } else {
745 return false;
746 }
747 }
748
749 /**
750 * Extract links (hrefs) from HTML content and if indexable media is found, it is indexed.
751 *
752 * @param string $content HTML content
753 */
754 public function extractLinks($content)
755 {
756 // Get links:
757 $list = $this->extractHyperLinks($content);
758 if ($this->indexerConfig['useCrawlerForExternalFiles'] && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('crawler')) {
759 $crawler = GeneralUtility::makeInstance(\tx_crawler_lib::class);
760 }
761 // Traverse links:
762 foreach ($list as $linkInfo) {
763 // Decode entities:
764 if ($linkInfo['localPath']) {
765 // 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!
766 $linkSource = htmlspecialchars_decode($linkInfo['localPath']);
767 } else {
768 $linkSource = htmlspecialchars_decode($linkInfo['href']);
769 }
770 // Parse URL:
771 $qParts = parse_url($linkSource);
772 // Check for jumpurl (TYPO3 specific thing...)
773 if ($qParts['query'] && strstr($qParts['query'], 'jumpurl=')) {
774 parse_str($qParts['query'], $getP);
775 $linkSource = $getP['jumpurl'];
776 $qParts = parse_url($linkSource);
777 }
778 if (!$linkInfo['localPath'] && $qParts['scheme']) {
779 if ($this->indexerConfig['indexExternalURLs']) {
780 // Index external URL (http or otherwise)
781 $this->indexExternalUrl($linkSource);
782 }
783 } elseif (!$qParts['query']) {
784 $linkSource = urldecode($linkSource);
785 if (GeneralUtility::isAllowedAbsPath($linkSource)) {
786 $localFile = $linkSource;
787 } else {
788 $localFile = GeneralUtility::getFileAbsFileName(PATH_site . $linkSource);
789 }
790 if ($localFile && @is_file($localFile)) {
791 // Index local file:
792 if ($linkInfo['localPath']) {
793 $fI = pathinfo($linkSource);
794 $ext = strtolower($fI['extension']);
795 if (is_object($crawler)) {
796 $params = [
797 'document' => $linkSource,
798 'alturl' => $linkInfo['href'],
799 'conf' => $this->conf
800 ];
801 unset($params['conf']['content']);
802 $crawler->addQueueEntry_callBack(0, $params, Hook\CrawlerFilesHook::class, $this->conf['id']);
803 $this->log_setTSlogMessage('media "' . $params['document'] . '" added to "crawler" queue.', 1);
804 } else {
805 $this->indexRegularDocument($linkInfo['href'], false, $linkSource, $ext);
806 }
807 } else {
808 if (is_object($crawler)) {
809 $params = [
810 'document' => $linkSource,
811 'conf' => $this->conf
812 ];
813 unset($params['conf']['content']);
814 $crawler->addQueueEntry_callBack(0, $params, Hook\CrawlerFilesHook::class, $this->conf['id']);
815 $this->log_setTSlogMessage('media "' . $params['document'] . '" added to "crawler" queue.', 1);
816 } else {
817 $this->indexRegularDocument($linkSource);
818 }
819 }
820 }
821 }
822 }
823 }
824
825 /**
826 * Extracts all links to external documents from the HTML content string
827 *
828 * @param string $html
829 * @return array Array of hyperlinks (keys: tag, href, localPath (empty if not local))
830 * @see extractLinks()
831 */
832 public function extractHyperLinks($html)
833 {
834 $htmlParser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Html\HtmlParser::class);
835 $htmlParts = $htmlParser->splitTags('a', $html);
836 $hyperLinksData = [];
837 foreach ($htmlParts as $index => $tagData) {
838 if ($index % 2 !== 0) {
839 $tagAttributes = $htmlParser->get_tag_attributes($tagData, true);
840 $firstTagName = $htmlParser->getFirstTagName($tagData);
841 if (strtolower($firstTagName) === 'a') {
842 if ($tagAttributes[0]['href'] && $tagAttributes[0]['href'][0] !== '#') {
843 $hyperLinksData[] = [
844 'tag' => $tagData,
845 'href' => $tagAttributes[0]['href'],
846 'localPath' => $this->createLocalPath($tagAttributes[0]['href'])
847 ];
848 }
849 }
850 }
851 }
852 return $hyperLinksData;
853 }
854
855 /**
856 * Extracts the "base href" from content string.
857 *
858 * @param string $html Content to analyze
859 * @return string The base href or an empty string if not found
860 */
861 public function extractBaseHref($html)
862 {
863 $href = '';
864 $htmlParser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Html\HtmlParser::class);
865 $htmlParts = $htmlParser->splitTags('base', $html);
866 foreach ($htmlParts as $index => $tagData) {
867 if ($index % 2 !== 0) {
868 $tagAttributes = $htmlParser->get_tag_attributes($tagData, true);
869 $firstTagName = $htmlParser->getFirstTagName($tagData);
870 if (strtolower($firstTagName) === 'base') {
871 $href = $tagAttributes[0]['href'];
872 if ($href) {
873 break;
874 }
875 }
876 }
877 }
878 return $href;
879 }
880
881 /******************************************
882 *
883 * Indexing; external URL
884 *
885 ******************************************/
886 /**
887 * Index External URLs HTML content
888 *
889 * @param string $externalUrl URL, eg. "http://typo3.org/
890 * @see indexRegularDocument()
891 */
892 public function indexExternalUrl($externalUrl)
893 {
894 // Get headers:
895 $urlHeaders = $this->getUrlHeaders($externalUrl);
896 if (stristr($urlHeaders['Content-Type'], 'text/html')) {
897 $content = ($this->indexExternalUrl_content = GeneralUtility::getUrl($externalUrl));
898 if ((string)$content !== '') {
899 // Create temporary file:
900 $tmpFile = GeneralUtility::tempnam('EXTERNAL_URL');
901 if ($tmpFile) {
902 GeneralUtility::writeFile($tmpFile, $content);
903 // Index that file:
904 $this->indexRegularDocument($externalUrl, true, $tmpFile, 'html');
905 // Using "TRUE" for second parameter to force indexing of external URLs (mtime doesn't make sense, does it?)
906 unlink($tmpFile);
907 }
908 }
909 }
910 }
911
912 /**
913 * Getting HTTP request headers of URL
914 *
915 * @param string $url The URL
916 * @return mixed If no answer, returns FALSE. Otherwise an array where HTTP headers are keys
917 */
918 public function getUrlHeaders($url)
919 {
920 // Try to get the headers only
921 $content = GeneralUtility::getUrl($url, 2);
922 if ((string)$content !== '') {
923 // Compile headers:
924 $headers = GeneralUtility::trimExplode(LF, $content, true);
925 $retVal = [];
926 foreach ($headers as $line) {
927 if (trim($line) === '') {
928 break;
929 }
930 list($headKey, $headValue) = explode(':', $line, 2);
931 $retVal[$headKey] = $headValue;
932 }
933 return $retVal;
934 }
935 }
936
937 /**
938 * Checks if the file is local
939 *
940 * @param string $sourcePath
941 * @return string Absolute path to file if file is local, else empty string
942 */
943 protected function createLocalPath($sourcePath)
944 {
945 $localPath = '';
946 static $pathFunctions = [
947 'createLocalPathFromT3vars',
948 'createLocalPathUsingAbsRefPrefix',
949 'createLocalPathUsingDomainURL',
950 'createLocalPathFromAbsoluteURL',
951 'createLocalPathFromRelativeURL'
952 ];
953 foreach ($pathFunctions as $functionName) {
954 $localPath = $this->{$functionName}($sourcePath);
955 if ($localPath != '') {
956 break;
957 }
958 }
959 return $localPath;
960 }
961
962 /**
963 * Attempts to create a local file path from T3VARs. This is useful for
964 * various download extensions that hide actual file name but still want the
965 * file to be indexed.
966 *
967 * @param string $sourcePath
968 * @return string
969 */
970 protected function createLocalPathFromT3vars($sourcePath)
971 {
972 $localPath = '';
973 $indexLocalFiles = $GLOBALS['T3_VAR']['ext']['indexed_search']['indexLocalFiles'];
974 if (is_array($indexLocalFiles)) {
975 $md5 = GeneralUtility::shortMD5($sourcePath);
976 // Note: not using self::isAllowedLocalFile here because this method
977 // is allowed to index files outside of the web site (for example,
978 // protected downloads)
979 if (isset($indexLocalFiles[$md5]) && is_file($indexLocalFiles[$md5])) {
980 $localPath = $indexLocalFiles[$md5];
981 }
982 }
983 return $localPath;
984 }
985
986 /**
987 * Attempts to create a local file path by matching a current request URL.
988 *
989 * @param string $sourcePath
990 * @return string
991 */
992 protected function createLocalPathUsingDomainURL($sourcePath)
993 {
994 $localPath = '';
995 $baseURL = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
996 $baseURLLength = strlen($baseURL);
997 if (substr($sourcePath, 0, $baseURLLength) == $baseURL) {
998 $sourcePath = substr($sourcePath, $baseURLLength);
999 $localPath = PATH_site . $sourcePath;
1000 if (!self::isAllowedLocalFile($localPath)) {
1001 $localPath = '';
1002 }
1003 }
1004 return $localPath;
1005 }
1006
1007 /**
1008 * Attempts to create a local file path by matching absRefPrefix. This
1009 * requires TSFE. If TSFE is missing, this function does nothing.
1010 *
1011 * @param string $sourcePath
1012 * @return string
1013 */
1014 protected function createLocalPathUsingAbsRefPrefix($sourcePath)
1015 {
1016 $localPath = '';
1017 if ($GLOBALS['TSFE'] instanceof \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController) {
1018 $absRefPrefix = $GLOBALS['TSFE']->config['config']['absRefPrefix'];
1019 $absRefPrefixLength = strlen($absRefPrefix);
1020 if ($absRefPrefixLength > 0 && substr($sourcePath, 0, $absRefPrefixLength) == $absRefPrefix) {
1021 $sourcePath = substr($sourcePath, $absRefPrefixLength);
1022 $localPath = PATH_site . $sourcePath;
1023 if (!self::isAllowedLocalFile($localPath)) {
1024 $localPath = '';
1025 }
1026 }
1027 }
1028 return $localPath;
1029 }
1030
1031 /**
1032 * Attempts to create a local file path from the absolute URL without
1033 * schema.
1034 *
1035 * @param string $sourcePath
1036 * @return string
1037 */
1038 protected function createLocalPathFromAbsoluteURL($sourcePath)
1039 {
1040 $localPath = '';
1041 if ($sourcePath[0] === '/') {
1042 $sourcePath = substr($sourcePath, 1);
1043 $localPath = PATH_site . $sourcePath;
1044 if (!self::isAllowedLocalFile($localPath)) {
1045 $localPath = '';
1046 }
1047 }
1048 return $localPath;
1049 }
1050
1051 /**
1052 * Attempts to create a local file path from the relative URL.
1053 *
1054 * @param string $sourcePath
1055 * @return string
1056 */
1057 protected function createLocalPathFromRelativeURL($sourcePath)
1058 {
1059 $localPath = '';
1060 if (self::isRelativeURL($sourcePath)) {
1061 $localPath = PATH_site . $sourcePath;
1062 if (!self::isAllowedLocalFile($localPath)) {
1063 $localPath = '';
1064 }
1065 }
1066 return $localPath;
1067 }
1068
1069 /**
1070 * Checks if URL is relative.
1071 *
1072 * @param string $url
1073 * @return bool
1074 */
1075 protected static function isRelativeURL($url)
1076 {
1077 $urlParts = @parse_url($url);
1078 return $urlParts['scheme'] == '' && $urlParts['path'][0] !== '/';
1079 }
1080
1081 /**
1082 * Checks if the path points to the file inside the web site
1083 *
1084 * @param string $filePath
1085 * @return bool
1086 */
1087 protected static function isAllowedLocalFile($filePath)
1088 {
1089 $filePath = GeneralUtility::resolveBackPath($filePath);
1090 $insideWebPath = substr($filePath, 0, strlen(PATH_site)) == PATH_site;
1091 $isFile = is_file($filePath);
1092 return $insideWebPath && $isFile;
1093 }
1094
1095 /******************************************
1096 *
1097 * Indexing; external files (PDF, DOC, etc)
1098 *
1099 ******************************************/
1100 /**
1101 * Indexing a regular document given as $file (relative to PATH_site, local file)
1102 *
1103 * @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
1104 * @param bool $force If set, indexing is forced (despite content hashes, mtime etc).
1105 * @param string $contentTmpFile Temporary file with the content to read it from (instead of $file). Used when the $file is a URL.
1106 * @param string $altExtension File extension for temporary file.
1107 */
1108 public function indexRegularDocument($file, $force = false, $contentTmpFile = '', $altExtension = '')
1109 {
1110 // Init
1111 $fI = pathinfo($file);
1112 $ext = $altExtension ?: strtolower($fI['extension']);
1113 // Create abs-path:
1114 if (!$contentTmpFile) {
1115 if (!GeneralUtility::isAbsPath($file)) {
1116 // Relative, prepend PATH_site:
1117 $absFile = GeneralUtility::getFileAbsFileName(PATH_site . $file);
1118 } else {
1119 // Absolute, pass-through:
1120 $absFile = $file;
1121 }
1122 $absFile = GeneralUtility::isAllowedAbsPath($absFile) ? $absFile : '';
1123 } else {
1124 $absFile = $contentTmpFile;
1125 }
1126 // Indexing the document:
1127 if ($absFile && @is_file($absFile)) {
1128 if ($this->external_parsers[$ext]) {
1129 $fileInfo = stat($absFile);
1130 $cParts = $this->fileContentParts($ext, $absFile);
1131 foreach ($cParts as $cPKey) {
1132 $this->internal_log = [];
1133 $this->log_push('Index: ' . str_replace('.', '_', basename($file)) . ($cPKey ? '#' . $cPKey : ''), '');
1134 $Pstart = GeneralUtility::milliseconds();
1135 $subinfo = ['key' => $cPKey];
1136 // Setting page range. This is "0" (zero) when no division is made, otherwise a range like "1-3"
1137 $phash_arr = ($this->file_phash_arr = $this->setExtHashes($file, $subinfo));
1138 $check = $this->checkMtimeTstamp($fileInfo['mtime'], $phash_arr['phash']);
1139 if ($check > 0 || $force) {
1140 if ($check > 0) {
1141 $this->log_setTSlogMessage('Indexing needed, reason: ' . $this->reasons[$check], 1);
1142 } else {
1143 $this->log_setTSlogMessage('Indexing forced by flag', 1);
1144 }
1145 // Check external file counter:
1146 if ($this->externalFileCounter < $this->maxExternalFiles || $force) {
1147 // Divide into title,keywords,description and body:
1148 $this->log_push('Split content', '');
1149 $contentParts = $this->readFileContent($ext, $absFile, $cPKey);
1150 $this->log_pull();
1151 if (is_array($contentParts)) {
1152 // Calculating a hash over what is to be the actual content. (see indexTypo3PageContent())
1153 $content_md5h = IndexedSearchUtility::md5inthash(implode($contentParts, ''));
1154 if ($this->checkExternalDocContentHash($phash_arr['phash_grouping'], $content_md5h) || $force) {
1155 // Increment counter:
1156 $this->externalFileCounter++;
1157 // Splitting words
1158 $this->log_push('Extract words from content', '');
1159 $splitInWords = $this->processWordsInArrays($contentParts);
1160 $this->log_pull();
1161 // Analyse the indexed words.
1162 $this->log_push('Analyse the extracted words', '');
1163 $indexArr = $this->indexAnalyze($splitInWords);
1164 $this->log_pull();
1165 // Submitting page (phash) record
1166 $this->log_push('Submitting page', '');
1167 // Unfortunately I cannot determine WHEN a file is originally made - so I must return the modification time...
1168 $this->submitFilePage($phash_arr, $file, $subinfo, $ext, $fileInfo['mtime'], $fileInfo['ctime'], $fileInfo['size'], $content_md5h, $contentParts);
1169 $this->log_pull();
1170 // Check words and submit to word list if not there
1171 $this->log_push('Check word list and submit words', '');
1172 if (IndexedSearchUtility::isTableUsed('index_words')) {
1173 $this->checkWordList($indexArr);
1174 $this->submitWords($indexArr, $phash_arr['phash']);
1175 }
1176 $this->log_pull();
1177 // Set parsetime
1178 $this->updateParsetime($phash_arr['phash'], GeneralUtility::milliseconds() - $Pstart);
1179 } else {
1180 // Update the timestamp
1181 $this->updateTstamp($phash_arr['phash'], $fileInfo['mtime']);
1182 $this->log_setTSlogMessage('Indexing not needed, the contentHash, ' . $content_md5h . ', has not changed. Timestamp updated.');
1183 }
1184 } else {
1185 $this->log_setTSlogMessage('Could not index file! Unsupported extension.');
1186 }
1187 } else {
1188 $this->log_setTSlogMessage('The limit of ' . $this->maxExternalFiles . ' has already been exceeded, so no indexing will take place this time.');
1189 }
1190 } else {
1191 $this->log_setTSlogMessage('Indexing not needed, reason: ' . $this->reasons[$check]);
1192 }
1193 // Checking and setting sections:
1194 $this->submitFile_section($phash_arr['phash']);
1195 // 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.
1196 $this->log_pull();
1197 }
1198 } else {
1199 $this->log_setTSlogMessage('Indexing not possible; The extension "' . $ext . '" was not supported.');
1200 }
1201 } else {
1202 $this->log_setTSlogMessage('Indexing not possible; File "' . $absFile . '" not found or valid.');
1203 }
1204 }
1205
1206 /**
1207 * Reads the content of an external file being indexed.
1208 * The content from the external parser MUST be returned in utf-8!
1209 *
1210 * @param string $fileExtension File extension, eg. "pdf", "doc" etc.
1211 * @param string $absoluteFileName Absolute filename of file (must exist and be validated OK before calling function)
1212 * @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.)
1213 * @return array Standard content array (title, description, keywords, body keys)
1214 */
1215 public function readFileContent($fileExtension, $absoluteFileName, $sectionPointer)
1216 {
1217 $contentArray = null;
1218 // Consult relevant external document parser:
1219 if (is_object($this->external_parsers[$fileExtension])) {
1220 $contentArray = $this->external_parsers[$fileExtension]->readFileContent($fileExtension, $absoluteFileName, $sectionPointer);
1221 }
1222 return $contentArray;
1223 }
1224
1225 /**
1226 * Creates an array with pointers to divisions of document.
1227 *
1228 * @param string $ext File extension
1229 * @param string $absFile Absolute filename (must exist and be validated OK before calling function)
1230 * @return array Array of pointers to sections that the document should be divided into
1231 */
1232 public function fileContentParts($ext, $absFile)
1233 {
1234 $cParts = [0];
1235 // Consult relevant external document parser:
1236 if (is_object($this->external_parsers[$ext])) {
1237 $cParts = $this->external_parsers[$ext]->fileContentParts($ext, $absFile);
1238 }
1239 return $cParts;
1240 }
1241
1242 /**
1243 * Splits non-HTML content (from external files for instance)
1244 *
1245 * @param string $content Input content (non-HTML) to index.
1246 * @return array Array of content, having the key "body" set (plus "title", "description" and "keywords", but empty)
1247 * @see splitHTMLContent()
1248 */
1249 public function splitRegularContent($content)
1250 {
1251 $contentArr = $this->defaultContentArray;
1252 $contentArr['body'] = $content;
1253 return $contentArr;
1254 }
1255
1256 /**********************************
1257 *
1258 * Analysing content, Extracting words
1259 *
1260 **********************************/
1261 /**
1262 * Convert character set and HTML entities in the value of input content array keys
1263 *
1264 * @param array $contentArr Standard content array
1265 * @param string $charset Charset of the input content (converted to utf-8)
1266 */
1267 public function charsetEntity2utf8(&$contentArr, $charset)
1268 {
1269 // Convert charset if necessary
1270 foreach ($contentArr as $key => $value) {
1271 if ((string)$contentArr[$key] !== '') {
1272 if ($charset !== 'utf-8') {
1273 $contentArr[$key] = mb_convert_encoding($contentArr[$key], 'utf-8', $charset);
1274 }
1275 // decode all numeric / html-entities in the string to real characters:
1276 $contentArr[$key] = html_entity_decode($contentArr[$key]);
1277 }
1278 }
1279 }
1280
1281 /**
1282 * Processing words in the array from split*Content -functions
1283 *
1284 * @param array $contentArr Array of content to index, see splitHTMLContent() and splitRegularContent()
1285 * @return array Content input array modified so each key is not a unique array of words
1286 */
1287 public function processWordsInArrays($contentArr)
1288 {
1289 // split all parts to words
1290 foreach ($contentArr as $key => $value) {
1291 $contentArr[$key] = $this->lexerObj->split2Words($contentArr[$key]);
1292 }
1293 // For title, keywords, and description we don't want duplicates:
1294 $contentArr['title'] = array_unique($contentArr['title']);
1295 $contentArr['keywords'] = array_unique($contentArr['keywords']);
1296 $contentArr['description'] = array_unique($contentArr['description']);
1297 // Return modified array:
1298 return $contentArr;
1299 }
1300
1301 /**
1302 * Extracts the sample description text from the content array.
1303 *
1304 * @param array $contentArr Content array
1305 * @return string Description string
1306 */
1307 public function bodyDescription($contentArr)
1308 {
1309 // Setting description
1310 $maxL = MathUtility::forceIntegerInRange($this->conf['index_descrLgd'], 0, 255, 200);
1311 if ($maxL) {
1312 $bodyDescription = preg_replace('/\s+/u', ' ', $contentArr['body']);
1313 // Shorten the string:
1314 $bodyDescription = mb_strcut($bodyDescription, 0, $maxL, 'utf-8');
1315 }
1316 return $bodyDescription;
1317 }
1318
1319 /**
1320 * Analyzes content to use for indexing,
1321 *
1322 * @param array $content Standard content array: an array with the keys title,keywords,description and body, which all contain an array of words.
1323 * @return array Index Array (whatever that is...)
1324 */
1325 public function indexAnalyze($content)
1326 {
1327 $indexArr = [];
1328 $this->analyzeHeaderinfo($indexArr, $content, 'title', 7);
1329 $this->analyzeHeaderinfo($indexArr, $content, 'keywords', 6);
1330 $this->analyzeHeaderinfo($indexArr, $content, 'description', 5);
1331 $this->analyzeBody($indexArr, $content);
1332 return $indexArr;
1333 }
1334
1335 /**
1336 * Calculates relevant information for headercontent
1337 *
1338 * @param array $retArr Index array, passed by reference
1339 * @param array $content Standard content array
1340 * @param string $key Key from standard content array
1341 * @param int $offset Bit-wise priority to type
1342 */
1343 public function analyzeHeaderinfo(&$retArr, $content, $key, $offset)
1344 {
1345 foreach ($content[$key] as $val) {
1346 $val = substr($val, 0, 60);
1347 // Cut after 60 chars because the index_words.baseword varchar field has this length. This MUST be the same.
1348 if (!isset($retArr[$val])) {
1349 // Word ID (wid)
1350 $retArr[$val]['hash'] = IndexedSearchUtility::md5inthash($val);
1351 // Metaphone value is also 60 only chars long
1352 $metaphone = $this->enableMetaphoneSearch ? substr($this->metaphone($val, $this->storeMetaphoneInfoAsWords), 0, 60) : '';
1353 $retArr[$val]['metaphone'] = $metaphone;
1354 }
1355 // Build metaphone fulltext string (can be used for fulltext indexing)
1356 if ($this->storeMetaphoneInfoAsWords) {
1357 $this->metaphoneContent .= ' ' . $retArr[$val]['metaphone'];
1358 }
1359 // Priority used for flagBitMask feature (see extension configuration)
1360 $retArr[$val]['cmp'] = $retArr[$val]['cmp'] | pow(2, $offset);
1361 // Increase number of occurrences
1362 $retArr[$val]['count']++;
1363 $this->wordcount++;
1364 }
1365 }
1366
1367 /**
1368 * Calculates relevant information for bodycontent
1369 *
1370 * @param array $retArr Index array, passed by reference
1371 * @param array $content Standard content array
1372 */
1373 public function analyzeBody(&$retArr, $content)
1374 {
1375 foreach ($content['body'] as $key => $val) {
1376 $val = substr($val, 0, 60);
1377 // Cut after 60 chars because the index_words.baseword varchar field has this length. This MUST be the same.
1378 if (!isset($retArr[$val])) {
1379 // First occurrence (used for ranking results)
1380 $retArr[$val]['first'] = $key;
1381 // Word ID (wid)
1382 $retArr[$val]['hash'] = IndexedSearchUtility::md5inthash($val);
1383 // Metaphone value is also only 60 chars long
1384 $metaphone = $this->enableMetaphoneSearch ? substr($this->metaphone($val, $this->storeMetaphoneInfoAsWords), 0, 60) : '';
1385 $retArr[$val]['metaphone'] = $metaphone;
1386 }
1387 // Build metaphone fulltext string (can be used for fulltext indexing)
1388 if ($this->storeMetaphoneInfoAsWords) {
1389 $this->metaphoneContent .= ' ' . $retArr[$val]['metaphone'];
1390 }
1391 // Increase number of occurrences
1392 $retArr[$val]['count']++;
1393 $this->wordcount++;
1394 }
1395 }
1396
1397 /**
1398 * Creating metaphone based hash from input word
1399 *
1400 * @param string $word Word to convert
1401 * @param bool $returnRawMetaphoneValue If set, returns the raw metaphone value (not hashed)
1402 * @return mixed Metaphone hash integer (or raw value, string)
1403 */
1404 public function metaphone($word, $returnRawMetaphoneValue = false)
1405 {
1406 if (is_object($this->metaphoneObj)) {
1407 $metaphoneRawValue = $this->metaphoneObj->metaphone($word, $this->conf['sys_language_uid']);
1408 } else {
1409 // Use native PHP function instead of advanced doubleMetaphone class
1410 $metaphoneRawValue = metaphone($word);
1411 }
1412 if ($returnRawMetaphoneValue) {
1413 $result = $metaphoneRawValue;
1414 } elseif ($metaphoneRawValue !== '') {
1415 // Create hash and return integer
1416 $result = IndexedSearchUtility::md5inthash($metaphoneRawValue);
1417 } else {
1418 $result = 0;
1419 }
1420 return $result;
1421 }
1422
1423 /********************************
1424 *
1425 * SQL; TYPO3 Pages
1426 *
1427 *******************************/
1428 /**
1429 * Updates db with information about the page (TYPO3 page, not external media)
1430 */
1431 public function submitPage()
1432 {
1433 // Remove any current data for this phash:
1434 $this->removeOldIndexedPages($this->hash['phash']);
1435 // setting new phash_row
1436 $fields = [
1437 'phash' => $this->hash['phash'],
1438 'phash_grouping' => $this->hash['phash_grouping'],
1439 'cHashParams' => serialize($this->cHashParams),
1440 'contentHash' => $this->content_md5h,
1441 'data_page_id' => $this->conf['id'],
1442 'data_page_reg1' => $this->conf['page_cache_reg1'],
1443 'data_page_type' => $this->conf['type'],
1444 'data_page_mp' => $this->conf['MP'],
1445 'gr_list' => $this->conf['gr_list'],
1446 'item_type' => 0,
1447 // TYPO3 page
1448 'item_title' => $this->contentParts['title'],
1449 'item_description' => $this->bodyDescription($this->contentParts),
1450 'item_mtime' => (int)$this->conf['mtime'],
1451 'item_size' => strlen($this->conf['content']),
1452 'tstamp' => $GLOBALS['EXEC_TIME'],
1453 'crdate' => $GLOBALS['EXEC_TIME'],
1454 'item_crdate' => $this->conf['crdate'],
1455 // Creation date of page
1456 'sys_language_uid' => $this->conf['sys_language_uid'],
1457 // Sys language uid of the page. Should reflect which language it DOES actually display!
1458 'externalUrl' => 0,
1459 'recordUid' => (int)$this->conf['recordUid'],
1460 'freeIndexUid' => (int)$this->conf['freeIndexUid'],
1461 'freeIndexSetId' => (int)$this->conf['freeIndexSetId']
1462 ];
1463 if (IndexedSearchUtility::isTableUsed('index_phash')) {
1464 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1465 ->getConnectionForTable('index_phash');
1466 $connection->insert(
1467 'index_phash',
1468 $fields,
1469 ['cHashParams' => Connection::PARAM_LOB]
1470 );
1471 }
1472 // PROCESSING index_section
1473 $this->submit_section($this->hash['phash'], $this->hash['phash']);
1474 // PROCESSING index_grlist
1475 $this->submit_grlist($this->hash['phash'], $this->hash['phash']);
1476 // PROCESSING index_fulltext
1477 $fields = [
1478 'phash' => $this->hash['phash'],
1479 'fulltextdata' => implode(' ', $this->contentParts),
1480 'metaphonedata' => $this->metaphoneContent
1481 ];
1482 if ($this->indexerConfig['fullTextDataLength'] > 0) {
1483 $fields['fulltextdata'] = substr($fields['fulltextdata'], 0, $this->indexerConfig['fullTextDataLength']);
1484 }
1485 if (IndexedSearchUtility::isTableUsed('index_fulltext')) {
1486 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1487 ->getConnectionForTable('index_fulltext');
1488 $connection->insert('index_fulltext', $fields);
1489 }
1490 // PROCESSING index_debug
1491 if ($this->indexerConfig['debugMode']) {
1492 $fields = [
1493 'phash' => $this->hash['phash'],
1494 'debuginfo' => serialize([
1495 'cHashParams' => $this->cHashParams,
1496 'external_parsers initialized' => array_keys($this->external_parsers),
1497 'conf' => array_merge($this->conf, ['content' => substr($this->conf['content'], 0, 1000)]),
1498 'contentParts' => array_merge($this->contentParts, ['body' => substr($this->contentParts['body'], 0, 1000)]),
1499 'logs' => $this->internal_log,
1500 'lexer' => $this->lexerObj->debugString
1501 ])
1502 ];
1503 if (IndexedSearchUtility::isTableUsed('index_debug')) {
1504 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1505 ->getConnectionForTable('index_debug');
1506 $connection->insert('index_debug', $fields);
1507 }
1508 }
1509 }
1510
1511 /**
1512 * Stores gr_list in the database.
1513 *
1514 * @param int $hash Search result record phash
1515 * @param int $phash_x Actual phash of current content
1516 * @see update_grlist()
1517 */
1518 public function submit_grlist($hash, $phash_x)
1519 {
1520 // Setting the gr_list record
1521 $fields = [
1522 'phash' => $hash,
1523 'phash_x' => $phash_x,
1524 'hash_gr_list' => IndexedSearchUtility::md5inthash($this->conf['gr_list']),
1525 'gr_list' => $this->conf['gr_list']
1526 ];
1527 if (IndexedSearchUtility::isTableUsed('index_grlist')) {
1528 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1529 ->getConnectionForTable('index_grlist');
1530 $connection->insert('index_grlist', $fields);
1531 }
1532 }
1533
1534 /**
1535 * Stores section
1536 * $hash and $hash_t3 are the same for TYPO3 pages, but different when it is external files.
1537 *
1538 * @param int $hash phash of TYPO3 parent search result record
1539 * @param int $hash_t3 phash of the file indexation search record
1540 */
1541 public function submit_section($hash, $hash_t3)
1542 {
1543 $fields = [
1544 'phash' => $hash,
1545 'phash_t3' => $hash_t3,
1546 'page_id' => (int)$this->conf['id']
1547 ];
1548 $this->getRootLineFields($fields);
1549 if (IndexedSearchUtility::isTableUsed('index_section')) {
1550 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1551 ->getConnectionForTable('index_section');
1552 $connection->insert('index_section', $fields);
1553 }
1554 }
1555
1556 /**
1557 * Removes records for the indexed page, $phash
1558 *
1559 * @param int $phash phash value to flush
1560 */
1561 public function removeOldIndexedPages($phash)
1562 {
1563 // Removing old registrations for all tables. Because the pages are TYPO3 pages
1564 // there can be nothing else than 1-1 relations here.
1565 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1566 $tableArray = ['index_phash', 'index_section', 'index_grlist', 'index_fulltext', 'index_debug'];
1567 foreach ($tableArray as $table) {
1568 if (IndexedSearchUtility::isTableUsed($table)) {
1569 $connectionPool->getConnectionForTable($table)->delete($table, ['phash' => (int)$phash]);
1570 }
1571 }
1572
1573 // Removing all index_section records with hash_t3 set to this hash (this includes such
1574 // records set for external media on the page as well!). The re-insert of these records
1575 // are done in indexRegularDocument($file).
1576 if (IndexedSearchUtility::isTableUsed('index_section')) {
1577 $connectionPool->getConnectionForTable('index_section')
1578 ->delete('index_section', ['phash_t3' => (int)$phash]);
1579 }
1580 }
1581
1582 /********************************
1583 *
1584 * SQL; External media
1585 *
1586 *******************************/
1587 /**
1588 * Updates db with information about the file
1589 *
1590 * @param array $hash Array with phash and phash_grouping keys for file
1591 * @param string $file File name
1592 * @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)
1593 * @param string $ext File extension determining the type of media.
1594 * @param int $mtime Modification time of file.
1595 * @param int $ctime Creation time of file.
1596 * @param int $size Size of file in bytes
1597 * @param int $content_md5h Content HASH value.
1598 * @param array $contentParts Standard content array (using only title and body for a file)
1599 */
1600 public function submitFilePage($hash, $file, $subinfo, $ext, $mtime, $ctime, $size, $content_md5h, $contentParts)
1601 {
1602 // Find item Type:
1603 $storeItemType = $this->external_parsers[$ext]->ext2itemtype_map[$ext];
1604 $storeItemType = $storeItemType ?: $ext;
1605 // Remove any current data for this phash:
1606 $this->removeOldIndexedFiles($hash['phash']);
1607 // Split filename:
1608 $fileParts = parse_url($file);
1609 // Setting new
1610 $fields = [
1611 'phash' => $hash['phash'],
1612 'phash_grouping' => $hash['phash_grouping'],
1613 'cHashParams' => serialize($subinfo),
1614 'contentHash' => $content_md5h,
1615 'data_filename' => $file,
1616 'item_type' => $storeItemType,
1617 'item_title' => trim($contentParts['title']) ?: basename($file),
1618 'item_description' => $this->bodyDescription($contentParts),
1619 'item_mtime' => $mtime,
1620 'item_size' => $size,
1621 'item_crdate' => $ctime,
1622 'tstamp' => $GLOBALS['EXEC_TIME'],
1623 'crdate' => $GLOBALS['EXEC_TIME'],
1624 'gr_list' => $this->conf['gr_list'],
1625 'externalUrl' => $fileParts['scheme'] ? 1 : 0,
1626 'recordUid' => (int)$this->conf['recordUid'],
1627 'freeIndexUid' => (int)$this->conf['freeIndexUid'],
1628 'freeIndexSetId' => (int)$this->conf['freeIndexSetId'],
1629 'sys_language_uid' => (int)$this->conf['sys_language_uid']
1630 ];
1631 if (IndexedSearchUtility::isTableUsed('index_phash')) {
1632 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1633 ->getConnectionForTable('index_phash');
1634 $connection->insert(
1635 'index_phash',
1636 $fields,
1637 ['cHashParams' => Connection::PARAM_LOB]
1638 );
1639 }
1640 // PROCESSING index_fulltext
1641 $fields = [
1642 'phash' => $hash['phash'],
1643 'fulltextdata' => implode(' ', $contentParts),
1644 'metaphonedata' => $this->metaphoneContent
1645 ];
1646 if ($this->indexerConfig['fullTextDataLength'] > 0) {
1647 $fields['fulltextdata'] = substr($fields['fulltextdata'], 0, $this->indexerConfig['fullTextDataLength']);
1648 }
1649 if (IndexedSearchUtility::isTableUsed('index_fulltext')) {
1650 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1651 ->getConnectionForTable('index_fulltext');
1652 $connection->insert('index_fulltext', $fields);
1653 }
1654 // PROCESSING index_debug
1655 if ($this->indexerConfig['debugMode']) {
1656 $fields = [
1657 'phash' => $hash['phash'],
1658 'debuginfo' => serialize([
1659 'cHashParams' => $subinfo,
1660 'contentParts' => array_merge($contentParts, ['body' => substr($contentParts['body'], 0, 1000)]),
1661 'logs' => $this->internal_log,
1662 'lexer' => $this->lexerObj->debugString
1663 ])
1664 ];
1665 if (IndexedSearchUtility::isTableUsed('index_debug')) {
1666 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
1667 ->getConnectionForTable('index_debug');
1668 $connection->insert('index_debug', $fields);
1669 }
1670 }
1671 }
1672
1673 /**
1674 * Stores file gr_list for a file IF it does not exist already
1675 *
1676 * @param int $hash phash value of file
1677 */
1678 public function submitFile_grlist($hash)
1679 {
1680 // 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.
1681 if (!IndexedSearchUtility::isTableUsed('index_grlist')) {
1682 return;
1683 }
1684
1685 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1686 ->getQueryBuilderForTable('index_grlist');
1687 $count = (int)$queryBuilder->count('*')
1688 ->from('index_grlist')
1689 ->where(
1690 $queryBuilder->expr()->eq(
1691 'phash',
1692 $queryBuilder->createNamedParameter($hash, \PDO::PARAM_INT)
1693 ),
1694 $queryBuilder->expr()->orX(
1695 $queryBuilder->expr()->eq(
1696 'hash_gr_list',
1697 $queryBuilder->createNamedParameter(
1698 IndexedSearchUtility::md5inthash($this->defaultGrList),
1699 \PDO::PARAM_INT
1700 )
1701 ),
1702 $queryBuilder->expr()->eq(
1703 'hash_gr_list',
1704 $queryBuilder->createNamedParameter(
1705 IndexedSearchUtility::md5inthash($this->conf['gr_list']),
1706 \PDO::PARAM_INT
1707 )
1708 )
1709 )
1710 )
1711 ->execute()
1712 ->fetchColumn();
1713
1714 if ($count === 0) {
1715 $this->submit_grlist($hash, $hash);
1716 }
1717 }
1718
1719 /**
1720 * Stores file section for a file IF it does not exist
1721 *
1722 * @param int $hash phash value of file
1723 */
1724 public function submitFile_section($hash)
1725 {
1726 // Testing if there is already a section
1727 if (!IndexedSearchUtility::isTableUsed('index_section')) {
1728 return;
1729 }
1730
1731 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1732 ->getQueryBuilderForTable('index_section');
1733 $count = (int)$queryBuilder->count('phash')
1734 ->from('index_section')
1735 ->where(
1736 $queryBuilder->expr()->eq(
1737 'phash',
1738 $queryBuilder->createNamedParameter($hash, \PDO::PARAM_INT)
1739 ),
1740 $queryBuilder->expr()->eq(
1741 'page_id',
1742 $queryBuilder->createNamedParameter($this->conf['id'], \PDO::PARAM_INT)
1743 )
1744 )
1745 ->execute()
1746 ->fetchColumn();
1747
1748 if ($count === 0) {
1749 $this->submit_section($hash, $this->hash['phash']);
1750 }
1751 }
1752
1753 /**
1754 * Removes records for the indexed page, $phash
1755 *
1756 * @param int $phash phash value to flush
1757 */
1758 public function removeOldIndexedFiles($phash)
1759 {
1760 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1761 // Removing old registrations for tables.
1762 $tableArray = ['index_phash', 'index_grlist', 'index_fulltext', 'index_debug'];
1763 foreach ($tableArray as $table) {
1764 if (!IndexedSearchUtility::isTableUsed($table)) {
1765 continue;
1766 }
1767 $connectionPool->getConnectionForTable($table)->delete($table, ['phash' => (int)$phash]);
1768 }
1769 }
1770
1771 /********************************
1772 *
1773 * SQL Helper functions
1774 *
1775 *******************************/
1776 /**
1777 * Check the mtime / tstamp of the currently indexed page/file (based on phash)
1778 * Return positive integer if the page needs to be indexed
1779 *
1780 * @param int $mtime mtime value to test against limits and indexed page (usually this is the mtime of the cached document)
1781 * @param int $phash "phash" used to select any already indexed page to see what its mtime is.
1782 * @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.
1783 */
1784 public function checkMtimeTstamp($mtime, $phash)
1785 {
1786 if (!IndexedSearchUtility::isTableUsed('index_phash')) {
1787 // Not indexed (not in index_phash)
1788 $result = 4;
1789 } else {
1790 $row = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_phash')
1791 ->select(
1792 ['item_mtime', 'tstamp'],
1793 'index_phash',
1794 ['phash' => (int)$phash],
1795 [],
1796 [],
1797 1
1798 )
1799 ->fetch();
1800 // If there was an indexing of the page...:
1801 if (!empty($row)) {
1802 if ($this->tstamp_maxAge && $row['tstamp'] + $this->tstamp_maxAge < $GLOBALS['EXEC_TIME']) {
1803 // If max age is exceeded, index the page
1804 // The configured max-age was exceeded for the document and thus it's indexed.
1805 $result = 1;
1806 } else {
1807 if (!$this->tstamp_minAge || $row['tstamp'] + $this->tstamp_minAge < $GLOBALS['EXEC_TIME']) {
1808 // if minAge is not set or if minAge is exceeded, consider at mtime
1809 if ($mtime) {
1810 // It mtime is set, then it's tested. If not, the page must clearly be indexed.
1811 if ($row['item_mtime'] != $mtime) {
1812 // And if mtime is different from the index_phash mtime, it's about time to re-index.
1813 // The minimum age was exceed and mtime was set and the mtime was different, so the page was indexed.
1814 $result = 2;
1815 } else {
1816 // mtime matched the document, so no changes detected and no content updated
1817 $result = -1;
1818 if ($this->tstamp_maxAge) {
1819 $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);
1820 } else {
1821 $this->updateTstamp($phash);
1822 $this->log_setTSlogMessage('mtime matched, timestamp updated.', 1);
1823 }
1824 }
1825 } else {
1826 // The minimum age was exceed, but mtime was not set, so the page was indexed.
1827 $result = 3;
1828 }
1829 } else {
1830 // The minimum age was not exceeded
1831 $result = -2;
1832 }
1833 }
1834 } else {
1835 // Page has never been indexed (is not represented in the index_phash table).
1836 $result = 4;
1837 }
1838 }
1839 return $result;
1840 }
1841
1842 /**
1843 * Check content hash in phash table
1844 *
1845 * @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!
1846 */
1847 public function checkContentHash()
1848 {
1849 // With this query the page will only be indexed if it's content is different from the same "phash_grouping" -page.
1850 $result = true;
1851 if (IndexedSearchUtility::isTableUsed('index_phash')) {
1852 $row = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_phash')
1853 ->select(
1854 ['phash'],
1855 'index_phash',
1856 [
1857 'phash_grouping' => (int)$this->hash['phash_grouping'],
1858 'contentHash' => (int)$this->content_md5h
1859 ],
1860 [],
1861 [],
1862 1
1863 )
1864 ->fetch();
1865
1866 if (!empty($row)) {
1867 $result = $row;
1868 }
1869 }
1870 return $result;
1871 }
1872
1873 /**
1874 * Check content hash for external documents
1875 * Returns TRUE if the document needs to be indexed (that is, there was no result)
1876 *
1877 * @param int $hashGr phash value to check (phash_grouping)
1878 * @param int $content_md5h Content hash to check
1879 * @return bool Returns TRUE if the document needs to be indexed (that is, there was no result)
1880 */
1881 public function checkExternalDocContentHash($hashGr, $content_md5h)
1882 {
1883 $result = true;
1884 if (IndexedSearchUtility::isTableUsed('index_phash')) {
1885 $count = (int)GeneralUtility::makeInstance(ConnectionPool::class)
1886 ->getConnectionForTable('index_phash')
1887 ->count(
1888 '*',
1889 'index_phash',
1890 [
1891 'phash_grouping' => (int)$hashGr,
1892 'contentHash' => (int)$content_md5h
1893 ]
1894 );
1895
1896 $result = $count === 0;
1897 }
1898 return $result;
1899 }
1900
1901 /**
1902 * 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)
1903 *
1904 * @param int $phash_x Phash integer to test.
1905 * @return bool
1906 */
1907 public function is_grlist_set($phash_x)
1908 {
1909 $result = false;
1910 if (IndexedSearchUtility::isTableUsed('index_grlist')) {
1911 $count = (int)GeneralUtility::makeInstance(ConnectionPool::class)
1912 ->getConnectionForTable('index_grlist')
1913 ->count(
1914 'phash_x',
1915 'index_grlist',
1916 ['phash_x' => (int)$phash_x]
1917 );
1918
1919 $result = $count > 0;
1920 }
1921 return $result;
1922 }
1923
1924 /**
1925 * Check if an grlist-entry for this hash exists and if not so, write one.
1926 *
1927 * @param int $phash phash of the search result that should be found
1928 * @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...
1929 * @see submit_grlist()
1930 */
1931 public function update_grlist($phash, $phash_x)
1932 {
1933 if (IndexedSearchUtility::isTableUsed('index_grlist')) {
1934 $count = (int)GeneralUtility::makeInstance(ConnectionPool::class)
1935 ->getConnectionForTable('index_grlist')
1936 ->count(
1937 'phash',
1938 'index_grlist',
1939 [
1940 'phash' => (int)$phash,
1941 'hash_gr_list' => IndexedSearchUtility::md5inthash($this->conf['gr_list'])
1942 ]
1943 );
1944
1945 if ($count === 0) {
1946 $this->submit_grlist($phash, $phash_x);
1947 $this->log_setTSlogMessage('Inserted gr_list \'' . $this->conf['gr_list'] . '\' for phash \'' . $phash . '\'', 1);
1948 }
1949 }
1950 }
1951
1952 /**
1953 * Update tstamp for a phash row.
1954 *
1955 * @param int $phash phash value
1956 * @param int $mtime If set, update the mtime field to this value.
1957 */
1958 public function updateTstamp($phash, $mtime = 0)
1959 {
1960 if (!IndexedSearchUtility::isTableUsed('index_phash')) {
1961 return;
1962 }
1963
1964 $updateFields = [
1965 'tstamp' => $GLOBALS['EXEC_TIME']
1966 ];
1967
1968 if ($mtime) {
1969 $updateFields['item_mtime'] = (int)$mtime;
1970 }
1971
1972 GeneralUtility::makeInstance(ConnectionPool::class)
1973 ->getConnectionForTable('index_phash')
1974 ->update(
1975 'index_phash',
1976 $updateFields,
1977 [
1978 'phash' => (int)$phash
1979 ]
1980 );
1981 }
1982
1983 /**
1984 * Update SetID of the index_phash record.
1985 *
1986 * @param int $phash phash value
1987 */
1988 public function updateSetId($phash)
1989 {
1990 if (!IndexedSearchUtility::isTableUsed('index_phash')) {
1991 return;
1992 }
1993
1994 GeneralUtility::makeInstance(ConnectionPool::class)
1995 ->getConnectionForTable('index_phash')
1996 ->update(
1997 'index_phash',
1998 [
1999 'freeIndexSetId' => (int)$this->conf['freeIndexSetId']
2000 ],
2001 [
2002 'phash' => (int)$phash
2003 ]
2004 );
2005 }
2006
2007 /**
2008 * Update parsetime for phash row.
2009 *
2010 * @param int $phash phash value.
2011 * @param int $parsetime Parsetime value to set.
2012 */
2013 public function updateParsetime($phash, $parsetime)
2014 {
2015 if (!IndexedSearchUtility::isTableUsed('index_phash')) {
2016 return;
2017 }
2018
2019 GeneralUtility::makeInstance(ConnectionPool::class)
2020 ->getConnectionForTable('index_phash')
2021 ->update(
2022 'index_phash',
2023 [
2024 'parsetime' => (int)$parsetime
2025 ],
2026 [
2027 'phash' => (int)$phash
2028 ]
2029 );
2030 }
2031
2032 /**
2033 * Update section rootline for the page
2034 */
2035 public function updateRootline()
2036 {
2037 if (!IndexedSearchUtility::isTableUsed('index_section')) {
2038 return;
2039 }
2040
2041 $updateFields = [];
2042 $this->getRootLineFields($updateFields);
2043
2044 GeneralUtility::makeInstance(ConnectionPool::class)
2045 ->getConnectionForTable('index_section')
2046 ->update(
2047 'index_section',
2048 $updateFields,
2049 [
2050 'page_id' => (int)$this->conf['id']
2051 ]
2052 );
2053 }
2054
2055 /**
2056 * Adding values for root-line fields.
2057 * rl0, rl1 and rl2 are standard. A hook might add more.
2058 *
2059 * @param array $fieldArray Field array, passed by reference
2060 */
2061 public function getRootLineFields(array &$fieldArray)
2062 {
2063 $fieldArray['rl0'] = (int)$this->conf['rootline_uids'][0];
2064 $fieldArray['rl1'] = (int)$this->conf['rootline_uids'][1];
2065 $fieldArray['rl2'] = (int)$this->conf['rootline_uids'][2];
2066 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['addRootLineFields'])) {
2067 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['indexed_search']['addRootLineFields'] as $fieldName => $rootLineLevel) {
2068 $fieldArray[$fieldName] = (int)$this->conf['rootline_uids'][$rootLineLevel];
2069 }
2070 }
2071 }
2072
2073 /********************************
2074 *
2075 * SQL; Submitting words
2076 *
2077 *******************************/
2078 /**
2079 * Adds new words to db
2080 *
2081 * @param array $wordListArray Word List array (where each word has information about position etc).
2082 */
2083 public function checkWordList($wordListArray)
2084 {
2085 if (!IndexedSearchUtility::isTableUsed('index_words') || empty($wordListArray)) {
2086 return;
2087 }
2088
2089 $wordListArrayCount = count($wordListArray);
2090 $phashArray = array_map('intval', array_column($wordListArray, 'hash'));
2091
2092 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('index_words');
2093 $count = (int)$queryBuilder->count('baseword')
2094 ->from('index_words')
2095 ->where(
2096 $queryBuilder->expr()->in(
2097 'wid',
2098 $queryBuilder->createNamedParameter($phashArray, Connection::PARAM_INT_ARRAY)
2099 )
2100 )
2101 ->execute()
2102 ->fetchColumn();
2103
2104 if ($count !== $wordListArrayCount) {
2105 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('index_words');
2106 $queryBuilder = $connection->createQueryBuilder();
2107
2108 $result = $queryBuilder->select('baseword')
2109 ->from('index_words')
2110 ->where(
2111 $queryBuilder->expr()->in(
2112 'wid',
2113 $queryBuilder->createNamedParameter($phashArray, Connection::PARAM_INT_ARRAY)
2114 )
2115 )
2116 ->execute();
2117
2118 $this->log_setTSlogMessage('Inserting words: ' . ($wordListArrayCount - $count), 1);
2119 while ($row = $result->fetch()) {
2120 unset($wordListArray[$row['baseword']]);
2121 }
2122
2123 foreach ($wordListArray as $key => $val) {
2124 // A duplicate-key error will occur here if a word is NOT unset in the unset() line. However as
2125 // long as the words in $wl are NOT longer as 60 chars (the baseword varchar is 60 characters...)
2126 // this is not a problem.
2127 $connection->insert(
2128 'index_words',
2129 [
2130 'wid' => $val['hash'],
2131 'baseword' => $key,
2132 'metaphone' => $val['metaphone']
2133 ]
2134 );
2135 }
2136 }
2137 }
2138
2139 /**
2140 * Submits RELATIONS between words and phash
2141 *
2142 * @param array $wordList Word list array
2143 * @param int $phash phash value
2144 */
2145 public function submitWords($wordList, $phash)
2146 {
2147 if (!IndexedSearchUtility::isTableUsed('index_rel')) {
2148 return;
2149 }
2150 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
2151 $queryBuilder = $connectionPool->getQueryBuilderForTable('index_words');
2152 $result = $queryBuilder->select('wid')
2153 ->from('index_words')
2154 ->where(
2155 $queryBuilder->expr()->neq('is_stopword', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
2156 )
2157 ->groupBy('wid')
2158 ->execute();
2159
2160 $stopWords = [];
2161 while ($row = $result->fetch()) {
2162 $stopWords[$row['wid']] = $row;
2163 }
2164
2165 $connectionPool->getConnectionForTable('index_rel')->delete('index_rel', ['phash' => (int)$phash]);
2166
2167 $fields = ['phash', 'wid', 'count', 'first', 'freq', 'flags'];
2168 $rows = [];
2169 foreach ($wordList as $val) {
2170 if (isset($stopWords[$val['hash']])) {
2171 continue;
2172 }
2173 $rows[] = [
2174 (int)$phash,
2175 (int)$val['hash'],
2176 (int)$val['count'],
2177 (int)$val['first'],
2178 $this->freqMap($val['count'] / $this->wordcount),
2179 $val['cmp'] & $this->flagBitMask
2180 ];
2181 }
2182
2183 if (!empty($rows)) {
2184 $connectionPool->getConnectionForTable('index_rel')->bulkInsert('index_rel', $rows, $fields);
2185 }
2186 }
2187
2188 /**
2189 * maps frequency from a real number in [0;1] to an integer in [0;$this->freqRange] with anything above $this->freqMax as 1
2190 * and back.
2191 *
2192 * @param float $freq Frequency
2193 * @return int Frequency in range.
2194 */
2195 public function freqMap($freq)
2196 {
2197 $mapFactor = $this->freqMax * 100 * $this->freqRange;
2198 if ($freq <= 1) {
2199 $newFreq = $freq * $mapFactor;
2200 $newFreq = $newFreq > $this->freqRange ? $this->freqRange : $newFreq;
2201 } else {
2202 $newFreq = $freq / $mapFactor;
2203 }
2204 return $newFreq;
2205 }
2206
2207 /********************************
2208 *
2209 * Hashing
2210 *
2211 *******************************/
2212 /**
2213 * Get search hash, T3 pages
2214 */
2215 public function setT3Hashes()
2216 {
2217 // Set main array:
2218 $hArray = [
2219 'id' => (int)$this->conf['id'],
2220 'type' => (int)$this->conf['type'],
2221 'sys_lang' => (int)$this->conf['sys_language_uid'],
2222 'MP' => (string)$this->conf['MP'],
2223 'cHash' => $this->cHashParams
2224 ];
2225 // Set grouping hash (Identifies a "page" combined of id, type, language, mountpoint and cHash parameters):
2226 $this->hash['phash_grouping'] = IndexedSearchUtility::md5inthash(serialize($hArray));
2227 // 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.)
2228 $hArray['gr_list'] = (string)$this->conf['gr_list'];
2229 $this->hash['phash'] = IndexedSearchUtility::md5inthash(serialize($hArray));
2230 }
2231
2232 /**
2233 * Get search hash, external files
2234 *
2235 * @param string $file File name / path which identifies it on the server
2236 * @param array $subinfo Additional content identifying the (subpart of) content. For instance; PDF files are divided into groups of pages for indexing.
2237 * @return array Array with "phash_grouping" and "phash" inside.
2238 */
2239 public function setExtHashes($file, $subinfo = [])
2240 {
2241 // Set main array:
2242 $hash = [];
2243 $hArray = [
2244 'file' => $file
2245 ];
2246 // Set grouping hash:
2247 $hash['phash_grouping'] = IndexedSearchUtility::md5inthash(serialize($hArray));
2248 // Add subinfo
2249 $hArray['subinfo'] = $subinfo;
2250 $hash['phash'] = IndexedSearchUtility::md5inthash(serialize($hArray));
2251 return $hash;
2252 }
2253
2254 /*********************************
2255 *
2256 * Internal logging functions
2257 *
2258 *********************************/
2259 /**
2260 * Push function wrapper for TT logging
2261 *
2262 * @param string $msg Title to set
2263 * @param string $key Key (?)
2264 */
2265 public function log_push($msg, $key)
2266 {
2267 $this->timeTracker->push($msg, $key);
2268 }
2269
2270 /**
2271 * Pull function wrapper for TT logging
2272 */
2273 public function log_pull()
2274 {
2275 $this->timeTracker->pull();
2276 }
2277
2278 /**
2279 * Set log message function wrapper for TT logging
2280 *
2281 * @param string $msg Message to set
2282 * @param int $errorNum Error number
2283 */
2284 public function log_setTSlogMessage($msg, $errorNum = 0)
2285 {
2286 $this->timeTracker->setTSlogMessage($msg, $errorNum);
2287 $this->internal_log[] = $msg;
2288 }
2289
2290 /**
2291 * Makes sure that keywords are space-separated. This is impotant for their
2292 * proper displaying as a part of fulltext index.
2293 *
2294 * @param string $keywordList
2295 * @return string
2296 * @see http://forge.typo3.org/issues/14959
2297 */
2298 protected function addSpacesToKeywordList($keywordList)
2299 {
2300 $keywords = GeneralUtility::trimExplode(',', $keywordList);
2301 return ' ' . implode(', ', $keywords) . ' ';
2302 }
2303 }