Completed
Push — master ( 1ccb29...3a83fd )
by Timo
8s
created

Queue::addNewItem()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
ccs 15
cts 15
cp 1
rs 8.5125
cc 5
eloc 15
nc 4
nop 4
crap 5
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 2 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\Domain\Index\Queue\RecordMonitor\Helper\ConfigurationAwareRecordService;
28
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\RootPageResolver;
29
use ApacheSolrForTypo3\Solr\IndexQueue\InitializationPostProcessor;
30
use ApacheSolrForTypo3\Solr\Site;
31
use ApacheSolrForTypo3\Solr\Util;
32
use ApacheSolrForTypo3\Solr\Utility\DatabaseUtility;
33
use TYPO3\CMS\Backend\Utility\BackendUtility;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
36
/**
37
 * The Indexing Queue. It allows us to decouple from frontend indexing and
38
 * reacting to changes faster.
39
 *
40
 * @author Ingo Renner <[email protected]>
41
 */
42
class Queue
43
{
44
    /**
45
     * @var RootPageResolver
46
     */
47
    protected $rootPageResolver;
48
49
    /**
50
     * @var ConfigurationAwareRecordService
51
     */
52
    protected $recordService;
53
54
    /**
55
     * Queue constructor.
56
     * @param RootPageResolver|null $rootPageResolver
57
     * @param ConfigurationAwareRecordService|null $recordService
58
     */
59 65
    public function __construct(RootPageResolver $rootPageResolver = null, ConfigurationAwareRecordService $recordService = null)
60
    {
61 65
        $this->rootPageResolver = isset($rootPageResolver) ? $rootPageResolver : GeneralUtility::makeInstance(RootPageResolver::class);
62 65
        $this->recordService = isset($recordService) ? $recordService : GeneralUtility::makeInstance(ConfigurationAwareRecordService::class);
63 65
    }
64
65
    // FIXME some of the methods should be renamed to plural forms
66
    // FIXME singular form methods should deal with exactly one item only
67
68
    /**
69
     * Returns the timestamp of the last indexing run.
70
     *
71
     * @param int $rootPageId The root page uid for which to get
72
     *      the last indexed item id
73
     * @return int Timestamp of last index run.
74
     */
75
    public function getLastIndexTime($rootPageId)
76
    {
77
        $lastIndexTime = 0;
78
79
        $lastIndexedRow = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
80
            'indexed',
81
            'tx_solr_indexqueue_item',
82
            'root = ' . (int)$rootPageId,
83
            '',
84
            'indexed DESC',
85
            1
86
        );
87
88
        if ($lastIndexedRow[0]['indexed']) {
89
            $lastIndexTime = $lastIndexedRow[0]['indexed'];
90
        }
91
92
        return $lastIndexTime;
93
    }
94
95
    /**
96
     * Returns the uid of the last indexed item in the queue
97
     *
98
     * @param int $rootPageId The root page uid for which to get
99
     *      the last indexed item id
100
     * @return int The last indexed item's ID.
101
     */
102
    public function getLastIndexedItemId($rootPageId)
103
    {
104
        $lastIndexedItemId = 0;
105
106
        $lastIndexedItemRow = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
107
            'uid',
108
            'tx_solr_indexqueue_item',
109
            'root = ' . (int)$rootPageId,
110
            '',
111
            'indexed DESC',
112
            1
113
        );
114
        if ($lastIndexedItemRow[0]['uid']) {
115
            $lastIndexedItemId = $lastIndexedItemRow[0]['uid'];
116
        }
117
118
        return $lastIndexedItemId;
119
    }
120
121
    /**
122
     * Truncate and rebuild the tx_solr_indexqueue_item table. This is the most
123
     * complete way to force reindexing, or to build the Index Queue for the
124
     * first time. The Index Queue initialization is site-specific.
125
     *
126
     * @param Site $site The site to initialize
127
     * @param string $indexingConfigurationName Name of a specific
128
     *      indexing configuration
129
     * @return array An array of booleans, each representing whether the
130
     *      initialization for an indexing configuration was successful
131
     */
132 5
    public function initialize(Site $site, $indexingConfigurationName = '')
