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