Passed
Push — master ( 960273...d66d7f )
by
unknown
19:18
created

ReferenceIndex::getRecord()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 40
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 40
rs 9.2248
c 0
b 0
f 0
cc 5
nc 7
nop 2
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Core\Database;
17
18
use Doctrine\DBAL\DBALException;
19
use Psr\EventDispatcher\EventDispatcherInterface;
20
use Psr\Log\LoggerAwareInterface;
21
use Psr\Log\LoggerAwareTrait;
22
use Psr\Log\LogLevel;
23
use TYPO3\CMS\Backend\Utility\BackendUtility;
24
use TYPO3\CMS\Backend\View\ProgressListenerInterface;
25
use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
26
use TYPO3\CMS\Core\Database\Platform\PlatformInformation;
27
use TYPO3\CMS\Core\DataHandling\DataHandler;
28
use TYPO3\CMS\Core\DataHandling\Event\IsTableExcludedFromReferenceIndexEvent;
29
use TYPO3\CMS\Core\Registry;
30
use TYPO3\CMS\Core\Utility\GeneralUtility;
31
32
/**
33
 * Reference index processing and relation extraction
34
 *
35
 * NOTICE: When the reference index is updated for an offline version the results may not be correct.
36
 * First, lets assumed that the reference update happens in LIVE workspace (ALWAYS update from Live workspace if you analyze whole database!)
37
 * Secondly, lets assume that in a Draft workspace you have changed the data structure of a parent page record - this is (in TemplaVoila) inherited by subpages.
38
 * When in the LIVE workspace the data structure for the records/pages in the offline workspace will not be evaluated to the right one simply because the data
39
 * structure is taken from a rootline traversal and in the Live workspace that will NOT include the changed DataStructure! Thus the evaluation will be based
40
 * on the Data Structure set in the Live workspace!
41
 * Somehow this scenario is rarely going to happen. Yet, it is an inconsistency and I see now practical way to handle it - other than simply ignoring
42
 * maintaining the index for workspace records. Or we can say that the index is precise for all Live elements while glitches might happen in an offline workspace?
43
 * Anyway, I just wanted to document this finding - I don't think we can find a solution for it. And its very TemplaVoila specific.
44
 */