133
    {
134 5
        $indexingConfigurations = [];
135 5
        $initializationStatus = [];
136
137 5
        if (empty($indexingConfigurationName)) {
138
            $solrConfiguration = $site->getSolrConfiguration();
139
            $indexingConfigurations = $solrConfiguration->getEnabledIndexQueueConfigurationNames();
140
        } else {
141 5
            $indexingConfigurations[] = $indexingConfigurationName;
142
        }
143
144 5
        foreach ($indexingConfigurations as $indexingConfigurationName) {
145 5
            $initializationStatus[$indexingConfigurationName] = $this->initializeIndexingConfiguration(
146
                $site,
147
                $indexingConfigurationName
148
            );
149
        }
150
151 5
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessIndexQueueInitialization'])) {
152
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessIndexQueueInitialization'] as $classReference) {
153
                $indexQueueInitializationPostProcessor = GeneralUtility::getUserObj($classReference);
154
155
                if ($indexQueueInitializationPostProcessor instanceof InitializationPostProcessor) {
156
                    $indexQueueInitializationPostProcessor->postProcessIndexQueueInitialization(
157
                        $site,
158
                        $indexingConfigurations,
159
                        $initializationStatus
160
                    );
161
                } else {
162
                    throw new \UnexpectedValueException(
163
                        get_class($indexQueueInitializationPostProcessor) .
164
                        ' must implement interface ' . InitializationPostProcessor::class,
165
                        1345815561
166
                    );
167
                }
168
            }
169
        }
170
171 5
        return $initializationStatus;
172
    }
173
174
    /**
175
     * Initializes the Index Queue for a specific indexing configuration.
176
     *
177
     * @param Site $site The site to initialize
178
     * @param string $indexingConfigurationName name of a specific
179
     *      indexing configuration
180
     * @return bool TRUE if the initialization was successful, FALSE otherwise
181
     */
182 5
    protected function initializeIndexingConfiguration(
183
        Site $site,
184
        $indexingConfigurationName
185
    ) {
186
        // clear queue
187 5
        $this->deleteItemsBySite($site, $indexingConfigurationName);
188
189 5
        $solrConfiguration = $site->getSolrConfiguration();
190
191 5
        $tableToIndex = $solrConfiguration->getIndexQueueTableNameOrFallbackToConfigurationName($indexingConfigurationName);
192 5
        $initializerClass = $solrConfiguration->getIndexQueueInitializerClassByConfigurationName($indexingConfigurationName);
193
194 5
        $initializer = GeneralUtility::makeInstance($initializerClass);
195
        /** @var $initializer \ApacheSolrForTypo3\Solr\IndexQueue\Initializer\AbstractInitializer */
196 5
        $initializer->setSite($site);
197 5
        $initializer->setType($tableToIndex);
198 5
        $initializer->setIndexingConfigurationName($indexingConfigurationName);
199
200 5
        $indexConfiguration = $solrConfiguration->getIndexQueueConfigurationByName($indexingConfigurationName);
201 5
        $initializer->setIndexingConfiguration($indexConfiguration);
202
203 5
        return $initializer->initialize();
204
    }
205
206
    /**
207
     * Gets the indexing configuration to use for an item.
208
     * Sometimes, when there are multiple configurations for a certain item type
209
     * (table) it can be hard or even impossible to find which one to use
210
     * though.
211
     * Currently selects the first indexing configuration where the name matches
212
     * the itemType or where the configured tbale is the same as the itemType.
213
     *
214
     * !!! Might return incorrect results for complex configurations !!!
215
     * Try to set the indexingConfiguration directly when using the updateItem()
216
     * method in such situations.
217
     *
218
     * @param string $itemType The item's type, usually a table name.
219
     * @param string $itemUid The item's uid, usually an integer uid, could be a
220
     *      different value for non-database-record types.
221
     * @param int $rootPageId The configuration's page tree's root page id.
222
     *      Optional, not needed for all types.
223
     * @return string The indexing configuration's name to use when indexing
224
     * @deprecated Use getIndexingConfigurationsByItem() now, which behaves
225
     *      almost the same way but returns an array of configurations, will be removed in version 7.0
226
     */
227
    protected function getIndexingConfigurationByItem(
228
        $itemType,
229
        $itemUid,
230
        $rootPageId = null
231
    ) {
232
        GeneralUtility::logDeprecatedFunction();
233
        $indexingConfigurationName = '';
234
235
        $configurations = $this->getIndexingConfigurationsByItem($itemType,
236
            $itemUid, $rootPageId);
237
        if (count($configurations) > 0) {
238
            $indexingConfigurationName = $configurations[0];
239
        }
240
241
        return $indexingConfigurationName;
242
    }
