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