File: class.t3lib_refindex.php

package info (click to toggle)
typo3-src 4.0.2%2Bdebian-3
  • links: PTS
  • area: main
  • in suites: etch-m68k
  • size: 29,856 kB
  • ctags: 33,382
  • sloc: php: 134,523; xml: 6,976; sql: 1,084; sh: 168; makefile: 45
file content (704 lines) | stat: -rw-r--r-- 26,408 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
<?php
/***************************************************************
*  Copyright notice
*
*  (c) 1999-2006 Kasper Skaarhoj (kasperYYYY@typo3.com)
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*  A copy is found in the textfile GPL.txt and important notices to the license
*  from the author is found in LICENSE.txt distributed with these scripts.
*
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * Reference index processing
 *
 * $Id: class.t3lib_refindex.php 1421 2006-04-10 09:27:15Z mundaun $
 *
 * @author	Kasper Skaarhoj <kasperYYYY@typo3.com>
 */
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 *
 *
 *   76: class t3lib_refindex
 *   94:     function updateRefIndexTable($table,$uid,$testOnly=FALSE)
 *  165:     function generateRefIndexData($table,$uid)
 *  242:     function createEntryData($table,$uid,$field,$flexpointer,$deleted,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='')
 *  269:     function createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$items)
 *  286:     function createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$items)
 *  307:     function createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$keys)
 *
 *              SECTION: Get relations from table row
 *  362:     function getRelations($table,$row)
 *  459:     function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, &$pObj)
 *  509:     function getRelations_procFiles($value, $conf, $uid)
 *  559:     function getRelations_procDB($value, $conf, $uid)
 *
 *              SECTION: Helper functions
 *  596:     function isReferenceField($conf)
 *  606:     function destPathFromUploadFolder($folder)
 *  616:     function error($msg)
 *  627:     function updateIndex($testOnly,$cli_echo=FALSE)
 *
 * TOTAL FUNCTIONS: 14
 * (This index is automatically created/updated by the extension "extdeveval")
 *
 */

require_once(PATH_t3lib.'class.t3lib_tcemain.php');
require_once(PATH_t3lib.'class.t3lib_flexformtools.php');



/**
 * Reference index processing and relation extraction
 *
 * NOTICE: When the reference index is updated for an offline version the results may not be correct. 
 * First, lets assumed that the reference update happens in LIVE workspace (ALWAYS update from Live workspace if you analyse whole database!)
 * 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.
 * 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! 
 * 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?
 * Anyway, I just wanted to document this finding - I don't think we can find a solution for it. And its very TemplaVoila specific.
 *
 * @author	Kasper Skaarhoj <kasperYYYY@typo3.com>
 * @package TYPO3
 * @subpackage t3lib
 */
class t3lib_refindex {

	var $temp_flexRelations = array();
	var $errorLog = array();
	var $WSOL = FALSE;
	var $relations = array();
	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.


	/**
	 * Call this function to update the sys_refindex table for a record.
	 * 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.
	 *
	 * @param	string		Table name
	 * @param	integer		UID of record
	 * @param	boolean		If set, nothing will be written to the index but the result value will still report statistics on what as added, deleted and kept. Can be used for mere analysis.
	 * @return	array		Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
	 */
	function updateRefIndexTable($table,$uid,$testOnly=FALSE)	{

			// First, secure that the index table is not updated with workspace tainted relations:
		$this->WSOL = FALSE;

			// Init:
		$result = array(
			'keptNodes' => 0,
			'deletedNodes' => 0,
			'addedNodes' => 0
		);

			// Get current index from Database:
		$currentRels = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
			'*',
			'sys_refindex',
			'tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table,'sys_refindex').
				' AND recuid='.intval($uid),
			'','','','hash'
		);

