* Added reference index table and class. See mail sent to Dev-list
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_refindex.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2005 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 * Reference index processing
29 *
30 * $Id$
31 *
32 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
33 */
34 /**
35 * [CLASS/FUNCTION INDEX of SCRIPT]
36 *
37 *
38 *
39 * 74: class t3lib_refindex
40 * 91: function updateRefIndexTable($table,$uid,$testOnly=FALSE)
41 * 162: function generateRefIndexData($table,$uid)
42 * 235: function createEntryData($table,$uid,$field,$flexpointer,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='')
43 * 260: function createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$items)
44 * 276: function createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$items)
45 * 296: function createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$keys)
46 *
47 * SECTION: Get relations from table row
48 * 351: function getRelations($table,$row)
49 * 456: function getRelations_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $structurePath)
50 * 503: function getRelations_procFiles($value, $conf, $uid)
51 * 553: function getRelations_procDB($value, $conf, $uid)
52 *
53 * SECTION: Helper functions
54 * 590: function isReferenceField($conf)
55 * 600: function destPathFromUploadFolder($folder)
56 * 610: function error($msg)
57 *
58 * TOTAL FUNCTIONS: 13
59 * (This index is automatically created/updated by the extension "extdeveval")
60 *
61 */
62
63 require_once(PATH_t3lib.'class.t3lib_tcemain.php');
64
65
66
67 /**
68 * Reference index processing and relation extraction
69 *
70 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
71 * @package TYPO3
72 * @subpackage t3lib
73 */
74 class t3lib_refindex {
75
76 var $temp_flexRelations = array();
77 var $errorLog = array();
78 var $WSOL = FALSE;
79 var $relations = array();
80 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.
81
82
83 /**
84 * Call this function to update the sys_refindex table for a record.
85 *
86 * @param string Table name
87 * @param uid UID of record
88 * @param boolean If set, nothing will be written to the index but the result value will still report statistics on what as added, deleted and kept. Can be used for mere analysis.
89 * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
90 */
91 function updateRefIndexTable($table,$uid,$testOnly=FALSE) {
92
93 // First, secure that the index table is not updated with workspace tainted relations:
94 $this->WSOL = FALSE;
95
96 // Init:
97 $result = array(
98 'keptNodes' => 0,
99 'deletedNodes' => 0,
100 'addedNodes' => 0
101 );
102
103 // Get current index from Database:
104 $currentRels = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
105 '*',
106 'sys_refindex',
107 'tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table,'sys_refindex').
108 ' AND recuid='.intval($uid),
109 '','','','hash'
110 );
111
112 // First, test to see if the record exists (being deleted also means it doesn't exist!)
113 if (t3lib_BEfunc::getRecord($table,$uid,'uid')) {
114
115 // Then, get relations:
116 $relations = $this->generateRefIndexData($table,$uid);
117
118 if (is_array($relations)) {
119
120 // Traverse the generated index:
121 foreach($relations as $k => $datRec) {
122 $relations[$k]['hash'] = md5(implode('///',$relations[$k]).'///'.$this->hashVersion);
123
124 // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
125 if (isset($currentRels[$relations[$k]['hash']])) {
126 unset($currentRels[$relations[$k]['hash']]);
127 $result['keptNodes']++;
128 $relations[$k]['_ACTION'] = 'KEPT';
129 } else {
130 // If new, add it:
131 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex',$relations[$k]);
132 $result['addedNodes']++;
133 $relations[$k]['_ACTION'] = 'ADDED';
134 }
135 }
136
137 $result['relations'] = $relations;
138 } else return FALSE; // Weird mistake I would say...
139 }
140
141 // If any old are left, remove them:
142 if (count($currentRels)) {
143 $hashList = array_keys($currentRels);
144 if (count($hashList)) {
145 $result['deletedNodes'] = count($hashList);
146 $result['deletedNodes_hashList'] = implode(',',$hashList);
147 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex','hash IN ('.implode(',',$GLOBALS['TYPO3_DB']->fullQuoteArray($hashList,'sys_refindex')).')');
148 }
149 }
150
151 return $result;
152 }
153
154 /**
155 * Returns array of arrays with an index of all references found in record from table/uid
156 * If the result is used to update the sys_refindex table then ->WSOL must NOT be true (no workspace overlay anywhere!)
157 *
158 * @param string Table name from $TCA
159 * @param integer Record UID
160 * @return array Index Rows
161 */
162 function generateRefIndexData($table,$uid) {
163 global $TCA;
164
165 if (isset($TCA[$table])) {
166 // Get raw record from DB:
167 list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$table,'uid='.intval($uid));
168
169 if (is_array($record)) {
170
171 // Get all relations from record:
172 $dbrels = $this->getRelations($table,$record);
173
174 // Traverse those relations, compile records to insert in table:
175 $this->relations = array();
176 foreach($dbrels as $fieldname => $dat) {
177
178 // Based on type,
179 switch((string)$dat['type']) {
180 case 'db':
181 $this->createEntryData_dbRels($table,$uid,$fieldname,'',$dat['itemArray']);
182 break;
183 case 'file':
184 $this->createEntryData_fileRels($table,$uid,$fieldname,'',$dat['newValueFiles']);
185 break;
186 case 'flex':
187 // DB references:
188 if (is_array($dat['flexFormRels']['db'])) {
189 foreach($dat['flexFormRels']['db'] as $flexpointer => $subList) {
190 $this->createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$subList);
191 }
192 }
193 // File references (NOT TESTED!)
194 if (is_array($dat['flexFormRels']['file'])) { // Not tested
195 foreach($dat['flexFormRels']['file'] as $flexpointer => $subList) {
196 $this->createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$subList);
197 }
198 }
199 // Soft references in flexforms (NOT TESTED!)
200 if (is_array($dat['flexFormRels']['softrefs'])) {
201 foreach($dat['flexFormRels']['softrefs'] as $flexpointer => $subList) {
202 $this->createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$subList['keys']);
203 }
204 }
205 break;
206 }
207
208 // Softreferences in the field:
209 if (is_array($dat['softrefs'])) {
210 $this->createEntryData_softreferences($table,$uid,$fieldname,'',$dat['softrefs']['keys']);
211 }
212 }
213
214 return $this->relations;
215 }
216 }
217 }
218
219 /**
220 * Create array with field/value pairs ready to insert in database.
221 * The "hash" field is a fingerprint value across this table.
222 *
223 * @param string Tablename of source record (where reference is located)
224 * @param integer UID of source record (where reference is located)
225 * @param string Fieldname of source record (where reference is located)
226 * @param string Pointer to location inside flexform structure where reference is located in [field]
227 * @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.
228 * @param integer For database references; The UID of the record (zero "ref_table" is "_FILE" or "_STRING")
229 * @param string For "_FILE" or "_STRING" references: The filepath (relative to PATH_site or absolute) or other string.
230 * @param integer The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
231 * @param string If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
232 * @param string Soft reference ID for key. Might be useful for replace operations.
233 * @return array Array record to insert into table.
234 */
235 function createEntryData($table,$uid,$field,$flexpointer,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='') {
236 return array(
237 'tablename' => $table,
238 'recuid' => $uid,
239 'field' => $field,
240 'flexpointer' => $flexpointer,
241 'softref_key' => $softref_key,
242 'softref_id' => $softref_id,
243 'sorting' => $sort,
244 'ref_table' => $ref_table,
245 'ref_uid' => $ref_uid,
246 'ref_string' => $ref_string,
247 );
248 }
249
250 /**
251 * Enter database references to ->relations array
252 *
253 * @param string [See createEntryData, arg 1]
254 * @param integer [See createEntryData, arg 2]
255 * @param string [See createEntryData, arg 3]
256 * @param string [See createEntryData, arg 4]
257 * @param array Data array with databaes relations (table/id)
258 * @return void
259 */
260 function createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$items) {
261 foreach($items as $sort => $i) {
262 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$i['table'],$i['id'],'',$sort);
263 }
264 }
265
266 /**
267 * Enter file references to ->relations array
268 *
269 * @param string [See createEntryData, arg 1]
270 * @param integer [See createEntryData, arg 2]
271 * @param string [See createEntryData, arg 3]
272 * @param string [See createEntryData, arg 4]
273 * @param array Data array with file relations
274 * @return void
275 */
276 function createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$items) {
277 foreach($items as $sort => $i) {
278 $filePath = $i['ID_absFile'];
279 if (t3lib_div::isFirstPartOfStr($filePath,PATH_site)) {
280 $filePath = substr($filePath,strlen(PATH_site));
281 }
282 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,'_FILE',0,$filePath,$sort);
283 }
284 }
285
286 /**
287 * Enter softref references to ->relations array
288 *
289 * @param string [See createEntryData, arg 1]
290 * @param integer [See createEntryData, arg 2]
291 * @param string [See createEntryData, arg 3]
292 * @param string [See createEntryData, arg 4]
293 * @param array Data array with soft reference keys
294 * @return void
295 */
296 function createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$keys) {
297 if (is_array($keys)) {
298 foreach($keys as $spKey => $elements) {
299 if (is_array($elements)) {
300 foreach($elements as $subKey => $el) {
301 if (is_array($el['subst'])) {
302 switch((string)$el['subst']['type']) {
303 case 'db':
304 list($tableName,$recordId) = explode(':',$el['subst']['recordRef']);
305 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$tableName,$recordId,'',-1,$spKey,$subKey);
306 break;
307 case 'file':
308 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,'_FILE',0,$el['subst']['relFileName'],-1,$spKey,$subKey);
309 break;
310 case 'string':
311 $this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,'_STRING',0,$el['subst']['tokenValue'],-1,$spKey,$subKey);
312 break;
313 }
314 }
315 }
316 }
317 }
318 }
319 }
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335 /*******************************
336 *
337 * Get relations from table row
338 *
339 *******************************/
340
341 /**
342 * Returns relation information for a $table/$row-array
343 * Traverses all fields in input row which are configured in TCA/columns
344 * It looks for hard relations to files and records in the TCA types "select" and "group"
345 *
346 * @param string Table
347 * @param array Row from table
348 * @return array Array with information about relations
349 * @see export_addRecord()
350 */
351 function getRelations($table,$row) {
352 global $TCA;
353
354 // Load full table description
355 t3lib_div::loadTCA($table);
356
357 // Initialize:
358 $uid = $row['uid'];
359 $nonFields = explode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,pid');
360
361 $outRow = array();
362 foreach($row as $field => $value) {
363 if (!in_array($field,$nonFields) && is_array($TCA[$table]['columns'][$field])) {
364 $conf = $TCA[$table]['columns'][$field]['config'];
365
366 // Add files
367 if ($result = $this->getRelations_procFiles($value, $conf, $uid)) {
368 // Creates an entry for the field with all the files:
369 $outRow[$field] = array(
370 'type' => 'file',
371 'newValueFiles' => $result,
372 );
373 }
374
375 // Add DB:
376 if ($result = $this->getRelations_procDB($value, $conf, $uid)) {
377 // Create an entry for the field with all DB relations:
378 $outRow[$field] = array(
379 'type' => 'db',
380 'itemArray' => $result,
381 );
382 }
383
384 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
385 if ($conf['type']=='flex') {
386
387 // Get current value array:
388 $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $row, $table,'',$this->WSOL);
389 $currentValueArray = t3lib_div::xml2array($value);
390
391 // Traversing the XML structure, processing files:
392 if (is_array($currentValueArray)) {
393 $this->temp_flexRelations = array(
394 'db' => array(),
395 'file' => array(),
396 'softrefs' => array()
397 );
398
399 $iteratorObj = t3lib_div::makeInstance('t3lib_TCEmain');
400 $iteratorObj->callBackObj = &$this;
401 $iteratorObj->checkValue_flex_procInData(
402 $currentValueArray['data'],
403 array(), // Not used.
404 array(), // Not used.
405 $dataStructArray,
406 array($table,$uid,$field), // Parameters.
407 'getRelations_flexFormCallBack'
408 );
409
410 // Create an entry for the field:
411 $outRow[$field] = array(
412 'type' => 'flex',
413 'flexFormRels' => $this->temp_flexRelations,
414 );
415 }
416 }
417
418 // Soft References:
419 if (strlen($value) && $softRefs = t3lib_BEfunc::explodeSoftRefParserList($conf['softref'], $table, $field)) {
420 $softRefValue = $value;
421 foreach($softRefs as $spKey => $spParams) {
422 $softRefObj = &t3lib_BEfunc::softRefParserObj($spKey);
423 if (is_object($softRefObj)) {
424 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
425 if (is_array($resultArray)) {
426 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
427 if (strlen($resultArray['content'])) {
428 $softRefValue = $resultArray['content'];
429 }
430 }
431 }
432 }
433
434 if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && strcmp($value,$softRefValue) && strstr($softRefValue,'{softref:')) {
435 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
436 }
437 }
438 }
439 }
440
441 return $outRow;
442 }
443
444 /**
445 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
446 *
447 * @param array Array of parameters in num-indexes: table, uid, field
448 * @param array TCA field configuration (from Data Structure XML)
449 * @param string The value of the flexForm field
450 * @param string Not used.
451 * @param string Not used.
452 * @param string Path of where in the data structure this element is.
453 * @return array Result array with key "value" containing the value of the processing.
454 * @see t3lib_TCEmain::checkValue_flex_procInData_travDS()
455 */
456 function getRelations_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $structurePath) {
457
458 // Implode parameter values:
459 list($table, $uid, $field) = $pParams;
460
461 // Add files
462 if ($result = $this->getRelations_procFiles($dataValue, $dsConf, $uid)) {
463
464 // Creates an entry for the field with all the files:
465 $this->temp_flexRelations['file'][$structurePath] = $result;
466 }
467
468 // Add DB:
469 if ($result = $this->getRelations_procDB($dataValue, $dsConf, $uid)) {
470
471 // Create an entry for the field with all DB relations:
472 $this->temp_flexRelations['db'][$structurePath] = $result;
473 }
474
475 // Soft References:
476 if (strlen($dataValue) && $softRefs = t3lib_BEfunc::explodeSoftRefParserList($dsConf['softref'], $table, $field)) {
477 $softRefValue = $dataValue;
478 foreach($softRefs as $spKey => $spParams) {
479 $softRefObj = &t3lib_BEfunc::softRefParserObj($spKey);
480 if (is_object($softRefObj)) {
481 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
482 if (is_array($resultArray) && is_array($resultArray['elements'])) {
483 $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
484 if (strlen($resultArray['content'])) $softRefValue = $resultArray['content'];
485 }
486 }
487 }
488
489 if (count($this->temp_flexRelations['softrefs']) && strcmp($dataValue,$softRefValue)) {
490 $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
491 }
492 }
493 }
494
495 /**
496 * Check field configuration if it is a file relation field and extract file relations if any
497 *
498 * @param string Field value
499 * @param array Field configuration array of type "TCA/columns"
500 * @param integer Field uid
501 * @return array If field type is OK it will return an array with the files inside. Else false
502 */
503 function getRelations_procFiles($value, $conf, $uid) {
504 // Take care of files...
505 if ($conf['type']=='group' && $conf['internal_type']=='file') {
506
507 // Collect file values in array:
508 if ($conf['MM']) {
509 $theFileValues = array();
510 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
511 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
512
513 foreach($dbAnalysis->itemArray as $somekey => $someval) {
514 if ($someval['id']) {
515 $theFileValues[] = $someval['id'];
516 }
517 }
518 } else {
519 $theFileValues = explode(',',$value);
520 }
521
522 // Traverse the files and add them:
523 $uploadFolder = $conf['uploadfolder'];
524 $dest = $this->destPathFromUploadFolder($uploadFolder);
525 $newValue = array();
526 $newValueFiles = array();
527
528 foreach($theFileValues as $file) {
529 if (trim($file)) {
530 $realFile = $dest.'/'.trim($file);
531 if (@is_file($realFile)) {
532 $newValueFiles[] = array(
533 'filename' => $file,
534 'ID' => md5($realFile),
535 'ID_absFile' => $realFile
536 ); // the order should be preserved here because.. (?)
537 } else $this->error('Missing file: '.$realFile);
538 }
539 }
540
541 return $newValueFiles;
542 }
543 }
544
545 /**
546 * Check field configuration if it is a DB relation field and extract DB relations if any
547 *
548 * @param string Field value
549 * @param array Field configuration array of type "TCA/columns"
550 * @param integer Field uid
551 * @return array If field type is OK it will return an array with the database relations. Else false
552 */
553 function getRelations_procDB($value, $conf, $uid) {
554
555 // DB record lists:
556 if ($this->isReferenceField($conf)) {
557 $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
558 $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
559
560 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
561 $dbAnalysis->start($value,$allowedTables,$conf['MM'],$uid);
562
563 return $dbAnalysis->itemArray;
564 }
565 }
566
567
568
569
570
571
572
573
574
575
576
577
578 /*******************************
579 *
580 * Helper functions
581 *
582 *******************************/
583
584 /**
585 * Returns true if the TCA/columns field type is a DB reference field
586 *
587 * @param array config array for TCA/columns field
588 * @return boolean True if DB reference field (group/db or select with foreign-table)
589 */
590 function isReferenceField($conf) {
591 return ($conf['type']=='group' && $conf['internal_type']=='db') || ($conf['type']=='select' && $conf['foreign_table']);
592 }
593
594 /**
595 * Returns destination path to an upload folder given by $folder
596 *
597 * @param string Folder relative to PATH_site
598 * @return string Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
599 */
600 function destPathFromUploadFolder($folder) {
601 return PATH_site.$folder;
602 }
603
604 /**
605 * Sets error message in the internal error log
606 *
607 * @param string Error message
608 * @return void
609 */
610 function error($msg) {
611 $this->errorLog[]=$msg;
612 }
613 }
614
615
616 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_refindex.php']) {
617 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_refindex.php']);
618 }
619 ?>