removeFromIndexAndQueueWhenItemInQueue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2.0625
1
<?php
2
namespace ApacheSolrForTypo3\Solr\IndexQueue;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2009-2015 Ingo Renner <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\AbstractDataHandlerListener;
28
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\ConfigurationAwareRecordService;
29
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\MountPagesUpdater;
30
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\RootPageResolver;
31
use ApacheSolrForTypo3\Solr\FrontendEnvironment;
32
use ApacheSolrForTypo3\Solr\GarbageCollector;
33
use ApacheSolrForTypo3\Solr\System\Configuration\ExtensionConfiguration;
34
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
35
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
36
use ApacheSolrForTypo3\Solr\System\Records\Pages\PagesRepository;
37
use ApacheSolrForTypo3\Solr\System\TCA\TCAService;
38
use ApacheSolrForTypo3\Solr\Util;
39
use TYPO3\CMS\Backend\Utility\BackendUtility;
40
use TYPO3\CMS\Core\DataHandling\DataHandler;
41
use TYPO3\CMS\Core\Utility\GeneralUtility;
42
43
/**
44
 * A class that monitors changes to records so that the changed record gets
45
 * passed to the index queue to update the according index document.
46
 *
47
 * @author Ingo Renner <[email protected]>
48
 */
49
class RecordMonitor extends AbstractDataHandlerListener
50
{
51
    /**
52
     * Index Queue
53
     *
54
     * @var Queue
55
     */
56
    protected $indexQueue;
57
58
    /**
59
     * Mount Page Updater
60
     *
61
     * @var MountPagesUpdater
62
     */
63
    protected $mountPageUpdater;
64
65
    /**
66
     * TCA Service
67
     *
68
     * @var TCAService
69
     */
70
    protected $tcaService;
71
72
    /**
73
     * RootPageResolver
74
     *
75
     * @var RootPageResolver
76
     */
77
    protected $rootPageResolver;
78
79
    /**
80
     * @var PagesRepository
81
     */
82
    protected $pagesRepository;
83
84
    /**
85
     * @var SolrLogManager
86
     */
87
    protected $logger = null;
88
89
    /**
90
     * @var FrontendEnvironment
91
     */
92
    protected $frontendEnvironment = null;
93
94
    /**
95
     * RecordMonitor constructor.
96
     *
97
     * @param Queue|null $indexQueue
98
     * @param MountPagesUpdater|null $mountPageUpdater
99 47
     * @param TCAService|null $TCAService
100
     * @param RootPageResolver $rootPageResolver
101 47
     * @param PagesRepository|null $pagesRepository
102 47
     * @param SolrLogManager|null $solrLogManager
103 47
     * @param ConfigurationAwareRecordService|null $recordService
104 47
     */
105 47
    public function __construct(
106 47
        Queue $indexQueue = null,
107 47
        MountPagesUpdater $mountPageUpdater = null,
108 47
        TCAService $TCAService = null,
109
        RootPageResolver $rootPageResolver = null,
110
        PagesRepository $pagesRepository = null,
111
        SolrLogManager $solrLogManager = null,
112
        ConfigurationAwareRecordService $recordService = null,
113 1
        FrontendEnvironment $frontendEnvironment = null
114
    )
115 1
    {
116 1
        parent::__construct($recordService);
117
        $this->indexQueue = $indexQueue ?? GeneralUtility::makeInstance(Queue::class);
118
        $this->mountPageUpdater = $mountPageUpdater ?? GeneralUtility::makeInstance(MountPagesUpdater::class);
119
        $this->tcaService = $TCAService ?? GeneralUtility::makeInstance(TCAService::class);
120
        $this->rootPageResolver = $rootPageResolver ?? GeneralUtility::makeInstance(RootPageResolver::class);
121
        $this->pagesRepository = $pagesRepository ?? GeneralUtility::makeInstance(PagesRepository::class);
122
        $this->logger = $solrLogManager ?? GeneralUtility::makeInstance(SolrLogManager::class, /** @scrutinizer ignore-type */ __CLASS__);
123
        $this->frontendEnvironment = $frontendEnvironment ?? GeneralUtility::makeInstance(FrontendEnvironment::class);
124 27
    }
125
126
    /**
127
     * @param SolrLogManager $logger
128 27
     */
129
    public function setLogger(SolrLogManager $logger)
130
    {
131
        $this->logger = $logger;
132
    }
133
134
    /**
135
     * Holds the configuration when a recursive page queing should be triggered.
136
     *
137
     * @var array
138
     * @return array
139
     */
140
    protected function getUpdateSubPagesRecursiveTriggerConfiguration()
141
    {
142
        return [
143
            // the current page has the field "extendToSubpages" enabled and the field "hidden" was set to 0 => requeue subpages
144
            'extendToSubpageEnabledAndHiddenFlagWasRemoved' => [
145
                'currentState' =>  ['extendToSubpages' => '1'],
146
                'changeSet' => ['hidden' => '0']
147
            ],
148
            // the current page has the field "hidden" enabled and the field "extendToSubpages" was set to 0 => requeue subpages
149 3
            'hiddenIsEnabledAndExtendToSubPagesWasRemoved' => [
150
                'currentState' =>  ['hidden' => '1'],
151
                'changeSet' => ['extendToSubpages' => '0']
152
            ]
153
        ];
154
    }
155
156
    /**
157 3
     * Hooks into TCE main and tracks record deletion commands.
158
     *
159 1
     * @param string $command The command.
160 1
     * @param string $table The table the record belongs to
161
     * @param int $uid The record's uid
162 3
     * @param string $value
163
     * @param DataHandler $tceMain TYPO3 Core Engine parent object
164
     */
165
    public function processCmdmap_preProcess(
166
        $command,
167
        $table,
168
        $uid,
169
        /** @noinspection PhpUnusedParameterInspection */
170
        $value,
171
        DataHandler $tceMain
172
    ) {
173
        if ($command === 'delete' && $table === 'tt_content' && $GLOBALS['BE_USER']->workspace == 0) {
174 10
            // skip workspaces: index only LIVE workspace
175
            $pid = $this->getValidatedPid($tceMain, $table, $uid);
176 10
            $this->indexQueue->updateItem('pages', $pid, time());
177
        }
178
    }
179
180
    /**
181
     * Hooks into TCE main and tracks workspace publish/swap events and
182
     * page move commands in LIVE workspace.
183 10
     *
184 5
     * @param string $command The command.
185
     * @param string $table The table the record belongs to
186
     * @param int $uid The record's uid
187 10
     * @param string $value
188
     * @param DataHandler $tceMain TYPO3 Core Engine parent object
189 2
     */
190
    public function processCmdmap_postProcess($command, $table, $uid, $value, DataHandler $tceMain)
191 10
    {
192
        if ($this->isDraftRecord($table, $uid)) {
193
            // skip workspaces: index only LIVE workspace
194
            return;
195
        }
196
197
        // track publish / swap events for records (workspace support)
198
        // command "version"
199
        if ($command === 'version' && $value['action'] === 'swap') {
200 5
            $this->applyVersionSwap($table, $uid, $tceMain);
201
        }
202 5
203 5
        // moving pages/records in LIVE workspace
204 3
        if ($command === 'move' && $GLOBALS['BE_USER']->workspace == 0) {
205 3
            if ($table === 'pages') {
206
                $this->applyPageChangesToQueue($uid);
207 2
            } else {
208 2
                $this->applyRecordChangesToQueue($table, $uid, $value);
0 ignored issues
show
Bug introduced by
$value of type string is incompatible with the type integer expected by parameter $pid of ApacheSolrForTypo3\Solr\...yRecordChangesToQueue(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

208
                $this->applyRecordChangesToQueue($table, $uid, /** @scrutinizer ignore-type */ $value);
Loading history...
209
            }
210 5
211
        }
212
    }
213
214
    /**
215
     * Apply's version swap to the IndexQueue.
216
     *
217
     * @param string $table
218 5
     * @param integer $uid
219
     * @param DataHandler $tceMain
220 5
     */
221 5
    protected function applyVersionSwap($table, $uid, DataHandler $tceMain)
222 5
    {
223 3
        $isPageRelatedRecord = $table === 'tt_content' || $table === 'pages';
224 3
        if($isPageRelatedRecord) {
225
            $uid = $table === 'tt_content' ? $this->getValidatedPid($tceMain, $table, $uid) : $uid;
226
            $this->applyPageChangesToQueue($uid);
227 2
        } else {
228
            $recordPageId = $this->getValidatedPid($tceMain, $table, $uid);
229 5
            $this->applyRecordChangesToQueue($table, $uid, $recordPageId);
230
        }
231
    }
232
233
    /**
234
     * Add's a page to the queue and updates mounts, when it is enabled, otherwise ensure that the page is removed
235
     * from the queue.
236
     *
237
     * @param integer $uid
238 2
     */
239
    protected function applyPageChangesToQueue($uid)
240 2
    {
241 2
        $solrConfiguration = $this->getSolrConfigurationFromPageId($uid);
242
        $record = $this->configurationAwareRecordService->getRecord('pages', $uid, $solrConfiguration);
243 2
        if (!empty($record) && $this->tcaService->isEnabledRecord('pages', $record)) {
244 2
            $this->mountPageUpdater->update($uid);
245
            $this->indexQueue->updateItem('pages', $uid);
246 2
        } else {
247 1
            // TODO should be moved to garbage collector
248 1
            $this->removeFromIndexAndQueueWhenItemInQueue('pages', $uid);
249
        }
250
    }
251 1
252
    /**
253
     * Add's a record to the queue if it is monitored and enabled, otherwise it removes the record from the queue.
254 2
     * 
255
     * @param string $table
256
     * @param integer $uid
257
     * @param integer $pid
258
     */
259
    protected function applyRecordChangesToQueue($table, $uid, $pid)
260
    {
261
        $solrConfiguration = $this->getSolrConfigurationFromPageId($pid);
262
        $isMonitoredTable = $solrConfiguration->getIndexQueueIsMonitoredTable($table);
263
264
        if ($isMonitoredTable) {
265
            $record = $this->configurationAwareRecordService->getRecord($table, $uid, $solrConfiguration);
266
267
            if (!empty($record) && $this->tcaService->isEnabledRecord($table, $record)) {
268 35
                $uid = $this->tcaService->getTranslationOriginalUidIfTranslated($table, $record, $uid);
269 35
                $this->indexQueue->updateItem($table, $uid);
270 35
            } else {
271
                // TODO should be moved to garbage collector
272 35
                $this->removeFromIndexAndQueueWhenItemInQueue($table, $uid);
273 1
            }
274
        }
275
    }
276 34
277 2
    /**
278
     * Hooks into TCE Main and watches all record creations and updates. If it
279 34
     * detects that the new/updated record belongs to a table configured for
280
     * indexing through Solr, we add the record to the index queue.
281
     *
282
     * @param string $status Status of the current operation, 'new' or 'update'
283
     * @param string $table The table the record belongs to
284
     * @param mixed $uid The record's uid, [integer] or [string] (like 'NEW...')
285 34
     * @param array $fields The record's data
286
     * @param DataHandler $tceMain TYPO3 Core Engine parent object
287
     * @return void
288 33
     */
289 6
    public function processDatamap_afterDatabaseOperations($status, $table, $uid, array $fields, DataHandler $tceMain) {
290 6
        $recordTable = $table;
291
        $recordUid = $uid;
292
293 33
        if ($this->skipMonitoringOfTable($table)) {
294 1
            return;
295 1
        }
296 1
297
        if ($status === 'new') {
298 34
            $recordUid = $tceMain->substNEWwithIDs[$recordUid];
299
        }
300
        if ($this->isDraftRecord($table, $recordUid)) {
301
            // skip workspaces: index only LIVE workspace
302
            return;
303
        }
304
305
        try {
306 35
            $recordPageId = $this->getRecordPageId($status, $recordTable, $recordUid, $uid, $fields, $tceMain);
307
308 35
            // when a content element changes we need to updated the page instead
309
            if ($recordTable === 'tt_content') {
310 35
                $recordTable = 'pages';
311 35
                $recordUid = $recordPageId;
312 35
            }
313
314
            $this->processRecord($recordTable, $recordPageId, $recordUid, $fields);
315
        } catch (NoPidException $e) {
316 35
            $message = 'Record without valid pid was processed ' . $table . ':' . $uid;
317 33
            $this->logger->log(SolrLogManager::WARNING, $message);
318
        }
319
    }
320 2
321
    /**
322
     * Check if the provided table is explicitly configured for monitoring
323
     *
324
     * @param string $table
325
     * @return bool
326
     */
327
    protected function skipMonitoringOfTable($table)
328
    {
329
        static $configurationMonitorTables;
330
331 33
        if (empty($configurationMonitorTables)) {
332
            $configuration = GeneralUtility::makeInstance(ExtensionConfiguration::class);
333 33
            $configurationMonitorTables = $configuration->getIsUseConfigurationMonitorTables();
334
        }
335 33
336
        // No explicit configuration => all tables should be monitored
337
        if (empty($configurationMonitorTables)) {
338
            return false;
339
        }
340
341 33
        return !in_array($table, $configurationMonitorTables);
342 33
    }
343
344 33
    /**
345
     * Process the record located in processDatamap_afterDatabaseOperations
346
     *
347
     * @param string $recordTable The table the record belongs to
348
     * @param int $recordPageId pageid
349 33
     * @param mixed $recordUid The record's uid, [integer] or [string] (like 'NEW...')
350
     * @param array $fields The record's data
351 33
     */
352
    protected function processRecord($recordTable, $recordPageId, $recordUid, $fields)
353
    {
354 1
        $configurationPageId = $this->getConfigurationPageId($recordTable, $recordPageId, $recordUid);
355 1
356
        if ($configurationPageId === 0) {
357
            // when the monitored record doesn't belong to a solr configured root-page and no alternative
358
            // siteroot can be found this is not a relevant record
359
            return;
360
        }
361 32
362 32
        $solrConfiguration = $this->getSolrConfigurationFromPageId($configurationPageId);
363 25
        $isMonitoredRecord = $solrConfiguration->getIndexQueueIsMonitoredTable($recordTable);
364
365
        if (!$isMonitoredRecord) {
366
            // when it is a non monitored record, we can skip it.
367 32
            return;
368 32
        }
369
370
        $record = $this->configurationAwareRecordService->getRecord($recordTable, $recordUid, $solrConfiguration);
371 32
372 3
        if (empty($record)) {
373
            // TODO move this part to the garbage collector
374
            // check if the item should be removed from the index because it no longer matches the conditions
375 32
            $this->removeFromIndexAndQueueWhenItemInQueue($recordTable, $recordUid);
376
            return;
377 1
        }
378
379
        // Clear existing index queue items to prevent mount point duplicates.
380 31
        // This needs to be done before the overlay handling, because handling an overlay record should
381 28
        // not trigger a deletion.
382
        $isTranslation = !empty($record['sys_language_uid']) && $record['sys_language_uid'] !== 0;
383
        if ($recordTable === 'pages' && !$isTranslation) {
384 31
            $this->indexQueue->deleteItem('pages', $recordUid);
385 27
        }
386
387 31
        // only update/insert the item if we actually found a record
388
        $isLocalizedRecord = $this->tcaService->isLocalizedRecord($recordTable, $record);
389
        $recordUid = $this->tcaService->getTranslationOriginalUidIfTranslated($recordTable, $record, $recordUid);
390
391
        if ($isLocalizedRecord && !$this->getIsTranslationParentRecordEnabled($recordTable, $recordUid)) {
392
            // we have a localized record without a visible parent record. Nothing to do.
393
            return;
394
        }
395
396
        if ($this->tcaService->isEnabledRecord($recordTable, $record)) {
397 33
            $this->indexQueue->updateItem($recordTable, $recordUid);
398
        }
399 33
400 33
        if ($recordTable === 'pages') {
401 31
            $this->doPagesPostUpdateOperations($fields, $recordUid);
402
        }
403
    }
404 2
405 2
    /**
406 2
     * This method is used to determine the pageId that should be used to retrieve the index queue configuration.
407
     *
408
     * @param string $recordTable
409
     * @param integer $recordPageId
410
     * @param integer $recordUid
411
     * @return integer
412
     */
413
    protected function getConfigurationPageId($recordTable, $recordPageId, $recordUid)
414
    {
415
        $rootPageId = $this->rootPageResolver->getRootPageId($recordPageId);
416 3
        if ($this->rootPageResolver->getIsRootPageId($rootPageId)) {
417
            return $recordPageId;
418 3
        }
419 3
420 3
        $alternativeSiteRoots = $this->rootPageResolver->getAlternativeSiteRootPagesIds($recordTable, $recordUid, $recordPageId);
421
        $lastRootPage = array_pop($alternativeSiteRoots);
422
        return empty($lastRootPage) ? 0 : $lastRootPage;
423
    }
424
425
    /**
426
     * Checks if the parent record of the translated record is enabled.
427
     *
428
     * @param string $recordTable
429 27
     * @param integer $recordUid
430
     * @return bool
431 27
     */
432 27
    protected function getIsTranslationParentRecordEnabled($recordTable, $recordUid)
433
    {
434 27
        $tableEnableFields = implode(', ', $GLOBALS['TCA'][$recordTable]['ctrl']['enablecolumns']);
435 5
        $l10nParentRecord = (array)BackendUtility::getRecord($recordTable, $recordUid, $tableEnableFields, '', false);
436 5
        return $this->tcaService->isEnabledRecord($recordTable, $l10nParentRecord);
437
    }
438 27
439
    /**
440
     * Applies needed updates when a pages record was processed by the RecordMonitor.
441
     *
442
     * @param array $fields
443
     * @param int $recordUid
444
     */
445
    protected function doPagesPostUpdateOperations(array $fields, $recordUid)
446
    {
447
        $this->updateCanonicalPages($recordUid);
448
        $this->mountPageUpdater->update($recordUid);
449
450
        if ($this->isRecursivePageUpdateRequired($recordUid, $fields)) {
451
            $treePageIds = $this->getSubPageIds($recordUid);
452 34
            $this->updatePageIdItems($treePageIds);
453
        }
454 34
    }
455
456
    /**
457
     * Determines the recordPageId (pid) of a record.
458 34
     *
459 22
     * @param string $status
460 21
     * @param string $recordTable
461 7
     * @param int $recordUid
462
     * @param int $originalUid
463
     * @param array $fields
464 21
     * @param DataHandler $tceMain
465
     *
466
     * @return int
467 12
     */
468
    protected function getRecordPageId($status, $recordTable, $recordUid, $originalUid, array $fields, DataHandler $tceMain)
469
    {
470
        if ($recordTable === 'pages' && isset($fields['l10n_parent']) && intval($fields['l10n_parent']) > 0) {
471
            return $fields['l10n_parent'];
472
        }
473
474
        if ($status === 'update' && !isset($fields['pid'])) {
475 5
            $recordPageId = $this->getValidatedPid($tceMain, $recordTable, $recordUid);
476
            if (($recordTable === 'pages') && ($this->rootPageResolver->getIsRootPageId($recordUid))) {
477 5
                $recordPageId = $originalUid;
478 4
            }
479
480 5
            return $recordPageId;
481
        }
482
483
        return $fields['pid'];
484
    }
485
486
    /**
487
     * Applies the updateItem instruction on a collection of pageIds.
488 1
     *
489
     * @param array $treePageIds
490 1
     */
491 1
    protected function updatePageIdItems(array $treePageIds)
492 1
    {
493
        foreach ($treePageIds as $treePageId) {
494
            $this->indexQueue->updateItem('pages', $treePageId);
495
        }
496
    }
497
498
    /**
499
     * Removes record from the index queue and from the solr index
500 1
     *
501
     * @param string $recordTable Name of table where the record lives
502 1
     * @param int $recordUid Id of record
503
     */
504
    protected function removeFromIndexAndQueue($recordTable, $recordUid)
505
    {
506 1
        $garbageCollector = GeneralUtility::makeInstance(GarbageCollector::class);
507 1
        $garbageCollector->collectGarbage($recordTable, $recordUid);
508
    }
509
510
    /**
511
     * Removes record from the index queue and from the solr index when the item is in the queue.
512
     *
513
     * @param string $recordTable Name of table where the record lives
514
     * @param int $recordUid Id of record
515
     */
516
    protected function removeFromIndexAndQueueWhenItemInQueue($recordTable, $recordUid)
517 27
    {
518
        if (!$this->indexQueue->containsItem($recordTable, $recordUid)) {
519 27
            return;
520 27
        }
521
522
        $this->removeFromIndexAndQueue($recordTable, $recordUid);
523 27
    }
524
525
    // Handle pages showing content from another page
526
527
    /**
528
     * Triggers Index Queue updates for other pages showing content from the
529
     * page currently being updated.
530
     *
531
     * @param int $pageId UID of the page currently being updated
532
     */
533
    protected function updateCanonicalPages($pageId)
534 25
    {
535
        $canonicalPages = $this->pagesRepository->findPageUidsWithContentsFromPid((int)$pageId);
536 25
        foreach ($canonicalPages as $page) {
537 25
            $this->indexQueue->updateItem('pages', $page['uid']);
538 1
        }
539
    }
540
541 24
    /**
542 24
     * Retrieves the pid of a record and throws an exception when getPid returns false.
543
     *
544
     * @param DataHandler $tceMain
545
     * @param string $table
546
     * @param integer $uid
547
     * @throws NoPidException
548
     * @return integer
549
     */
550
    protected function getValidatedPid(DataHandler $tceMain, $table, $uid)
551
    {
552 38
        $pid = $tceMain->getPID($table, $uid);
553
        if ($pid === false) {
554 38
            throw new NoPidException('Pid should not be false');
555
        }
556
557
        $pid = intval($pid);
558
        return $pid;
559
    }
560
561
    /**
562
     * Checks if the record is a draft record.
563 34
     *
564
     * @param string $table
565 34
     * @param int $uid
566
     * @return bool
567
     */
568
    protected function isDraftRecord($table, $uid)
569
    {
570
        return Util::isDraftRecord($table, $uid);
571
    }
572
573
    /**
574
     * @param $pageId
575
     * @param bool $initializeTsfe
576
     * @param int $language
577
     * @return TypoScriptConfiguration
578
     */
579
    protected function getSolrConfigurationFromPageId($pageId)
580
    {
581
        return $this->frontendEnvironment->getSolrConfigurationFromPageId($pageId);
582
    }
583
}
584