ReferenceIndex.php 62 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
15

16
17
namespace TYPO3\CMS\Core\Database;

18
use Doctrine\DBAL\Exception as DBALException;
19
use Psr\EventDispatcher\EventDispatcherInterface;
20
21
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
22
use Psr\Log\LogLevel;
23
use TYPO3\CMS\Backend\Utility\BackendUtility;
24
use TYPO3\CMS\Backend\View\ProgressListenerInterface;
Stephan Großberndt's avatar
Stephan Großberndt committed
25
use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
26
use TYPO3\CMS\Core\Database\Platform\PlatformInformation;
27
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
Stephan Großberndt's avatar
Stephan Großberndt committed
28
use TYPO3\CMS\Core\DataHandling\DataHandler;
29
use TYPO3\CMS\Core\DataHandling\Event\IsTableExcludedFromReferenceIndexEvent;
30
use TYPO3\CMS\Core\DataHandling\SoftReference\SoftReferenceParserFactory;
Stephan Großberndt's avatar
Stephan Großberndt committed
31
use TYPO3\CMS\Core\Registry;
32
use TYPO3\CMS\Core\Utility\ArrayUtility;
33
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
34
35
use TYPO3\CMS\Core\Utility\GeneralUtility;

36
37
38
/**
 * Reference index processing and relation extraction
 *
39
 * @internal Extensions shouldn't fiddle with the reference index themselves, it's task of DataHandler to do this.
40
 */
