Completed
Push — master ( 628f95...c852f1 )
by
unknown
16:56
created

ReferenceIndex::getRecordRawCached()   B

Complexity

Conditions 10
Paths 36

Size

Total Lines 53
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 33
nc 36
nop 2
dl 0
loc 53
rs 7.6666
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
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 and t3ver_state = 3 placeholder records
388
            $versionState = VersionState::cast($record['t3ver_state']);
389
            if ($versionState->equals(VersionState::NEW_PLACEHOLDER) || $versionState->equals(VersionState::MOVE_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),
0 ignored issues
show
Bug introduced by
It seems like $this->getRecordRawCached($table, $uid) can also be of type false; however, parameter $record of TYPO3\CMS\Core\Database\...eEntryDataUsingRecord() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

457
            /** @scrutinizer ignore-type */ $this->getRecordRawCached($table, $uid),
Loading history...
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),
0 ignored issues
show
Bug introduced by
It seems like $this->getRecordRawCached($table, $uid) can also be of type false; however, parameter $record of TYPO3\CMS\Core\Database\...eRelationsUsingRecord() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

530
            /** @scrutinizer ignore-type */ $this->getRecordRawCached($table, $uid),
Loading history...
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),
0 ignored issues
show
Bug introduced by
It seems like $this->getRecordRawCached($table, $uid) can also be of type false; however, parameter $record of TYPO3\CMS\Core\Database\...ReferencesUsingRecord() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

573
            /** @scrutinizer ignore-type */ $this->getRecordRawCached($table, $uid),
Loading history...
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->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
773
            return $dbAnalysis->itemArray;
774
            // DB record lists:
775
        }
776
        if ($this->isDbReferenceField($conf)) {
777
            $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
778
            if ($conf['MM_opposite_field']) {
779
                return [];
780
            }
781
            $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
782
            $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
783
            return $dbAnalysis->itemArray;
784
        }
785
        return false;
786
    }
787
788
    /*******************************
789
     *
790
     * Setting values
791
     *
792
     *******************************/
793
794
    /**
795
     * Setting the value of a reference or removing it completely.
796
     * Usage: For lowlevel clean up operations!
797
     * WARNING: With this you can set values that are not allowed in the database since it will bypass all checks for validity!
798
     * Hence it is targeted at clean-up operations. Please use DataHandler in the usual ways if you wish to manipulate references.
799
     * Since this interface allows updates to soft reference values (which DataHandler does not directly) you may like to use it
800
     * for that as an exception to the warning above.
801
     * Notice; If you want to remove multiple references from the same field, you MUST start with the one having the highest
802
     * sorting number. If you don't the removal of a reference with a lower number will recreate an index in which the remaining
803
     * references in that field has new hash-keys due to new sorting numbers - and you will get errors for the remaining operations
804
     * which cannot find the hash you feed it!
805
     * To ensure proper working only admin-BE_USERS in live workspace should use this function
806
     *
807
     * @param string $hash 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
808
     * @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
809
     * @param bool $returnDataArray Return $dataArray only, do not submit it to database.
810
     * @param bool $bypassWorkspaceAdminCheck If set, it will bypass check for workspace-zero and admin user
811
     * @return string|bool|array FALSE (=OK), error message string or array (if $returnDataArray is set!)
812
     */
813
    public function setReferenceValue($hash, $newValue, $returnDataArray = false, $bypassWorkspaceAdminCheck = false)
