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