243
244
    /**
245
     * Gets the indexing configurations to use for an item.
246
     * Multiple configurations for a certain item type (table) might be available.
247
     *
248
     * @param string $itemType The item's type, usually a table name.
249
     * @param string $itemUid The item's uid, usually an integer uid, could be a
250
     *      different value for non-database-record types.
251
     * @param int $rootPageId The configuration's page tree's root page id.
252
     *      Optional, not needed for all types.
253
     * @return array<string> The indexing configurations names to use when indexing
254
     */
255
    protected function getIndexingConfigurationsByItem(
256
        $itemType,
257
        $itemUid,
0 ignored issues
show
Unused Code introduced by
The parameter $itemUid is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
258
        $rootPageId = null
259
    ) {
260
        $possibleIndexingConfigurationNames = [];
261
262
        if (!is_null($rootPageId)) {
263
            // get configuration for the root's branch
264
            $solrConfiguration = Util::getSolrConfigurationFromPageId($rootPageId);
265
            $possibleIndexingConfigurationNames = $solrConfiguration->getIndexQueueConfigurationNamesByTableName($itemType);
266
        }
267
268
        return $possibleIndexingConfigurationNames;
269
    }
270
271
    /**
272
     * Marks an item as needing (re)indexing.
273
     *
274
     * Like with Solr itself, there's no add method, just a simple update method
275
     * that handles the adds, too.
276
     *
277
     * The method creates or updates the index queue items for all related rootPageIds.
278
     *
279
     * @param string $itemType The item's type, usually a table name.
280
     * @param string $itemUid The item's uid, usually an integer uid, could be a
281
     *      different value for non-database-record types.
282
     * @param int $forcedChangeTime The change time for the item if set, otherwise
283
     *          value from getItemChangedTime() is used.
284
     */
285 46
    public function updateItem($itemType, $itemUid, $forcedChangeTime = 0)
286
    {
287 46
        $rootPageIds = $this->rootPageResolver->getResponsibleRootPageIds($itemType, $itemUid);
288 46
        foreach ($rootPageIds as $rootPageId) {
289 45
            $skipInvalidRootPage = $rootPageId === 0;
290 45
            if ($skipInvalidRootPage) {
291
                continue;
292
            }
293
294 45
            $solrConfiguration = Util::getSolrConfigurationFromPageId($rootPageId);
295 45
            $indexingConfiguration = $this->recordService->getIndexingConfigurationName($itemType, $itemUid, $solrConfiguration);
296 45
            $itemInQueueForRootPage = $this->containsItemWithRootPageId($itemType, $itemUid, $rootPageId);
297 45
            if ($itemInQueueForRootPage) {
298
                // update the existing queue item
299 10
                $this->updateExistingItem($itemType, $itemUid, $indexingConfiguration, $rootPageId, $forcedChangeTime);
300
            } else {
301
                // add the item since it's not in the queue yet
302 45
                $this->addNewItem($itemType, $itemUid, $indexingConfiguration, $rootPageId);
303
            }
304
        }
305 46
    }
306
307
    /**
308
     * Updates an existing queue entry by $itemType $itemUid and $rootPageId.
309
     *
310
     * @param string $itemType  The item's type, usually a table name.
311
     * @param int $itemUid The item's uid, usually an integer uid, could be a
312
     *      different value for non-database-record types.
313
     * @param string $indexingConfiguration The name of the related indexConfiguration
314
     * @param int $rootPageId The uid of the rootPage
315
     * @param int $forcedChangeTime The forced change time that should be used for updating
316
     */
317 10
    protected function updateExistingItem($itemType, $itemUid, $indexingConfiguration, $rootPageId, $forcedChangeTime)
318
    {
319
        // update if that item is in the queue already
320
        $changes = [
321 10
            'changed' => ($forcedChangeTime > 0) ? $forcedChangeTime : $this->getItemChangedTime($itemType, $itemUid)
322
        ];
323
324 10
        if (!empty($indexingConfiguration)) {
325 10
            $changes['indexing_configuration'] = $indexingConfiguration;
326
        }
327
328 10
        $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
329 10
            'tx_solr_indexqueue_item',
330 10
            'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType, 'tx_solr_indexqueue_item') .
331 10
            ' AND item_uid = ' . (int)$itemUid . ' AND root = ' . (int)$rootPageId,
332
            $changes);
333 10
    }
334
335
    /**
336
     * Adds an item to the index queue.
337
     *
338
     * Not meant for public use.
339
     *
340
     * @param string $itemType The item's type, usually a table name.
341
     * @param string $itemUid The item's uid, usually an integer uid, could be a
342
     *      different value for non-database-record types.
343
     * @param string $indexingConfiguration The item's indexing configuration to use.
344
     *      Optional, overwrites existing / determined configuration.
345
     * @return void
346
     */
