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