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