[BUGFIX] Status Message broken in lowlevel --> Manage Reference Index
[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 // Prevent double references for files and file relations
432 if ($tableName !== 'sys_file' && $tableName !== 'sys_file_reference') {
433 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, $tableName, $recordId, '', -1, $spKey, $subKey);
434 }
435 break;
436 case 'file_reference':
437 // not used (see getRelations()), but fallback to file
438 case 'file':
439 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_FILE', 0, $el['subst']['relFileName'], -1, $spKey, $subKey);
440 break;
441 case 'string':
442 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_STRING', 0, $el['subst']['tokenValue'], -1, $spKey, $subKey);
443 break;
444 }
445 }
446 }
447 }
448 }
449 }
450 }
451
452 /*******************************
453 *
454 * Get relations from table row
455 *
456 *******************************/
457 /**
458 * Returns relation information for a $table/$row-array
459 * Traverses all fields in input row which are configured in TCA/columns
460 * It looks for hard relations to files and records in the TCA types "select" and "group"
461 *
462 * @param string $table Table name
463 * @param array $row Row from table
464 * @param string $onlyField Specific field to fetch for.
465 * @return array Array with information about relations
466 * @see export_addRecord()
467 */
468 public function getRelations($table, $row, $onlyField = '') {
469 // Initialize:
470 $uid = $row['uid'];
471 $outRow = array();
472 foreach ($row as $field => $value) {
473 if (!isset(static::$nonRelationFields[$field]) && is_array($GLOBALS['TCA'][$table]['columns'][$field]) && (!$onlyField || $onlyField === $field)) {
474 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
475 // Add files
476 $resultsFromFiles = $this->getRelations_procFiles($value, $conf, $uid);
477 if (!empty($resultsFromFiles)) {
478 // We have to fill different arrays here depending on the result.
479 // internal_type file is still a relation of type file and
480 // since http://forge.typo3.org/issues/49538 internal_type file_reference
481 // is a database relation to a sys_file record
482 $fileResultsFromFiles = array();
483 $dbResultsFromFiles = array();
484 foreach ($resultsFromFiles as $resultFromFiles) {
485 if (isset($resultFromFiles['table']) && $resultFromFiles['table'] === 'sys_file') {
486 $dbResultsFromFiles[] = $resultFromFiles;
487 } else {
488 // Creates an entry for the field with all the files:
489 $fileResultsFromFiles[] = $resultFromFiles;
490 }
491 }
492 if (!empty($fileResultsFromFiles)) {
493 $outRow[$field] = array(
494 'type' => 'file',
495 'newValueFiles' => $fileResultsFromFiles
496 );
497 }
498 if (!empty($dbResultsFromFiles)) {
499 $outRow[$field] = array(
500 'type' => 'db',
501 'itemArray' => $dbResultsFromFiles
502 );
503 }
504 }
505 // Add DB:
506 $resultsFromDatabase = $this->getRelations_procDB($value, $conf, $uid, $table, $field);
507 if (!empty($resultsFromDatabase)) {
508 // Create an entry for the field with all DB relations:
509 $outRow[$field] = array(
510 'type' => 'db',
511 'itemArray' => $resultsFromDatabase
512 );
513 }
514 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
515 if ($conf['type'] == 'flex') {
516 // Get current value array:
517 // 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()
518 $currentValueArray = GeneralUtility::xml2array($value);
519 // Traversing the XML structure, processing files:
520 if (is_array($currentValueArray)) {
521 $this->temp_flexRelations = array(
522 'db' => array(),
523 'file' => array(),
524 'softrefs' => array()
525 );
526 // Create and call iterator object:
527 $flexObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
528 $flexObj->traverseFlexFormXMLData($table, $field, $row, $this, 'getRelations_flexFormCallBack');
529 // Create an entry for the field:
530 $outRow[$field] = array(
531 'type' => 'flex',
532 'flexFormRels' => $this->temp_flexRelations
533 );
534 }
535 }
536 // Soft References:
537 if ((string)$value !== '' && ($softRefs = BackendUtility::explodeSoftRefParserList($conf['softref']))) {
538 $softRefValue = $value;
539 foreach ($softRefs as $spKey => $spParams) {
540 $softRefObj = BackendUtility::softRefParserObj($spKey);
541 if (is_object($softRefObj)) {
542 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
543 if (is_array($resultArray)) {
544 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
545 if ((string)$resultArray['content'] !== '') {
546 $softRefValue = $resultArray['content'];
547 }
548 }
549 }
550 }
551 if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && (string)$value !== (string)$softRefValue && strstr($softRefValue, '{softref:')) {
552 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
553 }
554 }
555 }
556 }
557 return $outRow;
558 }
559
560 /**
561 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
562 *
563 * @param array $dsArr Data structure for the current value
564 * @param mixed $dataValue Current value
565 * @param array $PA Additional configuration used in calling function
566 * @param string $structurePath Path of value in DS structure
567 * @param object $pObj Object reference to caller
568 * @return void
569 * @see \TYPO3\CMS\Core\DataHandling\DataHandler::checkValue_flex_procInData_travDS()
570 */
571 public function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, $pObj) {
572 // Removing "data/" in the beginning of path (which points to location in data array)
573 $structurePath = substr($structurePath, 5) . '/';
574 $dsConf = $dsArr['TCEforms']['config'];
575 // Implode parameter values:
576 list($table, $uid, $field) = array(
577 $PA['table'],
578 $PA['uid'],
579 $PA['field']
580 );
581 // Add files
582 $resultsFromFiles = $this->getRelations_procFiles($dataValue, $dsConf, $uid);
583 if (!empty($resultsFromFiles)) {
584 // We have to fill different arrays here depending on the result.
585 // internal_type file is still a relation of type file and
586 // since http://forge.typo3.org/issues/49538 internal_type file_reference
587 // is a database relation to a sys_file record
588 $fileResultsFromFiles = array();
589 $dbResultsFromFiles = array();
590 foreach ($resultsFromFiles as $resultFromFiles) {
591 if (isset($resultFromFiles['table']) && $resultFromFiles['table'] === 'sys_file') {
592 $dbResultsFromFiles[] = $resultFromFiles;
593 } else {
594 $fileResultsFromFiles[] = $resultFromFiles;
595 }
596 }
597 if (!empty($fileResultsFromFiles)) {
598 $this->temp_flexRelations['file'][$structurePath] = $fileResultsFromFiles;
599 }
600 if (!empty($dbResultsFromFiles)) {
601 $this->temp_flexRelations['db'][$structurePath] = $dbResultsFromFiles;
602 }
603 }
604 // Add DB:
605 $resultsFromDatabase = $this->getRelations_procDB($dataValue, $dsConf, $uid, $table, $field);
606 if (!empty($resultsFromDatabase)) {
607 // Create an entry for the field with all DB relations:
608 $this->temp_flexRelations['db'][$structurePath] = $resultsFromDatabase;
609 }
610 // Soft References:
611 if ((is_array($dataValue) || (string)$dataValue !== '') && $softRefs = BackendUtility::explodeSoftRefParserList($dsConf['softref'])) {
612 $softRefValue = $dataValue;
613 foreach ($softRefs as $spKey => $spParams) {
614 $softRefObj = BackendUtility::softRefParserObj($spKey);
615 if (is_object($softRefObj)) {
616 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
617 if (is_array($resultArray) && is_array($resultArray['elements'])) {
618 $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
619 if ((string)$resultArray['content'] !== '') {
620 $softRefValue = $resultArray['content'];
621 }
622 }
623 }
624 }
625 if (count($this->temp_flexRelations['softrefs']) && (string)$dataValue !== (string)$softRefValue) {
626 $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
627 }
628 }
629 }
630
631 /**
632 * Check field configuration if it is a file relation field and extract file relations if any
633 *
634 * @param string $value Field value
635 * @param array $conf Field configuration array of type "TCA/columns
636 * @param int $uid Field uid
637 * @return bool|array If field type is OK it will return an array with the files inside. Else FALSE
638 */
639 public function getRelations_procFiles($value, $conf, $uid) {
640 if ($conf['type'] !== 'group' || ($conf['internal_type'] !== 'file' && $conf['internal_type'] !== 'file_reference')) {
641 return FALSE;
642 }
643
644 // Collect file values in array:
645 if ($conf['MM']) {
646 $theFileValues = array();
647 $dbAnalysis = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
648 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
649 foreach ($dbAnalysis->itemArray as $someval) {
650 if ($someval['id']) {
651 $theFileValues[] = $someval['id'];
652 }
653 }
654 } else {
655 $theFileValues = explode(',', $value);
656 }
657 // Traverse the files and add them:
658 $uploadFolder = $conf['internal_type'] == 'file' ? $conf['uploadfolder'] : '';
659 $dest = $this->destPathFromUploadFolder($uploadFolder);
660 $newValueFiles = array();
661 foreach ($theFileValues as $file) {
662 if (trim($file)) {
663 $realFile = $dest . '/' . trim($file);
664 $newValueFile = array(
665 'filename' => basename($file),
666 'ID' => md5($realFile),
667 'ID_absFile' => $realFile
668 );
669 // Set sys_file and id for referenced files
670 if ($conf['internal_type'] === 'file_reference') {
671 try {
672 $file = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject($file);
673 if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
674 // For setting this as sys_file relation later, the keys filename, ID and ID_absFile
675 // have not to be included, because the are not evaluated for db relations.
676 $newValueFile = array(
677 'table' => 'sys_file',
678 'id' => $file->getUid()
679 );
680 }
681 } catch (\Exception $e) {
682
683 }
684 }
685 $newValueFiles[] = $newValueFile;
686 }
687 }
688 return $newValueFiles;
689 }
690
691 /**
692 * Check field configuration if it is a DB relation field and extract DB relations if any
693 *
694 * @param string $value Field value
695 * @param array $conf Field configuration array of type "TCA/columns
696 * @param int $uid Field uid
697 * @param string $table Table name
698 * @param string $field Field name
699 * @return array If field type is OK it will return an array with the database relations. Else FALSE
700 */
701 public function getRelations_procDB($value, $conf, $uid, $table = '', $field = '') {
702 // Get IRRE relations
703 if (empty($conf)) {
704 return FALSE;
705 } elseif ($conf['type'] === 'inline' && !empty($conf['foreign_table']) && empty($conf['MM'])) {
706 $dbAnalysis = $this->getRelationHandler();
707 $dbAnalysis->setUseLiveReferenceIds(FALSE);
708 $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
709 return $dbAnalysis->itemArray;
710 // DB record lists:
711 } elseif ($this->isDbReferenceField($conf)) {
712 $allowedTables = $conf['type'] == 'group' ? $conf['allowed'] : $conf['foreign_table'] . ',' . $conf['neg_foreign_table'];
713 if ($conf['MM_opposite_field']) {
714 return array();
715 }
716 $dbAnalysis = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
717 $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
718 return $dbAnalysis->itemArray;
719 } elseif ($conf['type'] == 'inline' && $conf['foreign_table'] == 'sys_file_reference') {
720 // @todo It looks like this was never called before since isDbReferenceField also checks for type 'inline' and any 'foreign_table'
721 $files = (array)$GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid_local', 'sys_file_reference', ('tablenames=\'' . $table . '\' AND fieldname=\'' . $field . '\' AND uid_foreign=' . $uid . ' AND deleted=0'));
722 $fileArray = array();
723 foreach ($files as $fileUid) {
724 $fileArray[] = array(
725 'table' => 'sys_file',
726 'id' => $fileUid['uid_local']
727 );
728 }
729 return $fileArray;
730 } elseif ($conf['type'] == 'input' && isset($conf['wizards']['link']) && $value !== NULL && StringUtility::beginsWith($value, 'file:')) {
731 try {
732 $file = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject($value);
733 } catch (\Exception $e) {
734
735 }
736 if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
737 return array(
738 0 => array(
739 'table' => 'sys_file',
740 'id' => $file->getUid()
741 )
742 );
743 }
744 }
745 }
746
747 /*******************************
748 *
749 * Setting values
750 *
751 *******************************/
752 /**
753 * Setting the value of a reference or removing it completely.
754 * Usage: For lowlevel clean up operations!
755 * 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.
756 * 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.
757 * 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!
758 * To ensure proper working only admin-BE_USERS in live workspace should use this function
759 *
760 * @param string $hash 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
761 * @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
762 * @param bool $returnDataArray Return $dataArray only, do not submit it to database.
763 * @param bool $bypassWorkspaceAdminCheck If set, it will bypass check for workspace-zero and admin user
764 * @return string If a return string, that carries an error message, otherwise FALSE (=OK) (except if $returnDataArray is set!)
765 */
766 public function setReferenceValue($hash, $newValue, $returnDataArray = FALSE, $bypassWorkspaceAdminCheck = FALSE) {
767 if ($GLOBALS['BE_USER']->workspace === 0 && $GLOBALS['BE_USER']->isAdmin() || $bypassWorkspaceAdminCheck) {
768 // Get current index from Database:
769 $refRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_refindex', 'hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'sys_refindex'));
770 // Check if reference existed.
771 if (is_array($refRec)) {
772 if ($GLOBALS['TCA'][$refRec['tablename']]) {
773 // Get that record from database:
774 $record = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', $refRec['tablename'], 'uid=' . (int)$refRec['recuid']);
775 if (is_array($record)) {
776 // Get all relations from record, filter with fieldname:
777 $dbrels = $this->getRelations($refRec['tablename'], $record, $refRec['field']);
778 if ($dat = $dbrels[$refRec['field']]) {
779 // Initialize data array that is to be sent to TCEmain afterwards:
780 $dataArray = array();
781 // Based on type,
782 switch ((string)$dat['type']) {
783 case 'db':
784 $error = $this->setReferenceValue_dbRels($refRec, $dat['itemArray'], $newValue, $dataArray);
785 if ($error) {
786 return $error;
787 }
788 break;
789 case 'file_reference':
790 // not used (see getRelations()), but fallback to file
791 case 'file':
792 $error = $this->setReferenceValue_fileRels($refRec, $dat['newValueFiles'], $newValue, $dataArray);
793 if ($error) {
794 return $error;
795 }
796 break;
797 case 'flex':
798 // DB references:
799 if (is_array($dat['flexFormRels']['db'][$refRec['flexpointer']])) {
800 $error = $this->setReferenceValue_dbRels($refRec, $dat['flexFormRels']['db'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
801 if ($error) {
802 return $error;
803 }
804 }
805 // File references
806 if (is_array($dat['flexFormRels']['file'][$refRec['flexpointer']])) {
807 $this->setReferenceValue_fileRels($refRec, $dat['flexFormRels']['file'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
808 if ($error) {
809 return $error;
810 }
811 }
812 // Soft references in flexforms
813 if ($refRec['softref_key'] && is_array($dat['flexFormRels']['softrefs'][$refRec['flexpointer']]['keys'][$refRec['softref_key']])) {
814 $error = $this->setReferenceValue_softreferences($refRec, $dat['flexFormRels']['softrefs'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
815 if ($error) {
816 return $error;
817 }
818 }
819 break;
820 }
821 // Softreferences in the field:
822 if ($refRec['softref_key'] && is_array($dat['softrefs']['keys'][$refRec['softref_key']])) {
823 $error = $this->setReferenceValue_softreferences($refRec, $dat['softrefs'], $newValue, $dataArray);
824 if ($error) {
825 return $error;
826 }
827 }
828 // Data Array, now ready to sent to TCEmain
829 if ($returnDataArray) {
830 return $dataArray;
831 } else {
832 // Execute CMD array:
833 $tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
834 $tce->stripslashes_values = FALSE;
835 $tce->dontProcessTransformations = TRUE;
836 $tce->bypassWorkspaceRestrictions = TRUE;
837 $tce->bypassFileHandling = TRUE;
838 // Otherwise this cannot update things in deleted records...
839 $tce->bypassAccessCheckForRecords = TRUE;
840 // Check has been done previously that there is a backend user which is Admin and also in live workspace
841 $tce->start($dataArray, array());
842 $tce->process_datamap();
843 // Return errors if any:
844 if (count($tce->errorLog)) {
845 return LF . 'TCEmain:' . implode((LF . 'TCEmain:'), $tce->errorLog);
846 }
847 }
848 }
849 }
850 } else {
851 return 'ERROR: Tablename "' . $refRec['tablename'] . '" was not in TCA!';
852 }
853 } else {
854 return 'ERROR: No reference record with hash="' . $hash . '" was found!';
855 }
856 } else {
857 return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
858 }
859 }
860
861 /**
862 * Setting a value for a reference for a DB field:
863 *
864 * @param array $refRec sys_refindex record
865 * @param array $itemArray Array of references from that field
866 * @param string $newValue Value to substitute current value with (or NULL to unset it)
867 * @param array $dataArray Data array in which the new value is set (passed by reference)
868 * @param string $flexpointer Flexform pointer, if in a flex form field.
869 * @return string Error message if any, otherwise FALSE = OK
870 */
871 public function setReferenceValue_dbRels($refRec, $itemArray, $newValue, &$dataArray, $flexpointer = '') {
872 if ((int)$itemArray[$refRec['sorting']]['id'] === (int)$refRec['ref_uid'] && (string)$itemArray[$refRec['sorting']]['table'] === (string)$refRec['ref_table']) {
873 // Setting or removing value:
874 // Remove value:
875 if ($newValue === NULL) {
876 unset($itemArray[$refRec['sorting']]);
877 } else {
878 list($itemArray[$refRec['sorting']]['table'], $itemArray[$refRec['sorting']]['id']) = explode(':', $newValue);
879 }
880 // Traverse and compile new list of records:
881 $saveValue = array();
882 foreach ($itemArray as $pair) {
883 $saveValue[] = $pair['table'] . '_' . $pair['id'];
884 }
885 // Set in data array:
886 if ($flexpointer) {
887 $flexToolObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
888 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
889 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
890 } else {
891 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
892 }
893 } else {
894 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'] . '"';
895 }
896 }
897
898 /**
899 * Setting a value for a reference for a FILE field:
900 *
901 * @param array $refRec sys_refindex record
902 * @param array $itemArray Array of references from that field
903 * @param string $newValue Value to substitute current value with (or NULL to unset it)
904 * @param array $dataArray Data array in which the new value is set (passed by reference)
905 * @param string $flexpointer Flexform pointer, if in a flex form field.
906 * @return string Error message if any, otherwise FALSE = OK
907 */
908 public function setReferenceValue_fileRels($refRec, $itemArray, $newValue, &$dataArray, $flexpointer = '') {
909 $ID_absFile = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($itemArray[$refRec['sorting']]['ID_absFile']);
910 if ($ID_absFile === (string)$refRec['ref_string'] && $refRec['ref_table'] === '_FILE') {
911 // Setting or removing value:
912 // Remove value:
913 if ($newValue === NULL) {
914 unset($itemArray[$refRec['sorting']]);
915 } else {
916 $itemArray[$refRec['sorting']]['filename'] = $newValue;
917 }
918 // Traverse and compile new list of records:
919 $saveValue = array();
920 foreach ($itemArray as $fileInfo) {
921 $saveValue[] = $fileInfo['filename'];
922 }
923 // Set in data array:
924 if ($flexpointer) {
925 $flexToolObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
926 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
927 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
928 } else {
929 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
930 }
931 } else {
932 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'] . '"';
933 }
934 }
935
936 /**
937 * Setting a value for a soft reference token
938 *
939 * @param array $refRec sys_refindex record
940 * @param array $softref Array of soft reference occurencies
941 * @param string $newValue Value to substitute current value with
942 * @param array $dataArray Data array in which the new value is set (passed by reference)
943 * @param string $flexpointer Flexform pointer, if in a flex form field.
944 * @return string Error message if any, otherwise FALSE = OK
945 */
946 public function setReferenceValue_softreferences($refRec, $softref, $newValue, &$dataArray, $flexpointer = '') {
947 if (is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
948 // Set new value:
949 $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = '' . $newValue;
950 // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
951 foreach ($softref['keys'] as $sfIndexes) {
952 foreach ($sfIndexes as $data) {
953 $softref['tokenizedContent'] = str_replace('{softref:' . $data['subst']['tokenID'] . '}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
954 }
955 }
956 // Set in data array:
957 if (!strstr($softref['tokenizedContent'], '{softref:')) {
958 if ($flexpointer) {
959 $flexToolObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
960 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
961 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], $softref['tokenizedContent']);
962 } else {
963 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
964 }
965 } else {
966 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.)';
967 }
968 } else {
969 return 'ERROR: Soft reference parser key "' . $refRec['softref_key'] . '" or the index "' . $refRec['softref_id'] . '" was not found.';
970 }
971 }
972
973 /*******************************
974 *
975 * Helper functions
976 *
977 *******************************/
978
979 /**
980 * Returns TRUE if the TCA/columns field type is a DB reference field
981 *
982 * @param array $configuration Config array for TCA/columns field
983 * @return bool TRUE if DB reference field (group/db or select with foreign-table)
984 */
985 protected function isDbReferenceField(array $configuration) {
986 return (
987 ($configuration['type'] === 'group' && $configuration['internal_type'] === 'db')
988 || (
989 ($configuration['type'] === 'select' || $configuration['type'] === 'inline')
990 && !empty($configuration['foreign_table'])
991 )
992 );
993 }
994
995 /**
996 * Returns TRUE if the TCA/columns field type is a reference field
997 *
998 * @param array $configuration Config array for TCA/columns field
999 * @return bool TRUE if reference field
1000 */
1001 public function isReferenceField(array $configuration) {
1002 return (
1003 $this->isDbReferenceField($configuration)
1004 ||
1005 ($configuration['type'] === 'group' && ($configuration['internal_type'] === 'file' || $configuration['internal_type'] === 'file_reference')) // getRelations_procFiles
1006 ||
1007 ($configuration['type'] === 'input' && isset($configuration['wizards']['link'])) // getRelations_procDB
1008 ||
1009 $configuration['type'] === 'flex'
1010 ||
1011 isset($configuration['softref'])
1012 ||
1013 (
1014 // @deprecated global soft reference parsers are deprecated since TYPO3 CMS 7 and will be removed in TYPO3 CMS 8
1015 is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])
1016 && !empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])
1017 )
1018 );
1019 }
1020
1021 /**
1022 * Returns all fields of a table which could contain a relation
1023 *
1024 * @param string $tableName Name of the table
1025 * @return string Fields which could contain a relation
1026 */
1027 protected function fetchTableRelationFields($tableName) {
1028 $fields = array();
1029
1030 foreach ($GLOBALS['TCA'][$tableName]['columns'] as $field => $fieldDefinition) {
1031 if (is_array($fieldDefinition['config'])) {
1032 // Check for flex field
1033 if (isset($fieldDefinition['config']['type']) && $fieldDefinition['config']['type'] === 'flex') {
1034 // Fetch all fields if the is a field of type flex in the table definition because the complete row is passed to
1035 // BackendUtility::getFlexFormDS in the end and might be needed in ds_pointerField or $hookObj->getFlexFormDS_postProcessDS
1036 return '*';
1037 }
1038 // Only fetch this field if it can contain a reference
1039 if ($this->isReferenceField($fieldDefinition['config'])) {
1040 $fields[] = $field;
1041 }
1042 }
1043 }
1044
1045 return implode(',', $fields);
1046 }
1047
1048 /**
1049 * Returns destination path to an upload folder given by $folder
1050 *
1051 * @param string $folder Folder relative to PATH_site
1052 * @return string Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
1053 */
1054 public function destPathFromUploadFolder($folder) {
1055 if (!$folder) {
1056 return substr(PATH_site, 0, -1);
1057 }
1058 return PATH_site . $folder;
1059 }
1060
1061 /**
1062 * Sets error message in the internal error log
1063 *
1064 * @param string $msg Error message
1065 * @return void
1066 */
1067 public function error($msg) {
1068 $this->errorLog[] = $msg;
1069 }
1070
1071 /**
1072 * Updating Index (External API)
1073 *
1074 * @param bool $testOnly If set, only a test
1075 * @param bool $cli_echo If set, output CLI status
1076 * @return array Header and body status content
1077 */
1078 public function updateIndex($testOnly, $cli_echo = FALSE) {
1079 $errors = array();
1080 $tableNames = array();
1081 $recCount = 0;
1082 $tableCount = 0;
1083 $headerContent = $testOnly ? 'Reference Index being TESTED (nothing written, use "--refindex update" to update)' : 'Reference Index being Updated';
1084 if ($cli_echo) {
1085 echo '*******************************************' . LF . $headerContent . LF . '*******************************************' . LF;
1086 }
1087 // Traverse all tables:
1088 foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
1089 // Traverse all records in tables, including deleted records:
1090 $fieldNames = (BackendUtility::isTableWorkspaceEnabled($tableName) ? 'uid,t3ver_wsid' : 'uid');
1091 $allRecs = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fieldNames, $tableName, '1=1');
1092 if (!is_array($allRecs)) {
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 foreach ($allRecs as $recdat) {
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 // Searching lost indexes for this table:
1118 $where = 'tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tableName, 'sys_refindex') . ' AND recuid NOT IN (' . implode(',', $uidList) . ')';
1119 $lostIndexes = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('hash', 'sys_refindex', $where);
1120 $lostIndexesCount = count($lostIndexes);
1121 if ($lostIndexesCount) {
1122 $Err = 'Table ' . $tableName . ' has ' . $lostIndexesCount . ' lost indexes which are now deleted';
1123 $errors[] = $Err;
1124 if ($cli_echo) {
1125 echo $Err . LF;
1126 }
1127 if (!$testOnly) {
1128 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex', $where);
1129 }
1130 }
1131 }
1132 // Searching lost indexes for non-existing tables:
1133 $where = 'tablename NOT IN (' . implode(',', $GLOBALS['TYPO3_DB']->fullQuoteArray($tableNames, 'sys_refindex')) . ')';
1134 $lostTables = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('hash', 'sys_refindex', $where);
1135 $lostTablesCount = count($lostTables);
1136 if ($lostTablesCount) {
1137 $Err = 'Index table hosted ' . $lostTablesCount . ' indexes for non-existing tables, now removed';
1138 $errors[] = $Err;
1139 if ($cli_echo) {
1140 echo $Err . LF;
1141 }
1142 if (!$testOnly) {
1143 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex', $where);
1144 }
1145 }
1146 $errorCount = count($errors);
1147 $recordsCheckedString = $recCount . ' records from ' . $tableCount . ' tables were checked/updated.' . LF;
1148 $flashMessage = GeneralUtility::makeInstance(
1149 FlashMessage::class,
1150 $errorCount ? implode('##LF##', $errors) : 'Index Integrity was perfect!',
1151 $recordsCheckedString,
1152 $errorCount ? FlashMessage::ERROR : FlashMessage::OK
1153 );
1154 $bodyContent = $flashMessage->render();
1155 if ($cli_echo) {
1156 echo $recordsCheckedString . ($errorCount ? 'Updates: ' . $errorCount : 'Index Integrity was perfect!') . LF;
1157 }
1158 if (!$testOnly) {
1159 $registry = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Registry::class);
1160 $registry->set('core', 'sys_refindex_lastUpdate', $GLOBALS['EXEC_TIME']);
1161 }
1162 return array($headerContent, $bodyContent, $errorCount);
1163 }
1164
1165 /**
1166 * @return RelationHandler
1167 */
1168 protected function getRelationHandler() {
1169 return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
1170 }
1171
1172 }