2 /***************************************************************
5 * (c) 1999-2010 Kasper Skårhøj (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")
67 * Reference index processing and relation extraction
69 * NOTICE: When the reference index is updated for an offline version the results may not be correct.
70 * First, lets assumed that the reference update happens in LIVE workspace (ALWAYS update from Live workspace if you analyse whole database!)
71 * Secondly, lets assume that in a Draft workspace you have changed the data structure of a parent page record - this is (in TemplaVoila) inherited by subpages.
72 * When in the LIVE workspace the data structure for the records/pages in the offline workspace will not be evaluated to the right one simply because the data structure is taken from a rootline traversal and in the Live workspace that will NOT include the changed DataSTructure! Thus the evaluation will be based on the Data Structure set in the Live workspace!
73 * Somehow this scenario is rarely going to happen. Yet, it is an inconsistency and I see now practical way to handle it - other than simply ignoring maintaining the index for workspace records. Or we can say that the index is precise for all Live elements while glitches might happen in an offline workspace?
74 * Anyway, I just wanted to document this finding - I don't think we can find a solution for it. And its very TemplaVoila specific.
76 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
80 class t3lib_refindex
{
82 var $temp_flexRelations = array();
83 var $errorLog = array();
85 var $relations = array();
87 var $words_strings = array();
90 var $hashVersion = 1; // Number which we can increase if a change in the code means we will have to force a re-generation of the index.
94 * Call this function to update the sys_refindex table for a record (even one just deleted)
95 * NOTICE: Currently, references updated for a deleted-flagged record will not include those from within flexform fields in some cases where the data structure is defined by another record since the resolving process ignores deleted records! This will also result in bad cleaning up in tcemain I think... Anyway, thats the story of flexforms; as long as the DS can change, lots of references can get lost in no time.
97 * @param string Table name
98 * @param integer UID of record
99 * @param boolean If set, nothing will be written to the index but the result value will still report statistics on what is added, deleted and kept. Can be used for mere analysis.
100 * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
102 function updateRefIndexTable($table,$uid,$testOnly=FALSE
) {
104 // First, secure that the index table is not updated with workspace tainted relations:
114 // Get current index from Database:
115 $currentRels = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
118 'tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table,'sys_refindex').
119 ' AND recuid='.intval($uid),
123 // First, test to see if the record exists (including deleted-flagged)
124 if (t3lib_BEfunc
::getRecordRaw($table,'uid='.intval($uid),'uid')) {
126 // Then, get relations:
127 $relations = $this->generateRefIndexData($table,$uid);
129 if (is_array($relations)) {
131 // Traverse the generated index:
132 foreach($relations as $k => $datRec) {
133 $relations[$k]['hash'] = md5(implode('///',$relations[$k]).'///'.$this->hashVersion
);
135 // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
136 if (isset($currentRels[$relations[$k]['hash']])) {
137 unset($currentRels[$relations[$k]['hash']]);
138 $result['keptNodes']++
;
139 $relations[$k]['_ACTION'] = 'KEPT';
142 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex',$relations[$k]);
143 $result['addedNodes']++
;
144 $relations[$k]['_ACTION'] = 'ADDED';
148 $result['relations'] = $relations;
149 } else return FALSE
; // Weird mistake I would say...
152 if (!$testOnly) $this->wordIndexing($table,$uid);
155 // If any old are left, remove them:
156 if (count($currentRels)) {
157 $hashList = array_keys($currentRels);
158 if (count($hashList)) {
159 $result['deletedNodes'] = count($hashList);
160 $result['deletedNodes_hashList'] = implode(',',$hashList);
161 if (!$testOnly) $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex','hash IN ('.implode(',',$GLOBALS['TYPO3_DB']->fullQuoteArray($hashList,'sys_refindex')).')');
169 * Returns array of arrays with an index of all references found in record from table/uid
170 * If the result is used to update the sys_refindex table then ->WSOL must NOT be true (no workspace overlay anywhere!)
172 * @param string Table name from $TCA
173 * @param integer Record UID
174 * @return array Index Rows
176 function generateRefIndexData($table,$uid) {
179 if (isset($TCA[$table])) {
180 // Get raw record from DB:
181 list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$table,'uid='.intval($uid));
183 if (is_array($record)) {
186 $this->words_strings
= array();
187 $this->words
= array();
190 $deleted = $TCA[$table]['ctrl']['delete'] ?
($record[$TCA[$table]['ctrl']['delete']]?
1:0) : 0;
192 // Get all relations from record:
193 $dbrels = $this->getRelations($table,$record);
195 // Traverse those relations, compile records to insert in table:
196 $this->relations
= array();
197 foreach($dbrels as $fieldname => $dat) {
200 switch((string)$dat['type']) {
202 $this->createEntryData_dbRels($table,$uid,$fieldname,'',$deleted,$dat['itemArray']);
204 case 'file_reference':
206 $this->createEntryData_fileRels($table,$uid,$fieldname,'',$deleted,$dat['newValueFiles']);
210 if (is_array($dat['flexFormRels']['db'])) {
211 foreach($dat['flexFormRels']['db'] as $flexpointer => $subList) {
212 $this->createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$subList);
215 // File references (NOT TESTED!)
216 if (is_array($dat['flexFormRels']['file'])) { // Not tested
217 foreach($dat['flexFormRels']['file'] as $flexpointer => $subList) {
218 $this->createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$subList);
221 // Soft references in flexforms (NOT TESTED!)
222 if (is_array($dat['flexFormRels']['softrefs'])) {
223 foreach($dat['flexFormRels']['softrefs'] as $flexpointer => $subList) {
224 $this->createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$subList['keys']);
230 // Softreferences in the field:
231 if (is_array($dat['softrefs'])) {
232 $this->createEntryData_softreferences($table,$uid,$fieldname,'',$deleted,$dat['softrefs']['keys']);
237 t3lib_div
::loadTCA($table);
238 foreach($TCA[$table]['columns'] as $field => $conf) {
239 if (t3lib_div
::inList('input,text',$conf['config']['type']) && strcmp($record[$field],'') && !t3lib_div
::testInt($record[$field])) {
240 $this->words_strings
[$field] = $record[$field];
244 return $this->relations
;
250 * Create array with field/value pairs ready to insert in database.
251 * The "hash" field is a fingerprint value across this table.
253 * @param string Tablename of source record (where reference is located)
254 * @param integer UID of source record (where reference is located)
255 * @param string Fieldname of source record (where reference is located)
256 * @param string Pointer to location inside flexform structure where reference is located in [field]
257 * @param integer Whether record is deleted-flagged or not
258 * @param string For database references; the tablename the reference points to. Special keyword "_FILE" indicates that "ref_string" is a file reference either absolute or relative to PATH_site. Special keyword "_STRING" indicates some special usage (typ. softreference) where "ref_string" is used for the value.
259 * @param integer For database references; The UID of the record (zero "ref_table" is "_FILE" or "_STRING")
260 * @param string For "_FILE" or "_STRING" references: The filepath (relative to PATH_site or absolute) or other string.
261 * @param integer The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
262 * @param string If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
263 * @param string Soft reference ID for key. Might be useful for replace operations.
264 * @return array Array record to insert into table.
266 function createEntryData($table,$uid,$field,$flexpointer,$deleted,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='') {
268 'tablename' => $table,
271 'flexpointer' => $flexpointer,
272 'softref_key' => $softref_key,
273 'softref_id' => $softref_id,
275 'deleted' => $deleted,
276 'ref_table' => $ref_table,
277 'ref_uid' => $ref_uid,
278 'ref_string' => $ref_string,
283 * Enter database references to ->relations array
285 * @param string [See createEntryData, arg 1]
286 * @param integer [See createEntryData, arg 2]
287 * @param string [See createEntryData, arg 3]
288 * @param string [See createEntryData, arg 4]
289 * @param string [See createEntryData, arg 5]
290 * @param array Data array with databaes relations (table/id)
293 function createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$items) {
294 foreach($items as $sort => $i) {
295 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,$i['table'],$i['id'],'',$sort);
300 * Enter file references to ->relations array
302 * @param string [See createEntryData, arg 1]
303 * @param integer [See createEntryData, arg 2]
304 * @param string [See createEntryData, arg 3]
305 * @param string [See createEntryData, arg 4]
306 * @param string [See createEntryData, arg 5]
307 * @param array Data array with file relations
310 function createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$items) {
311 foreach($items as $sort => $i) {
312 $filePath = $i['ID_absFile'];
313 if (t3lib_div
::isFirstPartOfStr($filePath,PATH_site
)) {
314 $filePath = substr($filePath,strlen(PATH_site
));
316 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_FILE',0,$filePath,$sort);
321 * Enter softref references to ->relations array
323 * @param string [See createEntryData, arg 1]
324 * @param integer [See createEntryData, arg 2]
325 * @param string [See createEntryData, arg 3]
326 * @param string [See createEntryData, arg 4]
327 * @param string [See createEntryData, arg 5]
328 * @param array Data array with soft reference keys
331 function createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$keys) {
332 if (is_array($keys)) {
333 foreach($keys as $spKey => $elements) {
334 if (is_array($elements)) {
335 foreach($elements as $subKey => $el) {
336 if (is_array($el['subst'])) {
337 switch((string)$el['subst']['type']) {
339 list($tableName,$recordId) = explode(':',$el['subst']['recordRef']);
340 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,$tableName,$recordId,'',-1,$spKey,$subKey);
342 case 'file_reference':
344 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_FILE',0,$el['subst']['relFileName'],-1,$spKey,$subKey);
347 $this->relations
[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_STRING',0,$el['subst']['tokenValue'],-1,$spKey,$subKey);
371 /*******************************
373 * Get relations from table row
375 *******************************/
378 * Returns relation information for a $table/$row-array
379 * Traverses all fields in input row which are configured in TCA/columns
380 * It looks for hard relations to files and records in the TCA types "select" and "group"
382 * @param string Table name
383 * @param array Row from table
384 * @param string Specific field to fetch for.
385 * @return array Array with information about relations
386 * @see export_addRecord()
388 function getRelations($table,$row,$onlyField='') {
391 // Load full table description
392 t3lib_div
::loadTCA($table);
396 $nonFields = explode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,pid');
399 foreach($row as $field => $value) {
400 if (!in_array($field,$nonFields) && is_array($TCA[$table]['columns'][$field]) && (!$onlyField ||
$onlyField===$field)) {
401 $conf = $TCA[$table]['columns'][$field]['config'];
404 if ($result = $this->getRelations_procFiles($value, $conf, $uid)) {
405 // Creates an entry for the field with all the files:
406 $outRow[$field] = array(
408 'newValueFiles' => $result,
413 if ($result = $this->getRelations_procDB($value, $conf, $uid, $table)) {
414 // Create an entry for the field with all DB relations:
415 $outRow[$field] = array(
417 'itemArray' => $result,
421 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
422 if ($conf['type']=='flex') {
424 // Get current value array:
425 // NOTICE: failure to resolve Data Structures can lead to integrity problems with the reference index. Please look up the note in the JavaDoc documentation for the function t3lib_BEfunc::getFlexFormDS()
426 $dataStructArray = t3lib_BEfunc
::getFlexFormDS($conf, $row, $table,'',$this->WSOL
);
427 $currentValueArray = t3lib_div
::xml2array($value);
429 // Traversing the XML structure, processing files:
430 if (is_array($currentValueArray)) {
431 $this->temp_flexRelations
= array(
434 'softrefs' => array()
437 // Create and call iterator object:
438 $flexObj = t3lib_div
::makeInstance('t3lib_flexformtools');
439 $flexObj->traverseFlexFormXMLData($table,$field,$row,$this,'getRelations_flexFormCallBack');
441 // Create an entry for the field:
442 $outRow[$field] = array(
444 'flexFormRels' => $this->temp_flexRelations
,
450 if (strlen($value) && $softRefs = t3lib_BEfunc
::explodeSoftRefParserList($conf['softref'])) {
451 $softRefValue = $value;
452 foreach($softRefs as $spKey => $spParams) {
453 $softRefObj = t3lib_BEfunc
::softRefParserObj($spKey);
454 if (is_object($softRefObj)) {
455 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
456 if (is_array($resultArray)) {
457 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
458 if (strlen($resultArray['content'])) {
459 $softRefValue = $resultArray['content'];
465 if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && strcmp($value,$softRefValue) && strstr($softRefValue,'{softref:')) {
466 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
476 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
478 * @param array Data structure for the current value
479 * @param mixed Current value
480 * @param array Additional configuration used in calling function
481 * @param string Path of value in DS structure
482 * @param object Object reference to caller
484 * @see t3lib_TCEmain::checkValue_flex_procInData_travDS()
486 function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, $pObj) {
487 $structurePath = substr($structurePath,5).'/'; // removing "data/" in the beginning of path (which points to location in data array)
489 $dsConf = $dsArr['TCEforms']['config'];
491 // Implode parameter values:
492 list($table, $uid, $field) = array($PA['table'],$PA['uid'],$PA['field']);
495 if ($result = $this->getRelations_procFiles($dataValue, $dsConf, $uid)) {
497 // Creates an entry for the field with all the files:
498 $this->temp_flexRelations
['file'][$structurePath] = $result;
502 if ($result = $this->getRelations_procDB($dataValue, $dsConf, $uid)) {
504 // Create an entry for the field with all DB relations:
505 $this->temp_flexRelations
['db'][$structurePath] = $result;
509 if (strlen($dataValue) && $softRefs = t3lib_BEfunc
::explodeSoftRefParserList($dsConf['softref'])) {
510 $softRefValue = $dataValue;
511 foreach($softRefs as $spKey => $spParams) {
512 $softRefObj = t3lib_BEfunc
::softRefParserObj($spKey);
513 if (is_object($softRefObj)) {
514 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
515 if (is_array($resultArray) && is_array($resultArray['elements'])) {
516 $this->temp_flexRelations
['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
517 if (strlen($resultArray['content'])) $softRefValue = $resultArray['content'];
522 if (count($this->temp_flexRelations
['softrefs']) && strcmp($dataValue,$softRefValue)) {
523 $this->temp_flexRelations
['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
529 * Check field configuration if it is a file relation field and extract file relations if any
531 * @param string Field value
532 * @param array Field configuration array of type "TCA/columns"
533 * @param integer Field uid
534 * @return array If field type is OK it will return an array with the files inside. Else false
536 function getRelations_procFiles($value, $conf, $uid) {
537 // Take care of files...
538 if ($conf['type'] == 'group' && ($conf['internal_type'] == 'file' ||
$conf['internal_type'] == 'file_reference')) {
540 // Collect file values in array:
542 $theFileValues = array();
543 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
544 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
546 foreach($dbAnalysis->itemArray
as $somekey => $someval) {
547 if ($someval['id']) {
548 $theFileValues[] = $someval['id'];
552 $theFileValues = explode(',',$value);
555 // Traverse the files and add them:
556 $uploadFolder = $conf['internal_type'] == 'file' ?
$conf['uploadfolder'] : '';
557 $dest = $this->destPathFromUploadFolder($uploadFolder);
559 $newValueFiles = array();
561 foreach($theFileValues as $file) {
563 $realFile = $dest.'/'.trim($file);
564 # if (@is_file($realFile)) { // Now, the refernece index should NOT look if files exist - just faithfully include them if they are in the records!
565 $newValueFiles[] = array(
566 'filename' => basename($file),
567 'ID' => md5($realFile),
568 'ID_absFile' => $realFile
569 ); // the order should be preserved here because.. (?)
570 # } else $this->error('Missing file: '.$realFile);
574 return $newValueFiles;
579 * Check field configuration if it is a DB relation field and extract DB relations if any
581 * @param string Field value
582 * @param array Field configuration array of type "TCA/columns"
583 * @param integer Field uid
584 * @param string Table name
585 * @return array If field type is OK it will return an array with the database relations. Else false
587 function getRelations_procDB($value, $conf, $uid, $table = '') {
590 if ($this->isReferenceField($conf)) {
591 $allowedTables = $conf['type']=='group' ?
$conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
592 $prependName = $conf['type']=='group' ?
$conf['prepend_tname'] : $conf['neg_foreign_table'];
594 if($conf['MM_opposite_field']) {
598 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
599 $dbAnalysis->start($value,$allowedTables,$conf['MM'],$uid,$table,$conf);
601 return $dbAnalysis->itemArray
;
616 /*******************************
620 *******************************/
623 * Setting the value of a reference or removing it completely.
624 * Usage: For lowlevel clean up operations!
625 * WARNING: With this you can set values that are not allowed in the database since it will bypass all checks for validity! Hence it is targetted at clean-up operations. Please use TCEmain in the usual ways if you wish to manipulate references.
626 * Since this interface allows updates to soft reference values (which TCEmain does not directly) you may like to use it for that as an exception to the warning above.
627 * Notice; If you want to remove multiple references from the same field, you MUST start with the one having the highest sorting number. If you don't the removal of a reference with a lower number will recreate an index in which the remaining references in that field has new hash-keys due to new sorting numbers - and you will get errors for the remaining operations which cannot find the hash you feed it!
628 * To ensure proper working only admin-BE_USERS in live workspace should use this function
630 * @param string 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
631 * @param mixed Value you wish to set for reference. If NULL, the reference is removed (unless a soft-reference in which case it can only be set to a blank string). If you wish to set a database reference, use the format "[table]:[uid]". Any other case, the input value is set as-is
632 * @param boolean Return $dataArray only, do not submit it to database.
633 * @param boolean If set, it will bypass check for workspace-zero and admin user
634 * @return string If a return string, that carries an error message, otherwise false (=OK) (except if $returnDataArray is set!)
636 function setReferenceValue($hash,$newValue,$returnDataArray=FALSE
,$bypassWorkspaceAdminCheck=FALSE
) {
638 if (($GLOBALS['BE_USER']->workspace
===0 && $GLOBALS['BE_USER']->isAdmin()) ||
$bypassWorkspaceAdminCheck) {
640 // Get current index from Database:
641 list($refRec) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
644 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash,'sys_refindex')
647 // Check if reference existed.
648 if (is_array($refRec)) {
649 if ($GLOBALS['TCA'][$refRec['tablename']]) {
651 // Get that record from database:
652 list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$refRec['tablename'],'uid='.intval($refRec['recuid']));
654 if (is_array($record)) {
656 // Get all relations from record, filter with fieldname:
657 $dbrels = $this->getRelations($refRec['tablename'],$record,$refRec['field']);
658 if ($dat = $dbrels[$refRec['field']]) {
660 // Initialize data array that is to be sent to TCEmain afterwards:
661 $dataArray = array();
664 switch((string)$dat['type']) {
666 $error = $this->setReferenceValue_dbRels($refRec,$dat['itemArray'],$newValue,$dataArray);
667 if ($error) return $error;
669 case 'file_reference':
671 $this->setReferenceValue_fileRels($refRec,$dat['newValueFiles'],$newValue,$dataArray);
672 if ($error) return $error;
676 if (is_array($dat['flexFormRels']['db'][$refRec['flexpointer']])) {
677 $error = $this->setReferenceValue_dbRels($refRec,$dat['flexFormRels']['db'][$refRec['flexpointer']],$newValue,$dataArray,$refRec['flexpointer']);
678 if ($error) return $error;
681 if (is_array($dat['flexFormRels']['file'][$refRec['flexpointer']])) {
682 $this->setReferenceValue_fileRels($refRec,$dat['flexFormRels']['file'][$refRec['flexpointer']],$newValue,$dataArray,$refRec['flexpointer']);
683 if ($error) return $error;
685 // Soft references in flexforms
686 if ($refRec['softref_key'] && is_array($dat['flexFormRels']['softrefs'][$refRec['flexpointer']]['keys'][$refRec['softref_key']])) {
687 $error = $this->setReferenceValue_softreferences($refRec,$dat['flexFormRels']['softrefs'][$refRec['flexpointer']],$newValue,$dataArray,$refRec['flexpointer']);
688 if ($error) return $error;
693 // Softreferences in the field:
694 if ($refRec['softref_key'] && is_array($dat['softrefs']['keys'][$refRec['softref_key']])) {
695 $error = $this->setReferenceValue_softreferences($refRec,$dat['softrefs'],$newValue,$dataArray);
696 if ($error) return $error;
700 // Data Array, now ready to sent to TCEmain
701 if ($returnDataArray) {
705 // Execute CMD array:
706 $tce = t3lib_div
::makeInstance('t3lib_TCEmain');
707 $tce->stripslashes_values
= FALSE
;
708 $tce->dontProcessTransformations
= TRUE
;
709 $tce->bypassWorkspaceRestrictions
= TRUE
;
710 $tce->bypassFileHandling
= TRUE
;
711 $tce->bypassAccessCheckForRecords
= TRUE
; // Otherwise this cannot update things in deleted records...
713 $tce->start($dataArray,array()); // check has been done previously that there is a backend user which is Admin and also in live workspace
714 $tce->process_datamap();
716 // Return errors if any:
717 if (count($tce->errorLog
)) {
718 return LF
.'TCEmain:'.implode(LF
.'TCEmain:',$tce->errorLog
);
723 } else return 'ERROR: Tablename "'.$refRec['tablename'].'" was not in TCA!';
724 } else return 'ERROR: No reference record with hash="'.$hash.'" was found!';
725 } else return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
729 * Setting a value for a reference for a DB field:
731 * @param array sys_refindex record
732 * @param array Array of references from that field
733 * @param string Value to substitute current value with (or NULL to unset it)
734 * @param array data array in which the new value is set (passed by reference)
735 * @param string Flexform pointer, if in a flex form field.
736 * @return string Error message if any, otherwise false = OK
738 function setReferenceValue_dbRels($refRec,$itemArray,$newValue,&$dataArray,$flexpointer='') {
739 if (!strcmp($itemArray[$refRec['sorting']]['id'],$refRec['ref_uid']) && !strcmp($itemArray[$refRec['sorting']]['table'],$refRec['ref_table'])) {
741 // Setting or removing value:
742 if ($newValue===NULL
) { // Remove value:
743 unset($itemArray[$refRec['sorting']]);
745 list($itemArray[$refRec['sorting']]['table'],$itemArray[$refRec['sorting']]['id']) = explode(':',$newValue);
748 // Traverse and compile new list of records:
749 $saveValue = array();
750 foreach($itemArray as $pair) {
751 $saveValue[] = $pair['table'].'_'.$pair['id'];
754 // Set in data array:
756 $flexToolObj = t3lib_div
::makeInstance('t3lib_flexformtools');
757 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
758 $flexToolObj->setArrayValueByPath(substr($flexpointer,0,-1),$dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'],implode(',',$saveValue));
760 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',',$saveValue);
763 } else return 'ERROR: table:id pair "'.$refRec['ref_table'].':'.$refRec['ref_uid'].'" did not match that of the record ("'.$itemArray[$refRec['sorting']]['table'].':'.$itemArray[$refRec['sorting']]['id'].'") in sorting index "'.$refRec['sorting'].'"';
767 * Setting a value for a reference for a FILE field:
769 * @param array sys_refindex record
770 * @param array Array of references from that field
771 * @param string Value to substitute current value with (or NULL to unset it)
772 * @param array data array in which the new value is set (passed by reference)
773 * @param string Flexform pointer, if in a flex form field.
774 * @return string Error message if any, otherwise false = OK
776 function setReferenceValue_fileRels($refRec,$itemArray,$newValue,&$dataArray,$flexpointer='') {
777 if (!strcmp(substr($itemArray[$refRec['sorting']]['ID_absFile'],strlen(PATH_site
)),$refRec['ref_string']) && !strcmp('_FILE',$refRec['ref_table'])) {
779 // Setting or removing value:
780 if ($newValue===NULL
) { // Remove value:
781 unset($itemArray[$refRec['sorting']]);
783 $itemArray[$refRec['sorting']]['filename'] = $newValue;
786 // Traverse and compile new list of records:
787 $saveValue = array();
788 foreach($itemArray as $fileInfo) {
789 $saveValue[] = $fileInfo['filename'];
792 // Set in data array:
794 $flexToolObj = t3lib_div
::makeInstance('t3lib_flexformtools');
795 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
796 $flexToolObj->setArrayValueByPath(substr($flexpointer,0,-1),$dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'],implode(',',$saveValue));
798 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',',$saveValue);
801 } else return 'ERROR: either "'.$refRec['ref_table'].'" was not "_FILE" or file PATH_site+"'.$refRec['ref_string'].'" did not match that of the record ("'.$itemArray[$refRec['sorting']]['ID_absFile'].'") in sorting index "'.$refRec['sorting'].'"';
805 * Setting a value for a soft reference token
807 * @param array sys_refindex record
808 * @param array Array of soft reference occurencies
809 * @param string Value to substitute current value with
810 * @param array data array in which the new value is set (passed by reference)
811 * @param string Flexform pointer, if in a flex form field.
812 * @return string Error message if any, otherwise false = OK
814 function setReferenceValue_softreferences($refRec,$softref,$newValue,&$dataArray,$flexpointer='') {
815 if (is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
818 $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = ''.$newValue;
820 // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
821 foreach($softref['keys'] as $sfIndexes) {
822 foreach($sfIndexes as $data) {
823 $softref['tokenizedContent'] = str_replace('{softref:'.$data['subst']['tokenID'].'}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
827 // Set in data array:
828 if (!strstr($softref['tokenizedContent'],'{softref:')) {
830 $flexToolObj = t3lib_div
::makeInstance('t3lib_flexformtools');
831 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
832 $flexToolObj->setArrayValueByPath(substr($flexpointer,0,-1),$dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'],$softref['tokenizedContent']);
834 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
836 } else return 'ERROR: After substituting all found soft references there were still soft reference tokens in the text. (theoretically this does not have to be an error if the string "{softref:" happens to be in the field for another reason.)';
837 } else return 'ERROR: Soft reference parser key "'.$refRec['softref_key'].'" or the index "'.$refRec['softref_id'].'" was not found.';
849 /*******************************
853 *******************************/
856 * Indexing words from table records. Can be useful for quick backend look ups in records across the system.
858 function wordIndexing($table,$uid) {
859 return; // Disabled until Kasper finishes this feature. If someone else needs it in the meantime you are welcome to complete it. Below my todo list.
862 // - Flag to disable indexing
863 // - Clean-up to remove words not used anymore and indexes for records not in the system anymore.
864 // - UTF-8 compliant substr()
865 $lexer = t3lib_div
::makeInstance('tx_indexedsearch_lexer');
866 $words = $lexer->split2Words(implode(' ',$this->words_strings
));
867 foreach($words as $w) {
868 $words[]=substr($w,0,3);
870 $words = array_unique($words);
871 $this->updateWordIndex($words,$table,$uid);
875 * Update/Create word index for record
877 * @param array Word list array (words are values in array)
878 * @param string Table
879 * @param integer Rec uid
882 function updateWordIndex($words,$table,$uid) {
885 $this->submitWords($words);
887 // Result id and remove relations:
888 $rid = t3lib_div
::md5int($table.':'.$uid);
889 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex_rel', 'rid='.intval($rid));
892 foreach($words as $w) {
893 $insertFields = array(
895 'wid' => t3lib_div
::md5int($w)
898 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_rel', $insertFields);
901 // Add result record:
902 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex_res', 'rid='.intval($rid));
903 $insertFields = array(
905 'tablename' => $table,
908 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_res', $insertFields);
912 * Adds new words to db
914 * @param array Word List array (where each word has information about position etc).
917 function submitWords($wl) {
921 $hashArr[] = t3lib_div
::md5int($w);
923 $wl = array_flip($wl);
925 if (count($hashArr)) {
926 $cwl = implode(',',$hashArr);
927 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('baseword', 'sys_refindex_words', 'wid IN ('.$cwl.')');
929 if($GLOBALS['TYPO3_DB']->sql_num_rows($res)!=count($wl)) {
930 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
931 unset($wl[$row['baseword']]);
934 foreach ($wl as $key => $val) {
935 $insertFields = array(
936 'wid' => t3lib_div
::md5int($key),
940 // 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.
941 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_words', $insertFields);
953 /*******************************
957 *******************************/
960 * Returns true if the TCA/columns field type is a DB reference field
962 * @param array config array for TCA/columns field
963 * @return boolean True if DB reference field (group/db or select with foreign-table)
965 function isReferenceField($conf) {
966 return ($conf['type']=='group' && $conf['internal_type']=='db') ||
(($conf['type']=='select' ||
$conf['type']=='inline') && $conf['foreign_table']);
970 * Returns destination path to an upload folder given by $folder
972 * @param string Folder relative to PATH_site
973 * @return string Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
975 function destPathFromUploadFolder($folder) {
977 return substr(PATH_site
, 0, -1);
979 return PATH_site
.$folder;
983 * Sets error message in the internal error log
985 * @param string Error message
988 function error($msg) {
989 $this->errorLog
[]=$msg;
993 * Updating Index (External API)
995 * @param boolean If set, only a test
996 * @param boolean If set, output CLI status
997 * @return array Header and body status content
999 function updateIndex($testOnly,$cli_echo=FALSE
) {
1000 global $TCA, $TYPO3_DB;
1003 $tableNames = array();
1007 $headerContent = $testOnly ?
'Reference Index being TESTED (nothing written, use "-e" to update)' : 'Reference Index being Updated';
1009 '*******************************************'.LF
.
1011 '*******************************************'.LF
;
1013 // Traverse all tables:
1014 foreach ($TCA as $tableName => $cfg) {
1015 $tableNames[] = $tableName;
1018 // Traverse all records in tables, including deleted records:
1019 $allRecs = $TYPO3_DB->exec_SELECTgetRows('uid',$tableName,'1=1'); //.t3lib_BEfunc::deleteClause($tableName)
1020 $uidList = array(0);
1021 foreach ($allRecs as $recdat) {
1022 $refIndexObj = t3lib_div
::makeInstance('t3lib_refindex');
1023 $result = $refIndexObj->updateRefIndexTable($tableName,$recdat['uid'],$testOnly);
1024 $uidList[]= $recdat['uid'];
1027 if ($result['addedNodes'] ||
$result['deletedNodes']) {
1028 $Err = 'Record '.$tableName.':'.$recdat['uid'].' had '.$result['addedNodes'].' added indexes and '.$result['deletedNodes'].' deleted indexes';
1030 if ($cli_echo) echo $Err.LF
;
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.LF
;
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.LF
;
1052 if (!$testOnly) $TYPO3_DB->exec_DELETEquery('sys_refindex',$where);
1055 $testedHowMuch = $recCount.' records from '.$tableCount.' tables were checked/updated.'.LF
;
1057 $bodyContent = $testedHowMuch.(count($errors)?
implode(LF
,$errors):'Index Integrity was perfect!');
1058 if ($cli_echo) echo $testedHowMuch.(count($errors)?
'Updates: '.count($errors):'Index Integrity was perfect!').LF
;
1061 $registry = t3lib_div
::makeInstance('t3lib_Registry');
1062 $registry->set('core', 'sys_refindex_lastUpdate', $GLOBALS['EXEC_TIME']);
1065 return array($headerContent,$bodyContent,count($errors));
1070 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_refindex.php']) {
1071 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_refindex.php']);