347 39
    private function addNewItem($itemType, $itemUid, $indexingConfiguration, $rootPageId)
348
    {
349 39
        $additionalRecordFields = '';
350 39
        if ($itemType == 'pages') {
351 27
            $additionalRecordFields = ', doktype, uid';
352
        }
353
354 39
        $record = BackendUtility::getRecord($itemType, $itemUid, 'pid' . $additionalRecordFields);
355 39
        if (empty($record) || ($itemType == 'pages' && !Util::isAllowedPageType($record, $indexingConfiguration))) {
356 1
            return;
357
        }
358
359
        $item = [
360 38
            'root' => $rootPageId,
361 38
            'item_type' => $itemType,
362 38
            'item_uid' => $itemUid,
363 38
            'changed' => $this->getItemChangedTime($itemType, $itemUid),
364 38
            'errors' => ''
365
        ];
366
367
        // make a backup of the current item
368 38
        $item['indexing_configuration'] = $indexingConfiguration;
369 38
        $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_solr_indexqueue_item', $item);
370 38
    }
371
372
    /**
373
     * Determines the time for when an item should be indexed. This timestamp
374
     * is then stored in the changed column in the Index Queue.
375
     *
376
     * The changed timestamp usually is now - time(). For records which are set
377
     * to published at a later time, this timestamp is the start time. So if a
378
     * future start time has been set, that will be used to delay indexing
379
     * of an item.
380
     *
381
     * @param string $itemType The item's table name.
382
     * @param string $itemUid The item's uid, usually an integer uid, could be a
383
     *      different value for non-database-record types.
384
     * @return int Timestamp of the item's changed time or future start time
385
     */
386 44
    protected function getItemChangedTime($itemType, $itemUid)
387
    {
388 44
        $itemTypeHasStartTimeColumn = false;
389 44
        $changedTimeColumns = $GLOBALS['TCA'][$itemType]['ctrl']['tstamp'];
390 44
        $startTime = 0;
391 44
        $pageChangedTime = 0;
392
393 44
        if (!empty($GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime'])) {
394 44
            $itemTypeHasStartTimeColumn = true;
395 44
            $changedTimeColumns .= ', ' . $GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime'];
396
        }
397 44
        if ($itemType == 'pages') {
398
            // does not carry time information directly, but needed to support
399
            // canonical pages
400 32
            $changedTimeColumns .= ', content_from_pid';
401
        }
402
403 44
        $record = BackendUtility::getRecord($itemType, $itemUid, $changedTimeColumns);
404 44
        $itemChangedTime = $record[$GLOBALS['TCA'][$itemType]['ctrl']['tstamp']];
405
406 44
        if ($itemTypeHasStartTimeColumn) {
407 44
            $startTime = $record[$GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime']];
408
        }
409
410 44
        if ($itemType == 'pages') {
411 32
            $record['uid'] = $itemUid;
412
            // overrule the page's last changed time with the most recent
413
            //content element change
414 32
            $pageChangedTime = $this->getPageItemChangedTime($record);
415
        }
416
417 44
        $localizationsChangedTime = $this->getLocalizableItemChangedTime($itemType, $itemUid);
418
419
        // if start time exists and start time is higher than last changed timestamp
420
        // then set changed to the future start time to make the item
421
        // indexed at a later time
422 44
        $changedTime = max(
423
            $itemChangedTime,
424
            $pageChangedTime,
425
            $localizationsChangedTime,
426
            $startTime
427
        );
428
429 44
        return $changedTime;
430
    }
431
432
    /**
433
     * Gets the most recent changed time of a page's content elements
434
     *
435
     * @param array $page Partial page record
436
     * @return int Timestamp of the most recent content element change
437
     */
438 32
    protected function getPageItemChangedTime(array $page)
439
    {
440 32
        if (!empty($page['content_from_pid'])) {
441
            // canonical page, get the original page's last changed time
442
            $pageContentLastChangedTime = $this->getPageItemChangedTime(['uid' => $page['content_from_pid']]);
443
        } else {
444 32
            $pageContentLastChangedTime = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
445 32
                'MAX(tstamp) AS changed_time',
446 32
                'tt_content',
447 32
                'pid = ' . (int)$page['uid']
448
            );
449 32
            $pageContentLastChangedTime = $pageContentLastChangedTime['changed_time'];
450
        }
451
452 32
        return $pageContentLastChangedTime;
453
    }
454
455
    /**
456
     * Gets the most recent changed time for an item taking into account
457
     * localized records.
458
     *
459
     * @param string $itemType The item's type, usually a table name.
460
     * @param string $itemUid The item's uid, usually an integer uid, could be a
461
     *      different value for non-database-record types.
462
     * @return int Timestamp of the most recent content element change
463
     */
464 44
    protected function getLocalizableItemChangedTime($itemType, $itemUid)
465
    {
466 44
        $localizedChangedTime = 0;
467
468 44
        if (isset($GLOBALS['TCA'][$itemType]['ctrl']['transOrigPointerField'])) {
469
            // table is localizable
470 12
            $translationOriginalPointerField = $GLOBALS['TCA'][$itemType]['ctrl']['transOrigPointerField'];
471
472 12
            $itemUid = intval($itemUid);
473 12
            $localizedChangedTime = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
474 12
                'MAX(tstamp) AS changed_time',
475
                $itemType,
476 12
                "uid = $itemUid OR $translationOriginalPointerField = $itemUid"
477
            );
478 12
            $localizedChangedTime = $localizedChangedTime['changed_time'];
479
        }
480
481 44
        return $localizedChangedTime;
482
    }
