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