Passed
Push — master ( 2b6b2d...30755c )
by
unknown
14:27
created

ReferenceIndex::createEntryData()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 4
nop 11
dl 0
loc 18
rs 8.8333
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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