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