41
class ReferenceIndex implements LoggerAwareInterface
42
{
43
44
    use LoggerAwareTrait;

45
    /**
46
     * Definition of tables to exclude from the ReferenceIndex
47
48
49
50
51
     *
     * Only tables which do not contain any relations and never did so far since references also won't be deleted for
     * these. Since only tables with an entry in $GLOBALS['TCA] are handled by ReferenceIndex there is no need to add
     * *_mm-tables.
     *
52
     * Implemented as array with fields as keys and booleans as values for fast isset() lookup instead of slow in_array()
53
54
55
     *
     * @var array
     * @see updateRefIndexTable()
56
     * @see shouldExcludeTableFromReferenceIndex()
57
     */
58
    protected array $excludedTables = [
59
        'sys_log' => true,
60
        'tx_extensionmanager_domain_model_extension' => true,
61
    ];
62
63

    /**
64
     * Definition of fields to exclude from ReferenceIndex in *every* table
65
     *
66
     * Implemented as array with fields as keys and booleans as values for fast isset() lookup instead of slow in_array()
67
68
69
70
     *
     * @var array
     * @see getRelations()
     * @see fetchTableRelationFields()
71
     * @see shouldExcludeTableColumnFromReferenceIndex()
72
     */
73
    protected array $excludedColumns = [
74
75
76
77
78
79
        'uid' => true,
        'perms_userid' => true,
        'perms_groupid' => true,
        'perms_user' => true,
        'perms_group' => true,
        'perms_everybody' => true,
80
        'pid' => true,
81
    ];
82
83
84
85
86

    /**
     * This array holds the FlexForm references of a record
     *
     * @var array
87
88
89
     * @see getRelations()
     * @see FlexFormTools::traverseFlexFormXMLData()
     * @see getRelations_flexFormCallBack()
90
     */
91
    protected $temp_flexRelations = [];
92
93

    /**
94
     * An index of all found references of a single record
95
96
97
     *
     * @var array
     */
98
    protected $relations = [];
99
100
101
102
103
104
105

    /**
     * Number which we can increase if a change in the code means we will have to force a re-generation of the index.
     *
     * @var int
     * @see updateRefIndexTable()
     */
106
    protected $hashVersion = 1;
107
108
109
110

    /**
     * Current workspace id
     */
111
    protected int $workspaceId = 0;
112

113
    /**
114
115
116
     * A list of fields that may contain relations per TCA table.
     * This is either ['*'] or an array of single field names. The list
     * depends on TCA and is built when a first table row is handled.
117
     */
118
    protected array $tableRelationFieldCache = [];
119

120
    protected EventDispatcherInterface $eventDispatcher;
121
    protected SoftReferenceParserFactory $softReferenceParserFactory;
122

123
    public function __construct(EventDispatcherInterface $eventDispatcher = null, SoftReferenceParserFactory $softReferenceParserFactory = null)
124
    {
125
        $this->eventDispatcher = $eventDispatcher ?? GeneralUtility::getContainer()->get(EventDispatcherInterface::class);
126
        $this->softReferenceParserFactory = $softReferenceParserFactory ?? GeneralUtility::makeInstance(SoftReferenceParserFactory::class);
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    }

    /**
     * Sets the current workspace id
     *
     * @param int $workspaceId
     * @see updateIndex()
     */
    public function setWorkspaceId($workspaceId)
    {
        $this->workspaceId = (int)$workspaceId;
    }

    /**
     * Gets the current workspace id
     *
     * @return int
144
     * @see updateRefIndexTable()
145
     */
146
    protected function getWorkspaceId()
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
    {
        return $this->workspaceId;
    }

    /**
     * Call this function to update the sys_refindex table for a record (even one just deleted)
     * NOTICE: Currently, references updated for a deleted-flagged record will not include those from within FlexForm
     * fields in some cases where the data structure is defined by another record since the resolving process ignores
     * deleted records! This will also result in bad cleaning up in DataHandler I think... Anyway, that's the story of
     * FlexForms; as long as the DS can change, lots of references can get lost in no time.
     *
     * @param string $tableName Table name
     * @param int $uid UID of record
     * @param bool $testOnly If set, nothing will be written to the index but the result value will still report statistics on what is added, deleted and kept. Can be used for mere analysis.
     * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
     */
    public function updateRefIndexTable($tableName, $uid, $testOnly = false)
    {
165
        $result = [
166
167
            'keptNodes' => 0,
            'deletedNodes' => 0,
168
            'addedNodes' => 0,
169
        ];
170

171
172
173
174
175
        $uid = $uid ? (int)$uid : 0;
        if (!$uid) {
            return $result;
        }

176
        // If this table cannot contain relations, skip it
177
        if ($this->shouldExcludeTableFromReferenceIndex($tableName)) {
178
179
180
            return $result;
        }

181
        $tableRelationFields = $this->fetchTableRelationFields($tableName);
182

183
184
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $connection = $connectionPool->getConnectionForTable('sys_refindex');
185

186
187
        // Get current index from Database with hash as index using $uidIndexField
        // no restrictions are needed, since sys_refindex is not a TCA table
188
189
        $queryBuilder = $connection->createQueryBuilder();
        $queryBuilder->getRestrictions()->removeAll();
190
        $queryResult = $queryBuilder->select('hash')->from('sys_refindex')->where(
191
192
193
194
195
196
            $queryBuilder->expr()->eq('tablename', $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)),
            $queryBuilder->expr()->eq('recuid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
            $queryBuilder->expr()->eq(
                'workspace',
                $queryBuilder->createNamedParameter($this->getWorkspaceId(), \PDO::PARAM_INT)
            )
197
        )->execute();
198
        $currentRelationHashes = [];
199
        while ($relation = $queryResult->fetchAssociative()) {
200
            $currentRelationHashes[$relation['hash']] = true;
201
        }
202

203
        // If the table has fields which could contain relations and the record does exist
204
205
        if ($tableRelationFields !== []) {
            $existingRecord = $this->getRecord($tableName, $uid);
206
207
208
209
210
211
212
            if ($existingRecord) {
                // Table has relation fields and record exists - get relations
                $this->relations = [];
                $relations = $this->generateDataUsingRecord($tableName, $existingRecord);
                if (!is_array($relations)) {
                    return $result;
                }
213
214
215
216
217
                // Traverse the generated index:
                foreach ($relations as &$relation) {
                    if (!is_array($relation)) {
                        continue;
                    }
218
219
220
221
                    // Exclude any relations TO a specific table
                    if (($relation['ref_table'] ?? '') && $this->shouldExcludeTableFromReferenceIndex($relation['ref_table'])) {
                        continue;
                    }
222
223
                    $relation['hash'] = md5(implode('///', $relation) . '///' . $this->hashVersion);
                    // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
224
225
                    if (isset($currentRelationHashes[$relation['hash']])) {
                        unset($currentRelationHashes[$relation['hash']]);
226
227
228
                        $result['keptNodes']++;
                        $relation['_ACTION'] = 'KEPT';
                    } else {
229
                        // If new, add it:
230
                        if (!$testOnly) {
231
                            $connection->insert('sys_refindex', $relation);
232
233
234
235
236
237
238
239
240
241
                        }
                        $result['addedNodes']++;
                        $relation['_ACTION'] = 'ADDED';
                    }
                }
                $result['relations'] = $relations;
            }
        }

        // If any old are left, remove them:
242
243
        if (!empty($currentRelationHashes)) {
            $hashList = array_keys($currentRelationHashes);
244
245
246
247
            if (!empty($hashList)) {
                $result['deletedNodes'] = count($hashList);
                $result['deletedNodes_hashList'] = implode(',', $hashList);
                if (!$testOnly) {
248
249
250
251
252
253
254
255
256
257
258
259
260
                    $maxBindParameters = PlatformInformation::getMaxBindParameters($connection->getDatabasePlatform());
                    foreach (array_chunk($hashList, $maxBindParameters - 10, true) as $chunk) {
                        if (empty($chunk)) {
                            continue;
                        }
                        $queryBuilder = $connection->createQueryBuilder();
                        $queryBuilder
                            ->delete('sys_refindex')
                            ->where(
                                $queryBuilder->expr()->in(
                                    'hash',
                                    $queryBuilder->createNamedParameter($chunk, Connection::PARAM_STR_ARRAY)
                                )
261
                            )
262
263
                            ->execute();
                    }
264
265
266
267
268
269
270
                }
            }
        }

        return $result;
    }

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
    /**
     * Returns the amount of references for the given record
     *
     * @param string $tableName
     * @param int $uid
     * @return int
     */
    public function getNumberOfReferencedRecords(string $tableName, int $uid): int
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
        return (int)$queryBuilder
            ->count('*')->from('sys_refindex')
            ->where(
                $queryBuilder->expr()->eq(
                    'ref_table',
                    $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
                ),
                $queryBuilder->expr()->eq(
                    'ref_uid',
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
                )
292
            )->execute()->fetchOne();
293
294
    }

295
296
297
298
299
300
301
    /**
     * Calculate the relations for a record of a given table
     *
     * @param string $tableName Table being processed
     * @param array $record Record from $tableName
     * @return array
     */
302
    protected function generateDataUsingRecord(string $tableName, array $record): array
303
304
    {
        $this->relations = [];
305
306
307
308
309
        // Get all relations from record:
        $recordRelations = $this->getRelations($tableName, $record);
        // Traverse those relations, compile records to insert in table:
        foreach ($recordRelations as $fieldName => $fieldRelations) {
            // Based on type
310
            switch ($fieldRelations['type'] ?? '') {
311
                case 'db':
312
                    $this->createEntryDataForDatabaseRelationsUsingRecord($tableName, $record, $fieldName, '', $fieldRelations['itemArray']);
313
314
315
316
317
                    break;
                case 'flex':
                    // DB references in FlexForms
                    if (is_array($fieldRelations['flexFormRels']['db'])) {
                        foreach ($fieldRelations['flexFormRels']['db'] as $flexPointer => $subList) {
318
                            $this->createEntryDataForDatabaseRelationsUsingRecord($tableName, $record, $fieldName, $flexPointer, $subList);
319
320
321
322
323
324
                        }
                    }
                    // Soft references in FlexForms
                    // @todo #65464 Test correct handling of soft references in FlexForms
                    if (is_array($fieldRelations['flexFormRels']['softrefs'])) {
                        foreach ($fieldRelations['flexFormRels']['softrefs'] as $flexPointer => $subList) {
325
                            $this->createEntryDataForSoftReferencesUsingRecord($tableName, $record, $fieldName, $flexPointer, $subList['keys']);
326
327
328
329
330
                        }
                    }
                    break;
            }
            // Soft references in the field
331
            if (is_array($fieldRelations['softrefs']['keys'] ?? false)) {
332
                $this->createEntryDataForSoftReferencesUsingRecord($tableName, $record, $fieldName, '', $fieldRelations['softrefs']['keys']);
333
334
335
            }
        }

336
        return array_filter($this->relations);
337
338
    }