483
484
    /**
485
     * Checks whether the Index Queue contains a specific item.
486
     *
487
     * @param string $itemType The item's type, usually a table name.
488
     * @param string $itemUid The item's uid, usually an integer uid, could be a
489
     *      different value for non-database-record types.
490
     * @return bool TRUE if the item is found in the queue, FALSE otherwise
491
     */
492 3
    public function containsItem($itemType, $itemUid)
493
    {
494 3
        $itemIsInQueue = (boolean)$GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
495 3
            'uid',
496 3
            'tx_solr_indexqueue_item',
497 3
            'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
498 3
                'tx_solr_indexqueue_item') .
499 3
            ' AND item_uid = ' . (int)$itemUid
500
        );
501
502 3
        return $itemIsInQueue;
503
    }
504
505
    /**
506
     * Checks whether the Index Queue contains a specific item.
507
     *
508
     * @param string $itemType The item's type, usually a table name.
509
     * @param string $itemUid The item's uid, usually an integer uid, could be a
510
     *      different value for non-database-record types.
511
     * @param integer $rootPageId
512
     * @return bool TRUE if the item is found in the queue, FALSE otherwise
513
     */
514 45
    public function containsItemWithRootPageId($itemType, $itemUid, $rootPageId)
515
    {
516 45
        $itemIsInQueue = (boolean)$GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
517 45
            'uid',
518 45
            'tx_solr_indexqueue_item',
519 45
            'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
520 45
                'tx_solr_indexqueue_item') .
521 45
            ' AND item_uid = ' . (int)$itemUid . ' AND root = ' . (int)$rootPageId
522
        );
523
524 45
        return $itemIsInQueue;
525
    }
526
527
    /**
528
     * Checks whether the Index Queue contains a specific item that has been
529
     * marked as indexed.
530
     *
531
     * @param string $itemType The item's type, usually a table name.
532
     * @param string $itemUid The item's uid, usually an integer uid, could be a
533
     *      different value for non-database-record types.
534
     * @return bool TRUE if the item is found in the queue and marked as
535
     *      indexed, FALSE otherwise
536
     */
537 3
    public function containsIndexedItem($itemType, $itemUid)
538
    {
539 3
        $itemIsInQueue = (boolean)$GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
540 3
            'uid',
541 3
            'tx_solr_indexqueue_item',
542 3
            'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
543 3
                'tx_solr_indexqueue_item') .
544 3
            ' AND item_uid = ' . (int)$itemUid .
545 3
            ' AND indexed > 0'
546
        );
547
548 3
        return $itemIsInQueue;
549
    }
550
551
    /**
552
     * Removes an item from the Index Queue.
553
     *
554
     * @param string $itemType The type of the item to remove, usually a table name.
555
     * @param int $itemUid The uid of the item to remove
556
     */
557 26
    public function deleteItem($itemType, $itemUid)
558
    {
559 26
        $uidList = [];
560
561
        // get the item uids to use them in the deletes afterwards
562 26
        $items = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
563 26
            'uid',
564 26
            'tx_solr_indexqueue_item',
565 26
            'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
566 26
                'tx_solr_indexqueue_item') .
567 26
            ' AND item_uid = ' . intval($itemUid)
568
        );
