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