45
class ReferenceIndex implements LoggerAwareInterface
46
{
47
    use LoggerAwareTrait;
48
49
    /**
50
     * Definition of tables to exclude from the ReferenceIndex
51
     *
52
     * Only tables which do not contain any relations and never did so far since references also won't be deleted for
53
     * these. Since only tables with an entry in $GLOBALS['TCA] are handled by ReferenceIndex there is no need to add
54
     * *_mm-tables.
55
     *
56
     * Implemented as array with fields as keys and booleans as values for fast isset() lookup instead of slow in_array()
57
     *
58
     * @var array
59
     * @see updateRefIndexTable()
60
     * @see shouldExcludeTableFromReferenceIndex()
61
     */
62
    protected array $excludedTables = [
63
        'sys_log' => true,
64
        'tx_extensionmanager_domain_model_extension' => true
65
    ];
66
67
    /**
68
     * Definition of fields to exclude from ReferenceIndex in *every* table
69
     *
70
     * Implemented as array with fields as keys and booleans as values for fast isset() lookup instead of slow in_array()
71
     *
72
     * @var array
73
     * @see getRelations()
74
     * @see fetchTableRelationFields()
75
     * @see shouldExcludeTableColumnFromReferenceIndex()
76
     */
77
    protected array $excludedColumns = [
78
        'uid' => true,
79
        'perms_userid' => true,
80
        'perms_groupid' => true,
81
        'perms_user' => true,
82
        'perms_group' => true,
83
        'perms_everybody' => true,
84
        'pid' => true
85
    ];
86
87
    /**
88
     * This array holds the FlexForm references of a record
89
     *
90
     * @var array
91
     * @see getRelations()
92
     * @see FlexFormTools::traverseFlexFormXMLData()
93
     * @see getRelations_flexFormCallBack()
94
     */
95
    protected $temp_flexRelations = [];
96
97
    /**
98
     * An index of all found references of a single record
99
     *
100
     * @var array
101
     */
102
    protected $relations = [];
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.
106
     *
107
     * @var int
108
     * @see updateRefIndexTable()
109
     */
110
    protected $hashVersion = 1;
111
112
    /**
113
     * Current workspace id
114
     */
115
    protected int $workspaceId = 0;
116
117
    /**
118
     * A list of fields that may contain relations per TCA table.
119
     * This is either ['*'] or an array of single field names. The list
120
     * depends on TCA and is built when a first table row is handled.
121
     */
122
    protected array $tableRelationFieldCache = [];
123
124
    protected EventDispatcherInterface $eventDispatcher;
125
126
    public function __construct(EventDispatcherInterface $eventDispatcher = null)
127
    {
128
        $this->eventDispatcher = $eventDispatcher ?? GeneralUtility::getContainer()->get(EventDispatcherInterface::class);
129
    }
130
131
    /**
132
     * Sets the current workspace id
133
     *
134
     * @param int $workspaceId
135
     * @see updateIndex()
136
     */
137
    public function setWorkspaceId($workspaceId)
138
    {
139
        $this->workspaceId = (int)$workspaceId;
140
    }
141
142
    /**
143
     * Gets the current workspace id
144
     *
145
     * @return int
146
     * @see updateRefIndexTable()
147
     */
148
    protected function getWorkspaceId()
149
    {
150
        return $this->workspaceId;
151
    }
152
153
    /**
154
     * Call this function to update the sys_refindex table for a record (even one just deleted)
155
     * NOTICE: Currently, references updated for a deleted-flagged record will not include those from within FlexForm
156
     * fields in some cases where the data structure is defined by another record since the resolving process ignores
157
     * deleted records! This will also result in bad cleaning up in DataHandler I think... Anyway, that's the story of
158
     * FlexForms; as long as the DS can change, lots of references can get lost in no time.
159
     *
160
     * @param string $tableName Table name
161
     * @param int $uid UID of record
162
     * @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.
163
     * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
164
     */
165
    public function updateRefIndexTable($tableName, $uid, $testOnly = false)
166
    {
167
        $result = [
168
            'keptNodes' => 0,
169
            'deletedNodes' => 0,
170
            'addedNodes' => 0
171
        ];
172
173
        $uid = $uid ? (int)$uid : 0;
174
        if (!$uid) {
175
            return $result;
176
        }
177
178
        // If this table cannot contain relations, skip it
179
        if ($this->shouldExcludeTableFromReferenceIndex($tableName)) {
180
            return $result;
181
        }
182
183
        $tableRelationFields = $this->fetchTableRelationFields($tableName);
184
185
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
186
        $connection = $connectionPool->getConnectionForTable('sys_refindex');
187
188
        // Get current index from Database with hash as index using $uidIndexField
189
        // no restrictions are needed, since sys_refindex is not a TCA table
190
        $queryBuilder = $connection->createQueryBuilder();
191
        $queryBuilder->getRestrictions()->removeAll();
192
        $queryResult = $queryBuilder->select('hash')->from('sys_refindex')->where(
193
            $queryBuilder->expr()->eq('tablename', $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)),
194
            $queryBuilder->expr()->eq('recuid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
195
            $queryBuilder->expr()->eq(
196
                'workspace',
197
                $queryBuilder->createNamedParameter($this->getWorkspaceId(), \PDO::PARAM_INT)
198
            )
199
        )->execute();
200
        $currentRelationHashes = [];
201
        while ($relation = $queryResult->fetch()) {
202
            $currentRelationHashes[$relation['hash']] = true;
203
        }
204
205
        // If the table has fields which could contain relations and the record does exist
206
        if ($tableRelationFields !== []) {
207
            $existingRecord = $this->getRecord($tableName, $uid);
208
            if ($existingRecord) {
209
                // Table has relation fields and record exists - get relations
210
                $this->relations = [];
211
                $relations = $this->generateDataUsingRecord($tableName, $existingRecord);
212
                if (!is_array($relations)) {
0 ignored issues
show
introduced by
The condition is_array($relations) is always true.
Loading history...
213
                    return $result;
214
                }
215
                // Traverse the generated index:
216
                foreach ($relations as &$relation) {
217
                    if (!is_array($relation)) {
218
                        continue;
219
                    }
220
                    // Exclude any relations TO a specific table
221
                    if (($relation['ref_table'] ?? '') && $this->shouldExcludeTableFromReferenceIndex($relation['ref_table'])) {
222
                        continue;
223
                    }
224
                    $relation['hash'] = md5(implode('///', $relation) . '///' . $this->hashVersion);
225
                    // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
226
                    if (isset($currentRelationHashes[$relation['hash']])) {
227
                        unset($currentRelationHashes[$relation['hash']]);
228
                        $result['keptNodes']++;
229
                        $relation['_ACTION'] = 'KEPT';
230
                    } else {
231
                        // If new, add it:
232
                        if (!$testOnly) {
233
                            $connection->insert('sys_refindex', $relation);
234
                        }
235
                        $result['addedNodes']++;
236
                        $relation['_ACTION'] = 'ADDED';
237
                    }
238
                }
239
                $result['relations'] = $relations;
240
            }
241
        }
242
243
        // If any old are left, remove them:
244
        if (!empty($currentRelationHashes)) {
245
            $hashList = array_keys($currentRelationHashes);
246
            if (!empty($hashList)) {
247
                $result['deletedNodes'] = count($hashList);
248
                $result['deletedNodes_hashList'] = implode(',', $hashList);
249
                if (!$testOnly) {
250
                    $maxBindParameters = PlatformInformation::getMaxBindParameters($connection->getDatabasePlatform());
251
                    foreach (array_chunk($hashList, $maxBindParameters - 10, true) as $chunk) {
252
                        if (empty($chunk)) {
253
                            continue;
254
                        }
255
                        $queryBuilder = $connection->createQueryBuilder();
256
                        $queryBuilder
257
                            ->delete('sys_refindex')
258
                            ->where(
259
                                $queryBuilder->expr()->in(
260
                                    'hash',
261
                                    $queryBuilder->createNamedParameter($chunk, Connection::PARAM_STR_ARRAY)
262
                                )
263
                            )
264
                            ->execute();
265
                    }
266
                }
267
            }
268
        }
269
270
        return $result;
271
    }
272
273
    /**
274
     * Returns the amount of references for the given record
275
     *
276
     * @param string $tableName
277
     * @param int $uid
278
     * @return int
279
     */
280
    public function getNumberOfReferencedRecords(string $tableName, int $uid): int
281
    {
282
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
283
        return (int)$queryBuilder
284
            ->count('*')->from('sys_refindex')
285
            ->where(
286
                $queryBuilder->expr()->eq(
287
                    'ref_table',
288
                    $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
289
                ),
290
                $queryBuilder->expr()->eq(
291
                    'ref_uid',
292
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
293
                )
294
            )->execute()->fetchColumn(0);
295
    }
296
297
    /**
298
     * Calculate the relations for a record of a given table
299
     *
300
     * @param string $tableName Table being processed
301
     * @param array $record Record from $tableName
302
     * @return array
303
     */
304
    protected function generateDataUsingRecord(string $tableName, array $record): array
305
    {
306
        $this->relations = [];
307
        // Get all relations from record:
308
        $recordRelations = $this->getRelations($tableName, $record);
309
        // Traverse those relations, compile records to insert in table:
310
        foreach ($recordRelations as $fieldName => $fieldRelations) {
311
            // Based on type
312
            switch ((string)$fieldRelations['type']) {
313
                case 'db':
314
                    $this->createEntryDataForDatabaseRelationsUsingRecord($tableName, $record, $fieldName, '', $fieldRelations['itemArray']);
315
                    break;
316
                case 'flex':
317
                    // DB references in FlexForms
318
                    if (is_array($fieldRelations['flexFormRels']['db'])) {
319
                        foreach ($fieldRelations['flexFormRels']['db'] as $flexPointer => $subList) {
320
                            $this->createEntryDataForDatabaseRelationsUsingRecord($tableName, $record, $fieldName, $flexPointer, $subList);
321
                        }
322
                    }
323
                    // Soft references in FlexForms
324
                    // @todo #65464 Test correct handling of soft references in FlexForms
325
                    if (is_array($fieldRelations['flexFormRels']['softrefs'])) {
326
                        foreach ($fieldRelations['flexFormRels']['softrefs'] as $flexPointer => $subList) {
327
                            $this->createEntryDataForSoftReferencesUsingRecord($tableName, $record, $fieldName, $flexPointer, $subList['keys']);
328
                        }
329
                    }
330
                    break;
331
            }
332
            // Soft references in the field
333
            if (is_array($fieldRelations['softrefs'])) {
334
                $this->createEntryDataForSoftReferencesUsingRecord($tableName, $record, $fieldName, '', $fieldRelations['softrefs']['keys']);
335
            }
336
        }
337
338
        return array_filter($this->relations);
339
    }
340
341
    /**
342
     * Create array with field/value pairs ready to insert in database
343
     *
344
     * @param string $tableName Tablename of source record (where reference is located)
345
     * @param array $record Record from $table
346
     * @param string $fieldName Fieldname of source record (where reference is located)
347
     * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in [$field]
348
     * @param string $referencedTable In database references the tablename the reference points to. Keyword "_STRING" indicates special usage (typ. SoftReference) in $referenceString
349
     * @param int $referencedUid In database references the UID of the record (zero $referencedTable is "_STRING")
350
     * @param string $referenceString For "_STRING" references: The string.
351
     * @param int $sort The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
352
     * @param string $softReferenceKey If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
353
     * @param string $softReferenceId Soft reference ID for key. Might be useful for replace operations.
354
     * @return array|bool Array to insert in DB or false if record should not be processed
355
     */
356
    protected function createEntryDataUsingRecord(string $tableName, array $record, string $fieldName, string $flexPointer, string $referencedTable, int $referencedUid, string $referenceString = '', int $sort = -1, string $softReferenceKey = '', string $softReferenceId = '')
357
    {
358
        $workspaceId = 0;
359
        if (BackendUtility::isTableWorkspaceEnabled($tableName)) {
360
            $workspaceId = $this->getWorkspaceId();
361
            if (isset($record['t3ver_wsid']) && (int)$record['t3ver_wsid'] !== $workspaceId) {
362
                // The given record is workspace-enabled but doesn't live in the selected workspace => don't add index as it's not actually there
363
                return false;
364
            }
365
        }
366
        return [
367
            'tablename' => $tableName,
368
            'recuid' => $record['uid'],
369
            'field' => $fieldName,
370
            'flexpointer' => $flexPointer,
371
            'softref_key' => $softReferenceKey,
372
            'softref_id' => $softReferenceId,
373
            'sorting' => $sort,
374
            'workspace' => $workspaceId,
375
            'ref_table' => $referencedTable,
376
            'ref_uid' => $referencedUid,
377
            'ref_string' => mb_substr($referenceString, 0, 1024)
378
        ];
379
    }
380
381
    /**
382
     * Add database references to ->relations array based on fetched record
383
     *
384
     * @param string $tableName Tablename of source record (where reference is located)
385
     * @param array $record Record from $tableName
386
     * @param string $fieldName Fieldname of source record (where reference is located)
387
     * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in $fieldName
388
     * @param array $items Data array with database relations (table/id)
389
     */
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
     * Add SoftReference references to ->relations array based on fetched record
399
     *
400
     * @param string $tableName Tablename of source record (where reference is located)
401
     * @param array $record Record from $tableName
402
     * @param string $fieldName Fieldname of source record (where reference is located)
403
     * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in $fieldName
404
     * @param array $keys Data array with soft reference keys
405
     */
406
    protected function createEntryDataForSoftReferencesUsingRecord(string $tableName, array $record, string $fieldName, string $flexPointer, array $keys)
407
    {
408
        foreach ($keys as $spKey => $elements) {
409
            if (is_array($elements)) {
410
                foreach ($elements as $subKey => $el) {
411
                    if (is_array($el['subst'])) {
412
                        switch ((string)$el['subst']['type']) {
413
                            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
                                break;
417
                            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
     * Get relations from table row
430
     *
431
     *******************************/
432
433
    /**
434
     * Returns relation information for a $table/$row-array
435
     * 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
     * @param string $table Table name
439
     * @param array $row Row from table
440
     * @param string $onlyField Specific field to fetch for.
441
     * @return array Array with information about relations
442
     * @see export_addRecord()
443
     */
444
    public function getRelations($table, $row, $onlyField = '')
445
    {
446
        // Initialize:
447
        $uid = $row['uid'];
448
        $outRow = [];
449
        foreach ($row as $field => $value) {
450
            if ($this->shouldExcludeTableColumnFromReferenceIndex($table, $field, $onlyField) === false) {
451
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
452
                // Add a softref definition for link fields if the TCA does not specify one already
453
                if ($conf['type'] === 'input' && $conf['renderType'] === 'inputLink' && empty($conf['softref'])) {
454
                    $conf['softref'] = 'typolink';
455
                }
456
                // Add DB:
457
                $resultsFromDatabase = $this->getRelations_procDB($value, $conf, $uid, $table);
458
                if (!empty($resultsFromDatabase)) {
459
                    // 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
                if ($conf['type'] === 'flex') {
467
                    // Get current value array:
468
                    // NOTICE: failure to resolve Data Structures can lead to integrity problems with the reference index. Please look up
469
                    // 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
                        $this->temp_flexRelations = [
474
                            'db' => [],
475
                            'softrefs' => []
476
                        ];
477
                        // Create and call iterator object:
478
                        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
479
                        $flexFormTools->traverseFlexFormXMLData($table, $field, $row, $this, 'getRelations_flexFormCallBack');
480
                        // Create an entry for the field:
481
                        $outRow[$field] = [
482
                            'type' => 'flex',
483
                            'flexFormRels' => $this->temp_flexRelations
484
                        ];
485
                    }
486
                }
487
                // Soft References:
488
                if ((string)$value !== '') {
489
                    $softRefValue = $value;
490
                    if (!empty($conf['softref'])) {
491
                        $softRefs = BackendUtility::explodeSoftRefParserList($conf['softref']);
492
                        foreach ($softRefs as $spKey => $spParams) {
493
                            $softRefObj = BackendUtility::softRefParserObj($spKey);
494
                            if (is_object($softRefObj)) {
495
                                $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
496
                                if (is_array($resultArray)) {
497
                                    $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
498
                                    if ((string)$resultArray['content'] !== '') {
499
                                        $softRefValue = $resultArray['content'];
500
                                    }
501
                                }
502
                            }
503
                        }
504
                    }
505
                    if (!empty($outRow[$field]['softrefs']) && (string)$value !== (string)$softRefValue && strpos($softRefValue, '{softref:') !== false) {
506
                        $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
507
                    }
508
                }
509
            }
510
        }
511
        return $outRow;
512
    }
513
514
    /**
515
     * Callback function for traversing the FlexForm structure in relation to finding DB references!
516
     *
517
     * @param array $dsArr Data structure for the current value
518
     * @param mixed $dataValue Current value
519
     * @param array $PA Additional configuration used in calling function
520
     * @param string $structurePath Path of value in DS structure
521
     * @see DataHandler::checkValue_flex_procInData_travDS()
522
     * @see FlexFormTools::traverseFlexFormXMLData()
523
     */
524
    public function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath)
525
    {
526
        // Removing "data/" in the beginning of path (which points to location in data array)
527
        $structurePath = substr($structurePath, 5) . '/';
528
        $dsConf = $dsArr['TCEforms']['config'];
529
        // Implode parameter values:
530
        [$table, $uid, $field] = [
531
            $PA['table'],
532
            $PA['uid'],
533
            $PA['field']
534
        ];
535
        // Add a softref definition for link fields if the TCA does not specify one already
536
        if ($dsConf['type'] === 'input' && $dsConf['renderType'] === 'inputLink' && empty($dsConf['softref'])) {
537
            $dsConf['softref'] = 'typolink';
538
        }
539
        // Add DB:
540
        $resultsFromDatabase = $this->getRelations_procDB($dataValue, $dsConf, $uid, $table);
541
        if (!empty($resultsFromDatabase)) {
542
            // Create an entry for the field with all DB relations:
543
            $this->temp_flexRelations['db'][$structurePath] = $resultsFromDatabase;
544
        }
545
        // Soft References:
546
        if (is_array($dataValue) || (string)$dataValue !== '') {
547
            $softRefValue = $dataValue;
548
            $softRefs = BackendUtility::explodeSoftRefParserList($dsConf['softref']);
549
            if ($softRefs !== false) {
550
                foreach ($softRefs as $spKey => $spParams) {
551
                    $softRefObj = BackendUtility::softRefParserObj($spKey);
552
                    if (is_object($softRefObj)) {
553
                        $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
554
                        if (is_array($resultArray) && is_array($resultArray['elements'])) {
555
                            $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
556
                            if ((string)$resultArray['content'] !== '') {
557
                                $softRefValue = $resultArray['content'];
558
                            }
559
                        }
560
                    }
561
                }
562
            }
563
            if (!empty($this->temp_flexRelations['softrefs']) && (string)$dataValue !== (string)$softRefValue) {
564
                $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
565
            }
566
        }
567
    }
568
569
    /**
570
     * Check field configuration if it is a DB relation field and extract DB relations if any
571
     *
572
     * @param string $value Field value
573
     * @param array $conf Field configuration array of type "TCA/columns
574
     * @param int $uid Field uid
575
     * @param string $table Table name
576
     * @return array|bool If field type is OK it will return an array with the database relations. Else FALSE
577
     */
578
    protected function getRelations_procDB($value, $conf, $uid, $table = '')
579
    {
580
        // Get IRRE relations
581
        if (empty($conf)) {
582
            return false;
583
        }
584
        if ($conf['type'] === 'inline' && !empty($conf['foreign_table']) && empty($conf['MM'])) {
585
            $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
586
            $dbAnalysis->setUseLiveReferenceIds(false);
587
            $dbAnalysis->setWorkspaceId($this->getWorkspaceId());
588
            $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
589
            return $dbAnalysis->itemArray;
590
            // DB record lists:
591
        }
592
        if ($this->isDbReferenceField($conf)) {
593
            $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
594
            if ($conf['MM_opposite_field']) {
595
                return [];
596
            }
597
            $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
598
            $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
599
            return $dbAnalysis->itemArray;
600
        }
601
        return false;
602
    }
603
604
    /*******************************
605
     *
606
     * Setting values
607
     *
608
     *******************************/
609
610
    /**
611
     * Setting the value of a reference or removing it completely.
612
     * Usage: For lowlevel clean up operations!
613
     * WARNING: With this you can set values that are not allowed in the database since it will bypass all checks for validity!
614
     * Hence it is targeted at clean-up operations. Please use DataHandler in the usual ways if you wish to manipulate references.
615
     * Since this interface allows updates to soft reference values (which DataHandler does not directly) you may like to use it
616
     * for that as an exception to the warning above.
617
     * Notice; If you want to remove multiple references from the same field, you MUST start with the one having the highest
618
     * sorting number. If you don't the removal of a reference with a lower number will recreate an index in which the remaining
619
     * references in that field has new hash-keys due to new sorting numbers - and you will get errors for the remaining operations
620
     * which cannot find the hash you feed it!
621
     * To ensure proper working only admin-BE_USERS in live workspace should use this function
622
     *
623
     * @param string $hash 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
624
     * @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
625
     * @param bool $returnDataArray Return $dataArray only, do not submit it to database.
626
     * @param bool $bypassWorkspaceAdminCheck If set, it will bypass check for workspace-zero and admin user
627
     * @return string|bool|array FALSE (=OK), error message string or array (if $returnDataArray is set!)
628
     */
629
    public function setReferenceValue($hash, $newValue, $returnDataArray = false, $bypassWorkspaceAdminCheck = false)
630
    {
631
        $backendUser = $this->getBackendUser();
632
        if ($backendUser->workspace === 0 && $backendUser->isAdmin() || $bypassWorkspaceAdminCheck) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($backendUser->workspace...passWorkspaceAdminCheck, Probably Intended Meaning: $backendUser->workspace ...assWorkspaceAdminCheck)
Loading history...
633
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
634
            $queryBuilder->getRestrictions()->removeAll();
635
636
            // Get current index from Database
637
            $referenceRecord = $queryBuilder
638
                ->select('*')
639
                ->from('sys_refindex')
640
                ->where(
641
                    $queryBuilder->expr()->eq('hash', $queryBuilder->createNamedParameter($hash, \PDO::PARAM_STR))
642
                )
643
                ->setMaxResults(1)
644
                ->execute()
645
                ->fetch();
646
647
            // Check if reference existed.
648
            if (!is_array($referenceRecord)) {
649
                return 'ERROR: No reference record with hash="' . $hash . '" was found!';
650
            }
651
652
            if (empty($GLOBALS['TCA'][$referenceRecord['tablename']])) {
653
                return 'ERROR: Table "' . $referenceRecord['tablename'] . '" was not in TCA!';
654
            }
655
656
            // Get that record from database
657
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
658
                ->getQueryBuilderForTable($referenceRecord['tablename']);
659
            $queryBuilder->getRestrictions()->removeAll();
660
            $record = $queryBuilder
661
                ->select('*')
662
                ->from($referenceRecord['tablename'])
663
                ->where(
664
                    $queryBuilder->expr()->eq(
665
                        'uid',
666
                        $queryBuilder->createNamedParameter($referenceRecord['recuid'], \PDO::PARAM_INT)
667
                    )
668
                )
669
                ->setMaxResults(1)
670
                ->execute()
671
                ->fetch();
672
673
            if (is_array($record)) {
674
                // Get relation for single field from record
675
                $recordRelations = $this->getRelations($referenceRecord['tablename'], $record, $referenceRecord['field']);
676
                if ($fieldRelation = $recordRelations[$referenceRecord['field']]) {
677
                    // Initialize data array that is to be sent to DataHandler afterwards:
678
                    $dataArray = [];
679
                    // Based on type
680
                    switch ((string)$fieldRelation['type']) {
681
                        case 'db':
682
                            $error = $this->setReferenceValue_dbRels($referenceRecord, $fieldRelation['itemArray'], $newValue, $dataArray);
683
                            if ($error) {
684
                                return $error;
685
                            }
686
                            break;
687
                        case 'flex':
688
                            // DB references in FlexForms
689
                            if (is_array($fieldRelation['flexFormRels']['db'][$referenceRecord['flexpointer']])) {
690
                                $error = $this->setReferenceValue_dbRels($referenceRecord, $fieldRelation['flexFormRels']['db'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
691
                                if ($error) {
692
                                    return $error;
693
                                }
694
                            }
695
                            // Soft references in FlexForms
696
                            if ($referenceRecord['softref_key'] && is_array($fieldRelation['flexFormRels']['softrefs'][$referenceRecord['flexpointer']]['keys'][$referenceRecord['softref_key']])) {
697
                                $error = $this->setReferenceValue_softreferences($referenceRecord, $fieldRelation['flexFormRels']['softrefs'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
698
                                if ($error) {
699
                                    return $error;
700
                                }
701
                            }
702
                            break;
703
                    }
704
                    // Soft references in the field:
705
                    if ($referenceRecord['softref_key'] && is_array($fieldRelation['softrefs']['keys'][$referenceRecord['softref_key']])) {
706
                        $error = $this->setReferenceValue_softreferences($referenceRecord, $fieldRelation['softrefs'], $newValue, $dataArray);
707
                        if ($error) {
708
                            return $error;
709
                        }
710
                    }
711
                    // Data Array, now ready to be sent to DataHandler
712
                    if ($returnDataArray) {
713
                        return $dataArray;
714
                    }
715
                    // Execute CMD array:
716
                    $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
717
                    $dataHandler->dontProcessTransformations = true;
718
                    $dataHandler->bypassWorkspaceRestrictions = true;
719
                    // Otherwise this may lead to permission issues if user is not admin
720
                    $dataHandler->bypassAccessCheckForRecords = true;
721
                    // Check has been done previously that there is a backend user which is Admin and also in live workspace
722
                    $dataHandler->start($dataArray, []);
723
                    $dataHandler->process_datamap();
724
                    // Return errors if any:
725
                    if (!empty($dataHandler->errorLog)) {
726
                        return LF . 'DataHandler:' . implode(LF . 'DataHandler:', $dataHandler->errorLog);
727
                    }
728
                }
729
            }
730
        } else {
731
            return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
732
        }
733
734
        return false;
735
    }
736
737
    /**
738
     * Setting a value for a reference for a DB field:
739
     *
740
     * @param array $refRec sys_refindex record
741
     * @param array $itemArray Array of references from that field
742
     * @param string $newValue Value to substitute current value with (or NULL to unset it)
743
     * @param array $dataArray Data array in which the new value is set (passed by reference)
744
     * @param string $flexPointer Flexform pointer, if in a flex form field.
745
     * @return string Error message if any, otherwise FALSE = OK
746
     */
747
    protected function setReferenceValue_dbRels($refRec, $itemArray, $newValue, &$dataArray, $flexPointer = '')
748
    {
749
        if ((int)$itemArray[$refRec['sorting']]['id'] === (int)$refRec['ref_uid'] && (string)$itemArray[$refRec['sorting']]['table'] === (string)$refRec['ref_table']) {
750
            // Setting or removing value:
751
            // Remove value:
752
            if ($newValue === null) {
0 ignored issues
show
introduced by
The condition $newValue === null is always false.
Loading history...
753
                unset($itemArray[$refRec['sorting']]);
754
            } else {
755
                [$itemArray[$refRec['sorting']]['table'], $itemArray[$refRec['sorting']]['id']] = explode(':', $newValue);
756
            }
757
            // Traverse and compile new list of records:
758
            $saveValue = [];
759
            foreach ($itemArray as $pair) {
760
                $saveValue[] = $pair['table'] . '_' . $pair['id'];
761
            }
762
            // Set in data array:
763
            if ($flexPointer) {
764
                $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
765
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = [];
766
                $flexFormTools->setArrayValueByPath(substr($flexPointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
767
            } else {
768
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
769
            }
770
        } else {
771
            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'] . '"';
772
        }
773
774
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
775
    }
776
777
    /**
778
     * Setting a value for a soft reference token
779
     *
780
     * @param array $refRec sys_refindex record
781
     * @param array $softref Array of soft reference occurrences
782
     * @param string $newValue Value to substitute current value with
783
     * @param array $dataArray Data array in which the new value is set (passed by reference)
784
     * @param string $flexPointer Flexform pointer, if in a flex form field.
785
     * @return string Error message if any, otherwise FALSE = OK
786
     */
787
    protected function setReferenceValue_softreferences($refRec, $softref, $newValue, &$dataArray, $flexPointer = '')
788
    {
789
        if (!is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
790
            return 'ERROR: Soft reference parser key "' . $refRec['softref_key'] . '" or the index "' . $refRec['softref_id'] . '" was not found.';
791
        }
792
793
        // Set new value:
794
        $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = '' . $newValue;
795
        // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
796
        foreach ($softref['keys'] as $sfIndexes) {
797
            foreach ($sfIndexes as $data) {
798
                $softref['tokenizedContent'] = str_replace('{softref:' . $data['subst']['tokenID'] . '}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
799
            }
800
        }
801
        // Set in data array:
802
        if (strpos($softref['tokenizedContent'], '{softref:') === false) {
803
            if ($flexPointer) {
804
                $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
805
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = [];
806
                $flexFormTools->setArrayValueByPath(substr($flexPointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], $softref['tokenizedContent']);
807
            } else {
808
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
809
            }
810
        } else {
811
            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.)';
812
        }
813
814
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
815
    }
816
817
    /*******************************
818
     *
819
     * Helper functions
820
     *
821
     *******************************/
822
823
    /**
824
     * Returns TRUE if the TCA/columns field type is a DB reference field
825
     *
826
     * @param array $configuration Config array for TCA/columns field
827
     * @return bool TRUE if DB reference field (group/db or select with foreign-table)
828
     */
829
    protected function isDbReferenceField(array $configuration): bool
830
    {
831
        return
832
            ($configuration['type'] === 'group' && $configuration['internal_type'] === 'db')
833
            || (
834
                ($configuration['type'] === 'select' || $configuration['type'] === 'inline')
835
                && !empty($configuration['foreign_table'])
836
            )
837
            ;
838
    }
839
840
    /**
841
     * Returns TRUE if the TCA/columns field type is a reference field
842
     *
843
     * @param array $configuration Config array for TCA/columns field
844
     * @return bool TRUE if reference field
845
     */
846
    protected function isReferenceField(array $configuration): bool
847
    {
848
        return
849
            $this->isDbReferenceField($configuration)
850
            ||
851
            ($configuration['type'] === 'input' && $configuration['renderType'] === 'inputLink') // getRelations_procDB
852
            ||
853
            $configuration['type'] === 'flex'
854
            ||
855
            isset($configuration['softref'])
856
            ;
857
    }
858
859
    /**
860
     * Returns all fields of a table which could contain a relation
861
     *
862
     * @param string $tableName Name of the table
863
     * @return array Fields which may contain relations
864
     */
865
    protected function fetchTableRelationFields(string $tableName): array
866
    {
867
        if (!empty($this->tableRelationFieldCache[$tableName])) {
868
            return $this->tableRelationFieldCache[$tableName];
869
        }
870
        if (!isset($GLOBALS['TCA'][$tableName]['columns'])) {
871
            return [];
872
        }
873
        $fields = [];
874
        foreach ($GLOBALS['TCA'][$tableName]['columns'] as $field => $fieldDefinition) {
875
            if (is_array($fieldDefinition['config'])) {
876
                // Check for flex field
877
                if (isset($fieldDefinition['config']['type']) && $fieldDefinition['config']['type'] === 'flex') {
878
                    // Fetch all fields if the is a field of type flex in the table definition because the complete row is passed to
879
                    // FlexFormTools->getDataStructureIdentifier() in the end and might be needed in ds_pointerField or a hook
880
                    $this->tableRelationFieldCache[$tableName] = ['*'];
881
                    return ['*'];
882
                }
883
                // Only fetch this field if it can contain a reference
884
                if ($this->isReferenceField($fieldDefinition['config'])) {
885
                    $fields[] = $field;
886
                }
887
            }
888
        }
889
        $this->tableRelationFieldCache[$tableName] = $fields;
890
        return $fields;
891
    }
892
893
    /**
894
     * Updating Index (External API)
895
     *
896
     * @param bool $testOnly If set, only a test
897
     * @param ProgressListenerInterface|null $progressListener If set, the current progress is added to the listener
898
     * @return array Header and body status content
899
     */
900
    public function updateIndex($testOnly, ?ProgressListenerInterface $progressListener = null)
901
    {
902
        $errors = [];
903
        $tableNames = [];
904
        $recCount = 0;
905
        // Traverse all tables:
906
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
907
        $refIndexConnectionName = empty($GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping']['sys_refindex'])
908
                ? ConnectionPool::DEFAULT_CONNECTION_NAME
909
                : $GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping']['sys_refindex'];
910
911
        foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
912
            if ($this->shouldExcludeTableFromReferenceIndex($tableName)) {
913
                continue;
914
            }
915
            $tableConnectionName = empty($GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping'][$tableName])
916
                ? ConnectionPool::DEFAULT_CONNECTION_NAME
917
                : $GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping'][$tableName];
918
919
            $fields = ['uid'];
920
            if (BackendUtility::isTableWorkspaceEnabled($tableName)) {
921
                $fields[] = 't3ver_wsid';
922
            }
923
            // Traverse all records in tables, including deleted records
924
            $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
925
            $queryBuilder->getRestrictions()->removeAll();
926
            try {
927
                $queryResult = $queryBuilder
928
                    ->select(...$fields)
929
                    ->from($tableName)
930
                    ->execute();
931
            } catch (DBALException $e) {
932
                // Table exists in TCA but does not exist in the database
933
                $msg = 'Table "' .
934
                        $tableName .
935
                        '" exists in TCA but does not exist in the database. You should run the Database Analyzer in the Install Tool to fix this.';
936
                $this->logger->error($msg, ['exception' => $e]);
937
                continue;
938
            }
939
940
            if ($progressListener) {
941
                $progressListener->start($queryResult->rowCount(), $tableName);
942
            }
943
            $tableNames[] = $tableName;
944
            while ($record = $queryResult->fetch()) {
945
                if ($progressListener) {
946
                    $progressListener->advance();
947
                }
948
                /** @var ReferenceIndex $refIndexObj */
949
                $refIndexObj = GeneralUtility::makeInstance(self::class);
950
                if (isset($record['t3ver_wsid'])) {
951
                    $refIndexObj->setWorkspaceId($record['t3ver_wsid']);
952
                }
953
                $result = $refIndexObj->updateRefIndexTable($tableName, $record['uid'], $testOnly);
954
                $recCount++;
955
                if ($result['addedNodes'] || $result['deletedNodes']) {
956
                    $error = 'Record ' . $tableName . ':' . $record['uid'] . ' had ' . $result['addedNodes'] . ' added indexes and ' . $result['deletedNodes'] . ' deleted indexes';
957
                    $errors[] = $error;
958
                    if ($progressListener) {
959
                        $progressListener->log($error, LogLevel::WARNING);
960
                    }
961
                }
962
            }
963
            if ($progressListener) {
964
                $progressListener->finish();
965
            }
966
967
            // Subselect based queries only work on the same connection
968
            if ($refIndexConnectionName !== $tableConnectionName) {
969
                $this->logger->error('Not checking table "' . $tableName . '" for lost indexes, "sys_refindex" table uses a different connection');
970
                continue;
971
            }
972
973
            // Searching for lost indexes for this table
974
            // Build sub-query to find lost records
975
            $subQueryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
976
            $subQueryBuilder->getRestrictions()->removeAll();
977
            $subQueryBuilder
978
                ->select('uid')
979
                ->from($tableName, 'sub_' . $tableName)
980
                ->where(
981
                    $subQueryBuilder->expr()->eq(
982
                        'sub_' . $tableName . '.uid',
983
                        $queryBuilder->quoteIdentifier('sys_refindex.recuid')
984
                    )
985
                );
986
987
            // Main query to find lost records
988
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
989
            $queryBuilder->getRestrictions()->removeAll();
990
            $lostIndexes = $queryBuilder
991
                ->count('hash')
992
                ->from('sys_refindex')
993
                ->where(
994
                    $queryBuilder->expr()->eq(
995
                        'tablename',
996
                        $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
997
                    ),
998
                    'NOT EXISTS (' . $subQueryBuilder->getSQL() . ')'
999
                )
1000
                ->execute()
1001
                ->fetchColumn(0);
1002
1003
            if ($lostIndexes > 0) {
1004
                $error = 'Table ' . $tableName . ' has ' . $lostIndexes . ' lost indexes which are now deleted';
1005
                $errors[] = $error;
1006
                if ($progressListener) {
1007
                    $progressListener->log($error, LogLevel::WARNING);
1008
                }
1009
                if (!$testOnly) {
1010
                    $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
1011
                    $queryBuilder->delete('sys_refindex')
1012
                        ->where(
1013
                            $queryBuilder->expr()->eq(
1014
                                'tablename',
1015
                                $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
1016
                            ),
1017
                            'NOT EXISTS (' . $subQueryBuilder->getSQL() . ')'
1018
                        )
1019
                        ->execute();
1020
                }
1021
            }
1022
        }
1023
1024
        // Searching lost indexes for non-existing tables
1025
        $lostTables = $this->getAmountOfUnusedTablesInReferenceIndex($tableNames);
1026
        if ($lostTables > 0) {
1027
            $error = 'Index table hosted ' . $lostTables . ' indexes for non-existing tables, now removed';
1028
            $errors[] = $error;
1029
            if ($progressListener) {
1030
                $progressListener->log($error, LogLevel::WARNING);
1031
            }
1032
            if (!$testOnly) {
1033
                $this->removeReferenceIndexDataFromUnusedDatabaseTables($tableNames);
1034
            }
1035
        }
1036
        $errorCount = count($errors);
1037
        $recordsCheckedString = $recCount . ' records from ' . count($tableNames) . ' tables were checked/updated.';
1038
        if ($progressListener) {
1039
            if ($errorCount) {
1040
                $progressListener->log($recordsCheckedString . 'Updates: ' . $errorCount, LogLevel::WARNING);
1041
            } else {
1042
                $progressListener->log($recordsCheckedString . 'Index Integrity was perfect!', LogLevel::INFO);
1043
            }
1044
        }
1045
        if (!$testOnly) {
1046
            $registry = GeneralUtility::makeInstance(Registry::class);
1047
            $registry->set('core', 'sys_refindex_lastUpdate', $GLOBALS['EXEC_TIME']);
1048
        }
1049
        return ['resultText' => trim($recordsCheckedString), 'errors' => $errors];
1050
    }
1051
1052
    protected function getAmountOfUnusedTablesInReferenceIndex(array $tableNames): int
1053
    {
1054
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1055
        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
1056
        $queryBuilder->getRestrictions()->removeAll();
1057
        $lostTables = $queryBuilder
1058
            ->count('hash')
1059
            ->from('sys_refindex')
1060
            ->where(
1061
                $queryBuilder->expr()->notIn(
1062
                    'tablename',
1063
                    $queryBuilder->createNamedParameter($tableNames, Connection::PARAM_STR_ARRAY)
1064
                )
1065
            )->execute()
1066
            ->fetchColumn(0);
1067
        return (int)$lostTables;
1068
    }
1069
1070
    protected function removeReferenceIndexDataFromUnusedDatabaseTables(array $tableNames): void
1071
    {
1072
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1073
        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
1074
        $queryBuilder->delete('sys_refindex')
1075
            ->where(
1076
                $queryBuilder->expr()->notIn(
1077
                    'tablename',
1078
                    $queryBuilder->createNamedParameter($tableNames, Connection::PARAM_STR_ARRAY)
1079
                )
1080
            )->execute();
1081
    }
1082
1083
    /**
1084
     * Get one record from database.
1085
     *
1086
     * @param string $tableName
1087
     * @param int $uid
1088
     * @return array|false
1089
     */
1090
    protected function getRecord(string $tableName, int $uid)
1091
    {
1092
        // Fetch fields of the table which might contain relations
1093
        $tableRelationFields = $this->fetchTableRelationFields($tableName);
1094
1095
        if ($tableRelationFields === []) {
1096
            // Return if there are no fields which could contain relations
1097
            return $this->relations;
1098
        }
1099
        if ($tableRelationFields !== ['*']) {
1100
            // Only fields that might contain relations are fetched
1101
            $tableRelationFields[] = 'uid';
1102
            if (BackendUtility::isTableWorkspaceEnabled($tableName)) {
1103
                $tableRelationFields = array_merge($tableRelationFields, ['t3ver_wsid', 't3ver_state']);
1104
            }
1105
        }
1106
1107
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1108
            ->getQueryBuilderForTable($tableName);
1109
        $queryBuilder->getRestrictions()->removeAll();
1110
        $queryBuilder
1111
            ->select(...array_unique($tableRelationFields))
1112
            ->from($tableName)
1113
            ->where(
1114
                $queryBuilder->expr()->eq(
1115
                    'uid',
1116
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1117
                )
1118
            );
1119
        // Do not fetch soft deleted records
1120
        $deleteField = (string)($GLOBALS['TCA'][$tableName]['ctrl']['delete'] ?? '');
1121
        if ($deleteField !== '') {
1122
            $queryBuilder->andWhere(
1123
                $queryBuilder->expr()->eq(
1124
                    $deleteField,
1125
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
1126
                )
1127
            );
1128
        }
1129
        return $queryBuilder->execute()->fetch();
1130
    }
1131
1132
    /**
1133
     * Checks if a given table should be excluded from ReferenceIndex
1134
     *
1135
     * @param string $tableName Name of the table
1136
     * @return bool true if it should be excluded
1137
     */
1138
    protected function shouldExcludeTableFromReferenceIndex(string $tableName): bool
1139
    {
1140
        if (isset($this->excludedTables[$tableName])) {
1141
            return $this->excludedTables[$tableName];
1142
        }
1143
        // Only exclude tables from ReferenceIndex which do not contain any relations and never
1144
        // did since existing references won't be deleted!
1145
        $event = new IsTableExcludedFromReferenceIndexEvent($tableName);
1146
        $event = $this->eventDispatcher->dispatch($event);
1147
        $this->excludedTables[$tableName] = $event->isTableExcluded();
1148
        return $this->excludedTables[$tableName];
1149
    }
1150
1151
    /**
1152
     * Checks if a given column in a given table should be excluded in the ReferenceIndex process
1153
     *
1154
     * @param string $tableName Name of the table
1155
     * @param string $column Name of the column
1156
     * @param string $onlyColumn Name of a specific column to fetch
1157
     * @return bool true if it should be excluded
1158
     */
1159
    protected function shouldExcludeTableColumnFromReferenceIndex(
1160
        string $tableName,
1161
        string $column,
1162
        string $onlyColumn
1163
    ): bool {
1164
        if (isset($this->excludedColumns[$column])) {
1165
            return true;
1166
        }
1167
        if (is_array($GLOBALS['TCA'][$tableName]['columns'][$column]) && (!$onlyColumn || $onlyColumn === $column)) {
1168
            return false;
1169
        }
1170
        return true;
1171
    }
1172
1173
    /**
1174
     * Enables the runtime-based caches
1175
     * Could lead to side effects, depending if the reference index instance is run multiple times
1176
     * while records would be changed.
1177
     *
1178
     * @deprecated since v11, will be removed in v12.
1179
     */
1180
    public function enableRuntimeCache()
1181
    {
1182
        trigger_error('Calling ReferenceIndex->enableRuntimeCache() is obsolete and should be dropped.', E_USER_DEPRECATED);
1183
    }
1184
1185
    /**
1186
     * Disables the runtime-based cache
1187
     *
1188
     * @deprecated since v11, will be removed in v12.
1189
     */
1190
    public function disableRuntimeCache()
1191
    {
1192
        trigger_error('Calling ReferenceIndex->disableRuntimeCache() is obsolete and should be dropped.', E_USER_DEPRECATED);
1193
    }
1194
1195
    /**
1196
     * Returns the current BE user.
1197
     *
1198
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1199
     */
1200
    protected function getBackendUser()
1201
    {
1202
        return $GLOBALS['BE_USER'];
1203
    }
1204
}
1205