569
570 26
        if (count($items)) {
571 10
            foreach ($items as $item) {
572 10
                $uidList[] = $item['uid'];
573
            }
574
575 10
            $GLOBALS['TYPO3_DB']->exec_DELETEquery(
576 10
                'tx_solr_indexqueue_item',
577 10
                'uid IN(' . implode(',', $uidList) . ')'
578
            );
579 10
            $GLOBALS['TYPO3_DB']->exec_DELETEquery(
580 10
                'tx_solr_indexqueue_indexing_property',
581 10
                'item_id IN(' . implode(',', $uidList) . ')'
582
            );
583
        }
584 26
    }
585
586
    /**
587
     * Removes all items of a certain type from the Index Queue.
588
     *
589
     * @param string $itemType The type of items to remove, usually a table name.
590
     */
591 1
    public function deleteItemsByType($itemType)
592
    {
593 1
        $uidList = [];
594
595
        // get the item uids to use them in the deletes afterwards
596 1
        $items = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
597 1
            'uid',
598 1
            'tx_solr_indexqueue_item',
599 1
            'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr(
600
                $itemType,
601 1
                'tx_solr_indexqueue_item'
602
            )
603
        );
604
605 1
        if (count($items)) {
606 1
            foreach ($items as $item) {
607 1
                $uidList[] = $item['uid'];
608
            }
609
610 1
            $GLOBALS['TYPO3_DB']->exec_DELETEquery(
611 1
                'tx_solr_indexqueue_item',
612 1
                'uid IN(' . implode(',', $uidList) . ')'
613
            );
614 1
            $GLOBALS['TYPO3_DB']->exec_DELETEquery(
615 1
                'tx_solr_indexqueue_indexing_property',
616 1
                'item_id IN(' . implode(',', $uidList) . ')'
617
            );
618
        }
619 1
    }
620
621
    /**
622
     * Removes all items of a certain site from the Index Queue. Accepts an
623
     * optional parameter to limit the deleted items by indexing configuration.
624
     *
625
     * @param Site $site The site to remove items for.
626
     * @param string $indexingConfigurationName Name of a specific indexing
627
     *      configuration
628
     */
629 5
    public function deleteItemsBySite(
630
        Site $site,
631
        $indexingConfigurationName = ''
632
    ) {
633 5
        $rootPageConstraint = 'tx_solr_indexqueue_item.root = ' . $site->getRootPageId();
634
635 5
        $indexingConfigurationConstraint = '';
636 5
        if (!empty($indexingConfigurationName)) {
637
            $indexingConfigurationConstraint =
638
                ' AND tx_solr_indexqueue_item.indexing_configuration = \'' .
639 5
                $indexingConfigurationName . '\'';
640
        }
641
642 5
        DatabaseUtility::transactionStart();
643
        try {
644
            // reset Index Queue
645 5
            $result = $GLOBALS['TYPO3_DB']->exec_DELETEquery(
646 5
                'tx_solr_indexqueue_item',
647 5
                $rootPageConstraint . $indexingConfigurationConstraint
648
            );
649 5
            if (!$result) {
650
                throw new \RuntimeException(
651
                    'Failed to reset Index Queue for site ' . $site->getLabel(),
652
                    1412986560
653
                );
654
            }
655
656
            // reset Index Queue Properties
657
            $indexQueuePropertyResetQuery = '
658
                DELETE tx_solr_indexqueue_indexing_property.*
659
                FROM tx_solr_indexqueue_indexing_property
660
                INNER JOIN tx_solr_indexqueue_item
661
                    ON tx_solr_indexqueue_item.uid = tx_solr_indexqueue_indexing_property.item_id
662
                    AND ' .
663 5
                $rootPageConstraint .
664 5
                $indexingConfigurationConstraint;
665
666 5
            $result = $GLOBALS['TYPO3_DB']->sql_query($indexQueuePropertyResetQuery);
667 5
            if (!$result) {
668
                throw new \RuntimeException(
669
                    'Failed to reset Index Queue properties for site ' . $site->getLabel(),
670
                    1412986604
671
                );
672
            }
673
674 5
            DatabaseUtility::transactionCommit();
675
        } catch (\RuntimeException $e) {
676
            DatabaseUtility::transactionRollback();
677
        }
678 5
    }
679
680
    /**
681
     * Removes all items from the Index Queue.
682
     *
683
     */
684
    public function deleteAllItems()
685
    {
686
        $GLOBALS['TYPO3_DB']->exec_TRUNCATEquery('tx_solr_indexqueue_item', '');
687
    }
