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