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