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