[BUGFIX] Fields of type file_reference are not properly indexed
[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 textfile 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=' . intval($uid), '', '', '', 'hash');
104 // First, test to see if the record exists (including deleted-flagged)
105 if (BackendUtility::getRecordRaw($table, 'uid=' . intval($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=' . intval($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
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']) && strcmp($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 = substr($filePath, strlen(PATH_site));
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 array $keys Data array with soft reference keys
299 * @return void
300 * @todo Define visibility
301 */
302 public function createEntryData_softreferences($table, $uid, $fieldname, $flexpointer, $deleted, $keys) {
303 if (is_array($keys)) {
304 foreach ($keys as $spKey => $elements) {
305 if (is_array($elements)) {
306 foreach ($elements as $subKey => $el) {
307 if (is_array($el['subst'])) {
308 switch ((string) $el['subst']['type']) {
309 case 'db':
310 list($tableName, $recordId) = explode(':', $el['subst']['recordRef']);
311 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, $tableName, $recordId, '', -1, $spKey, $subKey);
312 break;
313 case 'file_reference':
314
315 case 'file':
316 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_FILE', 0, $el['subst']['relFileName'], -1, $spKey, $subKey);
317 break;
318 case 'string':
319 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_STRING', 0, $el['subst']['tokenValue'], -1, $spKey, $subKey);
320 break;
321 }
322 }
323 }
324 }
325 }
326 }
327 }
328
329 /*******************************
330 *
331 * Get relations from table row
332 *
333 *******************************/
334 /**
335 * Returns relation information for a $table/$row-array
336 * Traverses all fields in input row which are configured in TCA/columns
337 * It looks for hard relations to files and records in the TCA types "select" and "group"
338 *
339 * @param string $table Table name
340 * @param array $row Row from table
341 * @param string $onlyField Specific field to fetch for.
342 * @return array Array with information about relations
343 * @see export_addRecord()
344 * @todo Define visibility
345 */
346 public function getRelations($table, $row, $onlyField = '') {
347 // Initialize:
348 $uid = $row['uid'];
349 $nonFields = explode(',', 'uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,pid');
350 $outRow = array();
351 foreach ($row as $field => $value) {
352 if (!in_array($field, $nonFields) && is_array($GLOBALS['TCA'][$table]['columns'][$field]) && (!$onlyField || $onlyField === $field)) {
353 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
354 // Add files
355 if ($result = $this->getRelations_procFiles($value, $conf, $uid)) {
356 // Creates an entry for the field with all the files:
357 $outRow[$field] = array(
358 'type' => 'db',
359 'itemArray' => $result
360 );
361 }
362 // Add DB:
363 if ($result = $this->getRelations_procDB($value, $conf, $uid, $table, $field)) {
364 // Create an entry for the field with all DB relations:
365 $outRow[$field] = array(
366 'type' => 'db',
367 'itemArray' => $result
368 );
369 }
370 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
371 if ($conf['type'] == 'flex') {
372 // Get current value array:
373 // 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()
374 $dataStructArray = BackendUtility::getFlexFormDS($conf, $row, $table, $field, $this->WSOL);
375 $currentValueArray = GeneralUtility::xml2array($value);
376 // Traversing the XML structure, processing files:
377 if (is_array($currentValueArray)) {
378 $this->temp_flexRelations = array(
379 'db' => array(),
380 'file' => array(),
381 'softrefs' => array()
382 );
383 // Create and call iterator object:
384 $flexObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\FlexForm\\FlexFormTools');
385 $flexObj->traverseFlexFormXMLData($table, $field, $row, $this, 'getRelations_flexFormCallBack');
386 // Create an entry for the field:
387 $outRow[$field] = array(
388 'type' => 'flex',
389 'flexFormRels' => $this->temp_flexRelations
390 );
391 }
392 }
393 // Soft References:
394 if (strlen($value) && ($softRefs = BackendUtility::explodeSoftRefParserList($conf['softref']))) {
395 $softRefValue = $value;
396 foreach ($softRefs as $spKey => $spParams) {
397 $softRefObj = BackendUtility::softRefParserObj($spKey);
398 if (is_object($softRefObj)) {
399 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
400 if (is_array($resultArray)) {
401 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
402 if (strlen($resultArray['content'])) {
403 $softRefValue = $resultArray['content'];
404 }
405 }
406 }
407 }
408 if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && strcmp($value, $softRefValue) && strstr($softRefValue, '{softref:')) {
409 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
410 }
411 }
412 }
413 }
414 return $outRow;
415 }
416
417 /**
418 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
419 *
420 * @param array $dsArr Data structure for the current value
421 * @param mixed $dataValue Current value
422 * @param array $PA Additional configuration used in calling function
423 * @param string $structurePath Path of value in DS structure
424 * @param object $pObj Object reference to caller
425 * @return void
426 * @see \TYPO3\CMS\Core\DataHandling\DataHandler::checkValue_flex_procInData_travDS()
427 * @todo Define visibility
428 */
429 public function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, $pObj) {
430 // Removing "data/" in the beginning of path (which points to location in data array)
431 $structurePath = substr($structurePath, 5) . '/';
432 $dsConf = $dsArr['TCEforms']['config'];
433 // Implode parameter values:
434 list($table, $uid, $field) = array($PA['table'], $PA['uid'], $PA['field']);
435 // Add files
436 if ($result = $this->getRelations_procFiles($dataValue, $dsConf, $uid)) {
437 // Creates an entry for the field with all the files:
438 $this->temp_flexRelations['file'][$structurePath] = $result;
439 }
440 // Add DB:
441 if ($result = $this->getRelations_procDB($dataValue, $dsConf, $uid, $field)) {
442 // Create an entry for the field with all DB relations:
443 $this->temp_flexRelations['db'][$structurePath] = $result;
444 }
445 // Soft References:
446 if (strlen($dataValue) && ($softRefs = BackendUtility::explodeSoftRefParserList($dsConf['softref']))) {
447 $softRefValue = $dataValue;
448 foreach ($softRefs as $spKey => $spParams) {
449 $softRefObj = BackendUtility::softRefParserObj($spKey);
450 if (is_object($softRefObj)) {
451 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
452 if (is_array($resultArray) && is_array($resultArray['elements'])) {
453 $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
454 if (strlen($resultArray['content'])) {
455 $softRefValue = $resultArray['content'];
456 }
457 }
458 }
459 }
460 if (count($this->temp_flexRelations['softrefs']) && strcmp($dataValue, $softRefValue)) {
461 $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
462 }
463 }
464 }
465
466 /**
467 * Check field configuration if it is a file relation field and extract file relations if any
468 *
469 * @param string $value Field value
470 * @param array $conf Field configuration array of type "TCA/columns
471 * @param integer $uid Field uid
472 * @return array If field type is OK it will return an array with the files inside. Else FALSE
473 * @todo Define visibility
474 */
475 public function getRelations_procFiles($value, $conf, $uid) {
476 if ($conf['type'] !== 'group' || ($conf['internal_type'] !== 'file' && $conf['internal_type'] !== 'file_reference')) {
477 return FALSE;
478 }
479
480 // Collect file values in array:
481 if ($conf['MM']) {
482 $theFileValues = array();
483 $dbAnalysis = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\RelationHandler');
484 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
485 foreach ($dbAnalysis->itemArray as $someval) {
486 if ($someval['id']) {
487 $theFileValues[] = $someval['id'];
488 }
489 }
490 } else {
491 $theFileValues = explode(',', $value);
492 }
493 // Traverse the files and add them:
494 $uploadFolder = $conf['internal_type'] == 'file' ? $conf['uploadfolder'] : '';
495 $dest = $this->destPathFromUploadFolder($uploadFolder);
496 $newValueFiles = array();
497 foreach ($theFileValues as $file) {
498 if (trim($file)) {
499 $realFile = $dest . '/' . trim($file);
500 $newValueFile = array(
501 'filename' => basename($file),
502 'ID' => md5($realFile),
503 'ID_absFile' => $realFile
504 );
505 // Set sys_file and id for referenced files
506 if ($conf['internal_type'] === 'file_reference') {
507 try {
508 $file = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject($file);
509 if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
510 $newValueFile['table'] = 'sys_file';
511 $newValueFile['id'] = $file->getUid();
512 }
513 } catch (\Exception $e) {
514
515 }
516 }
517 $newValueFiles[] = $newValueFile;
518 }
519 }
520 return $newValueFiles;
521 }
522
523 /**
524 * Check field configuration if it is a DB relation field and extract DB relations if any
525 *
526 * @param string $value Field value
527 * @param array $conf Field configuration array of type "TCA/columns
528 * @param integer $uid Field uid
529 * @param string $table Table name
530 * @param string $field Field name
531 * @return array If field type is OK it will return an array with the database relations. Else FALSE
532 * @todo Define visibility
533 */
534 public function getRelations_procDB($value, $conf, $uid, $table = '', $field = '') {
535 // DB record lists:
536 if ($this->isReferenceField($conf)) {
537 $allowedTables = $conf['type'] == 'group' ? $conf['allowed'] : $conf['foreign_table'] . ',' . $conf['neg_foreign_table'];
538 if ($conf['MM_opposite_field']) {
539 return array();
540 }
541 $dbAnalysis = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\RelationHandler');
542 $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
543 return $dbAnalysis->itemArray;
544 } elseif ($conf['type'] == 'inline' && $conf['foreign_table'] == 'sys_file_reference') {
545 $files = (array) $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid_local', 'sys_file_reference', ('tablenames=\'' . $table . '\' AND fieldname=\'' . $field . '\' AND uid_foreign=' . $uid));
546 $fileArray = array('0' => array());
547 foreach ($files as $fileUid) {
548 $fileArray[0][] = array('table' => 'sys_file', 'id' => $fileUid);
549 }
550 return $fileArray;
551 } elseif ($conf['type'] == 'input' && isset($conf['wizards']['link']) && trim($value)) {
552 try {
553 $file = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject($value);
554 } catch (\Exception $e) {
555
556 }
557 if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
558 return array(
559 0 => array(
560 'table' => 'sys_file',
561 'id' => $file->getUid()
562 )
563 );
564 }
565 }
566 }
567
568 /*******************************
569 *
570 * Setting values
571 *
572 *******************************/
573 /**
574 * Setting the value of a reference or removing it completely.
575 * Usage: For lowlevel clean up operations!
576 * 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.
577 * 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.
578 * 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!
579 * To ensure proper working only admin-BE_USERS in live workspace should use this function
580 *
581 * @param string $hash 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
582 * @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
583 * @param boolean $returnDataArray Return $dataArray only, do not submit it to database.
584 * @param boolean $bypassWorkspaceAdminCheck If set, it will bypass check for workspace-zero and admin user
585 * @return string If a return string, that carries an error message, otherwise FALSE (=OK) (except if $returnDataArray is set!)
586 * @todo Define visibility
587 */
588 public function setReferenceValue($hash, $newValue, $returnDataArray = FALSE, $bypassWorkspaceAdminCheck = FALSE) {
589 if ($GLOBALS['BE_USER']->workspace === 0 && $GLOBALS['BE_USER']->isAdmin() || $bypassWorkspaceAdminCheck) {
590 // Get current index from Database:
591 $refRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_refindex', 'hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'sys_refindex'));
592 // Check if reference existed.
593 if (is_array($refRec)) {
594 if ($GLOBALS['TCA'][$refRec['tablename']]) {
595 // Get that record from database:
596 $record = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', $refRec['tablename'], 'uid=' . intval($refRec['recuid']));
597 if (is_array($record)) {
598 // Get all relations from record, filter with fieldname:
599 $dbrels = $this->getRelations($refRec['tablename'], $record, $refRec['field']);
600 if ($dat = $dbrels[$refRec['field']]) {
601 // Initialize data array that is to be sent to TCEmain afterwards:
602 $dataArray = array();
603 // Based on type,
604 switch ((string) $dat['type']) {
605 case 'db':
606 $error = $this->setReferenceValue_dbRels($refRec, $dat['itemArray'], $newValue, $dataArray);
607 if ($error) {
608 return $error;
609 }
610 break;
611 case 'file_reference':
612
613 case 'file':
614 $error = $this->setReferenceValue_fileRels($refRec, $dat['newValueFiles'], $newValue, $dataArray);
615 if ($error) {
616 return $error;
617 }
618 break;
619 case 'flex':
620 // DB references:
621 if (is_array($dat['flexFormRels']['db'][$refRec['flexpointer']])) {
622 $error = $this->setReferenceValue_dbRels($refRec, $dat['flexFormRels']['db'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
623 if ($error) {
624 return $error;
625 }
626 }
627 // File references
628 if (is_array($dat['flexFormRels']['file'][$refRec['flexpointer']])) {
629 $this->setReferenceValue_fileRels($refRec, $dat['flexFormRels']['file'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
630 if ($error) {
631 return $error;
632 }
633 }
634 // Soft references in flexforms
635 if ($refRec['softref_key'] && is_array($dat['flexFormRels']['softrefs'][$refRec['flexpointer']]['keys'][$refRec['softref_key']])) {
636 $error = $this->setReferenceValue_softreferences($refRec, $dat['flexFormRels']['softrefs'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
637 if ($error) {
638 return $error;
639 }
640 }
641 break;
642 }
643 // Softreferences in the field:
644 if ($refRec['softref_key'] && is_array($dat['softrefs']['keys'][$refRec['softref_key']])) {
645 $error = $this->setReferenceValue_softreferences($refRec, $dat['softrefs'], $newValue, $dataArray);
646 if ($error) {
647 return $error;
648 }
649 }
650 // Data Array, now ready to sent to TCEmain
651 if ($returnDataArray) {
652 return $dataArray;
653 } else {
654 // Execute CMD array:
655 $tce = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
656 $tce->stripslashes_values = FALSE;
657 $tce->dontProcessTransformations = TRUE;
658 $tce->bypassWorkspaceRestrictions = TRUE;
659 $tce->bypassFileHandling = TRUE;
660 // Otherwise this cannot update things in deleted records...
661 $tce->bypassAccessCheckForRecords = TRUE;
662 // Check has been done previously that there is a backend user which is Admin and also in live workspace
663 $tce->start($dataArray, array());
664 $tce->process_datamap();
665 // Return errors if any:
666 if (count($tce->errorLog)) {
667 return LF . 'TCEmain:' . implode((LF . 'TCEmain:'), $tce->errorLog);
668 }
669 }
670 }
671 }
672 } else {
673 return 'ERROR: Tablename "' . $refRec['tablename'] . '" was not in TCA!';
674 }
675 } else {
676 return 'ERROR: No reference record with hash="' . $hash . '" was found!';
677 }
678 } else {
679 return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
680 }
681 }
682
683 /**
684 * Setting a value for a reference for a DB field:
685 *
686 * @param array $refRec sys_refindex record
687 * @param array $itemArray Array of references from that field
688 * @param string $newValue Value to substitute current value with (or NULL to unset it)
689 * @param array $dataArray Data array in which the new value is set (passed by reference)
690 * @param string $flexpointer Flexform pointer, if in a flex form field.
691 * @return string Error message if any, otherwise FALSE = OK
692 * @todo Define visibility
693 */
694 public function setReferenceValue_dbRels($refRec, $itemArray, $newValue, &$dataArray, $flexpointer = '') {
695 if (!strcmp($itemArray[$refRec['sorting']]['id'], $refRec['ref_uid']) && !strcmp($itemArray[$refRec['sorting']]['table'], $refRec['ref_table'])) {
696 // Setting or removing value:
697 // Remove value:
698 if ($newValue === NULL) {
699 unset($itemArray[$refRec['sorting']]);
700 } else {
701 list($itemArray[$refRec['sorting']]['table'], $itemArray[$refRec['sorting']]['id']) = explode(':', $newValue);
702 }
703 // Traverse and compile new list of records:
704 $saveValue = array();
705 foreach ($itemArray as $pair) {
706 $saveValue[] = $pair['table'] . '_' . $pair['id'];
707 }
708 // Set in data array:
709 if ($flexpointer) {
710 $flexToolObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\FlexForm\\FlexFormTools');
711 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
712 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
713 } else {
714 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
715 }
716 } else {
717 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'] . '"';
718 }
719 }
720
721 /**
722 * Setting a value for a reference for a FILE field:
723 *
724 * @param array $refRec sys_refindex record
725 * @param array $itemArray Array of references from that field
726 * @param string $newValue Value to substitute current value with (or NULL to unset it)
727 * @param array $dataArray Data array in which the new value is set (passed by reference)
728 * @param string $flexpointer Flexform pointer, if in a flex form field.
729 * @return string Error message if any, otherwise FALSE = OK
730 * @todo Define visibility
731 */
732 public function setReferenceValue_fileRels($refRec, $itemArray, $newValue, &$dataArray, $flexpointer = '') {
733 if (!strcmp(substr($itemArray[$refRec['sorting']]['ID_absFile'], strlen(PATH_site)), $refRec['ref_string']) && !strcmp('_FILE', $refRec['ref_table'])) {
734 // Setting or removing value:
735 // Remove value:
736 if ($newValue === NULL) {
737 unset($itemArray[$refRec['sorting']]);
738 } else {
739 $itemArray[$refRec['sorting']]['filename'] = $newValue;
740 }
741 // Traverse and compile new list of records:
742 $saveValue = array();
743 foreach ($itemArray as $fileInfo) {
744 $saveValue[] = $fileInfo['filename'];
745 }
746 // Set in data array:
747 if ($flexpointer) {
748 $flexToolObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\FlexForm\\FlexFormTools');
749 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
750 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
751 } else {
752 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
753 }
754 } else {
755 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'] . '"';
756 }
757 }
758
759 /**
760 * Setting a value for a soft reference token
761 *
762 * @param array $refRec sys_refindex record
763 * @param array $softref Array of soft reference occurencies
764 * @param string $newValue Value to substitute current value with
765 * @param array $dataArray Data array in which the new value is set (passed by reference)
766 * @param string $flexpointer Flexform pointer, if in a flex form field.
767 * @return string Error message if any, otherwise FALSE = OK
768 * @todo Define visibility
769 */
770 public function setReferenceValue_softreferences($refRec, $softref, $newValue, &$dataArray, $flexpointer = '') {
771 if (is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
772 // Set new value:
773 $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = '' . $newValue;
774 // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
775 foreach ($softref['keys'] as $sfIndexes) {
776 foreach ($sfIndexes as $data) {
777 $softref['tokenizedContent'] = str_replace('{softref:' . $data['subst']['tokenID'] . '}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
778 }
779 }
780 // Set in data array:
781 if (!strstr($softref['tokenizedContent'], '{softref:')) {
782 if ($flexpointer) {
783 $flexToolObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\FlexForm\\FlexFormTools');
784 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
785 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], $softref['tokenizedContent']);
786 } else {
787 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
788 }
789 } else {
790 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.)';
791 }
792 } else {
793 return 'ERROR: Soft reference parser key "' . $refRec['softref_key'] . '" or the index "' . $refRec['softref_id'] . '" was not found.';
794 }
795 }
796
797 /*******************************
798 *
799 * Helper functions
800 *
801 *******************************/
802 /**
803 * Returns TRUE if the TCA/columns field type is a DB reference field
804 *
805 * @param array $conf Config array for TCA/columns field
806 * @return boolean TRUE if DB reference field (group/db or select with foreign-table)
807 * @todo Define visibility
808 */
809 public function isReferenceField($conf) {
810 return $conf['type'] == 'group' && $conf['internal_type'] == 'db' || ($conf['type'] == 'select' || $conf['type'] == 'inline') && $conf['foreign_table'] && $conf['foreign_table'] !== 'sys_file_reference';
811 }
812
813 /**
814 * Returns destination path to an upload folder given by $folder
815 *
816 * @param string $folder Folder relative to PATH_site
817 * @return string Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
818 * @todo Define visibility
819 */
820 public function destPathFromUploadFolder($folder) {
821 if (!$folder) {
822 return substr(PATH_site, 0, -1);
823 }
824 return PATH_site . $folder;
825 }
826
827 /**
828 * Sets error message in the internal error log
829 *
830 * @param string $msg Error message
831 * @return void
832 * @todo Define visibility
833 */
834 public function error($msg) {
835 $this->errorLog[] = $msg;
836 }
837
838 /**
839 * Updating Index (External API)
840 *
841 * @param boolean $testOnly If set, only a test
842 * @param boolean $cli_echo If set, output CLI status
843 * @return array Header and body status content
844 * @todo Define visibility
845 */
846 public function updateIndex($testOnly, $cli_echo = FALSE) {
847 $errors = array();
848 $tableNames = array();
849 $recCount = 0;
850 $tableCount = 0;
851 $headerContent = $testOnly ? 'Reference Index being TESTED (nothing written, use "-e" to update)' : 'Reference Index being Updated';
852 if ($cli_echo) {
853 echo '*******************************************' . LF . $headerContent . LF . '*******************************************' . LF;
854 }
855 // Traverse all tables:
856 foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
857 // Traverse all records in tables, including deleted records:
858 $allRecs = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', $tableName, '1=1');
859 if (!is_array($allRecs)) {
860 // Table exists in $TCA but does not exist in the database
861 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);
862 continue;
863 }
864 $tableNames[] = $tableName;
865 $tableCount++;
866 $uidList = array(0);
867 foreach ($allRecs as $recdat) {
868 $refIndexObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\ReferenceIndex');
869 $result = $refIndexObj->updateRefIndexTable($tableName, $recdat['uid'], $testOnly);
870 $uidList[] = $recdat['uid'];
871 $recCount++;
872 if ($result['addedNodes'] || $result['deletedNodes']) {
873 $Err = 'Record ' . $tableName . ':' . $recdat['uid'] . ' had ' . $result['addedNodes'] . ' added indexes and ' . $result['deletedNodes'] . ' deleted indexes';
874 $errors[] = $Err;
875 if ($cli_echo) {
876 echo $Err . LF;
877 }
878 }
879 }
880 // Searching lost indexes for this table:
881 $where = 'tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tableName, 'sys_refindex') . ' AND recuid NOT IN (' . implode(',', $uidList) . ')';
882 $lostIndexes = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('hash', 'sys_refindex', $where);
883 if (count($lostIndexes)) {
884 $Err = 'Table ' . $tableName . ' has ' . count($lostIndexes) . ' lost indexes which are now deleted';
885 $errors[] = $Err;
886 if ($cli_echo) {
887 echo $Err . LF;
888 }
889 if (!$testOnly) {
890 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex', $where);
891 }
892 }
893 }
894 // Searching lost indexes for non-existing tables:
895 $where = 'tablename NOT IN (' . implode(',', $GLOBALS['TYPO3_DB']->fullQuoteArray($tableNames, 'sys_refindex')) . ')';
896 $lostTables = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('hash', 'sys_refindex', $where);
897 if (count($lostTables)) {
898 $Err = 'Index table hosted ' . count($lostTables) . ' indexes for non-existing tables, now removed';
899 $errors[] = $Err;
900 if ($cli_echo) {
901 echo $Err . LF;
902 }
903 if (!$testOnly) {
904 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex', $where);
905 }
906 }
907 $testedHowMuch = $recCount . ' records from ' . $tableCount . ' tables were checked/updated.' . LF;
908 $bodyContent = $testedHowMuch . (count($errors) ? implode(LF, $errors) : 'Index Integrity was perfect!');
909 if ($cli_echo) {
910 echo $testedHowMuch . (count($errors) ? 'Updates: ' . count($errors) : 'Index Integrity was perfect!') . LF;
911 }
912 if (!$testOnly) {
913 $registry = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
914 $registry->set('core', 'sys_refindex_lastUpdate', $GLOBALS['EXEC_TIME']);
915 }
916 return array($headerContent, $bodyContent, count($errors));
917 }
918
919 }