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