814
    {
815
        $backendUser = $this->getBackendUser();
816
        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...
817
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
818
            $queryBuilder->getRestrictions()->removeAll();
819
820
            // Get current index from Database
821
            $referenceRecord = $queryBuilder
822
                ->select('*')
823
                ->from('sys_refindex')
824
                ->where(
825
                    $queryBuilder->expr()->eq('hash', $queryBuilder->createNamedParameter($hash, \PDO::PARAM_STR))
826
                )
827
                ->setMaxResults(1)
828
                ->execute()
829
                ->fetch();
830
831
            // Check if reference existed.
832
            if (!is_array($referenceRecord)) {
833
                return 'ERROR: No reference record with hash="' . $hash . '" was found!';
834
            }
835
836
            if (empty($GLOBALS['TCA'][$referenceRecord['tablename']])) {
837
                return 'ERROR: Table "' . $referenceRecord['tablename'] . '" was not in TCA!';
838
            }
839
840
            // Get that record from database
841
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
842
                ->getQueryBuilderForTable($referenceRecord['tablename']);
843
            $queryBuilder->getRestrictions()->removeAll();
844
            $record = $queryBuilder
845
                ->select('*')
846
                ->from($referenceRecord['tablename'])
847
                ->where(
848
                    $queryBuilder->expr()->eq(
849
                        'uid',
850
                        $queryBuilder->createNamedParameter($referenceRecord['recuid'], \PDO::PARAM_INT)
851
                    )
852
                )
853
                ->setMaxResults(1)
854
                ->execute()
855
                ->fetch();
856
857
            if (is_array($record)) {
858
                // Get relation for single field from record
859
                $recordRelations = $this->getRelations($referenceRecord['tablename'], $record, $referenceRecord['field']);
860
                if ($fieldRelation = $recordRelations[$referenceRecord['field']]) {
861
                    // Initialize data array that is to be sent to DataHandler afterwards:
862
                    $dataArray = [];
863
                    // Based on type
864
                    switch ((string)$fieldRelation['type']) {
865
                        case 'db':
866
                            $error = $this->setReferenceValue_dbRels($referenceRecord, $fieldRelation['itemArray'], $newValue, $dataArray);
867
                            if ($error) {
868
                                return $error;
869
                            }
870
                            break;
871
                        case 'flex':
872
                            // DB references in FlexForms
873
                            if (is_array($fieldRelation['flexFormRels']['db'][$referenceRecord['flexpointer']])) {
874
                                $error = $this->setReferenceValue_dbRels($referenceRecord, $fieldRelation['flexFormRels']['db'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
875
                                if ($error) {
876
                                    return $error;
877
                                }
878
                            }
879
                            // Soft references in FlexForms
880
                            if ($referenceRecord['softref_key'] && is_array($fieldRelation['flexFormRels']['softrefs'][$referenceRecord['flexpointer']]['keys'][$referenceRecord['softref_key']])) {
881
                                $error = $this->setReferenceValue_softreferences($referenceRecord, $fieldRelation['flexFormRels']['softrefs'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
882
                                if ($error) {
883
                                    return $error;
884
                                }
885
                            }
886
                            break;
887
                    }
888
                    // Soft references in the field:
889
                    if ($referenceRecord['softref_key'] && is_array($fieldRelation['softrefs']['keys'][$referenceRecord['softref_key']])) {
890
                        $error = $this->setReferenceValue_softreferences($referenceRecord, $fieldRelation['softrefs'], $newValue, $dataArray);
891
                        if ($error) {
892
                            return $error;
893
                        }
894
                    }
895
                    // Data Array, now ready to be sent to DataHandler
896
                    if ($returnDataArray) {
897
                        return $dataArray;
898
                    }
899
                    // Execute CMD array:
900
                    $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
901
                    $dataHandler->dontProcessTransformations = true;
902
                    $dataHandler->bypassWorkspaceRestrictions = true;
903
                    // Otherwise this cannot update things in deleted records...
904
                    $dataHandler->bypassAccessCheckForRecords = true;
905
                    // Check has been done previously that there is a backend user which is Admin and also in live workspace
906
                    $dataHandler->start($dataArray, []);
907
                    $dataHandler->process_datamap();
908
                    // Return errors if any:
909
                    if (!empty($dataHandler->errorLog)) {
910
                        return LF . 'DataHandler:' . implode(LF . 'DataHandler:', $dataHandler->errorLog);
911
                    }
912
                }
913
            }
914
        } else {
915
            return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
916
        }
917
918
        return false;
919
    }
920
921
    /**
922
     * Setting a value for a reference for a DB field:
923
     *
924
     * @param array $refRec sys_refindex record
925
     * @param array $itemArray Array of references from that field
926
     * @param string $newValue Value to substitute current value with (or NULL to unset it)
927
     * @param array $dataArray Data array in which the new value is set (passed by reference)
928
     * @param string $flexPointer Flexform pointer, if in a flex form field.
929
     * @return string Error message if any, otherwise FALSE = OK
930
     */
931
    public function setReferenceValue_dbRels($refRec, $itemArray, $newValue, &$dataArray, $flexPointer = '')
932
    {
933
        if ((int)$itemArray[$refRec['sorting']]['id'] === (int)$refRec['ref_uid'] && (string)$itemArray[$refRec['sorting']]['table'] === (string)$refRec['ref_table']) {
934
            // Setting or removing value:
935
            // Remove value:
936
            if ($newValue === null) {
0 ignored issues
show
introduced by
The condition $newValue === null is always false.
Loading history...
937
                unset($itemArray[$refRec['sorting']]);
938
            } else {
939
                [$itemArray[$refRec['sorting']]['table'], $itemArray[$refRec['sorting']]['id']] = explode(':', $newValue);
940
            }
941
            // Traverse and compile new list of records:
942
            $saveValue = [];
943
            foreach ($itemArray as $pair) {
944
                $saveValue[] = $pair['table'] . '_' . $pair['id'];
945
            }
946
            // Set in data array:
947
            if ($flexPointer) {
948
                $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
949
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = [];
950
                $flexFormTools->setArrayValueByPath(substr($flexPointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
951
            } else {
952
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
953
            }
954
        } else {
955
            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'] . '"';
956
        }
957
958
        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...
959
    }
960
961
    /**
962
     * Setting a value for a soft reference token
963
     *
964
     * @param array $refRec sys_refindex record
965
     * @param array $softref Array of soft reference occurrences
966
     * @param string $newValue Value to substitute current value with
967
     * @param array $dataArray Data array in which the new value is set (passed by reference)
968
     * @param string $flexPointer Flexform pointer, if in a flex form field.
969
     * @return string Error message if any, otherwise FALSE = OK
970
     */
971
    public function setReferenceValue_softreferences($refRec, $softref, $newValue, &$dataArray, $flexPointer = '')
972
    {
973
        if (!is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
974
            return 'ERROR: Soft reference parser key "' . $refRec['softref_key'] . '" or the index "' . $refRec['softref_id'] . '" was not found.';
975
        }
976
977
        // Set new value:
978
        $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = '' . $newValue;
979
        // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
980
        foreach ($softref['keys'] as $sfIndexes) {
981
            foreach ($sfIndexes as $data) {
982
                $softref['tokenizedContent'] = str_replace('{softref:' . $data['subst']['tokenID'] . '}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
983
            }
984
        }
985
        // Set in data array:
986
        if (strpos($softref['tokenizedContent'], '{softref:') === false) {
987
            if ($flexPointer) {
988
                $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
989
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = [];
990
                $flexFormTools->setArrayValueByPath(substr($flexPointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], $softref['tokenizedContent']);
991
            } else {
992
                $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
993
            }
994
        } else {
995
            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.)';
996
        }
997
998
        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...
999
    }
1000
1001
    /*******************************
1002
     *
1003
     * Helper functions
1004
     *
1005
     *******************************/
1006
1007
    /**
1008
     * Returns TRUE if the TCA/columns field type is a DB reference field
1009
     *
1010
     * @param array $configuration Config array for TCA/columns field
1011
     * @return bool TRUE if DB reference field (group/db or select with foreign-table)
1012
     */
1013
    protected function isDbReferenceField(array $configuration)
1014
    {
1015
        return
1016
            ($configuration['type'] === 'group' && $configuration['internal_type'] === 'db')
1017
            || (
1018
                ($configuration['type'] === 'select' || $configuration['type'] === 'inline')
1019
                && !empty($configuration['foreign_table'])
1020
            )
1021
            ;
1022
    }
1023
1024
    /**
1025
     * Returns TRUE if the TCA/columns field type is a reference field
1026
     *
1027
     * @param array $configuration Config array for TCA/columns field
1028
     * @return bool TRUE if reference field
1029
     */
1030
    public function isReferenceField(array $configuration)
1031
    {
1032
        return
1033
            $this->isDbReferenceField($configuration)
1034
            ||
1035
            ($configuration['type'] === 'input' && $configuration['renderType'] === 'inputLink') // getRelations_procDB
1036
            ||
1037
            $configuration['type'] === 'flex'
1038
            ||
1039
            isset($configuration['softref'])
1040
            ;
1041
    }
1042
1043
    /**
1044
     * Returns all fields of a table which could contain a relation
1045
     *
1046
     * @param string $tableName Name of the table
1047
     * @return string Fields which could contain a relation
1048
     */
1049
    protected function fetchTableRelationFields($tableName)
1050
    {
1051
        if (!isset($GLOBALS['TCA'][$tableName]['columns'])) {
1052
            return '';
1053
        }
1054
1055
        $fields = [];
1056
1057
        foreach ($GLOBALS['TCA'][$tableName]['columns'] as $field => $fieldDefinition) {
1058
            if (is_array($fieldDefinition['config'])) {
1059
                // Check for flex field
1060
                if (isset($fieldDefinition['config']['type']) && $fieldDefinition['config']['type'] === 'flex') {
1061
                    // Fetch all fields if the is a field of type flex in the table definition because the complete row is passed to
1062
                    // FlexFormTools->getDataStructureIdentifier() in the end and might be needed in ds_pointerField or a hook
1063
                    return '*';
1064
                }
1065
                // Only fetch this field if it can contain a reference
1066
                if ($this->isReferenceField($fieldDefinition['config'])) {
1067
                    $fields[] = $field;
1068
                }
1069
            }
1070
        }
1071
1072
        return implode(',', $fields);
1073
    }
1074
1075
    /**
1076
     * Updating Index (External API)
1077
     *
1078
     * @param bool $testOnly If set, only a test
1079
     * @param ProgressListenerInterface|null $progressListener If set, the current progress is added to the listener
1080
     * @return array Header and body status content
1081
     */
1082
    public function updateIndex($testOnly, ?ProgressListenerInterface $progressListener = null)
1083
    {
1084
        $errors = [];
1085
        $tableNames = [];
1086
        $recCount = 0;
1087
        // Traverse all tables:
1088
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1089
        $refIndexConnectionName = empty($GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping']['sys_refindex'])
1090
                ? ConnectionPool::DEFAULT_CONNECTION_NAME
1091
                : $GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping']['sys_refindex'];
1092
1093
        foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
1094
            if ($this->shouldExcludeTableFromReferenceIndex($tableName)) {
1095
                continue;
1096
            }
1097
            $tableConnectionName = empty($GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping'][$tableName])
1098
                ? ConnectionPool::DEFAULT_CONNECTION_NAME
1099
                : $GLOBALS['TYPO3_CONF_VARS']['DB']['TableMapping'][$tableName];
1100
1101
            $fields = ['uid'];
1102
            if (BackendUtility::isTableWorkspaceEnabled($tableName)) {
1103
                $fields[] = 't3ver_wsid';
1104
            }
1105
            // Traverse all records in tables, including deleted records
1106
            $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
1107
            $queryBuilder->getRestrictions()->removeAll();
1108
            try {
1109
                $queryResult = $queryBuilder
1110
                    ->select(...$fields)
1111
                    ->from($tableName)
1112
                    ->execute();
1113
            } catch (DBALException $e) {
1114
                // Table exists in TCA but does not exist in the database
1115
                $msg = 'Table "' .
1116
                        $tableName .
1117
                        '" exists in TCA but does not exist in the database. You should run the Database Analyzer in the Install Tool to fix this.';
1118
                $this->logger->error($msg, ['exception' => $e]);
1119
                continue;
1120
            }
1121
1122
            if ($progressListener) {
1123
                $progressListener->start($queryResult->rowCount(), $tableName);
1124
            }
1125
            $tableNames[] = $tableName;
1126
            while ($record = $queryResult->fetch()) {
1127
                if ($progressListener) {
1128
                    $progressListener->advance();
1129
                }
1130
                $refIndexObj = GeneralUtility::makeInstance(self::class);
1131
                if (isset($record['t3ver_wsid'])) {
1132
                    $refIndexObj->setWorkspaceId($record['t3ver_wsid']);
1133
                }
1134
                $result = $refIndexObj->updateRefIndexTable($tableName, $record['uid'], $testOnly);
1135
                $recCount++;
1136
                if ($result['addedNodes'] || $result['deletedNodes']) {
1137
                    $error = 'Record ' . $tableName . ':' . $record['uid'] . ' had ' . $result['addedNodes'] . ' added indexes and ' . $result['deletedNodes'] . ' deleted indexes';
1138
                    $errors[] = $error;
1139
                    if ($progressListener) {
1140
                        $progressListener->log($error, LogLevel::WARNING);
1141
                    }
1142
                }
1143
            }
1144
            if ($progressListener) {
1145
                $progressListener->finish();
1146
            }
1147
1148
            // Subselect based queries only work on the same connection
1149
            if ($refIndexConnectionName !== $tableConnectionName) {
1150
                $this->logger->error('Not checking table "' . $tableName . '" for lost indexes, "sys_refindex" table uses a different connection');
1151
                continue;
1152
            }
1153
1154
            // Searching for lost indexes for this table
1155
            // Build sub-query to find lost records
1156
            $subQueryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
1157
            $subQueryBuilder->getRestrictions()->removeAll();
1158
            $subQueryBuilder
1159
                ->select('uid')
1160
                ->from($tableName, 'sub_' . $tableName)
1161
                ->where(
1162
                    $subQueryBuilder->expr()->eq(
1163
                        'sub_' . $tableName . '.uid',
1164
                        $queryBuilder->quoteIdentifier('sys_refindex.recuid')
1165
                    )
1166
                );
1167
1168
            // Main query to find lost records
1169
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
1170
            $queryBuilder->getRestrictions()->removeAll();
1171
            $lostIndexes = $queryBuilder
1172
                ->count('hash')
1173
                ->from('sys_refindex')
1174
                ->where(
1175
                    $queryBuilder->expr()->eq(
1176
                        'tablename',
1177
                        $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
1178
                    ),
1179
                    'NOT EXISTS (' . $subQueryBuilder->getSQL() . ')'
1180
                )
1181
                ->execute()
1182
                ->fetchColumn(0);
1183
1184
            if ($lostIndexes > 0) {
1185
                $error = 'Table ' . $tableName . ' has ' . $lostIndexes . ' lost indexes which are now deleted';
1186
                $errors[] = $error;
1187
                if ($progressListener) {
1188
                    $progressListener->log($error, LogLevel::WARNING);
1189
                }
1190
                if (!$testOnly) {
1191
                    $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
1192
                    $queryBuilder->delete('sys_refindex')
1193
                        ->where(
1194
                            $queryBuilder->expr()->eq(
1195
                                'tablename',
1196
                                $queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
1197
                            ),
1198
                            'NOT EXISTS (' . $subQueryBuilder->getSQL() . ')'
1199
                        )
1200
                        ->execute();
1201
                }
1202
            }
1203
        }
1204
1205
        // Searching lost indexes for non-existing tables
1206
        $lostTables = $this->getAmountOfUnusedTablesInReferenceIndex($tableNames);
1207
        if ($lostTables > 0) {
1208
            $error = 'Index table hosted ' . $lostTables . ' indexes for non-existing tables, now removed';
1209
            $errors[] = $error;
1210
            if ($progressListener) {
1211
                $progressListener->log($error, LogLevel::WARNING);
1212
            }
1213
            if (!$testOnly) {
1214
                $this->removeReferenceIndexDataFromUnusedDatabaseTables($tableNames);
1215
            }
1216
        }
1217
        $errorCount = count($errors);
1218
        $recordsCheckedString = $recCount . ' records from ' . count($tableNames) . ' tables were checked/updated.';
1219
        if ($progressListener) {
1220
            if ($errorCount) {
1221
                $progressListener->log($recordsCheckedString . 'Updates: ' . $errorCount, LogLevel::WARNING);
1222
            } else {
1223
                $progressListener->log($recordsCheckedString . 'Index Integrity was perfect!', LogLevel::INFO);
1224
            }
1225
        }
1226
        if (!$testOnly) {
1227
            $registry = GeneralUtility::makeInstance(Registry::class);
1228
            $registry->set('core', 'sys_refindex_lastUpdate', $GLOBALS['EXEC_TIME']);
1229
        }
1230
        return ['resultText' => trim($recordsCheckedString), 'errors' => $errors];
1231
    }
1232
1233
    protected function getAmountOfUnusedTablesInReferenceIndex(array $tableNames): int
1234
    {
1235
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1236
        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
1237
        $queryBuilder->getRestrictions()->removeAll();
1238
        $lostTables = $queryBuilder
1239
            ->count('hash')
1240
            ->from('sys_refindex')
1241
            ->where(
1242
                $queryBuilder->expr()->notIn(
1243
                    'tablename',
1244
                    $queryBuilder->createNamedParameter($tableNames, Connection::PARAM_STR_ARRAY)
1245
                )
1246
            )->execute()
1247
            ->fetchColumn(0);
1248
        return (int)$lostTables;
1249
    }
1250
1251
    protected function removeReferenceIndexDataFromUnusedDatabaseTables(array $tableNames): void
1252
    {
1253
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1254
        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_refindex');
1255
        $queryBuilder->delete('sys_refindex')
1256
            ->where(
1257
                $queryBuilder->expr()->notIn(
1258
                    'tablename',
1259
                    $queryBuilder->createNamedParameter($tableNames, Connection::PARAM_STR_ARRAY)
1260
                )
1261
            )->execute();
1262
    }
1263
1264
    /**
1265
     * Gets one record from database and stores it in an internal cache (which expires along with object lifecycle) for faster retrieval
1266
     *
1267
     * Assumption:
1268
     *
1269
     * - This method is only used from within delegate methods and so only caches queries generated based on the record being indexed; the query
1270
     *   to select origin side record is uncached
1271
     * - Origin side records do not change in database while updating the reference index
1272
     * - Origin record does not get removed while updating index
1273
     * - Relations may change during indexing, which is why only the origin record is cached and all relations are re-process even when repeating
1274
     *   indexing of the same origin record
1275
     *
1276
     * Please note that the cache is disabled by default but can be enabled using $this->enableRuntimeCaches()
1277
     * due to possible side-effects while handling references that were changed during one single
1278
     * request.
1279
     *
1280
     * @param string $tableName
1281
     * @param int $uid
1282
     * @return array|false
1283
     */
1284
    protected function getRecordRawCached(string $tableName, int $uid)
1285
    {
1286
        $recordCacheId = $tableName . ':' . $uid;
1287
        if (!$this->useRuntimeCache || !isset($this->recordCache[$recordCacheId])) {
1288
1289
            // Fetch fields of the table which might contain relations
1290
            $cacheId = static::$cachePrefixTableRelationFields . $tableName;
1291
            $tableRelationFields = $this->useRuntimeCache ? $this->runtimeCache->get($cacheId) : false;
1292
            if ($tableRelationFields === false) {
1293
                $tableRelationFields = $this->fetchTableRelationFields($tableName);
1294
                if ($this->useRuntimeCache) {
1295
                    $this->runtimeCache->set($cacheId, $tableRelationFields);
1296
                }
1297
            }
1298
1299
            // Return if there are no fields which could contain relations
1300
            if ($tableRelationFields === '') {
1301
                return $this->relations;
1302
            }
1303
1304
            if ($tableRelationFields === '*') {
1305
                // If one field of a record is of type flex, all fields have to be fetched to be passed to FlexFormTools->getDataStructureIdentifier()
1306
                $selectFields = '*';
1307
            } else {
1308
                // otherwise only fields that might contain relations are fetched
1309
                $selectFields = 'uid,' . $tableRelationFields;
1310
                $deleteField = $GLOBALS['TCA'][$tableName]['ctrl']['delete'];
1311
                if ($deleteField) {
1312
                    $selectFields .= ',' . $deleteField;
1313
                }
1314
                if (BackendUtility::isTableWorkspaceEnabled($tableName)) {
1315
                    $selectFields .= ',t3ver_wsid,t3ver_state';
1316
                }
1317
            }
1318
1319
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1320
                ->getQueryBuilderForTable($tableName);
1321
            $queryBuilder->getRestrictions()->removeAll();
1322
            $row = $queryBuilder
1323
                ->select(...GeneralUtility::trimExplode(',', $selectFields, true))
1324
                ->from($tableName)
1325
                ->where(
1326
                    $queryBuilder->expr()->eq(
1327
                        'uid',
1328
                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1329
                    )
1330
                )
1331
                ->execute()
1332
                ->fetch();
1333
1334
            $this->recordCache[$recordCacheId] = $row;
1335
        }
1336
        return $this->recordCache[$recordCacheId];
1337
    }
1338
1339
    /**
1340
     * Checks if a given table should be excluded from ReferenceIndex
1341
     *
1342
     * @param string $tableName Name of the table
1343
     * @return bool true if it should be excluded
1344
     */
1345
    protected function shouldExcludeTableFromReferenceIndex($tableName)
1346
    {
1347
        if (isset(static::$excludedTables[$tableName])) {
1348
            return static::$excludedTables[$tableName];
1349
        }
1350
1351
        // Only exclude tables from ReferenceIndex which do not contain any relations and never
1352
        // did since existing references won't be deleted!
1353
        $event = new IsTableExcludedFromReferenceIndexEvent($tableName);
1354
        $event = $this->eventDispatcher->dispatch($event);
1355
        static::$excludedTables[$tableName] = $event->isTableExcluded();
1356
1357
        return static::$excludedTables[$tableName];
1358
    }
1359
1360
    /**
1361
     * Checks if a given column in a given table should be excluded in the ReferenceIndex process
1362
     *
1363
     * @param string $tableName Name of the table
1364
     * @param string $column Name of the column
1365
     * @param string $onlyColumn Name of a specific column to fetch
1366
     * @return bool true if it should be excluded
1367
     */
1368
    protected function shouldExcludeTableColumnFromReferenceIndex($tableName, $column, $onlyColumn)
1369
    {
1370
        if (isset(static::$excludedColumns[$column])) {
1371
            return true;
1372
        }
1373
1374
        if (is_array($GLOBALS['TCA'][$tableName]['columns'][$column]) && (!$onlyColumn || $onlyColumn === $column)) {
1375
            return false;
1376
        }
1377
1378
        return true;
1379
    }
1380
1381
    /**
1382
     * Enables the runtime-based caches
1383
     * Could lead to side effects, depending if the reference index instance is run multiple times
1384
     * while records would be changed.
1385
     */
1386
    public function enableRuntimeCache()
1387
    {
1388
        $this->useRuntimeCache = true;
1389
    }
1390
1391
    /**
1392
     * Disables the runtime-based cache
1393
     */
1394
    public function disableRuntimeCache()
1395
    {
1396
        $this->useRuntimeCache = false;
1397
    }
1398
1399
    /**
1400
     * Returns the current BE user.
1401
     *
1402
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1403
     */
1404
    protected function getBackendUser()
1405
    {
1406
        return $GLOBALS['BE_USER'];
1407
    }
1408
}
1409