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