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