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