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