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