339
340
341
342
343
344
345
    /**
     * Create array with field/value pairs ready to insert in database
     *
     * @param string $tableName Tablename of source record (where reference is located)
     * @param array $record Record from $table
     * @param string $fieldName Fieldname of source record (where reference is located)
     * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in [$field]
346
347
348
     * @param string $referencedTable In database references the tablename the reference points to. Keyword "_STRING" indicates special usage (typ. SoftReference) in $referenceString
     * @param int $referencedUid In database references the UID of the record (zero $referencedTable is "_STRING")
     * @param string $referenceString For "_STRING" references: The string.
349
350
351
352
353
     * @param int $sort The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
     * @param string $softReferenceKey If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
     * @param string $softReferenceId Soft reference ID for key. Might be useful for replace operations.
     * @return array|bool Array to insert in DB or false if record should not be processed
     */
354
    protected function createEntryDataUsingRecord(string $tableName, array $record, string $fieldName, string $flexPointer, string $referencedTable, int $referencedUid, string $referenceString = '', int $sort = -1, string $softReferenceKey = '', string $softReferenceId = '')
355
    {
356
        $currentWorkspace = $this->getWorkspaceId();
357
        if (BackendUtility::isTableWorkspaceEnabled($tableName)) {
358
359
360
361
362
            $fieldConfig = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
            if (isset($record['t3ver_wsid']) && (int)$record['t3ver_wsid'] !== $currentWorkspace && empty($fieldConfig['MM'])) {
                // The given record is workspace-enabled but doesn't live in the selected workspace. Don't add index, it's not actually there.
                // We still add those rows if the record is a local side live record of an MM relation and can be a target of a workspace record.
                // See workspaces ManyToMany Modify addCategoryRelation for details on this case.
363
                return false;
364
365
            }
        }
366
        return [
367
368
369
            'tablename' => $tableName,
            'recuid' => $record['uid'],
            'field' => $fieldName,
370
            'flexpointer' => $flexPointer,
371
372
            'softref_key' => $softReferenceKey,
            'softref_id' => $softReferenceId,
373
            'sorting' => $sort,
374
            'workspace' => $currentWorkspace,
375
376
            'ref_table' => $referencedTable,
            'ref_uid' => $referencedUid,
377
            'ref_string' => mb_substr($referenceString, 0, 1024),
378
        ];
379
380
    }

381
382
383
384
385
386
387
388
389
    /**
     * Add database references to ->relations array based on fetched record
     *
     * @param string $tableName Tablename of source record (where reference is located)
     * @param array $record Record from $tableName
     * @param string $fieldName Fieldname of source record (where reference is located)
     * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in $fieldName
     * @param array $items Data array with database relations (table/id)
     */
390
    protected function createEntryDataForDatabaseRelationsUsingRecord(string $tableName, array $record, string $fieldName, string $flexPointer, array $items)
391
392
    {
        foreach ($items as $sort => $i) {
393
            $this->relations[] = $this->createEntryDataUsingRecord($tableName, $record, $fieldName, $flexPointer, $i['table'], (int)$i['id'], '', $sort);
394
395
396
        }
    }

397
398
399
400
401
402
403
404
405
    /**
     * Add SoftReference references to ->relations array based on fetched record
     *
     * @param string $tableName Tablename of source record (where reference is located)
     * @param array $record Record from $tableName
     * @param string $fieldName Fieldname of source record (where reference is located)
     * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in $fieldName
     * @param array $keys Data array with soft reference keys
     */
406
    protected function createEntryDataForSoftReferencesUsingRecord(string $tableName, array $record, string $fieldName, string $flexPointer, array $keys)
