2 /***************************************************************
5 * (c) 1999-2005 Kasper Skaarhoj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Reference index processing
32 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
35 * [CLASS/FUNCTION INDEX of SCRIPT]
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)
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)
53 * SECTION: Helper functions
54 * 590: function isReferenceField($conf)
55 * 600: function destPathFromUploadFolder($folder)
56 * 610: function error($msg)
59 * (This index is automatically created/updated by the extension "extdeveval")
63 require_once(PATH_t3lib
.'class.t3lib_tcemain.php');
68 * Reference index processing and relation extraction
70 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
74 class t3lib_refindex
{
76 var $temp_flexRelations = array();
77 var $errorLog = array();
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.
84 * Call this function to update the sys_refindex table for a record.
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.
91 function updateRefIndexTable($table,$uid,$testOnly=FALSE) {
93 // First, secure that the index table is not updated with workspace tainted relations:
103 // Get current index from Database:
104 $currentRels = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
107 'tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table,'sys_refindex').
108 ' AND recuid='.intval($uid),
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')) {
115 // Then, get relations:
116 $relations = $this->generateRefIndexData($table,$uid);
118 if (is_array($relations)) {
120 // Traverse the generated index:
121 foreach($relations as $k => $datRec) {
122 $relations[$k]['hash'] = md5(implode('///',$relations[$k]).'///'.$this->hashVersion
);
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';
131 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex',$relations[$k]);
132 $result['addedNodes']++
;
133 $relations[$k]['_ACTION'] = 'ADDED';
137 $result['relations'] = $relations;
138 } else return FALSE; // Weird mistake I would say...
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')).')');
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!)
158 * @param string Table name from $TCA
159 * @param integer Record UID
160 * @return array Index Rows
162 function generateRefIndexData($table,$uid) {
165 if (isset($TCA[$table])) {
166 // Get raw record from DB:
167 list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$table,'uid='.intval($uid));
169 if (is_array($record)) {
171 // Get all relations from record:
172 $dbrels = $this->getRelations($table,$record);
174 // Traverse those relations, compile records to insert in table:
175 $this->relations
= array();
176 foreach($dbrels as $fieldname => $dat) {
179 switch((string)$dat['type']) {
181 $this->createEntryData_dbRels($table,$uid,$fieldname,'',$dat['itemArray']);
184 $this->createEntryData_fileRels($table,$uid,$fieldname,'',$dat['newValueFiles']);
188 if (is_array($dat['flexFormRels']['db'])) {
189 foreach($dat['flexFormRels']['db'] as $flexpointer => $subList) {
190 $this->createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$subList);
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);
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']);
208 // Softreferences in the field:
209 if (is_array($dat['softrefs'])) {
210 $this->createEntryData_softreferences($table,$uid,$fieldname,'',$dat['softrefs']['keys']);
214 return $this->relations
;
220 * Create array with field/value pairs ready to insert in database.
221 * The "hash" field is a fingerprint value across this table.
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.
235 function createEntryData($table,$uid,$field,$flexpointer,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='') {
237 'tablename' => $table,
240 'flexpointer' => $flexpointer,
241 'softref_key' => $softref_key,
242 'softref_id' => $softref_id,
244 'ref_table' => $ref_table,
245 'ref_uid' => $ref_uid,
246 'ref_string' => $ref_string,
251 * Enter database references to ->relations array
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)
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);
267 * Enter file references to ->relations array
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
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
));
282 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,'_FILE',0,$filePath,$sort);
287 * Enter softref references to ->relations array
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
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']) {
304 list($tableName,$recordId) = explode(':',$el['subst']['recordRef']);
305 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$tableName,$recordId,'',-1,$spKey,$subKey);
308 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,'_FILE',0,$el['subst']['relFileName'],-1,$spKey,$subKey);
311 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,'_STRING',0,$el['subst']['tokenValue'],-1,$spKey,$subKey);
335 /*******************************
337 * Get relations from table row
339 *******************************/
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"
346 * @param string Table
347 * @param array Row from table
348 * @return array Array with information about relations
349 * @see export_addRecord()
351 function getRelations($table,$row) {
354 // Load full table description
355 t3lib_div
::loadTCA($table);
359 $nonFields = explode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,pid');
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'];
367 if ($result = $this->getRelations_procFiles($value, $conf, $uid)) {
368 // Creates an entry for the field with all the files:
369 $outRow[$field] = array(
371 'newValueFiles' => $result,
376 if ($result = $this->getRelations_procDB($value, $conf, $uid)) {
377 // Create an entry for the field with all DB relations:
378 $outRow[$field] = array(
380 'itemArray' => $result,
384 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
385 if ($conf['type']=='flex') {
387 // Get current value array:
388 $dataStructArray = t3lib_BEfunc
::getFlexFormDS($conf, $row, $table,'',$this->WSOL
);
389 $currentValueArray = t3lib_div
::xml2array($value);
391 // Traversing the XML structure, processing files:
392 if (is_array($currentValueArray)) {
393 $this->temp_flexRelations
= array(
396 'softrefs' => array()
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.
406 array($table,$uid,$field), // Parameters.
407 'getRelations_flexFormCallBack'
410 // Create an entry for the field:
411 $outRow[$field] = array(
413 'flexFormRels' => $this->temp_flexRelations
,
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'];
434 if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && strcmp($value,$softRefValue) && strstr($softRefValue,'{softref:')) {
435 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
445 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
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()
456 function getRelations_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $structurePath) {
458 // Implode parameter values:
459 list($table, $uid, $field) = $pParams;
462 if ($result = $this->getRelations_procFiles($dataValue, $dsConf, $uid)) {
464 // Creates an entry for the field with all the files:
465 $this->temp_flexRelations
['file'][$structurePath] = $result;
469 if ($result = $this->getRelations_procDB($dataValue, $dsConf, $uid)) {
471 // Create an entry for the field with all DB relations:
472 $this->temp_flexRelations
['db'][$structurePath] = $result;
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'];
489 if (count($this->temp_flexRelations
['softrefs']) && strcmp($dataValue,$softRefValue)) {
490 $this->temp_flexRelations
['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
496 * Check field configuration if it is a file relation field and extract file relations if any
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
503 function getRelations_procFiles($value, $conf, $uid) {
504 // Take care of files...
505 if ($conf['type']=='group' && $conf['internal_type']=='file') {
507 // Collect file values in array:
509 $theFileValues = array();
510 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
511 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
513 foreach($dbAnalysis->itemArray
as $somekey => $someval) {
514 if ($someval['id']) {
515 $theFileValues[] = $someval['id'];
519 $theFileValues = explode(',',$value);
522 // Traverse the files and add them:
523 $uploadFolder = $conf['uploadfolder'];
524 $dest = $this->destPathFromUploadFolder($uploadFolder);
526 $newValueFiles = array();
528 foreach($theFileValues as $file) {
530 $realFile = $dest.'/'.trim($file);
531 if (@is_file
($realFile)) {
532 $newValueFiles[] = array(
534 'ID' => md5($realFile),
535 'ID_absFile' => $realFile
536 ); // the order should be preserved here because.. (?)
537 } else $this->error('Missing file: '.$realFile);
541 return $newValueFiles;
546 * Check field configuration if it is a DB relation field and extract DB relations if any
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
553 function getRelations_procDB($value, $conf, $uid) {
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'];
560 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
561 $dbAnalysis->start($value,$allowedTables,$conf['MM'],$uid);
563 return $dbAnalysis->itemArray
;
578 /*******************************
582 *******************************/
585 * Returns true if the TCA/columns field type is a DB reference field
587 * @param array config array for TCA/columns field
588 * @return boolean True if DB reference field (group/db or select with foreign-table)
590 function isReferenceField($conf) {
591 return ($conf['type']=='group' && $conf['internal_type']=='db') ||
($conf['type']=='select' && $conf['foreign_table']);
595 * Returns destination path to an upload folder given by $folder
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.
600 function destPathFromUploadFolder($folder) {
601 return PATH_site
.$folder;
605 * Sets error message in the internal error log
607 * @param string Error message
610 function error($msg) {
611 $this->errorLog
[]=$msg;
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']);