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