407
408
409
410
    {
        foreach ($keys as $spKey => $elements) {
            if (is_array($elements)) {
                foreach ($elements as $subKey => $el) {
411
                    if (is_array($el['subst'] ?? false)) {
412
413
                        switch ((string)$el['subst']['type']) {
                            case 'db':
414
                                [$referencedTable, $referencedUid] = explode(':', $el['subst']['recordRef']);
415
                                $this->relations[] = $this->createEntryDataUsingRecord($tableName, $record, $fieldName, $flexPointer, $referencedTable, (int)$referencedUid, '', -1, $spKey, $subKey);
416
417
                                break;
                            case 'string':
418
                                $this->relations[] = $this->createEntryDataUsingRecord($tableName, $record, $fieldName, $flexPointer, '_STRING', 0, $el['subst']['tokenValue'], -1, $spKey, $subKey);
419
                                break;
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
                        }
                    }
                }
            }
        }
    }

    /*******************************
     *
     * Get relations from table row
     *
     *******************************/

    /**
     * Returns relation information for a $table/$row-array
     * Traverses all fields in input row which are configured in TCA/columns
436
     * It looks for hard relations to records in the TCA types "select" and "group"
437
438
439
440
441
442
443
444
445
446
447
     *
     * @param string $table Table name
     * @param array $row Row from table
     * @param string $onlyField Specific field to fetch for.
     * @return array Array with information about relations
     * @see export_addRecord()
     */
    public function getRelations($table, $row, $onlyField = '')
    {
        // Initialize:
        $uid = $row['uid'];
448
        $outRow = [];
449
        foreach ($row as $field => $value) {
450
            if ($this->shouldExcludeTableColumnFromReferenceIndex($table, $field, $onlyField) === false) {
451
452
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
                // Add a softref definition for link fields if the TCA does not specify one already
453
                if ($conf['type'] === 'input' && isset($conf['renderType']) && $conf['renderType'] === 'inputLink' && empty($conf['softref'])) {
454
455
456
                    $conf['softref'] = 'typolink';
                }
                // Add DB:
457
                $resultsFromDatabase = $this->getRelations_procDB($value, $conf, $uid, $table, $row);
458
459
                if (!empty($resultsFromDatabase)) {
                    // Create an entry for the field with all DB relations:
460
                    $outRow[$field] = [
461
                        'type' => 'db',
462
                        'itemArray' => $resultsFromDatabase,
463
                    ];
464
                }
465
                // For "flex" fieldtypes we need to traverse the structure looking for db references of course!
466
467
                if ($conf['type'] === 'flex') {
                    // Get current value array:
468
469
                    // NOTICE: failure to resolve Data Structures can lead to integrity problems with the reference index. Please look up
                    // the note in the JavaDoc documentation for the function FlexFormTools->getDataStructureIdentifier()
470
                    $currentValueArray = GeneralUtility::xml2array($value);
471
                    // Traversing the XML structure, processing:
472
                    if (is_array($currentValueArray)) {
473
474
                        $this->temp_flexRelations = [
                            'db' => [],
475
                            'softrefs' => [],
476
                        ];
477
478
479
480
                        // Create and call iterator object:
                        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
                        $flexFormTools->traverseFlexFormXMLData($table, $field, $row, $this, 'getRelations_flexFormCallBack');
                        // Create an entry for the field:
481
                        $outRow[$field] = [
482
                            'type' => 'flex',
483
                            'flexFormRels' => $this->temp_flexRelations,
484
                        ];
485
486
487
488
489
                    }
                }
                // Soft References:
                if ((string)$value !== '') {
                    $softRefValue = $value;
490
                    if (!empty($conf['softref'])) {
491
492
493
494
495
496
                        foreach ($this->softReferenceParserFactory->getParsersBySoftRefParserList($conf['softref']) as $softReferenceParser) {
                            $parserResult = $softReferenceParser->parse($table, $field, $uid, $softRefValue);
                            if ($parserResult->hasMatched()) {
                                $outRow[$field]['softrefs']['keys'][$softReferenceParser->getParserKey()] = $parserResult->getMatchedElements();
                                if ($parserResult->hasContent()) {
                                    $softRefValue = $parserResult->getContent();
497
498
499
500
                                }
                            }
                        }
                    }
501
                    if (!empty($outRow[$field]['softrefs']) && (string)$value !== (string)$softRefValue && str_contains($softRefValue, '{softref:')) {
502
503
504
505
506
507
508
509
510
                        $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
                    }
                }
            }
        }
        return $outRow;
    }

    /**
511
     * Callback function for traversing the FlexForm structure in relation to finding DB references!
512
513
514
515
516
     *
     * @param array $dsArr Data structure for the current value
     * @param mixed $dataValue Current value
     * @param array $PA Additional configuration used in calling function
     * @param string $structurePath Path of value in DS structure
517
518
     * @see DataHandler::checkValue_flex_procInData_travDS()
     * @see FlexFormTools::traverseFlexFormXMLData()
519
     */
520
    public function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath)
521
522
523
524
525
    {
        // Removing "data/" in the beginning of path (which points to location in data array)
        $structurePath = substr($structurePath, 5) . '/';
        $dsConf = $dsArr['TCEforms']['config'];
        // Implode parameter values:
526
        [$table, $uid, $field] = [
527
528
            $PA['table'],
            $PA['uid'],
529
            $PA['field'],
530
        ];
531
        // Add a softref definition for link fields if the TCA does not specify one already
532
        if (($dsConf['type'] ?? '') === 'input' && ($dsConf['renderType'] ?? '') === 'inputLink' && empty($dsConf['softref'])) {
533
534
535
            $dsConf['softref'] = 'typolink';
        }
        // Add DB:
536
        $resultsFromDatabase = $this->getRelations_procDB($dataValue, $dsConf, $uid, $table);
537
538
539
540
541
542
543
        if (!empty($resultsFromDatabase)) {
            // Create an entry for the field with all DB relations:
            $this->temp_flexRelations['db'][$structurePath] = $resultsFromDatabase;
        }
        // Soft References:
        if (is_array($dataValue) || (string)$dataValue !== '') {
            $softRefValue = $dataValue;
544
545
546
547
548
549
            foreach ($this->softReferenceParserFactory->getParsersBySoftRefParserList($dsConf['softref'] ?? '') as $softReferenceParser) {
                $parserResult = $softReferenceParser->parse($table, $field, $uid, $softRefValue, $structurePath);
                if ($parserResult->hasMatched()) {
                    $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$softReferenceParser->getParserKey()] = $parserResult->getMatchedElements();
                    if ($parserResult->hasContent()) {
                        $softRefValue = $parserResult->getContent();
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
                    }
                }
            }
            if (!empty($this->temp_flexRelations['softrefs']) && (string)$dataValue !== (string)$softRefValue) {
                $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
            }
        }
    }

    /**
     * Check field configuration if it is a DB relation field and extract DB relations if any
     *
     * @param string $value Field value
     * @param array $conf Field configuration array of type "TCA/columns
     * @param int $uid Field uid
     * @param string $table Table name
566
     * @param array $row
567
     * @return array|bool If field type is OK it will return an array with the database relations. Else FALSE
568
     */
569
    protected function getRelations_procDB($value, $conf, $uid, $table = '', array $row = [])
