Passed
Push — master ( 1e85f0...74899e )
by
unknown
14:10
created

ReferenceIndex::getRelations()   D

Complexity

Conditions 18
Paths 62

Size

Total Lines 68
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
eloc 38
nc 62
nop 3
dl 0
loc 68
rs 4.8666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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