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