			// First, test to see if the record exists (being deleted also means it doesn't exist!)
		if (t3lib_BEfunc::getRecordRaw($table,'uid='.intval($uid),'uid'))	{

				// Then, get relations:
			$relations = $this->generateRefIndexData($table,$uid);

			if (is_array($relations))	{

					// Traverse the generated index:
				foreach($relations as $k => $datRec)	{
					$relations[$k]['hash'] = md5(implode('///',$relations[$k]).'///'.$this->hashVersion);

						// First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
					if (isset($currentRels[$relations[$k]['hash']]))	{
						unset($currentRels[$relations[$k]['hash']]);
						$result['keptNodes']++;
						$relations[$k]['_ACTION'] = 'KEPT';
					} else {
							// If new, add it:
						if (!$testOnly)	$GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_refindex',$relations[$k]);
						$result['addedNodes']++;
						$relations[$k]['_ACTION'] = 'ADDED';
					}
				}

				$result['relations'] = $relations;
			} else return FALSE;	// Weird mistake I would say...
		}

			// If any old are left, remove them:
		if (count($currentRels))	{
			$hashList = array_keys($currentRels);
			if (count($hashList))	{
				$result['deletedNodes'] = count($hashList);
				$result['deletedNodes_hashList'] = implode(',',$hashList);
				if (!$testOnly)	$GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_refindex','hash IN ('.implode(',',$GLOBALS['TYPO3_DB']->fullQuoteArray($hashList,'sys_refindex')).')');
			}
		}

