Implemented an override of allowed language per workspace. This is an expert feature...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_refindex.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2009 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
64
65
66 /**
67 * Reference index processing and relation extraction
68 *
69 * NOTICE: When the reference index is updated for an offline version the results may not be correct.
70 * First, lets assumed that the reference update happens in LIVE workspace (ALWAYS update from Live workspace if you analyse whole database!)
71 * 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.
72 * 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!
73 * 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?
74 * Anyway, I just wanted to document this finding - I don't think we can find a solution for it. And its very TemplaVoila specific.
75 *
76 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
77 * @package TYPO3
78 * @subpackage t3lib
79 */
80 class t3lib_refindex {
81
82 var $temp_flexRelations = array();
83 var $errorLog = array();
84 var $WSOL = FALSE;
85 var $relations = array();
86
87 var $words_strings = array();
88 var $words = array();
89
90 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.
91
92
93 /**
94 * Call this function to update the sys_refindex table for a record (even one just deleted)
95 * 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.
96 *
97 * @param string Table name
98 * @param integer UID of record
99 * @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.
100 * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
101 */
102 function updateRefIndexTable($table,$uid,$testOnly=FALSE) {
103
104 // First, secure that the index table is not updated with workspace tainted relations:
105 $this->WSOL = FALSE;
106
107 // Init:
108 $result = array(
109 'keptNodes' => 0,
110 'deletedNodes' => 0,
111 'addedNodes' => 0
112 );
113
114 // Get current index from Database:
115 $currentRels = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
116 '*',
117 'sys_refindex',
118 'tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table,'sys_refindex').
119 ' AND recuid='.intval($uid),
120 '','','','hash'
121 );
122
123 // First, test to see if the record exists (including deleted-flagged)
124 if (t3lib_BEfunc::getRecordRaw($table,'uid='.intval($uid),'uid')) {
125
126 // Then, get relations:
127 $relations = $this->generateRefIndexData($table,$uid);
128
129 if (is_array($relations)) {
130
131 // Traverse the generated index:
132 foreach($relations as $k => $datRec) {
133 $relations[$k]['hash'] = md5(implode('///',$relations[$k]).'///'.$this->hashVersion);
134
135 // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
136 if (isset($currentRels[$relations[$k]['hash']])) {
137 unset($currentRels[$relations[$k]['hash']]);
138 $result['keptNodes']++;
139 $relations[$k]['_ACTION'] = 'KEPT';
140 } else {
141 // If new, add it:
142 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex',$relations[$k]);
143 $result['addedNodes']++;
144 $relations[$k]['_ACTION'] = 'ADDED';
145 }
146 }
147
148 $result['relations'] = $relations;
149 } else return FALSE; // Weird mistake I would say...
150
151 // Words:
152 if (!$testOnly) $this->wordIndexing($table,$uid);
153 }
154
155 // If any old are left, remove them:
156 if (count($currentRels)) {
157 $hashList = array_keys($currentRels);
158 if (count($hashList)) {
159 $result['deletedNodes'] = count($hashList);
160 $result['deletedNodes_hashList'] = implode(',',$hashList);
161 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex','hash IN ('.implode(',',$GLOBALS['TYPO3_DB']->fullQuoteArray($hashList,'sys_refindex')).')');
162 }
163 }
164
165 return $result;
166 }
167
168 /**
169 * Returns array of arrays with an index of all references found in record from table/uid
170 * If the result is used to update the sys_refindex table then ->WSOL must NOT be true (no workspace overlay anywhere!)
171 *
172 * @param string Table name from $TCA
173 * @param integer Record UID
174 * @return array Index Rows
175 */
176 function generateRefIndexData($table,$uid) {
177 global $TCA;
178
179 if (isset($TCA[$table])) {
180 // Get raw record from DB:
181 list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$table,'uid='.intval($uid));
182
183 if (is_array($record)) {
184
185 // Initialize:
186 $this->words_strings = array();
187 $this->words = array();
188
189 // Deleted:
190 $deleted = $TCA[$table]['ctrl']['delete'] ? ($record[$TCA[$table]['ctrl']['delete']]?1:0) : 0;
191
192 // Get all relations from record:
193 $dbrels = $this->getRelations($table,$record);
194
195 // Traverse those relations, compile records to insert in table:
196 $this->relations = array();
197 foreach($dbrels as $fieldname => $dat) {
198
199 // Based on type,
200 switch((string)$dat['type']) {
201 case 'db':
202 $this->createEntryData_dbRels($table,$uid,$fieldname,'',$deleted,$dat['itemArray']);
203 break;
204 case 'file_reference':
205 case 'file':
206 $this->createEntryData_fileRels($table,$uid,$fieldname,'',$deleted,$dat['newValueFiles']);
207 break;
208 case 'flex':
209 // DB references:
210 if (is_array($dat['flexFormRels']['db'])) {
211 foreach($dat['flexFormRels']['db'] as $flexpointer => $subList) {
212 $this->createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$subList);
213 }
214 }
215 // File references (NOT TESTED!)
216 if (is_array($dat['flexFormRels']['file'])) { // Not tested
217 foreach($dat['flexFormRels']['file'] as $flexpointer => $subList) {
218 $this->createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$subList);
219 }
220 }
221 // Soft references in flexforms (NOT TESTED!)
222 if (is_array($dat['flexFormRels']['softrefs'])) {
223 foreach($dat['flexFormRels']['softrefs'] as $flexpointer => $subList) {
224 $this->createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$subList['keys']);
225 }
226 }
227 break;
228 }
229
230 // Softreferences in the field:
231 if (is_array($dat['softrefs'])) {
232 $this->createEntryData_softreferences($table,$uid,$fieldname,'',$deleted,$dat['softrefs']['keys']);
233 }
234 }
235
236 // Word indexing:
237 t3lib_div::loadTCA($table);
238 foreach($TCA[$table]['columns'] as $field => $conf) {
239 if (t3lib_div::inList('input,text',$conf['config']['type']) && strcmp($record[$field],'') && !t3lib_div::testInt($record[$field])) {
240 $this->words_strings[$field] = $record[$field];
241 }
242 }
243
244 return $this->relations;
245 }
246 }
247 }
248
249 /**
250 * Create array with field/value pairs ready to insert in database.
251 * The "hash" field is a fingerprint value across this table.
252 *
253 * @param string Tablename of source record (where reference is located)
254 * @param integer UID of source record (where reference is located)
255 * @param string Fieldname of source record (where reference is located)
256 * @param string Pointer to location inside flexform structure where reference is located in [field]
257 * @param integer Whether record is deleted-flagged or not
258 * @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.
259 * @param integer For database references; The UID of the record (zero "ref_table" is "_FILE" or "_STRING")
260 * @param string For "_FILE" or "_STRING" references: The filepath (relative to PATH_site or absolute) or other string.
261 * @param integer The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
262 * @param string If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
263 * @param string Soft reference ID for key. Might be useful for replace operations.
264 * @return array Array record to insert into table.
265 */
266 function createEntryData($table,$uid,$field,$flexpointer,$deleted,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='') {
267 return array(
268 'tablename' => $table,
269 'recuid' => $uid,
270 'field' => $field,
271 'flexpointer' => $flexpointer,
272 'softref_key' => $softref_key,
273 'softref_id' => $softref_id,
274 'sorting' => $sort,
275 'deleted' => $deleted,
276 'ref_table' => $ref_table,
277 'ref_uid' => $ref_uid,
278 'ref_string' => $ref_string,
279 );
280 }
281
282 /**
283 * Enter database references to ->relations array
284 *
285 * @param string [See createEntryData, arg 1]
286 * @param integer [See createEntryData, arg 2]
287 * @param string [See createEntryData, arg 3]
288 * @param string [See createEntryData, arg 4]
289 * @param string [See createEntryData, arg 5]
290 * @param array Data array with databaes relations (table/id)
291 * @return void
292 */
293 function createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$items) {
294 foreach($items as $sort => $i) {
295 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,$i['table'],$i['id'],'',$sort);
296 }
297 }
298
299 /**
300 * Enter file references to ->relations array
301 *
302 * @param string [See createEntryData, arg 1]
303 * @param integer [See createEntryData, arg 2]
304 * @param string [See createEntryData, arg 3]
305 * @param string [See createEntryData, arg 4]
306 * @param string [See createEntryData, arg 5]
307 * @param array Data array with file relations
308 * @return void
309 */
310 function createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$items) {
311 foreach($items as $sort => $i) {
312 $filePath = $i['ID_absFile'];
313 if (t3lib_div::isFirstPartOfStr($filePath,PATH_site)) {
314 $filePath = substr($filePath,strlen(PATH_site));
315 }
316 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_FILE',0,$filePath,$sort);
317 }
318 }
319
320 /**
321 * Enter softref references to ->relations array
322 *
323 * @param string [See createEntryData, arg 1]
324 * @param integer [See createEntryData, arg 2]
325 * @param string [See createEntryData, arg 3]
326 * @param string [See createEntryData, arg 4]
327 * @param string [See createEntryData, arg 5]
328 * @param array Data array with soft reference keys
329 * @return void
330 */
331 function createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$keys) {
332 if (is_array($keys)) {
333 foreach($keys as $spKey => $elements) {
334 if (is_array($elements)) {
335 foreach($elements as $subKey => $el) {
336 if (is_array($el['subst'])) {
337 switch((string)$el['subst']['type']) {
338 case 'db':
339 list($tableName,$recordId) = explode(':',$el['subst']['recordRef']);
340 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,$tableName,$recordId,'',-1,$spKey,$subKey);
341 break;
342 case 'file_reference':
343 case 'file':
344 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_FILE',0,$el['subst']['relFileName'],-1,$spKey,$subKey);
345 break;
346 case 'string':
347 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_STRING',0,$el['subst']['tokenValue'],-1,$spKey,$subKey);
348 break;
349 }
350 }
351 }
352 }
353 }
354 }
355 }
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371 /*******************************
372 *
373 * Get relations from table row
374 *
375 *******************************/
376
377 /**
378 * Returns relation information for a $table/$row-array
379 * Traverses all fields in input row which are configured in TCA/columns
380 * It looks for hard relations to files and records in the TCA types "select" and "group"
381 *
382 * @param string Table name
383 * @param array Row from table
384 * @param string Specific field to fetch for.
385 * @return array Array with information about relations
386 * @see export_addRecord()
387 */
388 function getRelations($table,$row,$onlyField='') {
389 global $TCA;
390
391 // Load full table description
392 t3lib_div::loadTCA($table);
393
394 // Initialize:
395 $uid = $row['uid'];
396 $nonFields = explode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,pid');
397
398 $outRow = array();
399 foreach($row as $field => $value) {
400 if (!in_array($field,$nonFields) && is_array($TCA[$table]['columns'][$field]) && (!$onlyField || $onlyField===$field)) {
401 $conf = $TCA[$table]['columns'][$field]['config'];
402
403 // Add files
404 if ($result = $this->getRelations_procFiles($value, $conf, $uid)) {
405 // Creates an entry for the field with all the files:
406 $outRow[$field] = array(
407 'type' => 'file',
408 'newValueFiles' => $result,
409 );
410 }
411
412 // Add DB:
413 if ($result = $this->getRelations_procDB($value, $conf, $uid, $table)) {
414 // Create an entry for the field with all DB relations:
415 $outRow[$field] = array(
416 'type' => 'db',
417 'itemArray' => $result,
418 );
419 }
420
421 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
422 if ($conf['type']=='flex') {
423
424 // Get current value array:
425 // 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()
426 $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $row, $table,'',$this->WSOL);
427 $currentValueArray = t3lib_div::xml2array($value);
428
429 // Traversing the XML structure, processing files:
430 if (is_array($currentValueArray)) {
431 $this->temp_flexRelations = array(
432 'db' => array(),
433 'file' => array(),
434 'softrefs' => array()
435 );
436
437 // Create and call iterator object:
438 $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
439 $flexObj->traverseFlexFormXMLData($table,$field,$row,$this,'getRelations_flexFormCallBack');
440
441 // Create an entry for the field:
442 $outRow[$field] = array(
443 'type' => 'flex',
444 'flexFormRels' => $this->temp_flexRelations,
445 );
446 }
447 }
448
449 // Soft References:
450 if (strlen($value) && $softRefs = t3lib_BEfunc::explodeSoftRefParserList($conf['softref'])) {
451 $softRefValue = $value;
452 foreach($softRefs as $spKey => $spParams) {
453 $softRefObj = t3lib_BEfunc::softRefParserObj($spKey);
454 if (is_object($softRefObj)) {
455 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
456 if (is_array($resultArray)) {
457 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
458 if (strlen($resultArray['content'])) {
459 $softRefValue = $resultArray['content'];
460 }
461 }
462 }
463 }
464
465 if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && strcmp($value,$softRefValue) && strstr($softRefValue,'{softref:')) {
466 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
467 }
468 }
469 }
470 }
471
472 return $outRow;
473 }
474
475 /**
476 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
477 *
478 * @param array Data structure for the current value
479 * @param mixed Current value
480 * @param array Additional configuration used in calling function
481 * @param string Path of value in DS structure
482 * @param object Object reference to caller
483 * @return void
484 * @see t3lib_TCEmain::checkValue_flex_procInData_travDS()
485 */
486 function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, $pObj) {
487 $structurePath = substr($structurePath,5).'/'; // removing "data/" in the beginning of path (which points to location in data array)
488
489 $dsConf = $dsArr['TCEforms']['config'];
490
491 // Implode parameter values:
492 list($table, $uid, $field) = array($PA['table'],$PA['uid'],$PA['field']);
493
494 // Add files
495 if ($result = $this->getRelations_procFiles($dataValue, $dsConf, $uid)) {
496
497 // Creates an entry for the field with all the files:
498 $this->temp_flexRelations['file'][$structurePath] = $result;
499 }
500
501 // Add DB:
502 if ($result = $this->getRelations_procDB($dataValue, $dsConf, $uid)) {
503
504 // Create an entry for the field with all DB relations:
505 $this->temp_flexRelations['db'][$structurePath] = $result;
506 }
507
508 // Soft References:
509 if (strlen($dataValue) && $softRefs = t3lib_BEfunc::explodeSoftRefParserList($dsConf['softref'])) {
510 $softRefValue = $dataValue;
511 foreach($softRefs as $spKey => $spParams) {
512 $softRefObj = t3lib_BEfunc::softRefParserObj($spKey);
513 if (is_object($softRefObj)) {
514 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
515 if (is_array($resultArray) && is_array($resultArray['elements'])) {
516 $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
517 if (strlen($resultArray['content'])) $softRefValue = $resultArray['content'];
518 }
519 }
520 }
521
522 if (count($this->temp_flexRelations['softrefs']) && strcmp($dataValue,$softRefValue)) {
523 $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
524 }
525 }
526 }
527
528 /**
529 * Check field configuration if it is a file relation field and extract file relations if any
530 *
531 * @param string Field value
532 * @param array Field configuration array of type "TCA/columns"
533 * @param integer Field uid
534 * @return array If field type is OK it will return an array with the files inside. Else false
535 */
536 function getRelations_procFiles($value, $conf, $uid) {
537 // Take care of files...
538 if ($conf['type'] == 'group' && ($conf['internal_type'] == 'file' || $conf['internal_type'] == 'file_reference')) {
539
540 // Collect file values in array:
541 if ($conf['MM']) {
542 $theFileValues = array();
543 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
544 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
545
546 foreach($dbAnalysis->itemArray as $somekey => $someval) {
547 if ($someval['id']) {
548 $theFileValues[] = $someval['id'];
549 }
550 }
551 } else {
552 $theFileValues = explode(',',$value);
553 }
554
555 // Traverse the files and add them:
556 $uploadFolder = $conf['internal_type'] == 'file' ? $conf['uploadfolder'] : '';
557 $dest = $this->destPathFromUploadFolder($uploadFolder);
558 $newValue = array();
559 $newValueFiles = array();
560
561 foreach($theFileValues as $file) {
562 if (trim($file)) {
563 $realFile = $dest.'/'.trim($file);
564 # if (@is_file($realFile)) { // Now, the refernece index should NOT look if files exist - just faithfully include them if they are in the records!
565 $newValueFiles[] = array(
566 'filename' => basename($file),
567 'ID' => md5($realFile),
568 'ID_absFile' => $realFile
569 ); // the order should be preserved here because.. (?)
570 # } else $this->error('Missing file: '.$realFile);
571 }
572 }
573
574 return $newValueFiles;
575 }
576 }
577
578 /**
579 * Check field configuration if it is a DB relation field and extract DB relations if any
580 *
581 * @param string Field value
582 * @param array Field configuration array of type "TCA/columns"
583 * @param integer Field uid
584 * @param string Table name
585 * @return array If field type is OK it will return an array with the database relations. Else false
586 */
587 function getRelations_procDB($value, $conf, $uid, $table = '') {
588
589 // DB record lists:
590 if ($this->isReferenceField($conf)) {
591 $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
592 $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
593
594 if($conf['MM_opposite_field']) {
595 return array();
596 }
597
598 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
599 $dbAnalysis->start($value,$allowedTables,$conf['MM'],$uid,$table,$conf);
600
601 return $dbAnalysis->itemArray;
602 }
603 }
604
605
606
607
608
609
610
611
612
613
614
615
616 /*******************************
617 *
618 * Setting values
619 *
620 *******************************/
621
622 /**
623 * Setting the value of a reference or removing it completely.
624 * Usage: For lowlevel clean up operations!
625 * 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.
626 * 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.
627 * 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!
628 * To ensure proper working only admin-BE_USERS in live workspace should use this function
629 *
630 * @param string 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
631 * @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
632 * @param boolean Return $dataArray only, do not submit it to database.
633 * @param boolean If set, it will bypass check for workspace-zero and admin user
634 * @return string If a return string, that carries an error message, otherwise false (=OK) (except if $returnDataArray is set!)
635 */
636 function setReferenceValue($hash,$newValue,$returnDataArray=FALSE,$bypassWorkspaceAdminCheck=FALSE) {
637
638 if (($GLOBALS['BE_USER']->workspace===0 && $GLOBALS['BE_USER']->isAdmin()) || $bypassWorkspaceAdminCheck) {
639
640 // Get current index from Database:
641 list($refRec) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
642 '*',
643 'sys_refindex',
644 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash,'sys_refindex')
645 );
646
647 // Check if reference existed.
648 if (is_array($refRec)) {
649 if ($GLOBALS['TCA'][$refRec['tablename']]) {
650
651 // Get that record from database:
652 list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$refRec['tablename'],'uid='.intval($refRec['recuid']));
653
654 if (is_array($record)) {
655
656 // Get all relations from record, filter with fieldname:
657 $dbrels = $this->getRelations($refRec['tablename'],$record,$refRec['field']);
658 if ($dat = $dbrels[$refRec['field']]) {
659
660 // Initialize data array that is to be sent to TCEmain afterwards:
661 $dataArray = array();
662
663 // Based on type,
664 switch((string)$dat['type']) {
665 case 'db':
666 $error = $this->setReferenceValue_dbRels($refRec,$dat['itemArray'],$newValue,$dataArray);
667 if ($error) return $error;
668 break;
669 case 'file_reference':
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 if (!$folder) {
978 return substr(PATH_site, 0, -1);
979 }
980 return PATH_site.$folder;
981 }
982
983 /**
984 * Sets error message in the internal error log
985 *
986 * @param string Error message
987 * @return void
988 */
989 function error($msg) {
990 $this->errorLog[]=$msg;
991 }
992
993 /**
994 * Updating Index (External API)
995 *
996 * @param boolean If set, only a test
997 * @param boolean If set, output CLI status
998 * @return array Header and body status content
999 */
1000 function updateIndex($testOnly,$cli_echo=FALSE) {
1001 global $TCA, $TYPO3_DB;
1002
1003 $errors = array();
1004 $tableNames = array();
1005 $recCount=0;
1006 $tableCount=0;
1007
1008 $headerContent = $testOnly ? 'Reference Index being TESTED (nothing written, use "-e" to update)' : 'Reference Index being Updated';
1009 if ($cli_echo) echo
1010 '*******************************************'.chr(10).
1011 $headerContent.chr(10).
1012 '*******************************************'.chr(10);
1013
1014 // Traverse all tables:
1015 foreach ($TCA as $tableName => $cfg) {
1016 $tableNames[] = $tableName;
1017 $tableCount++;
1018
1019 // Traverse all records in tables, including deleted records:
1020 $allRecs = $TYPO3_DB->exec_SELECTgetRows('uid',$tableName,'1=1'); //.t3lib_BEfunc::deleteClause($tableName)
1021 $uidList = array(0);
1022 foreach ($allRecs as $recdat) {
1023 $refIndexObj = t3lib_div::makeInstance('t3lib_refindex');
1024 $result = $refIndexObj->updateRefIndexTable($tableName,$recdat['uid'],$testOnly);
1025 $uidList[]= $recdat['uid'];
1026 $recCount++;
1027
1028 if ($result['addedNodes'] || $result['deletedNodes']) {
1029 $Err = 'Record '.$tableName.':'.$recdat['uid'].' had '.$result['addedNodes'].' added indexes and '.$result['deletedNodes'].' deleted indexes';
1030 $errors[]= $Err;
1031 if ($cli_echo) echo $Err.chr(10);
1032 #$errors[] = t3lib_div::view_array($result);
1033 }
1034 }
1035
1036 // Searching lost indexes for this table:
1037 $where = 'tablename='.$TYPO3_DB->fullQuoteStr($tableName,'sys_refindex').' AND recuid NOT IN ('.implode(',',$uidList).')';
1038 $lostIndexes = $TYPO3_DB->exec_SELECTgetRows('hash','sys_refindex',$where);
1039 if (count($lostIndexes)) {
1040 $Err = 'Table '.$tableName.' has '.count($lostIndexes).' lost indexes which are now deleted';
1041 $errors[]= $Err;
1042 if ($cli_echo) echo $Err.chr(10);
1043 if (!$testOnly) $TYPO3_DB->exec_DELETEquery('sys_refindex',$where);
1044 }
1045 }
1046
1047 // Searching lost indexes for non-existing tables:
1048 $where = 'tablename NOT IN ('.implode(',',$TYPO3_DB->fullQuoteArray($tableNames,'sys_refindex')).')';
1049 $lostTables = $TYPO3_DB->exec_SELECTgetRows('hash','sys_refindex',$where);
1050 if (count($lostTables)) {
1051 $Err = 'Index table hosted '.count($lostTables).' indexes for non-existing tables, now removed';
1052 $errors[]= $Err;
1053 if ($cli_echo) echo $Err.chr(10);
1054 if (!$testOnly) $TYPO3_DB->exec_DELETEquery('sys_refindex',$where);
1055 }
1056
1057 $testedHowMuch = $recCount.' records from '.$tableCount.' tables were checked/updated.'.chr(10);
1058
1059 $bodyContent = $testedHowMuch.(count($errors)?implode(chr(10),$errors):'Index Integrity was perfect!');
1060 if ($cli_echo) echo $testedHowMuch.(count($errors)?'Updates: '.count($errors):'Index Integrity was perfect!').chr(10);
1061
1062 return array($headerContent,$bodyContent,count($errors));
1063 }
1064 }
1065
1066
1067 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_refindex.php']) {
1068 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_refindex.php']);
1069 }
1070
1071 ?>