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