Fixed bug #17150: Workspaces non-admin user cannot send to next stage (Thanks to...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_refindex.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * [CLASS/FUNCTION INDEX of SCRIPT]
29 *
30 *
31 *
32 * 89: class t3lib_refindex
33 * 107: function updateRefIndexTable($table,$uid,$testOnly=FALSE)
34 * 178: function generateRefIndexData($table,$uid)
35 * 255: function createEntryData($table,$uid,$field,$flexpointer,$deleted,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='')
36 * 282: function createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$items)
37 * 299: function createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$items)
38 * 320: function createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$keys)
39 *
40 * SECTION: Get relations from table row
41 * 376: function getRelations($table,$row,$onlyField='')
42 * 473: function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, &$pObj)
43 * 523: function getRelations_procFiles($value, $conf, $uid)
44 * 573: function getRelations_procDB($value, $conf, $uid)
45 *
46 * SECTION: Setting values
47 * 616: function setReferenceValue($hash,$newValue,$returnDataArray=FALSE)
48 * 699: function setReferenceValue_dbRels($refRec,$itemArray,$newValue,&$dataArray,$flexpointer='')
49 * 737: function setReferenceValue_fileRels($refRec,$itemArray,$newValue,&$dataArray,$flexpointer='')
50 * 775: function setReferenceValue_softreferences($refRec,$softref,$newValue,&$dataArray,$flexpointer='')
51 *
52 * SECTION: Helper functions
53 * 822: function isReferenceField($conf)
54 * 832: function destPathFromUploadFolder($folder)
55 * 842: function error($msg)
56 * 853: function updateIndex($testOnly,$cli_echo=FALSE)
57 *
58 * TOTAL FUNCTIONS: 18
59 * (This index is automatically created/updated by the extension "extdeveval")
60 *
61 */
62
63
64 /**
65 * Reference index processing and relation extraction
66 *
67 * NOTICE: When the reference index is updated for an offline version the results may not be correct.
68 * First, lets assumed that the reference update happens in LIVE workspace (ALWAYS update from Live workspace if you analyse whole database!)
69 * 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.
70 * 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!
71 * 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?
72 * Anyway, I just wanted to document this finding - I don't think we can find a solution for it. And its very TemplaVoila specific.
73 *
74 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
75 * @package TYPO3
76 * @subpackage t3lib
77 */
78 class t3lib_refindex {
79
80 var $temp_flexRelations = array();
81 var $errorLog = array();
82 var $WSOL = FALSE;
83 var $relations = array();
84
85 var $words_strings = array();
86 var $words = array();
87
88 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.
89
90
91 /**
92 * Call this function to update the sys_refindex table for a record (even one just deleted)
93 * 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.
94 *
95 * @param string Table name
96 * @param integer UID of record
97 * @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.
98 * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
99 */
100 function updateRefIndexTable($table, $uid, $testOnly = FALSE) {
101
102 // First, secure that the index table is not updated with workspace tainted relations:
103 $this->WSOL = FALSE;
104
105 // Init:
106 $result = array(
107 'keptNodes' => 0,
108 'deletedNodes' => 0,
109 'addedNodes' => 0
110 );
111
112 // Get current index from Database:
113 $currentRels = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
114 '*',
115 'sys_refindex',
116 'tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_refindex') .
117 ' AND recuid=' . intval($uid),
118 '', '', '', 'hash'
119 );
120
121 // First, test to see if the record exists (including deleted-flagged)
122 if (t3lib_BEfunc::getRecordRaw($table, 'uid=' . intval($uid), 'uid')) {
123
124 // Then, get relations:
125 $relations = $this->generateRefIndexData($table, $uid);
126
127 if (is_array($relations)) {
128
129 // Traverse the generated index:
130 foreach ($relations as $k => $datRec) {
131 $relations[$k]['hash'] = md5(implode('///', $relations[$k]) . '///' . $this->hashVersion);
132
133 // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
134 if (isset($currentRels[$relations[$k]['hash']])) {
135 unset($currentRels[$relations[$k]['hash']]);
136 $result['keptNodes']++;
137 $relations[$k]['_ACTION'] = 'KEPT';
138 } else {
139 // If new, add it:
140 if (!$testOnly) {
141 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex', $relations[$k]);
142 }
143 $result['addedNodes']++;
144 $relations[$k]['_ACTION'] = 'ADDED';
145 }
146 }
147
148 $result['relations'] = $relations;
149 } else {
150 return FALSE;
151 } // Weird mistake I would say...
152
153 // Words:
154 if (!$testOnly) {
155 $this->wordIndexing($table, $uid);
156 }
157 }
158
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) {
166 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex', 'hash IN (' . implode(',', $GLOBALS['TYPO3_DB']->fullQuoteArray($hashList, 'sys_refindex')) . ')');
167 }
168 }
169 }
170
171 return $result;
172 }
173
174 /**
175 * Returns array of arrays with an index of all references found in record from table/uid
176 * If the result is used to update the sys_refindex table then ->WSOL must NOT be true (no workspace overlay anywhere!)
177 *
178 * @param string Table name from $TCA
179 * @param integer Record UID
180 * @return array Index Rows
181 */
182 function generateRefIndexData($table, $uid) {
183 global $TCA;
184
185 if (isset($TCA[$table])) {
186 // Get raw record from DB:
187 $record = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', $table, 'uid=' . intval($uid));
188
189 if (is_array($record)) {
190
191 // Initialize:
192 $this->words_strings = array();
193 $this->words = array();
194
195 // Deleted:
196 $deleted = $TCA[$table]['ctrl']['delete'] ? ($record[$TCA[$table]['ctrl']['delete']] ? 1 : 0) : 0;
197
198 // Get all relations from record:
199 $dbrels = $this->getRelations($table, $record);
200
201 // Traverse those relations, compile records to insert in table:
202 $this->relations = array();
203 foreach ($dbrels as $fieldname => $dat) {
204
205 // Based on type,
206 switch ((string) $dat['type']) {
207 case 'db':
208 $this->createEntryData_dbRels($table, $uid, $fieldname, '', $deleted, $dat['itemArray']);
209 break;
210 case 'file_reference':
211 case 'file':
212 $this->createEntryData_fileRels($table, $uid, $fieldname, '', $deleted, $dat['newValueFiles']);
213 break;
214 case 'flex':
215 // DB references:
216 if (is_array($dat['flexFormRels']['db'])) {
217 foreach ($dat['flexFormRels']['db'] as $flexpointer => $subList) {
218 $this->createEntryData_dbRels($table, $uid, $fieldname, $flexpointer, $deleted, $subList);
219 }
220 }
221 // File references (NOT TESTED!)
222 if (is_array($dat['flexFormRels']['file'])) { // Not tested
223 foreach ($dat['flexFormRels']['file'] as $flexpointer => $subList) {
224 $this->createEntryData_fileRels($table, $uid, $fieldname, $flexpointer, $deleted, $subList);
225 }
226 }
227 // Soft references in flexforms (NOT TESTED!)
228 if (is_array($dat['flexFormRels']['softrefs'])) {
229 foreach ($dat['flexFormRels']['softrefs'] as $flexpointer => $subList) {
230 $this->createEntryData_softreferences($table, $uid, $fieldname, $flexpointer, $deleted, $subList['keys']);
231 }
232 }
233 break;
234 }
235
236 // Softreferences in the field:
237 if (is_array($dat['softrefs'])) {
238 $this->createEntryData_softreferences($table, $uid, $fieldname, '', $deleted, $dat['softrefs']['keys']);
239 }
240 }
241
242 // Word indexing:
243 t3lib_div::loadTCA($table);
244 foreach ($TCA[$table]['columns'] as $field => $conf) {
245 if (t3lib_div::inList('input,text', $conf['config']['type']) && strcmp($record[$field], '') && !t3lib_div::testInt($record[$field])) {
246 $this->words_strings[$field] = $record[$field];
247 }
248 }
249
250 return $this->relations;
251 }
252 }
253 }
254
255 /**
256 * Create array with field/value pairs ready to insert in database.
257 * The "hash" field is a fingerprint value across this table.
258 *
259 * @param string Tablename of source record (where reference is located)
260 * @param integer UID of source record (where reference is located)
261 * @param string Fieldname of source record (where reference is located)
262 * @param string Pointer to location inside flexform structure where reference is located in [field]
263 * @param integer Whether record is deleted-flagged or not
264 * @param string For database references; the tablename the reference points to. Special keyword "_FILE" indicates that "ref_string" is a file reference either absolute or relative to PATH_site. Special keyword "_STRING" indicates some special usage (typ. softreference) where "ref_string" is used for the value.
265 * @param integer For database references; The UID of the record (zero "ref_table" is "_FILE" or "_STRING")
266 * @param string For "_FILE" or "_STRING" references: The filepath (relative to PATH_site or absolute) or other string.
267 * @param integer The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
268 * @param string If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
269 * @param string Soft reference ID for key. Might be useful for replace operations.
270 * @return array Array record to insert into table.
271 */
272 function createEntryData($table, $uid, $field, $flexpointer, $deleted, $ref_table, $ref_uid, $ref_string = '', $sort = -1, $softref_key = '', $softref_id = '') {
273 return array(
274 'tablename' => $table,
275 'recuid' => $uid,
276 'field' => $field,
277 'flexpointer' => $flexpointer,
278 'softref_key' => $softref_key,
279 'softref_id' => $softref_id,
280 'sorting' => $sort,
281 'deleted' => $deleted,
282 'ref_table' => $ref_table,
283 'ref_uid' => $ref_uid,
284 'ref_string' => $ref_string,
285 );
286 }
287
288 /**
289 * Enter database references to ->relations array
290 *
291 * @param string [See createEntryData, arg 1]
292 * @param integer [See createEntryData, arg 2]
293 * @param string [See createEntryData, arg 3]
294 * @param string [See createEntryData, arg 4]
295 * @param string [See createEntryData, arg 5]
296 * @param array Data array with databaes relations (table/id)
297 * @return void
298 */
299 function createEntryData_dbRels($table, $uid, $fieldname, $flexpointer, $deleted, $items) {
300 foreach ($items as $sort => $i) {
301 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, $i['table'], $i['id'], '', $sort);
302 }
303 }
304
305 /**
306 * Enter file references to ->relations array
307 *
308 * @param string [See createEntryData, arg 1]
309 * @param integer [See createEntryData, arg 2]
310 * @param string [See createEntryData, arg 3]
311 * @param string [See createEntryData, arg 4]
312 * @param string [See createEntryData, arg 5]
313 * @param array Data array with file relations
314 * @return void
315 */
316 function createEntryData_fileRels($table, $uid, $fieldname, $flexpointer, $deleted, $items) {
317 foreach ($items as $sort => $i) {
318 $filePath = $i['ID_absFile'];
319 if (t3lib_div::isFirstPartOfStr($filePath, PATH_site)) {
320 $filePath = substr($filePath, strlen(PATH_site));
321 }
322 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_FILE', 0, $filePath, $sort);
323 }
324 }
325
326 /**
327 * Enter softref references to ->relations array
328 *
329 * @param string [See createEntryData, arg 1]
330 * @param integer [See createEntryData, arg 2]
331 * @param string [See createEntryData, arg 3]
332 * @param string [See createEntryData, arg 4]
333 * @param string [See createEntryData, arg 5]
334 * @param array Data array with soft reference keys
335 * @return void
336 */
337 function createEntryData_softreferences($table, $uid, $fieldname, $flexpointer, $deleted, $keys) {
338 if (is_array($keys)) {
339 foreach ($keys as $spKey => $elements) {
340 if (is_array($elements)) {
341 foreach ($elements as $subKey => $el) {
342 if (is_array($el['subst'])) {
343 switch ((string) $el['subst']['type']) {
344 case 'db':
345 list($tableName, $recordId) = explode(':', $el['subst']['recordRef']);
346 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, $tableName, $recordId, '', -1, $spKey, $subKey);
347 break;
348 case 'file_reference':
349 case 'file':
350 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_FILE', 0, $el['subst']['relFileName'], -1, $spKey, $subKey);
351 break;
352 case 'string':
353 $this->relations[] = $this->createEntryData($table, $uid, $fieldname, $flexpointer, $deleted, '_STRING', 0, $el['subst']['tokenValue'], -1, $spKey, $subKey);
354 break;
355 }
356 }
357 }
358 }
359 }
360 }
361 }
362
363
364 /*******************************
365 *
366 * Get relations from table row
367 *
368 *******************************/
369
370 /**
371 * Returns relation information for a $table/$row-array
372 * Traverses all fields in input row which are configured in TCA/columns
373 * It looks for hard relations to files and records in the TCA types "select" and "group"
374 *
375 * @param string Table name
376 * @param array Row from table
377 * @param string Specific field to fetch for.
378 * @return array Array with information about relations
379 * @see export_addRecord()
380 */
381 function getRelations($table, $row, $onlyField = '') {
382 global $TCA;
383
384 // Load full table description
385 t3lib_div::loadTCA($table);
386
387 // Initialize:
388 $uid = $row['uid'];
389 $nonFields = explode(',', 'uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,pid');
390
391 $outRow = array();
392 foreach ($row as $field => $value) {
393 if (!in_array($field, $nonFields) && is_array($TCA[$table]['columns'][$field]) && (!$onlyField || $onlyField === $field)) {
394 $conf = $TCA[$table]['columns'][$field]['config'];
395
396 // Add files
397 if ($result = $this->getRelations_procFiles($value, $conf, $uid)) {
398 // Creates an entry for the field with all the files:
399 $outRow[$field] = array(
400 'type' => 'file',
401 'newValueFiles' => $result,
402 );
403 }
404
405 // Add DB:
406 if ($result = $this->getRelations_procDB($value, $conf, $uid, $table)) {
407 // Create an entry for the field with all DB relations:
408 $outRow[$field] = array(
409 'type' => 'db',
410 'itemArray' => $result,
411 );
412 }
413
414 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
415 if ($conf['type'] == 'flex') {
416
417 // Get current value array:
418 // 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()
419 $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $row, $table, '', $this->WSOL);
420 $currentValueArray = t3lib_div::xml2array($value);
421
422 // Traversing the XML structure, processing files:
423 if (is_array($currentValueArray)) {
424 $this->temp_flexRelations = array(
425 'db' => array(),
426 'file' => array(),
427 'softrefs' => array()
428 );
429
430 // Create and call iterator object:
431 $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
432 $flexObj->traverseFlexFormXMLData($table, $field, $row, $this, 'getRelations_flexFormCallBack');
433
434 // Create an entry for the field:
435 $outRow[$field] = array(
436 'type' => 'flex',
437 'flexFormRels' => $this->temp_flexRelations,
438 );
439 }
440 }
441
442 // Soft References:
443 if (strlen($value) && $softRefs = t3lib_BEfunc::explodeSoftRefParserList($conf['softref'])) {
444 $softRefValue = $value;
445 foreach ($softRefs as $spKey => $spParams) {
446 $softRefObj = t3lib_BEfunc::softRefParserObj($spKey);
447 if (is_object($softRefObj)) {
448 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
449 if (is_array($resultArray)) {
450 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
451 if (strlen($resultArray['content'])) {
452 $softRefValue = $resultArray['content'];
453 }
454 }
455 }
456 }
457
458 if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && strcmp($value, $softRefValue) && strstr($softRefValue, '{softref:')) {
459 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
460 }
461 }
462 }
463 }
464
465 return $outRow;
466 }
467
468 /**
469 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
470 *
471 * @param array Data structure for the current value
472 * @param mixed Current value
473 * @param array Additional configuration used in calling function
474 * @param string Path of value in DS structure
475 * @param object Object reference to caller
476 * @return void
477 * @see t3lib_TCEmain::checkValue_flex_procInData_travDS()
478 */
479 function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, $pObj) {
480 $structurePath = substr($structurePath, 5) . '/'; // removing "data/" in the beginning of path (which points to location in data array)
481
482 $dsConf = $dsArr['TCEforms']['config'];
483
484 // Implode parameter values:
485 list($table, $uid, $field) = array($PA['table'], $PA['uid'], $PA['field']);
486
487 // Add files
488 if ($result = $this->getRelations_procFiles($dataValue, $dsConf, $uid)) {
489
490 // Creates an entry for the field with all the files:
491 $this->temp_flexRelations['file'][$structurePath] = $result;
492 }
493
494 // Add DB:
495 if ($result = $this->getRelations_procDB($dataValue, $dsConf, $uid)) {
496
497 // Create an entry for the field with all DB relations:
498 $this->temp_flexRelations['db'][$structurePath] = $result;
499 }
500
501 // Soft References:
502 if (strlen($dataValue) && $softRefs = t3lib_BEfunc::explodeSoftRefParserList($dsConf['softref'])) {
503 $softRefValue = $dataValue;
504 foreach ($softRefs as $spKey => $spParams) {
505 $softRefObj = t3lib_BEfunc::softRefParserObj($spKey);
506 if (is_object($softRefObj)) {
507 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
508 if (is_array($resultArray) && is_array($resultArray['elements'])) {
509 $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
510 if (strlen($resultArray['content'])) {
511 $softRefValue = $resultArray['content'];
512 }
513 }
514 }
515 }
516
517 if (count($this->temp_flexRelations['softrefs']) && strcmp($dataValue, $softRefValue)) {
518 $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
519 }
520 }
521 }
522
523 /**
524 * Check field configuration if it is a file relation field and extract file relations if any
525 *
526 * @param string Field value
527 * @param array Field configuration array of type "TCA/columns"
528 * @param integer Field uid
529 * @return array If field type is OK it will return an array with the files inside. Else false
530 */
531 function getRelations_procFiles($value, $conf, $uid) {
532 // Take care of files...
533 if ($conf['type'] == 'group' && ($conf['internal_type'] == 'file' || $conf['internal_type'] == 'file_reference')) {
534
535 // Collect file values in array:
536 if ($conf['MM']) {
537 $theFileValues = array();
538 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
539 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
540
541 foreach ($dbAnalysis->itemArray as $somekey => $someval) {
542 if ($someval['id']) {
543 $theFileValues[] = $someval['id'];
544 }
545 }
546 } else {
547 $theFileValues = explode(',', $value);
548 }
549
550 // Traverse the files and add them:
551 $uploadFolder = $conf['internal_type'] == 'file' ? $conf['uploadfolder'] : '';
552 $dest = $this->destPathFromUploadFolder($uploadFolder);
553 $newValue = array();
554 $newValueFiles = array();
555
556 foreach ($theFileValues as $file) {
557 if (trim($file)) {
558 $realFile = $dest . '/' . trim($file);
559 # if (@is_file($realFile)) { // Now, the refernece index should NOT look if files exist - just faithfully include them if they are in the records!
560 $newValueFiles[] = array(
561 'filename' => basename($file),
562 'ID' => md5($realFile),
563 'ID_absFile' => $realFile
564 ); // the order should be preserved here because.. (?)
565 # } else $this->error('Missing file: '.$realFile);
566 }
567 }
568
569 return $newValueFiles;
570 }
571 }
572
573 /**
574 * Check field configuration if it is a DB relation field and extract DB relations if any
575 *
576 * @param string Field value
577 * @param array Field configuration array of type "TCA/columns"
578 * @param integer Field uid
579 * @param string Table name
580 * @return array If field type is OK it will return an array with the database relations. Else false
581 */
582 function getRelations_procDB($value, $conf, $uid, $table = '') {
583
584 // DB record lists:
585 if ($this->isReferenceField($conf)) {
586 $allowedTables = $conf['type'] == 'group' ? $conf['allowed'] : $conf['foreign_table'] . ',' . $conf['neg_foreign_table'];
587 $prependName = $conf['type'] == 'group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
588
589 if ($conf['MM_opposite_field']) {
590 return array();
591 }
592
593 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
594 $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
595
596 return $dbAnalysis->itemArray;
597 }
598 }
599
600
601 /*******************************
602 *
603 * Setting values
604 *
605 *******************************/
606
607 /**
608 * Setting the value of a reference or removing it completely.
609 * Usage: For lowlevel clean up operations!
610 * 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.
611 * 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.
612 * 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!
613 * To ensure proper working only admin-BE_USERS in live workspace should use this function
614 *
615 * @param string 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
616 * @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
617 * @param boolean Return $dataArray only, do not submit it to database.
618 * @param boolean If set, it will bypass check for workspace-zero and admin user
619 * @return string If a return string, that carries an error message, otherwise false (=OK) (except if $returnDataArray is set!)
620 */
621 function setReferenceValue($hash, $newValue, $returnDataArray = FALSE, $bypassWorkspaceAdminCheck = FALSE) {
622
623 if (($GLOBALS['BE_USER']->workspace === 0 && $GLOBALS['BE_USER']->isAdmin()) || $bypassWorkspaceAdminCheck) {
624
625 // Get current index from Database:
626 $refRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
627 '*',
628 'sys_refindex',
629 'hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'sys_refindex')
630 );
631
632 // Check if reference existed.
633 if (is_array($refRec)) {
634 if ($GLOBALS['TCA'][$refRec['tablename']]) {
635
636 // Get that record from database:
637 $record = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', $refRec['tablename'], 'uid=' . intval($refRec['recuid']));
638
639 if (is_array($record)) {
640
641 // Get all relations from record, filter with fieldname:
642 $dbrels = $this->getRelations($refRec['tablename'], $record, $refRec['field']);
643 if ($dat = $dbrels[$refRec['field']]) {
644
645 // Initialize data array that is to be sent to TCEmain afterwards:
646 $dataArray = array();
647
648 // Based on type,
649 switch ((string) $dat['type']) {
650 case 'db':
651 $error = $this->setReferenceValue_dbRels($refRec, $dat['itemArray'], $newValue, $dataArray);
652 if ($error) {
653 return $error;
654 }
655 break;
656 case 'file_reference':
657 case 'file':
658 $this->setReferenceValue_fileRels($refRec, $dat['newValueFiles'], $newValue, $dataArray);
659 if ($error) {
660 return $error;
661 }
662 break;
663 case 'flex':
664 // DB references:
665 if (is_array($dat['flexFormRels']['db'][$refRec['flexpointer']])) {
666 $error = $this->setReferenceValue_dbRels($refRec, $dat['flexFormRels']['db'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
667 if ($error) {
668 return $error;
669 }
670 }
671 // File references
672 if (is_array($dat['flexFormRels']['file'][$refRec['flexpointer']])) {
673 $this->setReferenceValue_fileRels($refRec, $dat['flexFormRels']['file'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
674 if ($error) {
675 return $error;
676 }
677 }
678 // Soft references in flexforms
679 if ($refRec['softref_key'] && is_array($dat['flexFormRels']['softrefs'][$refRec['flexpointer']]['keys'][$refRec['softref_key']])) {
680 $error = $this->setReferenceValue_softreferences($refRec, $dat['flexFormRels']['softrefs'][$refRec['flexpointer']], $newValue, $dataArray, $refRec['flexpointer']);
681 if ($error) {
682 return $error;
683 }
684 }
685 break;
686 }
687
688 // Softreferences in the field:
689 if ($refRec['softref_key'] && is_array($dat['softrefs']['keys'][$refRec['softref_key']])) {
690 $error = $this->setReferenceValue_softreferences($refRec, $dat['softrefs'], $newValue, $dataArray);
691 if ($error) {
692 return $error;
693 }
694
695 }
696
697 // Data Array, now ready to sent to TCEmain
698 if ($returnDataArray) {
699 return $dataArray;
700 } else {
701
702 // Execute CMD array:
703 $tce = t3lib_div::makeInstance('t3lib_TCEmain');
704 $tce->stripslashes_values = FALSE;
705 $tce->dontProcessTransformations = TRUE;
706 $tce->bypassWorkspaceRestrictions = TRUE;
707 $tce->bypassFileHandling = TRUE;
708 $tce->bypassAccessCheckForRecords = TRUE; // Otherwise this cannot update things in deleted records...
709
710 $tce->start($dataArray, array()); // check has been done previously that there is a backend user which is Admin and also in live workspace
711 $tce->process_datamap();
712
713 // Return errors if any:
714 if (count($tce->errorLog)) {
715 return LF . 'TCEmain:' . implode(LF . 'TCEmain:', $tce->errorLog);
716 }
717 }
718 }
719 }
720 } else {
721 return 'ERROR: Tablename "' . $refRec['tablename'] . '" was not in TCA!';
722 }
723 } else {
724 return 'ERROR: No reference record with hash="' . $hash . '" was found!';
725 }
726 } else {
727 return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
728 }
729 }
730
731 /**
732 * Setting a value for a reference for a DB field:
733 *
734 * @param array sys_refindex record
735 * @param array Array of references from that field
736 * @param string Value to substitute current value with (or NULL to unset it)
737 * @param array data array in which the new value is set (passed by reference)
738 * @param string Flexform pointer, if in a flex form field.
739 * @return string Error message if any, otherwise false = OK
740 */
741 function setReferenceValue_dbRels($refRec, $itemArray, $newValue, &$dataArray, $flexpointer = '') {
742 if (!strcmp($itemArray[$refRec['sorting']]['id'], $refRec['ref_uid']) && !strcmp($itemArray[$refRec['sorting']]['table'], $refRec['ref_table'])) {
743
744 // Setting or removing value:
745 if ($newValue === NULL) { // Remove value:
746 unset($itemArray[$refRec['sorting']]);
747 } else {
748 list($itemArray[$refRec['sorting']]['table'], $itemArray[$refRec['sorting']]['id']) = explode(':', $newValue);
749 }
750
751 // Traverse and compile new list of records:
752 $saveValue = array();
753 foreach ($itemArray as $pair) {
754 $saveValue[] = $pair['table'] . '_' . $pair['id'];
755 }
756
757 // Set in data array:
758 if ($flexpointer) {
759 $flexToolObj = t3lib_div::makeInstance('t3lib_flexformtools');
760 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
761 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
762 } else {
763 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
764 }
765
766 } else {
767 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 }
769 }
770
771 /**
772 * Setting a value for a reference for a FILE field:
773 *
774 * @param array sys_refindex record
775 * @param array Array of references from that field
776 * @param string Value to substitute current value with (or NULL to unset it)
777 * @param array data array in which the new value is set (passed by reference)
778 * @param string Flexform pointer, if in a flex form field.
779 * @return string Error message if any, otherwise false = OK
780 */
781 function setReferenceValue_fileRels($refRec, $itemArray, $newValue, &$dataArray, $flexpointer = '') {
782 if (!strcmp(substr($itemArray[$refRec['sorting']]['ID_absFile'], strlen(PATH_site)), $refRec['ref_string']) && !strcmp('_FILE', $refRec['ref_table'])) {
783
784 // Setting or removing value:
785 if ($newValue === NULL) { // Remove value:
786 unset($itemArray[$refRec['sorting']]);
787 } else {
788 $itemArray[$refRec['sorting']]['filename'] = $newValue;
789 }
790
791 // Traverse and compile new list of records:
792 $saveValue = array();
793 foreach ($itemArray as $fileInfo) {
794 $saveValue[] = $fileInfo['filename'];
795 }
796
797 // Set in data array:
798 if ($flexpointer) {
799 $flexToolObj = t3lib_div::makeInstance('t3lib_flexformtools');
800 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
801 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
802 } else {
803 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
804 }
805
806 } else {
807 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'] . '"';
808 }
809 }
810
811 /**
812 * Setting a value for a soft reference token
813 *
814 * @param array sys_refindex record
815 * @param array Array of soft reference occurencies
816 * @param string Value to substitute current value with
817 * @param array data array in which the new value is set (passed by reference)
818 * @param string Flexform pointer, if in a flex form field.
819 * @return string Error message if any, otherwise false = OK
820 */
821 function setReferenceValue_softreferences($refRec, $softref, $newValue, &$dataArray, $flexpointer = '') {
822 if (is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
823
824 // Set new value:
825 $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = '' . $newValue;
826
827 // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
828 foreach ($softref['keys'] as $sfIndexes) {
829 foreach ($sfIndexes as $data) {
830 $softref['tokenizedContent'] = str_replace('{softref:' . $data['subst']['tokenID'] . '}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
831 }
832 }
833
834 // Set in data array:
835 if (!strstr($softref['tokenizedContent'], '{softref:')) {
836 if ($flexpointer) {
837 $flexToolObj = t3lib_div::makeInstance('t3lib_flexformtools');
838 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
839 $flexToolObj->setArrayValueByPath(substr($flexpointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], $softref['tokenizedContent']);
840 } else {
841 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
842 }
843 } else {
844 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.)';
845 }
846 } else {
847 return 'ERROR: Soft reference parser key "' . $refRec['softref_key'] . '" or the index "' . $refRec['softref_id'] . '" was not found.';
848 }
849 }
850
851
852 /*******************************
853 *
854 * Indexing words
855 *
856 *******************************/
857
858 /**
859 * Indexing words from table records. Can be useful for quick backend look ups in records across the system.
860 */
861 function wordIndexing($table, $uid) {
862 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
864 // TODO:
865 // - Flag to disable indexing
866 // - Clean-up to remove words not used anymore and indexes for records not in the system anymore.
867 // - UTF-8 compliant substr()
868 $lexer = t3lib_div::makeInstance('tx_indexedsearch_lexer');
869 $words = $lexer->split2Words(implode(' ', $this->words_strings));
870 foreach ($words as $w) {
871 $words[] = substr($w, 0, 3);
872 }
873 $words = array_unique($words);
874 $this->updateWordIndex($words, $table, $uid);
875 }
876
877 /**
878 * Update/Create word index for record
879 *
880 * @param array Word list array (words are values in array)
881 * @param string Table
882 * @param integer Rec uid
883 * @return void
884 */
885 function updateWordIndex($words, $table, $uid) {
886
887 // Submit words to
888 $this->submitWords($words);
889
890 // Result id and remove relations:
891 $rid = t3lib_div::md5int($table . ':' . $uid);
892 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex_rel', 'rid=' . intval($rid));
893
894 // Add relations:
895 foreach ($words as $w) {
896 $insertFields = array(
897 'rid' => $rid,
898 'wid' => t3lib_div::md5int($w)
899 );
900
901 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_rel', $insertFields);
902 }
903
904 // Add result record:
905 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex_res', 'rid=' . intval($rid));
906 $insertFields = array(
907 'rid' => $rid,
908 'tablename' => $table,
909 'recuid' => $uid
910 );
911 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_res', $insertFields);
912 }
913
914 /**
915 * Adds new words to db
916 *
917 * @param array Word List array (where each word has information about position etc).
918 * @return void
919 */
920 function submitWords($wl) {
921
922 $hashArr = array();
923 foreach ($wl as $w) {
924 $hashArr[] = t3lib_div::md5int($w);
925 }
926 $wl = array_flip($wl);
927
928 if (count($hashArr)) {
929 $cwl = implode(',', $hashArr);
930 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('baseword', 'sys_refindex_words', 'wid IN (' . $cwl . ')');
931
932 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) != count($wl)) {
933 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
934 unset($wl[$row['baseword']]);
935 }
936
937 foreach ($wl as $key => $val) {
938 $insertFields = array(
939 'wid' => t3lib_div::md5int($key),
940 'baseword' => $key
941 );
942
943 // 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.
944 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex_words', $insertFields);
945 }
946 }
947 }
948 }
949
950
951 /*******************************
952 *
953 * Helper functions
954 *
955 *******************************/
956
957 /**
958 * Returns true if the TCA/columns field type is a DB reference field
959 *
960 * @param array config array for TCA/columns field
961 * @return boolean True if DB reference field (group/db or select with foreign-table)
962 */
963 function isReferenceField($conf) {
964 return ($conf['type'] == 'group' && $conf['internal_type'] == 'db') || (($conf['type'] == 'select' || $conf['type'] == 'inline') && $conf['foreign_table']);
965 }
966
967 /**
968 * Returns destination path to an upload folder given by $folder
969 *
970 * @param string Folder relative to PATH_site
971 * @return string Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
972 */
973 function destPathFromUploadFolder($folder) {
974 if (!$folder) {
975 return substr(PATH_site, 0, -1);
976 }
977 return PATH_site . $folder;
978 }
979
980 /**
981 * Sets error message in the internal error log
982 *
983 * @param string Error message
984 * @return void
985 */
986 function error($msg) {
987 $this->errorLog[] = $msg;
988 }
989
990 /**
991 * Updating Index (External API)
992 *
993 * @param boolean If set, only a test
994 * @param boolean If set, output CLI status
995 * @return array Header and body status content
996 */
997 function updateIndex($testOnly, $cli_echo = FALSE) {
998 global $TCA, $TYPO3_DB;
999
1000 $errors = array();
1001 $tableNames = array();
1002 $recCount = 0;
1003 $tableCount = 0;
1004
1005 $headerContent = $testOnly ? 'Reference Index being TESTED (nothing written, use "-e" to update)' : 'Reference Index being Updated';
1006 if ($cli_echo) {
1007 echo
1008 '*******************************************' . LF .
1009 $headerContent . LF .
1010 '*******************************************' . LF;
1011 }
1012
1013 // Traverse all tables:
1014 foreach ($TCA as $tableName => $cfg) {
1015 $tableNames[] = $tableName;
1016 $tableCount++;
1017
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'];
1025 $recCount++;
1026
1027 if ($result['addedNodes'] || $result['deletedNodes']) {
1028 $Err = 'Record ' . $tableName . ':' . $recdat['uid'] . ' had ' . $result['addedNodes'] . ' added indexes and ' . $result['deletedNodes'] . ' deleted indexes';
1029 $errors[] = $Err;
1030 if ($cli_echo) {
1031 echo $Err . LF;
1032 }
1033 }
1034 }
1035
1036 // Searching lost indexes for this table:
1037 $where = 'tablename=' . $TYPO3_DB->fullQuoteStr($tableName, 'sys_refindex') . ' AND recuid NOT IN (' . implode(',', $uidList) . ')';
1038 $lostIndexes = $TYPO3_DB->exec_SELECTgetRows('hash', 'sys_refindex', $where);
1039 if (count($lostIndexes)) {
1040 $Err = 'Table ' . $tableName . ' has ' . count($lostIndexes) . ' lost indexes which are now deleted';
1041 $errors[] = $Err;
1042 if ($cli_echo) {
1043 echo $Err . LF;
1044 }
1045 if (!$testOnly) {
1046 $TYPO3_DB->exec_DELETEquery('sys_refindex', $where);
1047 }
1048 }
1049 }
1050
1051 // Searching lost indexes for non-existing tables:
1052 $where = 'tablename NOT IN (' . implode(',', $TYPO3_DB->fullQuoteArray($tableNames, 'sys_refindex')) . ')';
1053 $lostTables = $TYPO3_DB->exec_SELECTgetRows('hash', 'sys_refindex', $where);
1054 if (count($lostTables)) {
1055 $Err = 'Index table hosted ' . count($lostTables) . ' indexes for non-existing tables, now removed';
1056 $errors[] = $Err;
1057 if ($cli_echo) {
1058 echo $Err . LF;
1059 }
1060 if (!$testOnly) {
1061 $TYPO3_DB->exec_DELETEquery('sys_refindex', $where);
1062 }
1063 }
1064
1065 $testedHowMuch = $recCount . ' records from ' . $tableCount . ' tables were checked/updated.' . LF;
1066
1067 $bodyContent = $testedHowMuch . (count($errors) ? implode(LF, $errors) : 'Index Integrity was perfect!');
1068 if ($cli_echo) {
1069 echo $testedHowMuch . (count($errors) ? 'Updates: ' . count($errors) : 'Index Integrity was perfect!') . LF;
1070 }
1071
1072 if (!$testOnly) {
1073 $registry = t3lib_div::makeInstance('t3lib_Registry');
1074 $registry->set('core', 'sys_refindex_lastUpdate', $GLOBALS['EXEC_TIME']);
1075 }
1076
1077 return array($headerContent, $bodyContent, count($errors));
1078 }
1079 }
1080
1081
1082 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_refindex.php'])) {
1083 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_refindex.php']);
1084 }
1085
1086 ?>