688
689
    /**
690
     * Gets a single Index Queue item by its uid.
691
     *
692
     * @param int $itemId Index Queue item uid
693
     * @return Item The request Index Queue item or NULL
694
     *      if no item with $itemId was found
695
     */
696 10
    public function getItem($itemId)
697
    {
698 10
        $item = null;
699
700 10
        $indexQueueItemRecord = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
701 10
            '*',
702 10
            'tx_solr_indexqueue_item',
703 10
            'uid = ' . intval($itemId)
704
        );
705
706 10
        if (count($indexQueueItemRecord) == 1) {
707 10
            $indexQueueItemRecord = $indexQueueItemRecord[0];
708
709 10
            $item = GeneralUtility::makeInstance(
710 10
                Item::class,
711
                $indexQueueItemRecord
712
            );
713
        }
714
715 10
        return $item;
716
    }
717
718
    /**
719
     * Gets Index Queue items by type and uid.
720
     *
721
     * @param string $itemType item type, usually  the table name
722
     * @param int $itemUid item uid
723
     * @return Item[] An array of items matching $itemType and $itemUid
724
     */
725 19
    public function getItems($itemType, $itemUid)
726
    {
727 19
        $indexQueueItemRecords = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
728 19
            '*',
729 19
            'tx_solr_indexqueue_item',
730 19
            'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
731 19
                'tx_solr_indexqueue_item') .
732 19
            ' AND item_uid = ' . intval($itemUid)
733
        );
734
735 19
        return $this->getIndexQueueItemObjectsFromRecords($indexQueueItemRecords);
736
    }
737
738
    /**
739
     * Gets number of Index Queue items for a specific site / indexing configuration
740
     * optional parameter to limit the counted items by indexing configuration.
741
     *
742
     * @param Site $site The site to search for.
743
     * @param string $indexingConfigurationName name of a specific indexing
744
     *      configuration
745
     * @return int Number of items
746
     */
747 2
    public function getItemsCountBySite(Site $site, $indexingConfigurationName = '')
748
    {
749 2
        $indexingConfigurationConstraint = $this->buildIndexConfigurationConstraint($indexingConfigurationName);
750 2
        $where = 'root = ' . $site->getRootPageId() . $indexingConfigurationConstraint;
751 2
        return (int)$this->getItemCount($where);
752
    }
753
754
    /**
755
     * Gets number of unprocessed Index Queue items for a specific site / indexing configuration
756
     * optional parameter to limit the counted items by indexing configuration.
757
     *
758
     * @param Site $site The site to search for.
759
     * @param string $indexingConfigurationName name of a specific indexing
760
     *      configuration
761
     * @return int Number of items.
762
     */
763 2
    public function getRemainingItemsCountBySite(Site $site, $indexingConfigurationName = '')
764
    {
765 2
        $indexingConfigurationConstraint = $this->buildIndexConfigurationConstraint($indexingConfigurationName);
766 2
        $where = 'changed > indexed AND root = ' . $site->getRootPageId() . $indexingConfigurationConstraint;
767 2
        return (int)$this->getItemCount($where);
768
    }
769
770
    /**
771
     * Returns the number of items for all queues.
772
     *
773
     * @return int
774
     */
775 46
    public function getAllItemsCount()
776
    {
777 46
        return $this->getItemCount();
778
    }
779
780
    /**
781
     * @param string $where
782
     * @return int
783
     */
784 49
    private function getItemCount($where = '1=1')
785
    {
786
        /**  @var $db \TYPO3\CMS\Core\Database\DatabaseConnection */
787 49
        $db = $GLOBALS['TYPO3_DB'];
788
789 49
        return (int)$db->exec_SELECTcountRows('uid', 'tx_solr_indexqueue_item', $where);
790
    }
791
792
    /**
793
     * Build a database constraint that limits to a certain indexConfigurationName
794
     *
795
     * @param string $indexingConfigurationName
796
     * @return string
797
     */
798 3
    protected function buildIndexConfigurationConstraint($indexingConfigurationName)
799
    {
800 3
        $indexingConfigurationConstraint = '';
801 3
        if (!empty($indexingConfigurationName)) {
802
            $indexingConfigurationConstraint = ' AND indexing_configuration = \'' . $indexingConfigurationName . '\'';
803
            return $indexingConfigurationConstraint;
804
        }
805 3
        return $indexingConfigurationConstraint;
806
    }
807
808
    /**
809
     * Gets $limit number of items to index for a particular $site.
810
     *
811
     * @param Site $site TYPO3 site
812
     * @param int $limit Number of items to get from the queue
813
     * @return Item[] Items to index to the given solr server
814
     */