		return $result;
	}

	/**
	 * Returns array of arrays with an index of all references found in record from table/uid
	 * If the result is used to update the sys_refindex table then ->WSOL must NOT be true (no workspace overlay anywhere!)
	 *
	 * @param	string		Table name from $TCA
	 * @param	integer		Record UID
	 * @return	array		Index Rows
	 */
	function generateRefIndexData($table,$uid)	{
		global $TCA;

		if (isset($TCA[$table]))	{
				// Get raw record from DB:
			list($record) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*',$table,'uid='.intval($uid));

			if (is_array($record))	{

					// Deleted:
				$deleted = $TCA[$table]['ctrl']['delete'] ? ($record[$TCA[$table]['ctrl']['delete']]?1:0) : 0;

					// Get all relations from record:
				$dbrels = $this->getRelations($table,$record);

					// Traverse those relations, compile records to insert in table:
				$this->relations = array();
				foreach($dbrels as $fieldname => $dat)	{

 						// Based on type,
 					switch((string)$dat['type'])	{
 						case 'db':
 							$this->createEntryData_dbRels($table,$uid,$fieldname,'',$deleted,$dat['itemArray']);
 						break;
 						case 'file':
 							$this->createEntryData_fileRels($table,$uid,$fieldname,'',$deleted,$dat['newValueFiles']);
 						break;
 						case 'flex':
								// DB references:
							if (is_array($dat['flexFormRels']['db']))	{
								foreach($dat['flexFormRels']['db'] as $flexpointer => $subList)	{
									$this->createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$subList);
								}
							}
								// File references (NOT TESTED!)
							if (is_array($dat['flexFormRels']['file']))	{	// Not tested
								foreach($dat['flexFormRels']['file'] as $flexpointer => $subList)	{
									$this->createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$subList);
								}
							}
								// Soft references in flexforms (NOT TESTED!)
							if (is_array($dat['flexFormRels']['softrefs']))	{
								foreach($dat['flexFormRels']['softrefs'] as $flexpointer => $subList)	{
									$this->createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$subList['keys']);
								}
							}
 						break;
 					}

 						// Softreferences in the field:
 					if (is_array($dat['softrefs']))	{
 						$this->createEntryData_softreferences($table,$uid,$fieldname,'',$deleted,$dat['softrefs']['keys']);
 					}
				}

				return $this->relations;
			}
		}
	}

	/**
	 * Create array with field/value pairs ready to insert in database.
	 * The "hash" field is a fingerprint value across this table.
	 *
	 * @param	string		Tablename of source record (where reference is located)
	 * @param	integer		UID of source record (where reference is located)
	 * @param	string		Fieldname of source record (where reference is located)
	 * @param	string		Pointer to location inside flexform structure where reference is located in [field]
	 * @param	integer		Whether record is deleted-flagged or not
	 * @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.
	 * @param	integer		For database references; The UID of the record (zero "ref_table" is "_FILE" or "_STRING")
	 * @param	string		For "_FILE" or "_STRING" references: The filepath (relative to PATH_site or absolute) or other string.
	 * @param	integer		The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
	 * @param	string		If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
	 * @param	string		Soft reference ID for key. Might be useful for replace operations.
	 * @return	array		Array record to insert into table.
	 */
	function createEntryData($table,$uid,$field,$flexpointer,$deleted,$ref_table,$ref_uid,$ref_string='',$sort=-1,$softref_key='',$softref_id='')	{
		return array(
			'tablename' => $table,
			'recuid' => $uid,
			'field' => $field,
			'flexpointer' => $flexpointer,
			'softref_key' => $softref_key,
			'softref_id' => $softref_id,
			'sorting' => $sort,
			'deleted' => $deleted,
			'ref_table' => $ref_table,
			'ref_uid' => $ref_uid,
			'ref_string' => $ref_string,
		);
	}

	/**
	 * Enter database references to ->relations array
	 *
	 * @param	string		[See createEntryData, arg 1]
	 * @param	integer		[See createEntryData, arg 2]
	 * @param	string		[See createEntryData, arg 3]
	 * @param	string		[See createEntryData, arg 4]
	 * @param	string		[See createEntryData, arg 5]
	 * @param	array		Data array with databaes relations (table/id)
	 * @return	void
	 */
	function createEntryData_dbRels($table,$uid,$fieldname,$flexpointer,$deleted,$items)	{
		foreach($items as $sort => $i)	{
			$this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,$i['table'],$i['id'],'',$sort);
		}
	}

	/**
	 * Enter file references to ->relations array
	 *
	 * @param	string		[See createEntryData, arg 1]
	 * @param	integer		[See createEntryData, arg 2]
	 * @param	string		[See createEntryData, arg 3]
	 * @param	string		[See createEntryData, arg 4]
	 * @param	string		[See createEntryData, arg 5]
	 * @param	array		Data array with file relations
	 * @return	void
	 */
	function createEntryData_fileRels($table,$uid,$fieldname,$flexpointer,$deleted,$items)	{
		foreach($items as $sort => $i)	{
			$filePath = $i['ID_absFile'];
			if (t3lib_div::isFirstPartOfStr($filePath,PATH_site))	{
				$filePath = substr($filePath,strlen(PATH_site));
			}
			$this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_FILE',0,$filePath,$sort);
		}
	}

	/**
	 * Enter softref references to ->relations array
	 *
	 * @param	string		[See createEntryData, arg 1]
	 * @param	integer		[See createEntryData, arg 2]
	 * @param	string		[See createEntryData, arg 3]
	 * @param	string		[See createEntryData, arg 4]
	 * @param	string		[See createEntryData, arg 5]
	 * @param	array		Data array with soft reference keys
	 * @return	void
	 */
	function createEntryData_softreferences($table,$uid,$fieldname,$flexpointer,$deleted,$keys)	{
		if (is_array($keys))	{
			foreach($keys as $spKey => $elements)	{
				if (is_array($elements))	{
					foreach($elements as $subKey => $el)	{
						if (is_array($el['subst']))	{
							switch((string)$el['subst']['type'])	{
								 case 'db':
								 	list($tableName,$recordId) = explode(':',$el['subst']['recordRef']);
								 	$this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,$tableName,$recordId,'',-1,$spKey,$subKey);
								 break;
								 case 'file':
								 	$this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_FILE',0,$el['subst']['relFileName'],-1,$spKey,$subKey);
								 break;
								 case 'string':
								 	$this->relations[] = $this->createEntryData($table,$uid,$fieldname,$flexpointer,$deleted,'_STRING',0,$el['subst']['tokenValue'],-1,$spKey,$subKey);
								 break;
							}
						}
					}
				}
			}
		}
	}















	/*******************************
	 *
	 * Get relations from table row
	 *
	 *******************************/

	/**
	 * Returns relation information for a $table/$row-array
	 * Traverses all fields in input row which are configured in TCA/columns
	 * It looks for hard relations to files and records in the TCA types "select" and "group"
	 *
	 * @param	string		Table name
	 * @param	array		Row from table
	 * @return	array		Array with information about relations
	 * @see export_addRecord()
	 */
	function getRelations($table,$row)	{
		global $TCA;

			// Load full table description
		t3lib_div::loadTCA($table);

			// Initialize:
		$uid = $row['uid'];
		$nonFields = explode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,pid');

		$outRow = array();
		foreach($row as $field => $value)	{
			if (!in_array($field,$nonFields) && is_array($TCA[$table]['columns'][$field]))	{
				$conf = $TCA[$table]['columns'][$field]['config'];

					// Add files
				if ($result = $this->getRelations_procFiles($value, $conf, $uid))	{
						// Creates an entry for the field with all the files:
					$outRow[$field] = array(
						'type' => 'file',
						'newValueFiles' => $result,
					);
				}

					// Add DB:
				if ($result = $this->getRelations_procDB($value, $conf, $uid))	{
						// Create an entry for the field with all DB relations:
					$outRow[$field] = array(
						'type' => 'db',
						'itemArray' => $result,
					);
				}

					// For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
				if ($conf['type']=='flex')	{

						// Get current value array:
					$dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $row, $table,'',$this->WSOL);
					$currentValueArray = t3lib_div::xml2array($value);

						// Traversing the XML structure, processing files:
					if (is_array($currentValueArray))	{
						$this->temp_flexRelations = array(
							'db' => array(),
							'file' => array(),
							'softrefs' => array()
						);

							// Create and call iterator object:
						$flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
						$flexObj->traverseFlexFormXMLData($table,$field,$row,$this,'getRelations_flexFormCallBack');

							// Create an entry for the field:
						$outRow[$field] = array(
							'type' => 'flex',
							'flexFormRels' => $this->temp_flexRelations,
						);
					}
				}

					// Soft References:
				if (strlen($value) && $softRefs = t3lib_BEfunc::explodeSoftRefParserList($conf['softref']))	{
					$softRefValue = $value;
					foreach($softRefs as $spKey => $spParams)	{
						$softRefObj = &t3lib_BEfunc::softRefParserObj($spKey);
						if (is_object($softRefObj))	{
							$resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
							if (is_array($resultArray))	{
								$outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
								if (strlen($resultArray['content'])) {
									$softRefValue = $resultArray['content'];
								}
							}
						}
					}

					if (is_array($outRow[$field]['softrefs']) && count($outRow[$field]['softrefs']) && strcmp($value,$softRefValue) && strstr($softRefValue,'{softref:'))	{
						$outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
					}
				}
			}
		}

		return $outRow;
	}

	/**
	 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
	 *
	 * @param	array		Data structure for the current value
	 * @param	mixed		Current value
	 * @param	array		Additional configuration used in calling function
	 * @param	string		Path of value in DS structure
	 * @param	object		Object reference to caller
	 * @return	void
	 * @see t3lib_TCEmain::checkValue_flex_procInData_travDS()
	 */
	function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, &$pObj)	{
		$structurePath = substr($structurePath,5).'/';	// removing "data/" in the beginning of path (which points to location in data array)

		$dsConf = $dsArr['TCEforms']['config'];

			// Implode parameter values:
		list($table, $uid, $field) = array($PA['table'],$PA['uid'],$PA['field']);

			// Add files
		if ($result = $this->getRelations_procFiles($dataValue, $dsConf, $uid))	{

				// Creates an entry for the field with all the files:
			$this->temp_flexRelations['file'][$structurePath] = $result;
		}

			// Add DB:
		if ($result = $this->getRelations_procDB($dataValue, $dsConf, $uid))	{

				// Create an entry for the field with all DB relations:
			$this->temp_flexRelations['db'][$structurePath] = $result;
		}

			// Soft References:
		if (strlen($dataValue) && $softRefs = t3lib_BEfunc::explodeSoftRefParserList($dsConf['softref']))	{
			$softRefValue = $dataValue;
			foreach($softRefs as $spKey => $spParams)	{
				$softRefObj = &t3lib_BEfunc::softRefParserObj($spKey);
				if (is_object($softRefObj))	{
					$resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
					if (is_array($resultArray) && is_array($resultArray['elements']))	{
						$this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
						if (strlen($resultArray['content'])) $softRefValue = $resultArray['content'];
					}
				}
			}

			if (count($this->temp_flexRelations['softrefs']) && strcmp($dataValue,$softRefValue))	{
				$this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
			}
		}
	}

	/**
	 * Check field configuration if it is a file relation field and extract file relations if any
	 *
	 * @param	string		Field value
	 * @param	array		Field configuration array of type "TCA/columns"
	 * @param	integer		Field uid
	 * @return	array		If field type is OK it will return an array with the files inside. Else false
	 */
	function getRelations_procFiles($value, $conf, $uid)	{
			// Take care of files...
		if ($conf['type']=='group' && $conf['internal_type']=='file')	{

				// Collect file values in array:
			if ($conf['MM'])	{
				$theFileValues = array();
				$dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
				$dbAnalysis->start('', 'files', $conf['MM'], $uid);

				foreach($dbAnalysis->itemArray as $somekey => $someval)	{
					if ($someval['id'])	{
						$theFileValues[] = $someval['id'];
					}
				}
			} else {
				$theFileValues = explode(',',$value);
			}

				// Traverse the files and add them:
			$uploadFolder = $conf['uploadfolder'];
			$dest = $this->destPathFromUploadFolder($uploadFolder);
			$newValue = array();
			$newValueFiles = array();

			foreach($theFileValues as $file)	{
				if (trim($file))	{
					$realFile = $dest.'/'.trim($file);
					if (@is_file($realFile))	{
						$newValueFiles[] = array(
							'filename' => $file,
							'ID' => md5($realFile),
							'ID_absFile' => $realFile
						);	// the order should be preserved here because.. (?)
					} else $this->error('Missing file: '.$realFile);
				}
			}

			return $newValueFiles;
		}
	}

	/**
	 * Check field configuration if it is a DB relation field and extract DB relations if any
	 *
	 * @param	string		Field value
	 * @param	array		Field configuration array of type "TCA/columns"
	 * @param	integer		Field uid
	 * @return	array		If field type is OK it will return an array with the database relations. Else false
	 */
	function getRelations_procDB($value, $conf, $uid)	{

			// DB record lists:
		if ($this->isReferenceField($conf))	{
			$allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
			$prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];

			$dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
			$dbAnalysis->start($value,$allowedTables,$conf['MM'],$uid);

			return $dbAnalysis->itemArray;
		}
	}












	/*******************************
	 *
	 * Helper functions
	 *
	 *******************************/

	/**
	 * Returns true if the TCA/columns field type is a DB reference field
	 *
	 * @param	array		config array for TCA/columns field
	 * @return	boolean		True if DB reference field (group/db or select with foreign-table)
	 */
	function isReferenceField($conf)	{
		return ($conf['type']=='group' && $conf['internal_type']=='db') ||	($conf['type']=='select' && $conf['foreign_table']);
	}

	/**
	 * Returns destination path to an upload folder given by $folder
	 *
	 * @param	string		Folder relative to PATH_site
	 * @return	string		Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
	 */
	function destPathFromUploadFolder($folder)	{
		return PATH_site.$folder;
	}

	/**
	 * Sets error message in the internal error log
	 *
	 * @param	string		Error message
	 * @return	void
	 */
	function error($msg)	{
		$this->errorLog[]=$msg;
	}

	/**
	 * Updating Index (External API)
	 *
	 * @param	boolean		If set, only a test
	 * @param	boolean		If set, output CLI status
	 * @return	array		Header and body status content
	 */
	function updateIndex($testOnly,$cli_echo=FALSE)	{
		global $TCA, $TYPO3_DB;

		$errors = array();
		$tableNames = array();
		$recCount=0;
		$tableCount=0;

		$headerContent = $testOnly ? 'Reference Index TESTED (nothing written)' : 'Reference Index Updated';
		if ($cli_echo) echo
						'*******************************************'.chr(10).
						$headerContent.chr(10).
						'*******************************************'.chr(10);

			// Traverse all tables:
		foreach ($TCA as $tableName => $cfg)	{
			$tableNames[] = $tableName;
			$tableCount++;

				// Traverse all non-deleted records in tables:
			$allRecs = $TYPO3_DB->exec_SELECTgetRows('uid',$tableName,'1=1');	//.t3lib_BEfunc::deleteClause($tableName)
			$uidList = array(0);
			foreach ($allRecs as $recdat)	{
				$refIndexObj = t3lib_div::makeInstance('t3lib_refindex');
				$result = $refIndexObj->updateRefIndexTable($tableName,$recdat['uid'],$testOnly);
				$uidList[]= $recdat['uid'];
				$recCount++;

				if ($result['addedNodes'] || $result['deletedNodes'])	{
					$Err = 'Record '.$tableName.':'.$recdat['uid'].' had '.$result['addedNodes'].' added indexes and '.$result['deletedNodes'].' deleted indexes';
					$errors[]= $Err;
					if ($cli_echo) echo $Err.chr(10);
					#$errors[] = t3lib_div::view_array($result);
				}
			}

				// Searching lost indexes for this table:
			$where = 'tablename='.$TYPO3_DB->fullQuoteStr($tableName,'sys_refindex').' AND recuid NOT IN ('.implode(',',$uidList).')';
			$lostIndexes = $TYPO3_DB->exec_SELECTgetRows('hash','sys_refindex',$where);
			if (count($lostIndexes))	{
				$Err = 'Table '.$tableName.' has '.count($lostIndexes).' lost indexes which are now deleted';
				$errors[]= $Err;
				if ($cli_echo) echo $Err.chr(10);
				if (!$testOnly)	$TYPO3_DB->exec_DELETEquery('sys_refindex',$where);
			}
		}

			// Searching lost indexes for non-existing tables:
		$where = 'tablename NOT IN ('.implode(',',$TYPO3_DB->fullQuoteArray($tableNames,'sys_refindex')).')';
		$lostTables = $TYPO3_DB->exec_SELECTgetRows('hash','sys_refindex',$where);
		if (count($lostTables))	{
			$Err = 'Index table hosted '.count($lostTables).' indexes for non-existing tables, now removed';
			$errors[]= $Err;
			if ($cli_echo) echo $Err.chr(10);
			if (!$testOnly)	$TYPO3_DB->exec_DELETEquery('sys_refindex',$where);
		}

		$testedHowMuch = $recCount.' records from '.$tableCount.' tables were checked/updated.'.chr(10);

		$bodyContent = $testedHowMuch.(count($errors)?implode(chr(10),$errors):'Index Integrity was perfect!');
		if ($cli_echo) echo $testedHowMuch.(count($errors)?'Updates: '.count($errors):'Index Integrity was perfect!').chr(10);

		return array($headerContent,$bodyContent);
	}
}


if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_refindex.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_refindex.php']);
}
?>