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