815 7
    public function getItemsToIndex(Site $site, $limit = 50)
816
    {
817 7
        $itemsToIndex = [];
818
819
        // determine which items to index with this run
820 7
        $indexQueueItemRecords = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
821 7
            '*',
822 7
            'tx_solr_indexqueue_item',
823 7
            'root = ' . $site->getRootPageId() .
824 7
            ' AND changed > indexed' .
825 7
            ' AND changed <= ' . time() .
826 7
            ' AND errors = \'\'',
827 7
            '',
828 7
            'indexing_priority DESC, changed DESC, uid DESC',
829
            intval($limit)
830
        );
831 7
        if (!empty($indexQueueItemRecords)) {
832
            // convert queued records to index queue item objects
833 7
            $itemsToIndex = $this->getIndexQueueItemObjectsFromRecords($indexQueueItemRecords);
834
        }
835
836 7
        return $itemsToIndex;
837
    }
838
839
    /**
840
     * Creates an array of ApacheSolrForTypo3\Solr\IndexQueue\Item objects from an array of
841
     * index queue records.
842
     *
843
     * @param array $indexQueueItemRecords Array of plain index queue records
844
     * @return array Array of ApacheSolrForTypo3\Solr\IndexQueue\Item objects
845
     */
846 24
    protected function getIndexQueueItemObjectsFromRecords(
847
        array $indexQueueItemRecords
848
    ) {
849 24
        $indexQueueItems = [];
850 24
        $tableUids = [];
851 24
        $tableRecords = [];
852
853
        // grouping records by table
854 24
        foreach ($indexQueueItemRecords as $indexQueueItemRecord) {
855 24
            $tableUids[$indexQueueItemRecord['item_type']][] = $indexQueueItemRecord['item_uid'];
856
        }
857
858
        // fetching records by table, saves us a lot of single queries
859 24
        foreach ($tableUids as $table => $uids) {
860 24
            $uidList = implode(',', $uids);
861 24
            $records = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
862 24
                '*',
863
                $table,
864 24
                'uid IN(' . $uidList . ')',
865 24
                '', '', '', // group, order, limit
866 24
                'uid'
867
            );
868 24
            $tableRecords[$table] = $records;
869
870 24
            if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessFetchRecordsForIndexQueueItem'])) {
871
                $params = ['table' => $table, 'uids' => $uids, 'tableRecords' => &$tableRecords];
872
                foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessFetchRecordsForIndexQueueItem'] as $reference) {
873
                    GeneralUtility::callUserFunction($reference, $params, $this);
874
                }
875 24
                unset($params);
876
            }
877
        }
878
879
        // creating index queue item objects and assigning / mapping
880
        // records to index queue items
881 24
        foreach ($indexQueueItemRecords as $indexQueueItemRecord) {
882 24
            if (isset($tableRecords[$indexQueueItemRecord['item_type']][$indexQueueItemRecord['item_uid']])) {
883 23
                $indexQueueItems[] = GeneralUtility::makeInstance(
884 23
                    Item::class,
885
                    $indexQueueItemRecord,
886 23
                    $tableRecords[$indexQueueItemRecord['item_type']][$indexQueueItemRecord['item_uid']]
887
                );
888
            } else {
889 1
                GeneralUtility::devLog('Record missing for Index Queue item. Item removed.',
890 1
                    'solr', 3, [$indexQueueItemRecord]);
891 1
                $this->deleteItem($indexQueueItemRecord['item_type'],
892 24
                    $indexQueueItemRecord['item_uid']);
893
            }
894
        }
895
896 24
        return $indexQueueItems;
897
    }
898
899
    /**
900
     * Marks an item as failed and causes the indexer to skip the item in the
901
     * next run.
902
     *
903
     * @param int|Item $item Either the item's Index Queue
904
     *      uid or the complete item
905
     * @param string $errorMessage Error message
906
     */
907
    public function markItemAsFailed($item, $errorMessage = '')
908
    {
909
        if ($item instanceof Item) {
910
            $itemUid = $item->getIndexQueueUid();
911
        } else {
912
            $itemUid = (int)$item;
913
        }
914
915
        if (empty($errorMessage)) {
916
            // simply set to "TRUE"
917
            $errorMessage = '1';
918
        }
919
920
        $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
921
            'tx_solr_indexqueue_item',
922
            'uid = ' . $itemUid,
923
            [
924
                'errors' => $errorMessage
925
            ]
926
        );
927
    }
928
}
929