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