e18a1b16edf925c625910c58d46b17fdb9893e74
[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 TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Messaging\FlashMessage;
19 use TYPO3\CMS\Core\Cache\CacheManager;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21 use TYPO3\CMS\Core\Utility\StringUtility;
22
23 /**
24 * Reference index processing and relation extraction
25 *
26 * NOTICE: When the reference index is updated for an offline version the results may not be correct.
27 * First, lets assumed that the reference update happens in LIVE workspace (ALWAYS update from Live workspace if you analyse whole database!)
28 * 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.
29 * 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 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 on the Data Structure set in the Live workspace!
30 * 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 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?
31 * Anyway, I just wanted to document this finding - I don't think we can find a solution for it. And its very TemplaVoila specific.
32 *
33 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
34 */
35 class ReferenceIndex {
36
37 /**
38 * Definition of tables to exclude from searching for relations
39 *
40 * Only tables which do not contain any relations and never did so far since references also won't be deleted for
41 * these. Since only tables with an entry in $GLOBALS['TCA] are handled by ReferenceIndex there is no need to add
42 * *_mm-tables.
43 *
44 * This is implemented as an array with fields as keys and booleans as values to be able to fast isset() instead of
45 * slow in_array() lookup.
46 *
47 * @var array
48 * @see updateRefIndexTable()
49 * @todo #65461 Create configuration for tables to exclude from ReferenceIndex
50 */
51 static protected $nonRelationTables = array(
52 'sys_log' => TRUE,
53 'sys_history' => TRUE,
54 'tx_extensionmanager_domain_model_extension' => TRUE
55 );
56
57 /**
58 * Definition of fields to exclude from searching for relations
59 *
60 * This is implemented as an array with fields as keys and booleans as values to be able to fast isset() instead of
61 * slow in_array() lookup.
62 *
63 * @var array
64 * @see getRelations()
65 * @see fetchTableRelationFields()
66 * @todo #65460 Create configuration for fields to exclude from ReferenceIndex
67 */
68 static protected $nonRelationFields = array(
69 'uid' => TRUE,
70 'perms_userid' => TRUE,
71 'perms_groupid' => TRUE,
72 'perms_user' => TRUE,
73 'perms_group' => TRUE,
74 'perms_everybody' => TRUE,
75 'pid' => TRUE
76 );
77
78 /**
79 * Fields of tables that could contain relations are cached per table. This is the prefix for the cache entries since
80 * the runtimeCache has a global scope.
81 *
82 * @var string
83 */
84 static protected $cachePrefixTableRelationFields = 'core-refidx-tblRelFields-';
85
86 /**
87 * @var array
88 */
89 public $temp_flexRelations = array();
90
91 /**
92 * @var array
93 */
94 public $errorLog = array();
95
96 /**
97 * @var bool
98 */
99 public $WSOL = FALSE;
100
101 /**
102 * @var array
103 */
104 public $relations = array();
105
106 /**
107 * Number which we can increase if a change in the code means we will have to force a re-generation of the index.
108 *
109 * @var int
110 */
111 public $hashVersion = 1;
112
113 /**
114 * @var int
115 */
116 protected $workspaceId = 0;
117
118 /**
119 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
120 */
121 protected $runtimeCache = NULL;
122
123 /**
124 * Constructor
125 */
126 public function __construct() {
127 $this->runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
128 }
129
130 /**
131 * Sets the current workspace id.
132 *
133 * @param int $workspaceId
134 */
135 public function setWorkspaceId($workspaceId) {
136 $this->workspaceId = (int)$workspaceId;
137 }
138
139 /**
140 * Gets the current workspace id.
141 *
142 * @return int
143 */
144 public function getWorkspaceId() {
145 return $this->workspaceId;
146 }
147
148 /**
149 * Call this function to update the sys_refindex table for a record (even one just deleted)
150 * NOTICE: Currently, references updated for a deleted-flagged record will not include those from within flexform fields in some cases where the data structure is defined by another record since the resolving process ignores deleted records! This will also result in bad cleaning up in tcemain I think... Anyway, thats the story of flexforms; as long as the DS can change, lots of references can get lost in no time.
151 *
152 * @param string $tableName Table name
153 * @param int $uid UID of record
154 * @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.
155 * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
156 */
157 public function updateRefIndexTable($tableName, $uid, $testOnly = FALSE) {
158
159 // First, secure that the index table is not updated with workspace tainted relations:
160 $this->WSOL = FALSE;
161
162 // Init:
163 $result = array(
164 'keptNodes' => 0,
165 'deletedNodes' => 0,
166 'addedNodes' => 0
167 );
168
169 // If this table cannot contain relations, skip it
170 if (isset(static::$nonRelationTables[$tableName])) {
171 return $result;
172 }
173
174 // Fetch tableRelationFields and save them in cache if not there yet
175 $cacheId = static::$cachePrefixTableRelationFields. $tableName;
176 if (!$this->runtimeCache->has($cacheId)) {
177 $tableRelationFields = $this->fetchTableRelationFields($tableName);
178 $this->runtimeCache->set($cacheId, $tableRelationFields);
179 } else {
180 $tableRelationFields = $this->runtimeCache->get($cacheId);
181 }
182
183 // Get current index from Database with hash as index using $uidIndexField
184 $currentRelations = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
185 '*',
186 'sys_refindex',
187 'tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tableName, 'sys_refindex')
188 . ' AND recuid=' . (int)$uid . ' AND workspace=' . (int)$this->getWorkspaceId(),
189 '', '', '', 'hash'
190 );
191
192 // If the table has fields which could contain relations and the record does exist (including deleted-flagged)
193 if ($tableRelationFields !== '' && BackendUtility::getRecordRaw($tableName, 'uid=' . (int)$uid, 'uid')) {
194 // Then, get relations:
195 $relations = $this->generateRefIndexData($tableName, $uid);
196 if (is_array($relations)) {
197 // Traverse the generated index:
198 foreach ($relations as $k => $datRec) {
199 if (!is_array($relations[$k])) {
200 continue;
201 }
202 $relations[$k]['hash'] = md5(implode('///', $relations[$k]) . '///' . $this->hashVersion);
203 // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
204 if (isset($currentRelations[$relations[$k]['hash']])) {
205 unset($currentRelations[$relations[$k]['hash']]);
206 $result['keptNodes']++;
207 $relations[$k]['_ACTION'] = 'KEPT';
208 } else {
209 // If new, add it:
210 if (!$testOnly) {
211 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex', $relations[$k]);
212 }
213 $result['addedNodes']++;
214 $relations[$k]['_ACTION'] = 'ADDED';
215 }
216 }
217 $result['relations'] = $relations;
218 } else {
219 return $result;
220 }
221 }
222
223 // If any old are left, remove them:
224 if (!empty($currentRelations)) {
225 $hashList = array_keys($currentRelations);
226 if (!empty($hashList)) {
227 $result['deletedNodes'] = count($hashList);
228 $result['deletedNodes_hashList'] = implode(',', $hashList);
229 if (!$testOnly) {
230 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex', 'hash IN (' . implode(',', $GLOBALS['TYPO3_DB']->fullQuoteArray($hashList, 'sys_refindex')) . ')');
231 }
232 }
233 }
234
235 return $result;
236 }
237
238 /**
239 * Returns array of arrays with an index of all references found in record from table/uid
240 * If the result is used to update the sys_refindex table then ->WSOL must NOT be TRUE (no workspace overlay anywhere!)
241 *
242 * @param string $tableName Table name from $GLOBALS['TCA']
243 * @param int $uid Record UID
244 * @return array|NULL Index Rows
245 */
246 public function generateRefIndexData($tableName, $uid) {
247
248 if (!isset($GLOBALS['TCA'][$tableName])) {
249 return NULL;
250 }
251
252 $this->relations = array();
253
254 // Fetch tableRelationFields and save them in cache if not there yet
255 $cacheId = static::$cachePrefixTableRelationFields . $tableName;
256 if (!$this->runtimeCache->has($cacheId)) {
257 $tableRelationFields = $this->fetchTableRelationFields($tableName);
258 $this->runtimeCache->set($cacheId, $tableRelationFields);
259 } else {
260 $tableRelationFields = $this->runtimeCache->get($cacheId);
261 }
262
263 // Return if there are no fields which could contain relations
264 if ($tableRelationFields === '') {
265 return $this->relations;
266 }
267
268 $deleteField = $GLOBALS['TCA'][$tableName]['ctrl']['delete'];
269
270 if ($tableRelationFields === '*') {
271 // If one field of a record is of type flex, all fields have to be fetched to be passed to BackendUtility::getFlexFormDS
272 $selectFields = '*';
273 } else {
274 // otherwise only fields that might contain relations are fetched
275 $selectFields = 'uid,' . $tableRelationFields . ($deleteField ? ',' . $deleteField : '');
276 }
277
278 // Get raw record from DB:
279 $record = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow($selectFields, $tableName, 'uid=' . (int)$uid);
280 if (!is_array($record)) {
281 return NULL;
282 }
283
284 // Deleted:
285 $deleted = $deleteField && $record[$deleteField] ? 1 : 0;
286
287 // Get all relations from record:
288 $recordRelations = $this->getRelations($tableName, $record);
289 // Traverse those relations, compile records to insert in table:
290 foreach ($recordRelations as $fieldName => $fieldRelations) {
291 // Based on type,
292 switch ((string)$fieldRelations['type']) {
293 case 'db':
294 $this->createEntryData_dbRels($tableName, $uid, $fieldName, '', $deleted, $fieldRelations['itemArray']);
295 break;
296 case 'file_reference':
297 // not used (see getRelations()), but fallback to file
298 case 'file':
299 $this->createEntryData_fileRels($tableName, $uid, $fieldName, '', $deleted, $fieldRelations['newValueFiles']);
300 break;
301 case 'flex':
302 // DB references:
303 if (is_array($fieldRelations['flexFormRels']['db'])) {
304 foreach ($fieldRelations['flexFormRels']['db'] as $flexPointer => $subList) {
305 $this->createEntryData_dbRels($tableName, $uid, $fieldName, $flexPointer, $deleted, $subList);
306 }
307 }
308 // @todo #65463 Test correct handling of file references in flexforms
309 if (is_array($fieldRelations['flexFormRels']['file'])) {
310 foreach ($fieldRelations['flexFormRels']['file'] as $flexPointer => $subList) {
311 $this->createEntryData_fileRels($tableName, $uid, $fieldName, $flexPointer, $deleted, $subList);
312 }
313 }
314 // @todo #65464 Test correct handling of soft references in flexforms
315 if (is_array($fieldRelations['flexFormRels']['softrefs'])) {
316 foreach ($fieldRelations['flexFormRels']['softrefs'] as $flexPointer => $subList) {
317 $this->createEntryData_softreferences($tableName, $uid, $fieldName, $flexPointer, $deleted, $subList['keys']);
318 }
319 }
320 break;
321 }
322 // Soft references in the field:
323 if (is_array($fieldRelations['softrefs'])) {
324 $this->createEntryData_softreferences($tableName, $uid, $fieldName, '', $deleted, $fieldRelations['softrefs']['keys']);
325 }
326 }
327
328 return $this->relations;
329 }
330
331 /**
332 * Create array with field/value pairs ready to insert in database.
333 * The "hash" field is a fingerprint value across this table.
334 *
335 * @param string $table Tablename of source record (where reference is located)
336 * @param int $uid UID of source record (where reference is located)
337 * @param string $field Fieldname of source record (where reference is located)
338 * @param string $flexpointer Pointer to location inside flexform structure where reference is located in [field]
339 * @param int $deleted Whether record is deleted-flagged or not
340 * @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.
341 * @param int $ref_uid For database references; The UID of the record (zero "ref_table" is "_FILE" or "_STRING")
342 * @param string $ref_string For "_FILE" or "_STRING" references: The filepath (relative to PATH_site or absolute) or other string.
343 * @param int $sort The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
344 * @param string $softref_key If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
345 * @param string $softref_id Soft reference ID for key. Might be useful for replace operations.
346 * @return array Array record to insert into table.
347 */
348 public function createEntryData($table, $uid, $field, $flexpointer, $deleted, $ref_table, $ref_uid, $ref_string = '', $sort = -1, $softref_key = '', $softref_id = '') {
349 if (BackendUtility::isTableWorkspaceEnabled($table)) {
350 $element = BackendUtility::getRecord($table, $uid, 't3ver_wsid');
351 if ($element !== NULL && isset($element['t3ver_wsid']) && (int)$element['t3ver_wsid'] !== $this->getWorkspaceId()) {
352 //The given Element is ws-enabled but doesn't live in the selected workspace
353 // => don't add index as it's not actually there
354 return FALSE;
355 }
356 }
357 return array(
358 'tablename' => $table,
359 'recuid' => $uid,
360 'field' => $field,
361 'flexpointer' => $flexpointer,
362 'softref_key' => $softref_key,
363 'softref_id' => $softref_id,
364 'sorting' => $sort,
365 'deleted' => $deleted,
366 'workspace' => $this->getWorkspaceId(),
367 'ref_table' => $ref_table,
368 'ref_uid' => $ref_uid,
369 'ref_string' => $ref_string
370 );
371 }
372
373 /**
374 * Enter database references to ->relations array
375 *
376 * @param string $table Tablename of source record (where reference is located)
377 * @param int $uid UID of source record (where reference is located)
378 * @param string $fieldname Fieldname of source record (where reference is located)
379 * @param string $flexpointer Pointer to location inside flexform structure where reference is located in [field]
380 * @param int $deleted Whether record is deleted-flagged or not
381 * @param array $items Data array with databaes relations (table/id)
382 * @return void
383 */
384 public function createEntryData_dbRels($table, $uid, $fieldname, $flexpointer, $deleted, $items) {
385 foreach ($items as $sort => $i) {
386 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, $i['table'], $i['id'], '', $sort);
387 }
388 }
389
390 /**
391 * Enter file references to ->relations array
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 $fieldname 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 array $items Data array with file relations
399 * @return void
400 */
401 public function createEntryData_fileRels($table, $uid, $fieldname, $flexpointer, $deleted, $items) {
402 foreach ($items as $sort => $i) {
403 $filePath = $i['ID_absFile'];
404 if (GeneralUtility::isFirstPartOfStr($filePath, PATH_site)) {
405 $filePath = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($filePath);
406 }
407 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_FILE', 0, $filePath, $sort);
408 }
409 }
410
411 /**
412 * Enter softref references to ->relations array
413 *
414 * @param string $table Tablename of source record (where reference is located)
415 * @param int $uid UID of source record (where reference is located)
416 * @param string $fieldname Fieldname of source record (where reference is located)
417 * @param string $flexpointer Pointer to location inside flexform struc
418 * @param int $deleted
419 * @param array $keys Data array with soft reference keys
420 * @return void
421 */
422 public function createEntryData_softreferences($table, $uid, $fieldname, $flexpointer, $deleted, $keys) {
423 if (is_array($keys)) {
424 foreach ($keys as $spKey => $elements) {
425 if (is_array($elements)) {
426 foreach ($elements as $subKey => $el) {
427 if (is_array($el['subst'])) {
428 switch ((string)$el['subst']['type']) {
429 case 'db':
430 list($tableName, $recordId) = explode(':', $el['subst']['recordRef']);
431 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, $tableName, $recordId, '', -1, $spKey, $subKey);
432 break;
433 case 'file_reference':
434 // not used (see getRelations()), but fallback to file
435 case 'file':
436 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_FILE', 0, $el['subst']['relFileName'], -1, $spKey, $subKey);
437 break;
438 case 'string':
439 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_STRING', 0, $el['subst']['tokenValue'], -1, $spKey, $subKey);
440 break;
441 }
442 }
443 }
444 }
445 }
446 }
447 }
448
449 /*******************************
450 *
451 * Get relations from table row
452 *
453 *******************************/
454 /**
455 * Returns relation information for a $table/$row-array
456 * Traverses all fields in input row which are configured in TCA/columns
457 * It looks for hard relations to files and records in the TCA types "select" and "group"
458 *
459 * @param string $table Table name
460 * @param array $row Row from table
461 * @param string $onlyField Specific field to fetch for.
462 * @return array Array with information about relations
463 * @see export_addRecord()
464 */
465 public function getRelations($table, $row, $onlyField = '') {
466 // Initialize:
467 $uid = $row['uid'];
468 $outRow = array();
469 foreach ($row as $field => $value) {
470 if (!isset(static::$nonRelationFields[$field]) && is_array($GLOBALS['TCA'][$table]['columns'][$field]) && (!$onlyField || $onlyField === $field)) {
471 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
472 // Add files
473 $resultsFromFiles = $this->getRelations_procFiles($value, $conf, $uid);
474 if (!empty($resultsFromFiles)) {
475 // We have to fill different arrays here depending on the result.
476 // internal_type file is still a relation of type file and
477 // since http://forge.typo3.org/issues/49538 internal_type file_reference
478 // is a database relation to a sys_file record
479 $fileResultsFromFiles = array();
480 $dbResultsFromFiles = array();
481 foreach ($resultsFromFiles as $resultFromFiles) {
482 if (isset($resultFromFiles['table']) && $resultFromFiles['table'] === 'sys_file') {
483 $dbResultsFromFiles[] = $resultFromFiles;
484 } else {
485 // Creates an entry for the field with all the files:
486 $fileResultsFromFiles[] = $resultFromFiles;
487 }
488 }
489 if (!empty($fileResultsFromFiles)) {
490 $outRow[$field] = array(
491 'type' => 'file',
492 'newValueFiles' => $fileResultsFromFiles
493 );
494 }
495 if (!empty($dbResultsFromFiles)) {
496 $outRow[$field] = array(
497 'type' => 'db',
498 'itemArray' => $dbResultsFromFiles
499 );
500 }
501 }
502 // Add a softref definition for link fields if the TCA does not specify one already
503 if ($conf['type'] === 'input' && isset($conf['wizards']['link']) && empty($conf['softref'])) {
504 $conf['softref'] = 'typolink';
505 }
506 // Add DB:
507 $resultsFromDatabase = $this->getRelations_procDB($value, $conf, $uid, $table, $field);
508 if (!empty($resultsFromDatabase)) {
509 // Create an entry for the field with all DB relations:
510 $outRow[$field] = array(
511 'type' => 'db',
512 'itemArray' => $resultsFromDatabase
513 );
514 }
515 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
516 if ($conf['type'] == 'flex') {
517 // Get current value array:
518 // NOTICE: failure to resolve Data Structures can lead to integrity problems with the reference index. Please look up the note in the JavaDoc documentation for the function \TYPO3\CMS\Backend\Utility\BackendUtility::getFlexFormDS()
519 $currentValueArray = GeneralUtility::xml2array($value);
520 // Traversing the XML structure, processing files:
521 if (is_array($currentValueArray)) {
522 $this->temp_flexRelations = array(
523 'db' => array(),
524 'file' => array(),
525 'softrefs' => array()
526 );
527 // Create and call iterator object:
528 $flexObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
529 $flexObj->traverseFlexFormXMLData($table, $field, $row, $this, 'getRelations_flexFormCallBack');
530 // Create an entry for the field:
531 $outRow[$field] = array(
532 'type' => 'flex',
533 'flexFormRels' => $this->temp_flexRelations
534 );
535 }
536 }
537 // Soft References:
538 if ((string)$value !== '') {
539 $softRefValue = $value;
540 $softRefs = BackendUtility::explodeSoftRefParserList($conf['softref']);
541 if ($softRefs !== FALSE) {
542 foreach ($softRefs as $spKey => $spParams) {
543 $softRefObj = BackendUtility::softRefParserObj($spKey);
544 if (is_object($softRefObj)) {
545 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
546 if (is_array($resultArray)) {
547 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
548 if ((string)$resultArray['content'] !== '') {
549 $softRefValue = $resultArray['content'];
550 }
551 }
552 }
553 }
554 }
555 if (!empty($outRow[$field]['softrefs']) && (string)$value !== (string)$softRefValue && strpos($softRefValue, '{softref:') !== FALSE) {
556 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
557 }
558 }
559 }
560 }
561 return $outRow;
562 }
563
564 /**
565 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
566 *
567 * @param array $dsArr Data structure for the current value
568 * @param mixed $dataValue Current value
569 * @param array $PA Additional configuration used in calling function
570 * @param string $structurePath Path of value in DS structure
571 * @param object $pObj Object reference to caller
572 * @return void
573 * @see \TYPO3\CMS\Core\DataHandling\DataHandler::checkValue_flex_procInData_travDS()
574 */
575 public function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, $pObj) {
576 // Removing "data/" in the beginning of path (which points to location in data array)
577 $structurePath = substr($structurePath, 5) . '/';
578 $dsConf = $dsArr['TCEforms']['config'];
579 // Implode parameter values:
580 list($table, $uid, $field) = array(
581 $PA['table'],
582 $PA['uid'],
583 $PA['field']
584 );
585 // Add files
586 $resultsFromFiles = $this->getRelations_procFiles($dataValue, $dsConf, $uid);
587 if (!empty($resultsFromFiles)) {
588 // We have to fill different arrays here depending on the result.
589 // internal_type file is still a relation of type file and
590 // since http://forge.typo3.org/issues/49538 internal_type file_reference
591 // is a database relation to a sys_file record
592 $fileResultsFromFiles = array();
593 $dbResultsFromFiles = array();
594 foreach ($resultsFromFiles as $resultFromFiles) {
595 if (isset($resultFromFiles['table']) && $resultFromFiles['table'] === 'sys_file') {
596 $dbResultsFromFiles[] = $resultFromFiles;
597 } else {
598 $fileResultsFromFiles[] = $resultFromFiles;
599 }
600 }
601 if (!empty($fileResultsFromFiles)) {
602 $this->temp_flexRelations['file'][$structurePath] = $fileResultsFromFiles;
603 }
604 if (!empty($dbResultsFromFiles)) {
605 $this->temp_flexRelations['db'][$structurePath] = $dbResultsFromFiles;
606 }
607 }
608 // Add a softref definition for link fields if the TCA does not specify one already
609 if ($dsConf['type'] === 'input' && isset($dsConf['wizards']['link']) && empty($dsConf['softref'])) {
610 $dsConf['softref'] = 'typolink';
611 }
612 // Add DB:
613 $resultsFromDatabase = $this->getRelations_procDB($dataValue, $dsConf, $uid, $table, $field);
614 if (!empty($resultsFromDatabase)) {
615 // Create an entry for the field with all DB relations:
616 $this->temp_flexRelations['db'][$structurePath] = $resultsFromDatabase;
617 }
618 // Soft References:
619 if (is_array($dataValue) || (string)$dataValue !== '') {
620 $softRefValue = $dataValue;
621 $softRefs = BackendUtility::explodeSoftRefParserList($dsConf['softref']);
622 if ($softRefs !== FALSE) {
623 foreach ($softRefs as $spKey => $spParams) {
624 $softRefObj = BackendUtility::softRefParserObj($spKey);
625 if (is_object($softRefObj)) {
626 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
627 if (is_array($resultArray) && is_array($resultArray['elements'])) {
628 $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
629 if ((string)$resultArray['content'] !== '') {
630 $softRefValue = $resultArray['content'];
631 }
632 }
633 }
634 }
635 }
636 if (!empty($this->temp_flexRelations['softrefs']) && (string)$dataValue !== (string)$softRefValue) {
637 $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
638 }
639 }
640 }
641
642 /**
643 * Check field configuration if it is a file relation field and extract file relations if any
644 *
645 * @param string $value Field value
646 * @param array $conf Field configuration array of type "TCA/columns
647 * @param int $uid Field uid
648 * @return bool|array If field type is OK it will return an array with the files inside. Else FALSE
649 */
650 public function getRelations_procFiles($value, $conf, $uid) {
651 if ($conf['type'] !== 'group' || ($conf['internal_type'] !== 'file' && $conf['internal_type'] !== 'file_reference')) {
652 return FALSE;
653 }
654
655 // Collect file values in array:
656 if ($conf['MM']) {
657 $theFileValues = array();
658 $dbAnalysis = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
659 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
660 foreach ($dbAnalysis->itemArray as $someval) {
661 if ($someval['id']) {
662 $theFileValues[] = $someval['id'];
663 }
664 }
665 } else {
666 $theFileValues = explode(',', $value);
667 }
668 // Traverse the files and add them:
669 $uploadFolder = $conf['internal_type'] == 'file' ? $conf['uploadfolder'] : '';
670 $dest = $this->destPathFromUploadFolder($uploadFolder);
671 $newValueFiles = array();
672 foreach ($theFileValues as $file) {
673 if (trim($file)) {
674 $realFile = $dest . '/' . trim($file);
675 $newValueFile = array(
676 'filename' => basename($file),
677 'ID' => md5($realFile),
678 'ID_absFile' => $realFile
679 );
680 // Set sys_file and id for referenced files
681 if ($conf['internal_type'] === 'file_reference') {
682 try {
683 $file = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject($file);
684 if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
685 // For setting this as sys_file relation later, the keys filename, ID and ID_absFile
686 // have not to be included, because the are not evaluated for db relations.
687 $newValueFile = array(
688 'table' => 'sys_file',
689 'id' => $file->getUid()
690 );
691 }
692 } catch (\Exception $e) {
693
694 }
695 }
696 $newValueFiles[] = $newValueFile;
697 }
698 }
699 return $newValueFiles;
700 }
701
702 /**
703 * Check field configuration if it is a DB relation field and extract DB relations if any
704 *
705 * @param string $value Field value
706 * @param array $conf Field configuration array of type "TCA/columns
707 * @param int $uid Field uid
708 * @param string $table Table name
709 * @param string $field Field name
710 * @return array If field type is OK it will return an array with the database relations. Else FALSE
711 */
712 public function getRelations_procDB($value, $conf, $uid, $table = '', $field = '') {
713 // Get IRRE relations
714 if (empty($conf)) {
715 return FALSE;
716 } elseif ($conf['type'] === 'inline' && !empty($conf['foreign_table']) && empty($conf['MM'])) {
717 $dbAnalysis = $this->getRelationHandler();
718 $dbAnalysis->setUseLiveReferenceIds(FALSE);
719 $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
720 return $dbAnalysis->itemArray;
721 // DB record lists:
722 } elseif ($this->isDbReferenceField($conf)) {
723 $allowedTables = $conf['type'] == 'group' ? $conf['allowed'] : $conf['foreign_table'] . ',' . $conf['neg_foreign_table'];
724 if ($conf['MM_opposite_field']) {
725 return array();
726 }
727 $dbAnalysis = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
728 $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
729 return $dbAnalysis->itemArray;
730 } elseif ($conf['type'] == 'inline' && $conf['foreign_table'] == 'sys_file_reference') {
731 // @todo It looks like this was never called before since isDbReferenceField also checks for type 'inline' and any 'foreign_table'
732 $files = (array)$GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid_local', 'sys_file_reference', ('tablenames=\'' . $table . '\' AND fieldname=\'' . $field . '\' AND uid_foreign=' . $uid . ' AND deleted=0'));
733 $fileArray = array();
734 foreach ($files as $fileUid) {
735 $fileArray[] = array(
736 'table' => 'sys_file',
737 'id' => $fileUid['uid_local']
738 );
739 }
740 return $fileArray;
741 }
742 }
743
744 /*******************************
745 *
746 * Setting values
747 *
748 *******************************/
749 /**
750 * Setting the value of a reference or removing it completely.
751 * Usage: For lowlevel clean up operations!
752 * WARNING: With this you can set values that are not allowed in the database since it will bypass all checks for validity! Hence it is targetted at clean-up operations. Please use TCEmain in the usual ways if you wish to manipulate references.
753 * Since this interface allows updates to soft reference values (which TCEmain does not directly) you may like to use it for that as an exception to the warning above.
754 * Notice; If you want to remove multiple references from the same field, you MUST start with the one having the highest sorting number. If you don't the removal of a reference with a lower number will recreate an index in which the remaining references in that field has new hash-keys due to new sorting numbers - and you will get errors for the remaining operations which cannot find the hash you feed it!
755 * To ensure proper working only admin-BE_USERS in live workspace should use this function
756 *
757 * @param string $hash 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
758 * @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
759 * @param bool $returnDataArray Return $dataArray only, do not submit it to database.
760 * @param bool $bypassWorkspaceAdminCheck If set, it will bypass check for workspace-zero and admin user
761 * @return string If a return string, that carries an error message, otherwise FALSE (=OK) (except if $returnDataArray is set!)
762 */
763 public function setReferenceValue($hash, $newValue, $returnDataArray = FALSE, $bypassWorkspaceAdminCheck = FALSE) {
764 if ($GLOBALS['BE_USER']->workspace === 0 && $GLOBALS['BE_USER']->isAdmin() || $bypassWorkspaceAdminCheck) {
765 // Get current index from Database:
766 $refRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_refindex', 'hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'sys_refindex'));
767 // Check if reference existed.
768 if (is_array($refRec)) {
769 if ($GLOBALS['TCA'][$refRec['tablename']]) {
770 // Get that record from database:
771 $record = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', $refRec['tablename'], 'uid=' . (int)$refRec['recuid']);
772 if (is_array($record)) {
773 // Get all relations from record, filter with fieldname:
774 $dbrels = $this->getRelations($refRec['tablename'], $record, $refRec['field']);
775 if ($dat = $dbrels[$refRec['field']]) {
776 // Initialize data array that is to be sent to TCEmain afterwards:
777 $dataArray = array();
778 // Based on type,
779 switch ((string)$dat['type']) {
780 case 'db':
781 $error = $this->setReferenceValue_dbRels($refRec, $dat['itemArray'], $newValue, $dataArray);
782 if ($error) {
783 return $error;
784 }
785 break;
786 case 'file_reference':
787 // not used (see getRelations()), but fallback to file
788 case 'file':
789 $error = $this->setReferenceValue_fileRels($refRec, $dat['newValueFiles'], $newValue, $dataArray);
790 if ($error) {
791 return $error;
792 }
793 break;
794 case 'flex':
795 // DB references:
796 if (is_array($dat['flexFormRels']['db'][$refRec['flexpointer']])) {
797 $error = $this->setReferenceValue_dbRels($refRec, $dat['flexFormRels']['db'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
798 if ($error) {
799 return $error;
800 }
801 }
802 // File references
803 if (is_array($dat['flexFormRels']['file'][$refRec['flexpointer']])) {
804 $this->setReferenceValue_fileRels($refRec, $dat['flexFormRels']['file'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
805 if ($error) {
806 return $error;
807 }
808 }
809 // Soft references in flexforms
810 if ($refRec['softref_key'] && is_array($dat['flexFormRels']['softrefs'][$refRec['flexpointer']]['keys'][$refRec['softref_key']])) {
811 $error = $this->setReferenceValue_softreferences($refRec, $dat['flexFormRels']['softrefs'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
812 if ($error) {
813 return $error;
814 }
815 }
816 break;
817 }
818 // Softreferences in the field:
819 if ($refRec['softref_key'] && is_array($dat['softrefs']['keys'][$refRec['softref_key']])) {
820 $error = $this->setReferenceValue_softreferences($refRec, $dat['softrefs'], $newValue, $dataArray);
821 if ($error) {
822 return $error;
823 }
824 }
825 // Data Array, now ready to sent to TCEmain
826 if ($returnDataArray) {
827 return $dataArray;
828 } else {
829 // Execute CMD array:
830 $tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
831 $tce->stripslashes_values = FALSE;
832 $tce->dontProcessTransformations = TRUE;
833 $tce->bypassWorkspaceRestrictions = TRUE;
834 $tce->bypassFileHandling = TRUE;
835 // Otherwise this cannot update things in deleted records...
836 $tce->bypassAccessCheckForRecords = TRUE;
837 // Check has been done previously that there is a backend user which is Admin and also in live workspace
838 $tce->start($dataArray, array());
839 $tce->process_datamap();
840 // Return errors if any:
841 if (count($tce->errorLog)) {
842 return LF . 'TCEmain:' . implode((LF . 'TCEmain:'), $tce->errorLog);
843 }
844 }
845 }
846 }
847 } else {
848 return 'ERROR: Tablename "' . $refRec['tablename'] . '" was not in TCA!';
849 }
850 } else {
851 return 'ERROR: No reference record with hash="' . $hash . '" was found!';
852 }
853 } else {
854 return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
855 }
856 }
857
858 /**
859 * Setting a value for a reference for a DB field:
860 *
861 * @param array $refRec sys_refindex record
862 * @param array $itemArray Array of references from that field
863 * @param string $newValue Value to substitute current value with (or NULL to unset it)
864 * @param array $dataArray Data array in which the new value is set (passed by reference)
865 * @param string $flexpointer Flexform pointer, if in a flex form field.
866 * @return string Error message if any, otherwise FALSE = OK
867 */
868 public function setReferenceValue_dbRels($refRec, $itemArray, $newValue, &$dataArray, $flexpointer = '') {
869 if ((int)$itemArray[$refRec['sorting']]['id'] === (int)$refRec['ref_uid'] && (string)$itemArray[$refRec['sorting']]['table'] === (string)$refRec['ref_table']) {
870 // Setting or removing value:
871 // Remove value:
872 if ($newValue === NULL) {
873 unset($itemArray[$refRec['sorting']]);
874 } else {
875 list($itemArray[$refRec['sorting']]['table'], $itemArray[$refRec['sorting']]['id']) = explode(':', $newValue);
876 }
877 // Traverse and compile new list of records:
878 $saveValue = array();
879 foreach ($itemArray as $pair) {
880 $saveValue[] = $pair['table'] . '_' . $pair['id'];
881 }
882 // Set in data array:
883 if ($flexpointer) {
884 $flexToolObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
885 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
886 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
887 } else {
888 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
889 }
890 } else {
891 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'] . '"';
892 }
893 }
894
895 /**
896 * Setting a value for a reference for a FILE field:
897 *
898 * @param array $refRec sys_refindex record
899 * @param array $itemArray Array of references from that field
900 * @param string $newValue Value to substitute current value with (or NULL to unset it)
901 * @param array $dataArray Data array in which the new value is set (passed by reference)
902 * @param string $flexpointer Flexform pointer, if in a flex form field.
903 * @return string Error message if any, otherwise FALSE = OK
904 */
905 public function setReferenceValue_fileRels($refRec, $itemArray, $newValue, &$dataArray, $flexpointer = '') {
906 $ID_absFile = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($itemArray[$refRec['sorting']]['ID_absFile']);
907 if ($ID_absFile === (string)$refRec['ref_string'] && $refRec['ref_table'] === '_FILE') {
908 // Setting or removing value:
909 // Remove value:
910 if ($newValue === NULL) {
911 unset($itemArray[$refRec['sorting']]);
912 } else {
913 $itemArray[$refRec['sorting']]['filename'] = $newValue;
914 }
915 // Traverse and compile new list of records:
916 $saveValue = array();
917 foreach ($itemArray as $fileInfo) {
918 $saveValue[] = $fileInfo['filename'];
919 }
920 // Set in data array:
921 if ($flexpointer) {
922 $flexToolObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
923 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
924 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
925 } else {
926 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
927 }
928 } else {
929 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'] . '"';
930 }
931 }
932
933 /**
934 * Setting a value for a soft reference token
935 *
936 * @param array $refRec sys_refindex record
937 * @param array $softref Array of soft reference occurencies
938 * @param string $newValue Value to substitute current value with
939 * @param array $dataArray Data array in which the new value is set (passed by reference)
940 * @param string $flexpointer Flexform pointer, if in a flex form field.
941 * @return string Error message if any, otherwise FALSE = OK
942 */
943 public function setReferenceValue_softreferences($refRec, $softref, $newValue, &$dataArray, $flexpointer = '') {
944 if (is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
945 // Set new value:
946 $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = '' . $newValue;
947 // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
948 foreach ($softref['keys'] as $sfIndexes) {
949 foreach ($sfIndexes as $data) {
950 $softref['tokenizedContent'] = str_replace('{softref:' . $data['subst']['tokenID'] . '}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
951 }
952 }
953 // Set in data array:
954 if (!strstr($softref['tokenizedContent'], '{softref:')) {
955 if ($flexpointer) {
956 $flexToolObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
957 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
958 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], $softref['tokenizedContent']);
959 } else {
960 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
961 }
962 } else {
963 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.)';
964 }
965 } else {
966 return 'ERROR: Soft reference parser key "' . $refRec['softref_key'] . '" or the index "' . $refRec['softref_id'] . '" was not found.';
967 }
968 }
969
970 /*******************************
971 *
972 * Helper functions
973 *
974 *******************************/
975
976 /**
977 * Returns TRUE if the TCA/columns field type is a DB reference field
978 *
979 * @param array $configuration Config array for TCA/columns field
980 * @return bool TRUE if DB reference field (group/db or select with foreign-table)
981 */
982 protected function isDbReferenceField(array $configuration) {
983 return (
984 ($configuration['type'] === 'group' && $configuration['internal_type'] === 'db')
985 || (
986 ($configuration['type'] === 'select' || $configuration['type'] === 'inline')
987 && !empty($configuration['foreign_table'])
988 )
989 );
990 }
991
992 /**
993 * Returns TRUE if the TCA/columns field type is a reference field
994 *
995 * @param array $configuration Config array for TCA/columns field
996 * @return bool TRUE if reference field
997 */
998 public function isReferenceField(array $configuration) {
999 return (
1000 $this->isDbReferenceField($configuration)
1001 ||
1002 ($configuration['type'] === 'group' && ($configuration['internal_type'] === 'file' || $configuration['internal_type'] === 'file_reference')) // getRelations_procFiles
1003 ||
1004 ($configuration['type'] === 'input' && isset($configuration['wizards']['link'])) // getRelations_procDB
1005 ||
1006 $configuration['type'] === 'flex'
1007 ||
1008 isset($configuration['softref'])
1009 ||
1010 (
1011 // @deprecated global soft reference parsers are deprecated since TYPO3 CMS 7 and will be removed in TYPO3 CMS 8
1012 is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])
1013 && !empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])
1014 )
1015 );
1016 }
1017
1018 /**
1019 * Returns all fields of a table which could contain a relation
1020 *
1021 * @param string $tableName Name of the table
1022 * @return string Fields which could contain a relation
1023 */
1024 protected function fetchTableRelationFields($tableName) {
1025 $fields = array();
1026
1027 foreach ($GLOBALS['TCA'][$tableName]['columns'] as $field => $fieldDefinition) {
1028 if (is_array($fieldDefinition['config'])) {
1029 // Check for flex field
1030 if (isset($fieldDefinition['config']['type']) && $fieldDefinition['config']['type'] === 'flex') {
1031 // Fetch all fields if the is a field of type flex in the table definition because the complete row is passed to
1032 // BackendUtility::getFlexFormDS in the end and might be needed in ds_pointerField or $hookObj->getFlexFormDS_postProcessDS
1033 return '*';
1034 }
1035 // Only fetch this field if it can contain a reference
1036 if ($this->isReferenceField($fieldDefinition['config'])) {
1037 $fields[] = $field;
1038 }
1039 }
1040 }
1041
1042 return implode(',', $fields);
1043 }
1044
1045 /**
1046 * Returns destination path to an upload folder given by $folder
1047 *
1048 * @param string $folder Folder relative to PATH_site
1049 * @return string Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
1050 */
1051 public function destPathFromUploadFolder($folder) {
1052 if (!$folder) {
1053 return substr(PATH_site, 0, -1);
1054 }
1055 return PATH_site . $folder;
1056 }
1057
1058 /**
1059 * Sets error message in the internal error log
1060 *
1061 * @param string $msg Error message
1062 * @return void
1063 */
1064 public function error($msg) {
1065 $this->errorLog[] = $msg;
1066 }
1067
1068 /**
1069 * Updating Index (External API)
1070 *
1071 * @param bool $testOnly If set, only a test
1072 * @param bool $cli_echo If set, output CLI status
1073 * @return array Header and body status content
1074 */
1075 public function updateIndex($testOnly, $cli_echo = FALSE) {
1076 $errors = array();
1077 $tableNames = array();
1078 $recCount = 0;
1079 $tableCount = 0;
1080 $headerContent = $testOnly ? 'Reference Index being TESTED (nothing written, use "--refindex update" to update)' : 'Reference Index being Updated';
1081 if ($cli_echo) {
1082 echo '*******************************************' . LF . $headerContent . LF . '*******************************************' . LF;
1083 }
1084 // Traverse all tables:
1085 foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
1086 if (isset(static::$nonRelationTables[$tableName])) {
1087 continue;
1088 }
1089 // Traverse all records in tables, including deleted records:
1090 $fieldNames = (BackendUtility::isTableWorkspaceEnabled($tableName) ? 'uid,t3ver_wsid' : 'uid');
1091 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fieldNames, $tableName, '1=1');
1092 if ($GLOBALS['TYPO3_DB']->sql_error()) {
1093 // Table exists in $TCA but does not exist in the database
1094 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);
1095 continue;
1096 }
1097 $tableNames[] = $tableName;
1098 $tableCount++;
1099 $uidList = array(0);
1100 while ($recdat = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1101 /** @var $refIndexObj ReferenceIndex */
1102 $refIndexObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ReferenceIndex::class);
1103 if (isset($recdat['t3ver_wsid'])) {
1104 $refIndexObj->setWorkspaceId($recdat['t3ver_wsid']);
1105 }
1106 $result = $refIndexObj->updateRefIndexTable($tableName, $recdat['uid'], $testOnly);
1107 $uidList[] = $recdat['uid'];
1108 $recCount++;
1109 if ($result['addedNodes'] || $result['deletedNodes']) {
1110 $Err = 'Record ' . $tableName . ':' . $recdat['uid'] . ' had ' . $result['addedNodes'] . ' added indexes and ' . $result['deletedNodes'] . ' deleted indexes';
1111 $errors[] = $Err;
1112 if ($cli_echo) {
1113 echo $Err . LF;
1114 }
1115 }
1116 }
1117 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1118
1119 // Searching lost indexes for this table:
1120 $where = 'tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tableName, 'sys_refindex') . ' AND recuid NOT IN (' . implode(',', $uidList) . ')';
1121 $lostIndexes = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('hash', 'sys_refindex', $where);
1122 $lostIndexesCount = count($lostIndexes);
1123 if ($lostIndexesCount) {
1124 $Err = 'Table ' . $tableName . ' has ' . $lostIndexesCount . ' lost indexes which are now deleted';
1125 $errors[] = $Err;
1126 if ($cli_echo) {
1127 echo $Err . LF;
1128 }
1129 if (!$testOnly) {
1130 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex', $where);
1131 }
1132 }
1133 }
1134 // Searching lost indexes for non-existing tables:
1135 $where = 'tablename NOT IN (' . implode(',', $GLOBALS['TYPO3_DB']->fullQuoteArray($tableNames, 'sys_refindex')) . ')';
1136 $lostTables = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('hash', 'sys_refindex', $where);
1137 $lostTablesCount = count($lostTables);
1138 if ($lostTablesCount) {
1139 $Err = 'Index table hosted ' . $lostTablesCount . ' indexes for non-existing tables, now removed';
1140 $errors[] = $Err;
1141 if ($cli_echo) {
1142 echo $Err . LF;
1143 }
1144 if (!$testOnly) {
1145 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex', $where);
1146 }
1147 }
1148 $errorCount = count($errors);
1149 $recordsCheckedString = $recCount . ' records from ' . $tableCount . ' tables were checked/updated.' . LF;
1150 $flashMessage = GeneralUtility::makeInstance(
1151 FlashMessage::class,
1152 $errorCount ? implode('##LF##', $errors) : 'Index Integrity was perfect!',
1153 $recordsCheckedString,
1154 $errorCount ? FlashMessage::ERROR : FlashMessage::OK
1155 );
1156 $bodyContent = $flashMessage->render();
1157 if ($cli_echo) {
1158 echo $recordsCheckedString . ($errorCount ? 'Updates: ' . $errorCount : 'Index Integrity was perfect!') . LF;
1159 }
1160 if (!$testOnly) {
1161 $registry = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Registry::class);
1162 $registry->set('core', 'sys_refindex_lastUpdate', $GLOBALS['EXEC_TIME']);
1163 }
1164 return array($headerContent, $bodyContent, $errorCount);
1165 }
1166
1167 /**
1168 * @return RelationHandler
1169 */
1170 protected function getRelationHandler() {
1171 return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
1172 }
1173
1174 }