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