570
571
572
573
    {
        // Get IRRE relations
        if (empty($conf)) {
            return false;
574
575
        }
        if ($conf['type'] === 'inline' && !empty($conf['foreign_table']) && empty($conf['MM'])) {
576
577
            $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
            $dbAnalysis->setUseLiveReferenceIds(false);
578
            $dbAnalysis->setWorkspaceId($this->getWorkspaceId());
579
580
581
            $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
            return $dbAnalysis->itemArray;
            // DB record lists:
582
583
        }
        if ($this->isDbReferenceField($conf)) {
584
            $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
585
            if ($conf['MM_opposite_field'] ?? false) {
586
                // Never handle sys_refindex when looking at MM from foreign side
587
                return [];
588
            }
589

590
            $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
591
            $dbAnalysis->setWorkspaceId($this->getWorkspaceId());
592
            $dbAnalysis->start($value, $allowedTables, $conf['MM'] ?? '', $uid, $table, $conf);
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
            $itemArray = $dbAnalysis->itemArray;

            if (ExtensionManagementUtility::isLoaded('workspaces')
                && $this->getWorkspaceId() > 0
                && !empty($conf['MM'] ?? '')
                && !empty($conf['allowed'] ?? '')
                && empty($conf['MM_opposite_field'] ?? '')
                && (int)($row['t3ver_wsid'] ?? 0) === 0
            ) {
                // When dealing with local side mm relations in workspace 0, there may be workspace records on the foreign
                // side, for instance when those got an additional category. See ManyToMany Modify addCategoryRelations test.
                // In those cases, the full set of relations must be written to sys_refindex as workspace rows.
                // But, if the relations in this workspace and live are identical, no sys_refindex workspace rows
                // have to be added.
                $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
                $dbAnalysis->setWorkspaceId(0);
                $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
                $itemArrayLive = $dbAnalysis->itemArray;
                if ($itemArrayLive === $itemArray) {
                    $itemArray = false;
                }
            }
            return $itemArray;
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
        }
        return false;
    }

    /*******************************
     *
     * Setting values
     *
     *******************************/

    /**
     * Setting the value of a reference or removing it completely.
     * Usage: For lowlevel clean up operations!
     * WARNING: With this you can set values that are not allowed in the database since it will bypass all checks for validity!
     * Hence it is targeted at clean-up operations. Please use DataHandler in the usual ways if you wish to manipulate references.
     * Since this interface allows updates to soft reference values (which DataHandler does not directly) you may like to use it
     * for that as an exception to the warning above.
     * Notice; If you want to remove multiple references from the same field, you MUST start with the one having the highest
     * sorting number. If you don't the removal of a reference with a lower number will recreate an index in which the remaining
     * references in that field has new hash-keys due to new sorting numbers - and you will get errors for the remaining operations
     * which cannot find the hash you feed it!
     * To ensure proper working only admin-BE_USERS in live workspace should use this function
     *
     * @param string $hash 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
     * @param mixed $newValue Value you wish to set for reference. If NULL, the reference is removed (unless a soft-reference in which case it can only be set to a blank string). If you wish to set a database reference, use the format "[table]:[uid]". Any other case, the input value is set as-is
     * @param bool $returnDataArray Return $dataArray only, do not submit it to database.
     * @param bool $bypassWorkspaceAdminCheck If set, it will bypass check for workspace-zero and admin user
     * @return string|bool|array FALSE (=OK), error message string or array (if $returnDataArray is set!)
     */
    public function setReferenceValue($hash, $newValue, $returnDataArray = false, $bypassWorkspaceAdminCheck = false)
    {
        $backendUser = $this->getBackendUser();
        if ($backendUser->workspace === 0 && $backendUser->isAdmin() || $bypassWorkspaceAdminCheck) {
649
650
651
652
653
654
655
656
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
            $queryBuilder->getRestrictions()->removeAll();

            // Get current index from Database
            $referenceRecord = $queryBuilder
                ->select('*')
                ->from('sys_refindex')
                ->where(
657
                    $queryBuilder->expr()->eq('hash', $queryBuilder->createNamedParameter($hash, \PDO::PARAM_STR))
658
659
660
                )
                ->setMaxResults(1)
                ->execute()
661
                ->fetchAssociative();
662
663
664
665
666
667
668
669
670
671

            // Check if reference existed.
            if (!is_array($referenceRecord)) {
                return 'ERROR: No reference record with hash="' . $hash . '" was found!';
            }

            if (empty($GLOBALS['TCA'][$referenceRecord['tablename']])) {
                return 'ERROR: Table "' . $referenceRecord['tablename'] . '" was not in TCA!';
            }

672
673
674
675
676
677
678
679
            // Get that record from database
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
                ->getQueryBuilderForTable($referenceRecord['tablename']);
            $queryBuilder->getRestrictions()->removeAll();
            $record = $queryBuilder
                ->select('*')
                ->from($referenceRecord['tablename'])
                ->where(
680
681
682
683
                    $queryBuilder->expr()->eq(
                        'uid',
                        $queryBuilder->createNamedParameter($referenceRecord['recuid'], \PDO::PARAM_INT)
                    )
684
685
686
                )
                ->setMaxResults(1)
                ->execute()
687
                ->fetchAssociative();
688

689
690
691
692
693
            if (is_array($record)) {
                // Get relation for single field from record
                $recordRelations = $this->getRelations($referenceRecord['tablename'], $record, $referenceRecord['field']);
                if ($fieldRelation = $recordRelations[$referenceRecord['field']]) {
                    // Initialize data array that is to be sent to DataHandler afterwards:
694
                    $dataArray = [];
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
                    // Based on type
                    switch ((string)$fieldRelation['type']) {
                        case 'db':
                            $error = $this->setReferenceValue_dbRels($referenceRecord, $fieldRelation['itemArray'], $newValue, $dataArray);
                            if ($error) {
                                return $error;
                            }
                            break;
                        case 'flex':
                            // DB references in FlexForms
                            if (is_array($fieldRelation['flexFormRels']['db'][$referenceRecord['flexpointer']])) {
                                $error = $this->setReferenceValue_dbRels($referenceRecord, $fieldRelation['flexFormRels']['db'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
                                if ($error) {
                                    return $error;
                                }
                            }
                            // Soft references in FlexForms
                            if ($referenceRecord['softref_key'] && is_array($fieldRelation['flexFormRels']['softrefs'][$referenceRecord['flexpointer']]['keys'][$referenceRecord['softref_key']])) {
                                $error = $this->setReferenceValue_softreferences($referenceRecord, $fieldRelation['flexFormRels']['softrefs'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
                                if ($error) {
                                    return $error;
                                }
                            }
                            break;
                    }
                    // Soft references in the field:
                    if ($referenceRecord['softref_key'] && is_array($fieldRelation['softrefs']['keys'][$referenceRecord['softref_key']])) {
                        $error = $this->setReferenceValue_softreferences($referenceRecord, $fieldRelation['softrefs'], $newValue, $dataArray);
                        if ($error) {
                            return $error;
                        }
                    }
                    // Data Array, now ready to be sent to DataHandler
                    if ($returnDataArray) {
                        return $dataArray;
730
731
732
733
734
                    }
                    // Execute CMD array:
                    $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
                    $dataHandler->dontProcessTransformations = true;
                    $dataHandler->bypassWorkspaceRestrictions = true;
735
                    // Otherwise this may lead to permission issues if user is not admin
736
737
738
739
740
741
                    $dataHandler->bypassAccessCheckForRecords = true;
                    // Check has been done previously that there is a backend user which is Admin and also in live workspace
                    $dataHandler->start($dataArray, []);
                    $dataHandler->process_datamap();
                    // Return errors if any:
                    if (!empty($dataHandler->errorLog)) {
742
                        return LF . 'DataHandler:' . implode(LF . 'DataHandler:', $dataHandler->errorLog);
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
                    }
                }
            }
        } else {
            return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
        }

        return false;
    }

    /**
     * Setting a value for a reference for a DB field:
     *
     * @param array $refRec sys_refindex record
     * @param array $itemArray Array of references from that field
     * @param string $newValue Value to substitute current value with (or NULL to unset it)
     * @param array $dataArray Data array in which the new value is set (passed by reference)
     * @param string $flexPointer Flexform pointer, if in a flex form field.
     * @return string Error message if any, otherwise FALSE = OK
     */
763
    protected function setReferenceValue_dbRels($refRec, $itemArray, $newValue, &$dataArray, $flexPointer = '')
764
765
766
767
768
769
770
    {
        if ((int)$itemArray[$refRec['sorting']]['id'] === (int)$refRec['ref_uid'] && (string)$itemArray[$refRec['sorting']]['table'] === (string)$refRec['ref_table']) {
            // Setting or removing value:
            // Remove value:
            if ($newValue === null) {
                unset($itemArray[$refRec['sorting']]);
            } else {
771
                [$itemArray[$refRec['sorting']]['table'], $itemArray[$refRec['sorting']]['id']] = explode(':', $newValue);
772
773
            }
            // Traverse and compile new list of records:
774
            $saveValue = [];
775
776
777
778
779
            foreach ($itemArray as $pair) {
                $saveValue[] = $pair['table'] . '_' . $pair['id'];
            }
            // Set in data array:
            if ($flexPointer) {
780
781
782
783
784
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = ArrayUtility::setValueByPath(
                    [],
                    substr($flexPointer, 0, -1),
                    implode(',', $saveValue)
                );
785
786
787
788
789
790
791
792
793
794
795
796
797
798
            } else {
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
            }
        } else {
            return 'ERROR: table:id pair "' . $refRec['ref_table'] . ':' . $refRec['ref_uid'] . '" did not match that of the record ("' . $itemArray[$refRec['sorting']]['table'] . ':' . $itemArray[$refRec['sorting']]['id'] . '") in sorting index "' . $refRec['sorting'] . '"';
        }

        return false;
    }

    /**
     * Setting a value for a soft reference token
     *
     * @param array $refRec sys_refindex record
799
     * @param array $softref Array of soft reference occurrences
800
801
802
803
804
     * @param string $newValue Value to substitute current value with
     * @param array $dataArray Data array in which the new value is set (passed by reference)
     * @param string $flexPointer Flexform pointer, if in a flex form field.
     * @return string Error message if any, otherwise FALSE = OK
     */
805
    protected function setReferenceValue_softreferences($refRec, $softref, $newValue, &$dataArray, $flexPointer = '')
806
807
808
809
810
811
812
813
814
815
816
817
818
819
    {
        if (!is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
            return 'ERROR: Soft reference parser key "' . $refRec['softref_key'] . '" or the index "' . $refRec['softref_id'] . '" was not found.';
        }

        // Set new value:
        $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = '' . $newValue;
        // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
        foreach ($softref['keys'] as $sfIndexes) {
            foreach ($sfIndexes as $data) {
                $softref['tokenizedContent'] = str_replace('{softref:' . $data['subst']['tokenID'] . '}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
            }
        }
        // Set in data array:
820
        if (!str_contains($softref['tokenizedContent'], '{softref:')) {
821
            if ($flexPointer) {
822
823
824
825
826
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = ArrayUtility::setValueByPath(
                    [],
                    substr($flexPointer, 0, -1),
                    $softref['tokenizedContent']
                );
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
            } else {
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
            }
        } else {
            return 'ERROR: After substituting all found soft references there were still soft reference tokens in the text. (theoretically this does not have to be an error if the string "{softref:" happens to be in the field for another reason.)';
        }

        return false;
    }

    /*******************************
     *
     * Helper functions
     *
     *******************************/

    /**
     * Returns TRUE if the TCA/columns field type is a DB reference field
     *
     * @param array $configuration Config array for TCA/columns field
     * @return bool TRUE if DB reference field (group/db or select with foreign-table)
     */
849
    protected function isDbReferenceField(array $configuration): bool
850
    {
851
        return
852
            ($configuration['type'] === 'group' && ($configuration['internal_type'] ?? '') !== 'folder')
853
            || (
854
                in_array($configuration['type'], ['select', 'category', 'inline'], true)
855
                && !empty($configuration['foreign_table'])
856
            );
857
858
859
860
861
862
863
864
    }

    /**
     * Returns TRUE if the TCA/columns field type is a reference field
     *
     * @param array $configuration Config array for TCA/columns field
     * @return bool TRUE if reference field
     */
865
    protected function isReferenceField(array $configuration): bool
866
    {
867
        return
868
            $this->isDbReferenceField($configuration)
869
870
871
            || ($configuration['type'] === 'input' && isset($configuration['renderType']) && $configuration['renderType'] === 'inputLink')
            || $configuration['type'] === 'flex'
            || isset($configuration['softref'])
872
            ;
873
874
875
876
877
878
    }

    /**
     * Returns all fields of a table which could contain a relation
     *
     * @param string $tableName Name of the table
879
     * @return array Fields which may contain relations
880
     */
881
    protected function fetchTableRelationFields(string $tableName): array
882
    {
883
884
885
        if (!empty($this->tableRelationFieldCache[$tableName])) {
            return $this->tableRelationFieldCache[$tableName];
        }
886
        if (!isset($GLOBALS['TCA'][$tableName]['columns'])) {
887
            return [];
888
        }
889
        $fields = [];
890
891
892
893
894
        foreach ($GLOBALS['TCA'][$tableName]['columns'] as $field => $fieldDefinition) {
            if (is_array($fieldDefinition['config'])) {
                // Check for flex field
                if (isset($fieldDefinition['config']['type']) && $fieldDefinition['config']['type'] === 'flex') {
                    // Fetch all fields if the is a field of type flex in the table definition because the complete row is passed to
895
                    // FlexFormTools->getDataStructureIdentifier() in the end and might be needed in ds_pointerField or a hook
896
897
                    $this->tableRelationFieldCache[$tableName] = ['*'];
                    return ['*'];
898
899
900
901
902
903
904
                }
                // Only fetch this field if it can contain a reference
                if ($this->isReferenceField($fieldDefinition['config'])) {
                    $fields[] = $field;
                }
            }
        }
905
906
        $this->tableRelationFieldCache[$tableName] = $fields;
        return $fields;
907
908
909
910
911
912
    }

    /**
     * Updating Index (External API)
     *
     * @param bool $testOnly If set, only a test
913
     * @param ProgressListenerInterface|null $progressListener If set, the current progress is added to the listener
914
     * @return array Header and body status content
915
     * @todo: Consider moving this together with the helper methods to a dedicated class.
916
     */
917
    public function updateIndex($testOnly, ?ProgressListenerInterface $progressListener = null)
918
    {
919
920
        $errors = [];
        $tableNames = [];
921
        $recCount = 0;
922
        $isWorkspacesLoaded = ExtensionManagementUtility::isLoaded('workspaces');
923
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
924
925
926
927
        $refIndexConnectionName = empty($GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping']['sys_refindex'])
                ? ConnectionPool::DEFAULT_CONNECTION_NAME
                : $GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping']['sys_refindex'];

928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
        // Drop sys_refindex rows from deleted workspaces
        $listOfActiveWorkspaces = $this->getListOfActiveWorkspaces();
        $unusedWorkspaceRows = $this->getAmountOfUnusedWorkspaceRowsInReferenceIndex($listOfActiveWorkspaces);
        if ($unusedWorkspaceRows > 0) {
            $error = 'Index table hosted ' . $unusedWorkspaceRows . ' indexes for non-existing or deleted workspaces, now removed.';
            $errors[] = $error;
            if ($progressListener) {
                $progressListener->log($error, LogLevel::WARNING);
            }
            if (!$testOnly) {
                $this->removeUnusedWorkspaceRowsFromReferenceIndex($listOfActiveWorkspaces);
            }
        }

        // Main loop traverses all records of all TCA tables
943
        foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
944
            if ($this->shouldExcludeTableFromReferenceIndex($tableName)) {
945
946
                continue;
            }
947
948
949
950
            $tableConnectionName = empty($GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping'][$tableName])
                ? ConnectionPool::DEFAULT_CONNECTION_NAME
                : $GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping'][$tableName];

951
952
953
954
955
956
957
958
959
960
961
962
            // Some additional magic is needed if the table has a field that is the local side of
            // a mm relation. See the variable usage below for details.
            $tableHasLocalSideMmRelation = false;
            foreach (($cfg['columns'] ?? []) as $fieldConfig) {
                if (!empty($fieldConfig['config']['MM'] ?? '')
                    && !empty($fieldConfig['config']['allowed'] ?? '')
                    && empty($fieldConfig['config']['MM_opposite_field'] ?? '')
                ) {
                    $tableHasLocalSideMmRelation = true;
                }
            }

963
964
965
966
967
968
969
970
971
972
973
            $fields = ['uid'];
            if (BackendUtility::isTableWorkspaceEnabled($tableName)) {
                $fields[] = 't3ver_wsid';
            }
            // Traverse all records in tables, including deleted records
            $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
            $queryBuilder->getRestrictions()->removeAll();
            try {
                $queryResult = $queryBuilder
                    ->select(...$fields)
                    ->from($tableName)
974
                    ->orderBy('uid')
975
976
                    ->execute();
            } catch (DBALException $e) {
977
                // Table exists in TCA but does not exist in the database
978
979
980
981
                $this->logger->error('Table {table_name} exists in TCA but does not exist in the database. You should run the Database Analyzer in the Install Tool to fix this.', [
                    'table_name' => $tableName,
                    'exception' => $e,
                ]);
982
983
                continue;
            }
984

985
986
987
            if ($progressListener) {
                $progressListener->start($queryResult->rowCount(), $tableName);
            }
988
            $tableNames[] = $tableName;
989
            while ($record = $queryResult->fetchAssociative()) {
990
991
992
                if ($progressListener) {
                    $progressListener->advance();
                }
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024

                if ($isWorkspacesLoaded && $tableHasLocalSideMmRelation && (int)($record['t3ver_wsid'] ?? 0) === 0) {
                    // If we have record that can be the local side of a workspace relation, workspace records
                    // may point to it, even though the record has no workspace overlay. See workspace ManyToMany
                    // Modify addCategoryRelation as example. In those cases, we need to iterate all active workspaces
                    // and update refindex for all foreign workspace records that point to it.
                    foreach ($listOfActiveWorkspaces as $workspaceId) {
                        $refIndexObj = GeneralUtility::makeInstance(self::class);
                        $refIndexObj->setWorkspaceId($workspaceId);
                        $result = $refIndexObj->updateRefIndexTable($tableName, $record['uid'], $testOnly);
                        $recCount++;
                        if ($result['addedNodes'] || $result['deletedNodes']) {
                            $error = 'Record ' . $tableName . ':' . $record['uid'] . ' had ' . $result['addedNodes'] . ' added indexes and ' . $result['deletedNodes'] . ' deleted indexes';
                            $errors[] = $error;
                            if ($progressListener) {
                                $progressListener->log($error, LogLevel::WARNING);
                            }
                        }
                    }
                } else {
                    $refIndexObj = GeneralUtility::makeInstance(self::class);
                    if (isset($record['t3ver_wsid'])) {
                        $refIndexObj->setWorkspaceId($record['t3ver_wsid']);
                    }
                    $result = $refIndexObj->updateRefIndexTable($tableName, $record['uid'], $testOnly);
                    $recCount++;
                    if ($result['addedNodes'] || $result['deletedNodes']) {
                        $error = 'Record ' . $tableName . ':' . $record['uid'] . ' had ' . $result['addedNodes'] . ' added indexes and ' . $result['deletedNodes'] . ' deleted indexes';
                        $errors[] = $error;
                        if ($progressListener) {
                            $progressListener->log($error, LogLevel::WARNING);
                        }
1025
                    }
1026
1027
                }
            }
1028
1029
1030
            if ($progressListener) {
                $progressListener->finish();
            }
1031

1032
            // Subselect based queries only work on the same connection
1033
1034
1035
1036
1037
1038
1039
            // @todo: Consider dropping this in v12 and always use sub select: The base set of tables should
            //        be in exactly one DB and only tables like caches should be "extractable" to a different DB?!
            //        Even though sys_refindex is a "cache-like" table since it only holds secondary information that
            //        can always be re-created by analyzing the entire data set, it shouldn't be possible to run it
            //        on a different database since that prevents quick joins between sys_refindex and target relations.
            //        We should probably have some report and/or install tool check to make sure all main tables
            //        are on the same connection in v12.
1040
            if ($refIndexConnectionName !== $tableConnectionName) {
1041
                $this->logger->error('Not checking table {table_name} for lost indexes, "sys_refindex" table uses a different connection', ['table_name' => $tableName]);
1042
1043
1044
                continue;
            }

1045
            // Searching for lost indexes for this table
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
            // Build sub-query to find lost records
            $subQueryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
            $subQueryBuilder->getRestrictions()->removeAll();
            $subQueryBuilder
                ->select('uid')
                ->from($tableName, 'sub_' . $tableName)
                ->where(
                    $subQueryBuilder->expr()->eq(
                        'sub_' . $tableName . '.uid',
                        $queryBuilder->quoteIdentifier('sys_refindex.recuid')
                    )
                );

            // Main query to find lost records
1060
1061
1062
1063
1064
1065
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
            $queryBuilder->getRestrictions()->removeAll();
            $lostIndexes = $queryBuilder
                ->count('hash')
                ->from('sys_refindex')
                ->where(
1066
1067
1068
1069
                    $queryBuilder->expr()->eq(
                        'tablename',
                        $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
                    ),
1070
                    'NOT EXISTS (' . $subQueryBuilder->getSQL() . ')'
1071
1072
                )
                ->execute()
1073
                ->fetchOne();
1074
1075
1076

            if ($lostIndexes > 0) {
                $error = 'Table ' . $tableName . ' has ' . $lostIndexes . ' lost indexes which are now deleted';
1077
                $errors[] = $error;
1078
1079
1080
                if ($progressListener) {
                    $progressListener->log($error, LogLevel::WARNING);
                }
1081
                if (!$testOnly) {
1082
1083
1084
                    $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
                    $queryBuilder->delete('sys_refindex')
                        ->where(
1085
1086
1087
1088
                            $queryBuilder->expr()->eq(
                                'tablename',
                                $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
                            ),
1089
1090
1091
                            'NOT EXISTS (' . $subQueryBuilder->getSQL() . ')'
                        )
                        ->execute();
1092
1093
1094
                }
            }
        }
1095
1096

        // Searching lost indexes for non-existing tables
1097
1098
        // @todo: Consider moving this *before* the main re-index logic to have a smaller
        //        dataset when starting with heavy lifting.
1099
        $lostTables = $this->getAmountOfUnusedTablesInReferenceIndex($tableNames);
1100
1101
        if ($lostTables > 0) {
            $error = 'Index table hosted ' . $lostTables . ' indexes for non-existing tables, now removed';
1102
            $errors[] = $error;
1103
1104
1105
            if ($progressListener) {
                $progressListener->log($error, LogLevel::WARNING);
            }
1106
            if (!$testOnly) {
1107
                $this->removeReferenceIndexDataFromUnusedDatabaseTables($tableNames);
1108
1109
1110
            }
        }
        $errorCount = count($errors);