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