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