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