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