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