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