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