2 /***************************************************************
5 * (c) 1999-2008 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 * [CLASS/FUNCTION INDEX of SCRIPT]
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)
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)
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='')
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)
59 * (This index is automatically created/updated by the extension "extdeveval")
63 require_once(PATH_t3lib
.'class.t3lib_befunc.php');
64 require_once(PATH_t3lib
.'class.t3lib_tcemain.php');
65 require_once(PATH_t3lib
.'class.t3lib_flexformtools.php');
66 //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.
71 * Reference index processing and relation extraction
73 * NOTICE: When the reference index is updated for an offline version the results may not be correct.
74 * First, lets assumed that the reference update happens in LIVE workspace (ALWAYS update from Live workspace if you analyse whole database!)
75 * 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.
76 * 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!
77 * 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?
78 * Anyway, I just wanted to document this finding - I don't think we can find a solution for it. And its very TemplaVoila specific.
80 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
84 class t3lib_refindex
{
86 var $temp_flexRelations = array();
87 var $errorLog = array();
89 var $relations = array();
91 var $words_strings = array();
94 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.
98 * Call this function to update the sys_refindex table for a record (even one just deleted)
99 * 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.
101 * @param string Table name
102 * @param integer UID of record
103 * @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.
104 * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
106 function updateRefIndexTable($table,$uid,$testOnly=FALSE
) {
108 // First, secure that the index table is not updated with workspace tainted relations:
118 // Get current index from Database:
119 $currentRels = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
122 'tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table,'sys_refindex').
123 ' AND recuid='.intval($uid),
127 // First, test to see if the record exists (including deleted-flagged)
128 if (t3lib_BEfunc
::getRecordRaw($table,'uid='.intval($uid),'uid')) {
130 // Then, get relations:
131 $relations = $this->generateRefIndexData($table,$uid);
133 if (is_array($relations)) {
135 // Traverse the generated index:
136 foreach($relations as $k => $datRec) {
137 $relations[$k]['hash'] = md5(implode('///',$relations[$k]).'///'.$this->hashVersion
);
139 // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
140 if (isset($currentRels[$relations[$k]['hash']])) {
141 unset($currentRels[$relations[$k]['hash']]);
142 $result['keptNodes']++
;
143 $relations[$k]['_ACTION'] = 'KEPT';
146 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex',$relations[$k]);
147 $result['addedNodes']++
;
148 $relations[$k]['_ACTION'] = 'ADDED';
152 $result['relations'] = $relations;
153 } else return FALSE
; // Weird mistake I would say...
156 if (!$testOnly) $this->wordIndexing($table,$uid);
159 // If any old are left, remove them:
160 if (count($currentRels)) {
161 $hashList = array_keys($currentRels);
162 if (count($hashList)) {
163 $result['deletedNodes'] = count($hashList);
164 $result['deletedNodes_hashList'] = implode(',',$hashList);
165 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex','hash IN ('.implode(',',$GLOBALS['TYPO3_DB']->fullQuoteArray($hashList,'sys_refindex')).')');
173 * Returns array of arrays with an index of all references found in record from table/uid
174 * If the result is used to update the sys_refindex table then ->WSOL must NOT be true (no workspace overlay anywhere!)
176 * @param string Table name from $TCA
177 * @param integer Record UID
178 * @return array Index Rows
180 function generateRefIndexData($table,$uid) {
183 if (isset($TCA[$table])) {
184 // Get raw record from DB:
185 list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$table,'uid='.intval($uid));
187 if (is_array($record)) {
190 $this->words_strings
= array();
191 $this->words
= array();
194 $deleted = $TCA[$table]['ctrl']['delete'] ?
($record[$TCA[$table]['ctrl']['delete']]?
1:0) : 0;
196 // Get all relations from record:
197 $dbrels = $this->getRelations($table,$record);
199 // Traverse those relations, compile records to insert in table:
200 $this->relations
= array();
201 foreach($dbrels as $fieldname => $dat) {
204 switch((string)$dat['type']) {
206 $this->createEntryData_dbRels($table,$uid,$fieldname,'',$deleted,$dat['itemArray']);
209 $this->createEntryData_fileRels($table,$uid,$fieldname,'',$deleted,$dat['newValueFiles']);
213 if (is_array($dat['flexFormRels']['db'])) {
214 foreach($dat['flexFormRels']['db'] as $flexpointer => $subList) {
215 $this->createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$subList);
218 // File references (NOT TESTED!)
219 if (is_array($dat['flexFormRels']['file'])) { // Not tested
220 foreach($dat['flexFormRels']['file'] as $flexpointer => $subList) {
221 $this->createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$subList);
224 // Soft references in flexforms (NOT TESTED!)
225 if (is_array($dat['flexFormRels']['softrefs'])) {
226 foreach($dat['flexFormRels']['softrefs'] as $flexpointer => $subList) {
227 $this->createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$subList['keys']);
233 // Softreferences in the field:
234 if (is_array($dat['softrefs'])) {
235 $this->createEntryData_softreferences($table,$uid,$fieldname,'',$deleted,$dat['softrefs']['keys']);
240 t3lib_div
::loadTCA($table);
241 foreach($TCA[$table]['columns'] as $field => $conf) {
242 if (t3lib_div
::inList('input,text',$conf['config']['type']) && strcmp($record[$field],'') && !t3lib_div
::testInt($record[$field])) {
243 $this->words_strings
[$field] = $record[$field];
247 return $this->relations
;
253 * Create array with field/value pairs ready to insert in database.
254 * The "hash" field is a fingerprint value across this table.
256 * @param string Tablename of source record (where reference is located)
257 * @param integer UID of source record (where reference is located)
258 * @param string Fieldname of source record (where reference is located)
259 * @param string Pointer to location inside flexform structure where reference is located in [field]
260 * @param integer Whether record is deleted-flagged or not
261 * @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.
262 * @param integer For database references; The UID of the record (zero "ref_table" is "_FILE" or "_STRING")
263 * @param string For "_FILE" or "_STRING" references: The filepath (relative to PATH_site or absolute) or other string.
264 * @param integer The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
265 * @param string If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
266 * @param string Soft reference ID for key. Might be useful for replace operations.
267 * @return array Array record to insert into table.
269 function createEntryData($table,$uid,$field,$flexpointer,$deleted,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='') {
271 'tablename' => $table,
274 'flexpointer' => $flexpointer,
275 'softref_key' => $softref_key,
276 'softref_id' => $softref_id,
278 'deleted' => $deleted,
279 'ref_table' => $ref_table,
280 'ref_uid' => $ref_uid,
281 'ref_string' => $ref_string,
286 * Enter database references to ->relations array
288 * @param string [See createEntryData, arg 1]
289 * @param integer [See createEntryData, arg 2]
290 * @param string [See createEntryData, arg 3]
291 * @param string [See createEntryData, arg 4]
292 * @param string [See createEntryData, arg 5]
293 * @param array Data array with databaes relations (table/id)
296 function createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$items) {
297 foreach($items as $sort => $i) {
298 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,$i['table'],$i['id'],'',$sort);
303 * Enter file references to ->relations array
305 * @param string [See createEntryData, arg 1]
306 * @param integer [See createEntryData, arg 2]
307 * @param string [See createEntryData, arg 3]
308 * @param string [See createEntryData, arg 4]
309 * @param string [See createEntryData, arg 5]
310 * @param array Data array with file relations
313 function createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$items) {
314 foreach($items as $sort => $i) {
315 $filePath = $i['ID_absFile'];
316 if (t3lib_div
::isFirstPartOfStr($filePath,PATH_site
)) {
317 $filePath = substr($filePath,strlen(PATH_site
));
319 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_FILE',0,$filePath,$sort);
324 * Enter softref references to ->relations array
326 * @param string [See createEntryData, arg 1]
327 * @param integer [See createEntryData, arg 2]
328 * @param string [See createEntryData, arg 3]
329 * @param string [See createEntryData, arg 4]
330 * @param string [See createEntryData, arg 5]
331 * @param array Data array with soft reference keys
334 function createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$keys) {
335 if (is_array($keys)) {
336 foreach($keys as $spKey => $elements) {
337 if (is_array($elements)) {
338 foreach($elements as $subKey => $el) {
339 if (is_array($el['subst'])) {
340 switch((string)$el['subst']['type']) {
342 list($tableName,$recordId) = explode(':',$el['subst']['recordRef']);
343 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,$tableName,$recordId,'',-1,$spKey,$subKey);
346 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_FILE',0,$el['subst']['relFileName'],-1,$spKey,$subKey);
349 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_STRING',0,$el['subst']['tokenValue'],-1,$spKey,$subKey);
373 /*******************************
375 * Get relations from table row
377 *******************************/
380 * Returns relation information for a $table/$row-array
381 * Traverses all fields in input row which are configured in TCA/columns
382 * It looks for hard relations to files and records in the TCA types "select" and "group"
384 * @param string Table name
385 * @param array Row from table
386 * @param string Specific field to fetch for.
387 * @return array Array with information about relations
388 * @see export_addRecord()
390 function getRelations($table,$row,$onlyField='') {
393 // Load full table description
394 t3lib_div
::loadTCA($table);
398 $nonFields = explode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,pid');
401 foreach($row as $field => $value) {
402 if (!in_array($field,$nonFields) && is_array($TCA[$table]['columns'][$field]) && (!$onlyField ||
$onlyField===$field)) {
403 $conf = $TCA[$table]['columns'][$field]['config'];
406 if ($result = $this->getRelations_procFiles($value, $conf, $uid)) {
407 // Creates an entry for the field with all the files:
408 $outRow[$field] = array(
410 'newValueFiles' => $result,
415 if ($result = $this->getRelations_procDB($value, $conf, $uid, $table)) {
416 // Create an entry for the field with all DB relations:
417 $outRow[$field] = array(
419 'itemArray' => $result,
423 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
424 if ($conf['type']=='flex') {
426 // Get current value array:
427 // 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()
428 $dataStructArray = t3lib_BEfunc
::getFlexFormDS($conf, $row, $table,'',$this->WSOL
);
429 $currentValueArray = t3lib_div
::xml2array($value);
431 // Traversing the XML structure, processing files:
432 if (is_array($currentValueArray)) {
433 $this->temp_flexRelations
= array(
436 'softrefs' => array()
439 // Create and call iterator object:
440 $flexObj = t3lib_div
::makeInstance('t3lib_flexformtools');
441 $flexObj->traverseFlexFormXMLData($table,$field,$row,$this,'getRelations_flexFormCallBack');
443 // Create an entry for the field:
444 $outRow[$field] = array(
446 'flexFormRels' => $this->temp_flexRelations
,
452 if (strlen($value) && $softRefs = t3lib_BEfunc
::explodeSoftRefParserList($conf['softref'])) {
453 $softRefValue = $value;
454 foreach($softRefs as $spKey => $spParams) {
455 $softRefObj = &t3lib_BEfunc
::softRefParserObj($spKey);
456 if (is_object($softRefObj)) {
457 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
458 if (is_array($resultArray)) {
459 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
460 if (strlen($resultArray['content'])) {
461 $softRefValue = $resultArray['content'];
467 if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && strcmp($value,$softRefValue) && strstr($softRefValue,'{softref:')) {
468 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
478 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
480 * @param array Data structure for the current value
481 * @param mixed Current value
482 * @param array Additional configuration used in calling function
483 * @param string Path of value in DS structure
484 * @param object Object reference to caller
486 * @see t3lib_TCEmain::checkValue_flex_procInData_travDS()
488 function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, &$pObj) {
489 $structurePath = substr($structurePath,5).'/'; // removing "data/" in the beginning of path (which points to location in data array)
491 $dsConf = $dsArr['TCEforms']['config'];
493 // Implode parameter values:
494 list($table, $uid, $field) = array($PA['table'],$PA['uid'],$PA['field']);
497 if ($result = $this->getRelations_procFiles($dataValue, $dsConf, $uid)) {
499 // Creates an entry for the field with all the files:
500 $this->temp_flexRelations
['file'][$structurePath] = $result;
504 if ($result = $this->getRelations_procDB($dataValue, $dsConf, $uid)) {
506 // Create an entry for the field with all DB relations:
507 $this->temp_flexRelations
['db'][$structurePath] = $result;
511 if (strlen($dataValue) && $softRefs = t3lib_BEfunc
::explodeSoftRefParserList($dsConf['softref'])) {
512 $softRefValue = $dataValue;
513 foreach($softRefs as $spKey => $spParams) {
514 $softRefObj = &t3lib_BEfunc
::softRefParserObj($spKey);
515 if (is_object($softRefObj)) {
516 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
517 if (is_array($resultArray) && is_array($resultArray['elements'])) {
518 $this->temp_flexRelations
['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
519 if (strlen($resultArray['content'])) $softRefValue = $resultArray['content'];
524 if (count($this->temp_flexRelations
['softrefs']) && strcmp($dataValue,$softRefValue)) {
525 $this->temp_flexRelations
['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
531 * Check field configuration if it is a file relation field and extract file relations if any
533 * @param string Field value
534 * @param array Field configuration array of type "TCA/columns"
535 * @param integer Field uid
536 * @return array If field type is OK it will return an array with the files inside. Else false
538 function getRelations_procFiles($value, $conf, $uid) {
539 // Take care of files...
540 if ($conf['type']=='group' && $conf['internal_type']=='file') {
542 // Collect file values in array:
544 $theFileValues = array();
545 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
546 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
548 foreach($dbAnalysis->itemArray
as $somekey => $someval) {
549 if ($someval['id']) {
550 $theFileValues[] = $someval['id'];
554 $theFileValues = explode(',',$value);
557 // Traverse the files and add them:
558 $uploadFolder = $conf['uploadfolder'];
559 $dest = $this->destPathFromUploadFolder($uploadFolder);
561 $newValueFiles = array();
563 foreach($theFileValues as $file) {
565 $realFile = $dest.'/'.trim($file);
566 # if (@is_file($realFile)) { // Now, the refernece index should NOT look if files exist - just faithfully include them if they are in the records!
567 $newValueFiles[] = array(
569 'ID' => md5($realFile),
570 'ID_absFile' => $realFile
571 ); // the order should be preserved here because.. (?)
572 # } else $this->error('Missing file: '.$realFile);
576 return $newValueFiles;
581 * Check field configuration if it is a DB relation field and extract DB relations if any
583 * @param string Field value
584 * @param array Field configuration array of type "TCA/columns"
585 * @param integer Field uid
586 * @param string Table name
587 * @return array If field type is OK it will return an array with the database relations. Else false
589 function getRelations_procDB($value, $conf, $uid, $table = '') {
592 if ($this->isReferenceField($conf)) {
593 $allowedTables = $conf['type']=='group' ?
$conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
594 $prependName = $conf['type']=='group' ?
$conf['prepend_tname'] : $conf['neg_foreign_table'];
596 if($conf['MM_opposite_field']) {
600 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
601 $dbAnalysis->start($value,$allowedTables,$conf['MM'],$uid,$table,$conf);
603 return $dbAnalysis->itemArray
;
618 /*******************************
622 *******************************/
625 * Setting the value of a reference or removing it completely.
626 * Usage: For lowlevel clean up operations!
627 * 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.
628 * 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.
629 * 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!
630 * To ensure proper working only admin-BE_USERS in live workspace should use this function
632 * @param string 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
633 * @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
634 * @param boolean Return $dataArray only, do not submit it to database.
635 * @param boolean If set, it will bypass check for workspace-zero and admin user
636 * @return string If a return string, that carries an error message, otherwise false (=OK) (except if $returnDataArray is set!)
638 function setReferenceValue($hash,$newValue,$returnDataArray=FALSE
,$bypassWorkspaceAdminCheck=FALSE
) {
640 if (($GLOBALS['BE_USER']->workspace
===0 && $GLOBALS['BE_USER']->isAdmin()) ||
$bypassWorkspaceAdminCheck) {
642 // Get current index from Database:
643 list($refRec) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
646 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash,'sys_refindex')
649 // Check if reference existed.
650 if (is_array($refRec)) {
651 if ($GLOBALS['TCA'][$refRec['tablename']]) {
653 // Get that record from database:
654 list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$refRec['tablename'],'uid='.intval($refRec['recuid']));
656 if (is_array($record)) {
658 // Get all relations from record, filter with fieldname:
659 $dbrels = $this->getRelations($refRec['tablename'],$record,$refRec['field']);
660 if ($dat = $dbrels[$refRec['field']]) {
662 // Initialize data array that is to be sent to TCEmain afterwards:
663 $dataArray = array();
666 switch((string)$dat['type']) {
668 $error = $this->setReferenceValue_dbRels($refRec,$dat['itemArray'],$newValue,$dataArray);
669 if ($error) return $error;
672 $this->setReferenceValue_fileRels($refRec,$dat['newValueFiles'],$newValue,$dataArray);
673 if ($error) return $error;
677 if (is_array($dat['flexFormRels']['db'][$refRec['flexpointer']])) {
678 $error = $this->setReferenceValue_dbRels($refRec,$dat['flexFormRels']['db'][$refRec['flexpointer']],$newValue,$dataArray,$refRec['flexpointer']);
679 if ($error) return $error;
682 if (is_array($dat['flexFormRels']['file'][$refRec['flexpointer']])) {
683 $this->setReferenceValue_fileRels($refRec,$dat['flexFormRels']['file'][$refRec['flexpointer']],$newValue,$dataArray,$refRec['flexpointer']);
684 if ($error) return $error;
686 // Soft references in flexforms
687 if ($refRec['softref_key'] && is_array($dat['flexFormRels']['softrefs'][$refRec['flexpointer']]['keys'][$refRec['softref_key']])) {
688 $error = $this->setReferenceValue_softreferences($refRec,$dat['flexFormRels']['softrefs'][$refRec['flexpointer']],$newValue,$dataArray,$refRec['flexpointer']);
689 if ($error) return $error;
694 // Softreferences in the field:
695 if ($refRec['softref_key'] && is_array($dat['softrefs']['keys'][$refRec['softref_key']])) {
696 $error = $this->setReferenceValue_softreferences($refRec,$dat['softrefs'],$newValue,$dataArray);
697 if ($error) return $error;
701 // Data Array, now ready to sent to TCEmain
702 if ($returnDataArray) {
706 // Execute CMD array:
707 $tce = t3lib_div
::makeInstance('t3lib_TCEmain');
708 $tce->stripslashes_values
= FALSE
;
709 $tce->dontProcessTransformations
= TRUE
;
710 $tce->bypassWorkspaceRestrictions
= TRUE
;
711 $tce->bypassFileHandling
= TRUE
;
712 $tce->bypassAccessCheckForRecords
= TRUE
; // Otherwise this cannot update things in deleted records...
714 $tce->start($dataArray,array()); // check has been done previously that there is a backend user which is Admin and also in live workspace
715 $tce->process_datamap();
717 // Return errors if any:
718 if (count($tce->errorLog
)) {
719 return chr(10).'TCEmain:'.implode(chr(10).'TCEmain:',$tce->errorLog
);
724 } else return 'ERROR: Tablename "'.$refRec['tablename'].'" was not in TCA!';
725 } else return 'ERROR: No reference record with hash="'.$hash.'" was found!';
726 } else return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
730 * Setting a value for a reference for a DB field:
732 * @param array sys_refindex record
733 * @param array Array of references from that field
734 * @param string Value to substitute current value with (or NULL to unset it)
735 * @param array data array in which the new value is set (passed by reference)
736 * @param string Flexform pointer, if in a flex form field.
737 * @return string Error message if any, otherwise false = OK
739 function setReferenceValue_dbRels($refRec,$itemArray,$newValue,&$dataArray,$flexpointer='') {
740 if (!strcmp($itemArray[$refRec['sorting']]['id'],$refRec['ref_uid']) && !strcmp($itemArray[$refRec['sorting']]['table'],$refRec['ref_table'])) {
742 // Setting or removing value:
743 if ($newValue===NULL
) { // Remove value:
744 unset($itemArray[$refRec['sorting']]);
746 list($itemArray[$refRec['sorting']]['table'],$itemArray[$refRec['sorting']]['id']) = explode(':',$newValue);
749 // Traverse and compile new list of records:
750 $saveValue = array();
751 foreach($itemArray as $pair) {
752 $saveValue[] = $pair['table'].'_'.$pair['id'];
755 // Set in data array:
757 $flexToolObj = t3lib_div
::makeInstance('t3lib_flexformtools');
758 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
759 $flexToolObj->setArrayValueByPath(substr($flexpointer,0,-1),$dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'],implode(',',$saveValue));
761 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',',$saveValue);
764 } 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'].'"';
768 * Setting a value for a reference for a FILE field:
770 * @param array sys_refindex record
771 * @param array Array of references from that field
772 * @param string Value to substitute current value with (or NULL to unset it)
773 * @param array data array in which the new value is set (passed by reference)
774 * @param string Flexform pointer, if in a flex form field.
775 * @return string Error message if any, otherwise false = OK
777 function setReferenceValue_fileRels($refRec,$itemArray,$newValue,&$dataArray,$flexpointer='') {
778 if (!strcmp(substr($itemArray[$refRec['sorting']]['ID_absFile'],strlen(PATH_site
)),$refRec['ref_string']) && !strcmp('_FILE',$refRec['ref_table'])) {
780 // Setting or removing value:
781 if ($newValue===NULL
) { // Remove value:
782 unset($itemArray[$refRec['sorting']]);
784 $itemArray[$refRec['sorting']]['filename'] = $newValue;
787 // Traverse and compile new list of records:
788 $saveValue = array();
789 foreach($itemArray as $fileInfo) {
790 $saveValue[] = $fileInfo['filename'];
793 // Set in data array:
795 $flexToolObj = t3lib_div
::makeInstance('t3lib_flexformtools');
796 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
797 $flexToolObj->setArrayValueByPath(substr($flexpointer,0,-1),$dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'],implode(',',$saveValue));
799 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',',$saveValue);
802 } 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'].'"';
806 * Setting a value for a soft reference token
808 * @param array sys_refindex record
809 * @param array Array of soft reference occurencies
810 * @param string Value to substitute current value with
811 * @param array data array in which the new value is set (passed by reference)
812 * @param string Flexform pointer, if in a flex form field.
813 * @return string Error message if any, otherwise false = OK
815 function setReferenceValue_softreferences($refRec,$softref,$newValue,&$dataArray,$flexpointer='') {
816 if (is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
819 $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = ''.$newValue;
821 // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
822 foreach($softref['keys'] as $sfIndexes) {
823 foreach($sfIndexes as $data) {
824 $softref['tokenizedContent'] = str_replace('{softref:'.$data['subst']['tokenID'].'}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
828 // Set in data array:
829 if (!strstr($softref['tokenizedContent'],'{softref:')) {
831 $flexToolObj = t3lib_div
::makeInstance('t3lib_flexformtools');
832 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
833 $flexToolObj->setArrayValueByPath(substr($flexpointer,0,-1),$dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'],$softref['tokenizedContent']);
835 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
837 } 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.)';
838 } else return 'ERROR: Soft reference parser key "'.$refRec['softref_key'].'" or the index "'.$refRec['softref_id'].'" was not found.';
850 /*******************************
854 *******************************/
857 * Indexing words from table records. Can be useful for quick backend look ups in records across the system.
859 function wordIndexing($table,$uid) {
860 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.
863 // - Flag to disable indexing
864 // - Clean-up to remove words not used anymore and indexes for records not in the system anymore.
865 // - UTF-8 compliant substr()
866 $lexer = t3lib_div
::makeInstance('tx_indexedsearch_lexer');
867 $words = $lexer->split2Words(implode(' ',$this->words_strings
));
868 foreach($words as $w) {
869 $words[]=substr($w,0,3);
871 $words = array_unique($words);
872 $this->updateWordIndex($words,$table,$uid);
876 * Update/Create word index for record
878 * @param array Word list array (words are values in array)
879 * @param string Table
880 * @param integer Rec uid
883 function updateWordIndex($words,$table,$uid) {
886 $this->submitWords($words);
888 // Result id and remove relations:
889 $rid = t3lib_div
::md5int($table.':'.$uid);
890 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex_rel', 'rid='.intval($rid));
893 foreach($words as $w) {
894 $insertFields = array(
896 'wid' => t3lib_div
::md5int($w)
899 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_rel', $insertFields);
902 // Add result record:
903 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex_res', 'rid='.intval($rid));
904 $insertFields = array(
906 'tablename' => $table,
909 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_res', $insertFields);
913 * Adds new words to db
915 * @param array Word List array (where each word has information about position etc).
918 function submitWords($wl) {
922 $hashArr[] = t3lib_div
::md5int($w);
924 $wl = array_flip($wl);
926 if (count($hashArr)) {
927 $cwl = implode(',',$hashArr);
928 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('baseword', 'sys_refindex_words', 'wid IN ('.$cwl.')');
930 if($GLOBALS['TYPO3_DB']->sql_num_rows($res)!=count($wl)) {
931 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
932 unset($wl[$row['baseword']]);
936 while(list($key,$val)=each($wl)) {
937 $insertFields = array(
938 'wid' => t3lib_div
::md5int($key),
942 // 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.
943 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_words', $insertFields);
955 /*******************************
959 *******************************/
962 * Returns true if the TCA/columns field type is a DB reference field
964 * @param array config array for TCA/columns field
965 * @return boolean True if DB reference field (group/db or select with foreign-table)
967 function isReferenceField($conf) {
968 return ($conf['type']=='group' && $conf['internal_type']=='db') ||
(($conf['type']=='select' ||
$conf['type']=='inline') && $conf['foreign_table']);
972 * Returns destination path to an upload folder given by $folder
974 * @param string Folder relative to PATH_site
975 * @return string Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
977 function destPathFromUploadFolder($folder) {
978 return PATH_site
.$folder;
982 * Sets error message in the internal error log
984 * @param string Error message
987 function error($msg) {
988 $this->errorLog
[]=$msg;
992 * Updating Index (External API)
994 * @param boolean If set, only a test
995 * @param boolean If set, output CLI status
996 * @return array Header and body status content
998 function updateIndex($testOnly,$cli_echo=FALSE
) {
999 global $TCA, $TYPO3_DB;
1002 $tableNames = array();
1006 $headerContent = $testOnly ?
'Reference Index being TESTED (nothing written, use "-e" to update)' : 'Reference Index being Updated';
1008 '*******************************************'.chr(10).
1009 $headerContent.chr(10).
1010 '*******************************************'.chr(10);
1012 // Traverse all tables:
1013 foreach ($TCA as $tableName => $cfg) {
1014 $tableNames[] = $tableName;
1017 // Traverse all records in tables, including deleted records:
1018 $allRecs = $TYPO3_DB->exec_SELECTgetRows('uid',$tableName,'1=1'); //.t3lib_BEfunc::deleteClause($tableName)
1019 $uidList = array(0);
1020 foreach ($allRecs as $recdat) {
1021 $refIndexObj = t3lib_div
::makeInstance('t3lib_refindex');
1022 $result = $refIndexObj->updateRefIndexTable($tableName,$recdat['uid'],$testOnly);
1023 $uidList[]= $recdat['uid'];
1026 if ($result['addedNodes'] ||
$result['deletedNodes']) {
1027 $Err = 'Record '.$tableName.':'.$recdat['uid'].' had '.$result['addedNodes'].' added indexes and '.$result['deletedNodes'].' deleted indexes';
1029 if ($cli_echo) echo $Err.chr(10);
1030 #$errors[] = t3lib_div::view_array($result);
1034 // Searching lost indexes for this table:
1035 $where = 'tablename='.$TYPO3_DB->fullQuoteStr($tableName,'sys_refindex').' AND recuid NOT IN ('.implode(',',$uidList).')';
1036 $lostIndexes = $TYPO3_DB->exec_SELECTgetRows('hash','sys_refindex',$where);
1037 if (count($lostIndexes)) {
1038 $Err = 'Table '.$tableName.' has '.count($lostIndexes).' lost indexes which are now deleted';
1040 if ($cli_echo) echo $Err.chr(10);
1041 if (!$testOnly) $TYPO3_DB->exec_DELETEquery('sys_refindex',$where);
1045 // Searching lost indexes for non-existing tables:
1046 $where = 'tablename NOT IN ('.implode(',',$TYPO3_DB->fullQuoteArray($tableNames,'sys_refindex')).')';
1047 $lostTables = $TYPO3_DB->exec_SELECTgetRows('hash','sys_refindex',$where);
1048 if (count($lostTables)) {
1049 $Err = 'Index table hosted '.count($lostTables).' indexes for non-existing tables, now removed';
1051 if ($cli_echo) echo $Err.chr(10);
1052 if (!$testOnly) $TYPO3_DB->exec_DELETEquery('sys_refindex',$where);
1055 $testedHowMuch = $recCount.' records from '.$tableCount.' tables were checked/updated.'.chr(10);
1057 $bodyContent = $testedHowMuch.(count($errors)?
implode(chr(10),$errors):'Index Integrity was perfect!');
1058 if ($cli_echo) echo $testedHowMuch.(count($errors)?
'Updates: '.count($errors):'Index Integrity was perfect!').chr(10);
1060 return array($headerContent,$bodyContent,count($errors));
1065 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_refindex.php']) {
1066 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_refindex.php']);