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