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