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