[CLEANUP] ReferenceIndex
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Database / ReferenceIndex.php
1 <?php
2 namespace TYPO3\CMS\Core\Database;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Cache\CacheManager;
19 use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
20 use TYPO3\CMS\Core\DataHandling\DataHandler;
21 use TYPO3\CMS\Core\Messaging\FlashMessage;
22 use TYPO3\CMS\Core\Registry;
23 use TYPO3\CMS\Core\Resource\File;
24 use TYPO3\CMS\Core\Resource\Folder;
25 use TYPO3\CMS\Core\Resource\ResourceFactory;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\PathUtility;
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
36 * 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
37 * on the Data Structure set in the Live workspace!
38 * 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
39 * 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 * Definition of tables to exclude from searching for relations
48 *
49 * Only tables which do not contain any relations and never did so far since references also won't be deleted for
50 * these. Since only tables with an entry in $GLOBALS['TCA] are handled by ReferenceIndex there is no need to add
51 * *_mm-tables.
52 *
53 * This is implemented as an array with fields as keys and booleans as values to be able to fast isset() instead of
54 * slow in_array() lookup.
55 *
56 * @var array
57 * @see updateRefIndexTable()
58 * @todo #65461 Create configuration for tables to exclude from ReferenceIndex
59 */
60 static protected $nonRelationTables = array(
61 'sys_log' => TRUE,
62 'sys_history' => TRUE,
63 'tx_extensionmanager_domain_model_extension' => TRUE
64 );
65
66 /**
67 * Definition of fields to exclude from searching for relations
68 *
69 * This is implemented as an array with fields as keys and booleans as values to be able to fast isset() instead of
70 * slow in_array() lookup.
71 *
72 * @var array
73 * @see getRelations()
74 * @see fetchTableRelationFields()
75 * @todo #65460 Create configuration for fields to exclude from ReferenceIndex
76 */
77 static protected $nonRelationFields = array(
78 'uid' => TRUE,
79 'perms_userid' => TRUE,
80 'perms_groupid' => TRUE,
81 'perms_user' => TRUE,
82 'perms_group' => TRUE,
83 'perms_everybody' => TRUE,
84 'pid' => TRUE
85 );
86
87 /**
88 * Fields of tables that could contain relations are cached per table. This is the prefix for the cache entries since
89 * the runtimeCache has a global scope.
90 *
91 * @var string
92 */
93 static protected $cachePrefixTableRelationFields = 'core-refidx-tblRelFields-';
94
95 /**
96 * This array holds the FlexForm references of a record
97 *
98 * @var array
99 * @see getRelations(),FlexFormTools::traverseFlexFormXMLData(),getRelations_flexFormCallBack()
100 */
101 public $temp_flexRelations = array();
102
103 /**
104 * Unused log for errors in ReferenceIndex
105 *
106 * @var array
107 * @see error()
108 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
109 */
110 public $errorLog = array();
111
112 /**
113 * This variable used to indicate whether referencing should take workspace overlays into account
114 * It is not used since commit 0c34dac08605ba from 10.04.2006, the bug is investigated in https://forge.typo3.org/issues/65725
115 *
116 * @var bool
117 * @see getRelations()
118 */
119 public $WSOL = FALSE;
120
121 /**
122 * An index of all found references of a single record created in createEntryData() and accumulated in generateRefIndexData()
123 *
124 * @var array
125 * @see createEntryData(),generateRefIndexData()
126 */
127 public $relations = array();
128
129 /**
130 * Number which we can increase if a change in the code means we will have to force a re-generation of the index.
131 *
132 * @var int
133 * @see updateRefIndexTable()
134 */
135 public $hashVersion = 1;
136
137 /**
138 * Current workspace id
139 *
140 * @var int
141 */
142 protected $workspaceId = 0;
143
144 /**
145 * Runtime Cache to store and retrieve data computed for a single request
146 *
147 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
148 */
149 protected $runtimeCache = NULL;
150
151 /**
152 * Constructor
153 */
154 public function __construct() {
155 $this->runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
156 }
157
158 /**
159 * Sets the current workspace id
160 *
161 * @param int $workspaceId
162 * @see updateIndex()
163 */
164 public function setWorkspaceId($workspaceId) {
165 $this->workspaceId = (int)$workspaceId;
166 }
167
168 /**
169 * Gets the current workspace id
170 *
171 * @return int
172 * @see updateRefIndexTable(),createEntryData()
173 */
174 public function getWorkspaceId() {
175 return $this->workspaceId;
176 }
177
178 /**
179 * Call this function to update the sys_refindex table for a record (even one just deleted)
180 * NOTICE: Currently, references updated for a deleted-flagged record will not include those from within FlexForm
181 * fields in some cases where the data structure is defined by another record since the resolving process ignores
182 * deleted records! This will also result in bad cleaning up in DataHandler I think... Anyway, that's the story of
183 * FlexForms; as long as the DS can change, lots of references can get lost in no time.
184 *
185 * @param string $tableName Table name
186 * @param int $uid UID of record
187 * @param bool $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.
188 * @return array Array with statistics about how many index records were added, deleted and not altered plus the complete reference set for the record.
189 */
190 public function updateRefIndexTable($tableName, $uid, $testOnly = FALSE) {
191
192 // First, secure that the index table is not updated with workspace tainted relations:
193 $this->WSOL = FALSE;
194
195 // Init:
196 $result = array(
197 'keptNodes' => 0,
198 'deletedNodes' => 0,
199 'addedNodes' => 0
200 );
201
202 // If this table cannot contain relations, skip it
203 if (isset(static::$nonRelationTables[$tableName])) {
204 return $result;
205 }
206
207 // Fetch tableRelationFields and save them in cache if not there yet
208 $cacheId = static::$cachePrefixTableRelationFields . $tableName;
209 if (!$this->runtimeCache->has($cacheId)) {
210 $tableRelationFields = $this->fetchTableRelationFields($tableName);
211 $this->runtimeCache->set($cacheId, $tableRelationFields);
212 } else {
213 $tableRelationFields = $this->runtimeCache->get($cacheId);
214 }
215
216 $databaseConnection = $this->getDatabaseConnection();
217
218 // Get current index from Database with hash as index using $uidIndexField
219 $currentRelations = $databaseConnection->exec_SELECTgetRows(
220 '*',
221 'sys_refindex',
222 'tablename=' . $databaseConnection->fullQuoteStr($tableName, 'sys_refindex')
223 . ' AND recuid=' . (int)$uid . ' AND workspace=' . $this->getWorkspaceId(),
224 '', '', '', 'hash'
225 );
226
227 // If the table has fields which could contain relations and the record does exist (including deleted-flagged)
228 if ($tableRelationFields !== '' && BackendUtility::getRecordRaw($tableName, 'uid=' . (int)$uid, 'uid')) {
229 // Then, get relations:
230 $relations = $this->generateRefIndexData($tableName, $uid);
231 if (is_array($relations)) {
232 // Traverse the generated index:
233 foreach ($relations as &$relation) {
234 if (!is_array($relation)) {
235 continue;
236 }
237 $relation['hash'] = md5(implode('///', $relation) . '///' . $this->hashVersion);
238 // First, check if already indexed and if so, unset that row (so in the end we know which rows to remove!)
239 if (isset($currentRelations[$relation['hash']])) {
240 unset($currentRelations[$relation['hash']]);
241 $result['keptNodes']++;
242 $relation['_ACTION'] = 'KEPT';
243 } else {
244 // If new, add it:
245 if (!$testOnly) {
246 $databaseConnection->exec_INSERTquery('sys_refindex', $relation);
247 }
248 $result['addedNodes']++;
249 $relation['_ACTION'] = 'ADDED';
250 }
251 }
252 $result['relations'] = $relations;
253 } else {
254 return $result;
255 }
256 }
257
258 // If any old are left, remove them:
259 if (!empty($currentRelations)) {
260 $hashList = array_keys($currentRelations);
261 if (!empty($hashList)) {
262 $result['deletedNodes'] = count($hashList);
263 $result['deletedNodes_hashList'] = implode(',', $hashList);
264 if (!$testOnly) {
265 $databaseConnection->exec_DELETEquery(
266 'sys_refindex', 'hash IN (' . implode(',', $databaseConnection->fullQuoteArray($hashList, 'sys_refindex')) . ')'
267 );
268 }
269 }
270 }
271
272 return $result;
273 }
274
275 /**
276 * Returns array of arrays with an index of all references found in record from table/uid
277 * If the result is used to update the sys_refindex table then ->WSOL must NOT be TRUE (no workspace overlay anywhere!)
278 *
279 * @param string $tableName Table name from $GLOBALS['TCA']
280 * @param int $uid Record UID
281 * @return array|NULL Index Rows
282 */
283 public function generateRefIndexData($tableName, $uid) {
284
285 if (!isset($GLOBALS['TCA'][$tableName])) {
286 return NULL;
287 }
288
289 $this->relations = array();
290
291 // Fetch tableRelationFields and save them in cache if not there yet
292 $cacheId = static::$cachePrefixTableRelationFields . $tableName;
293 if (!$this->runtimeCache->has($cacheId)) {
294 $tableRelationFields = $this->fetchTableRelationFields($tableName);
295 $this->runtimeCache->set($cacheId, $tableRelationFields);
296 } else {
297 $tableRelationFields = $this->runtimeCache->get($cacheId);
298 }
299
300 // Return if there are no fields which could contain relations
301 if ($tableRelationFields === '') {
302 return $this->relations;
303 }
304
305 $deleteField = $GLOBALS['TCA'][$tableName]['ctrl']['delete'];
306
307 if ($tableRelationFields === '*') {
308 // If one field of a record is of type flex, all fields have to be fetched to be passed to BackendUtility::getFlexFormDS
309 $selectFields = '*';
310 } else {
311 // otherwise only fields that might contain relations are fetched
312 $selectFields = 'uid,' . $tableRelationFields . ($deleteField ? ',' . $deleteField : '');
313 }
314
315 // Get raw record from DB:
316 $record = $this->getDatabaseConnection()->exec_SELECTgetSingleRow($selectFields, $tableName, 'uid=' . (int)$uid);
317 if (!is_array($record)) {
318 return NULL;
319 }
320
321 // Deleted:
322 $deleted = $deleteField && $record[$deleteField] ? 1 : 0;
323
324 // Get all relations from record:
325 $recordRelations = $this->getRelations($tableName, $record);
326 // Traverse those relations, compile records to insert in table:
327 foreach ($recordRelations as $fieldName => $fieldRelations) {
328 // Based on type
329 switch ((string)$fieldRelations['type']) {
330 case 'db':
331 $this->createEntryData_dbRels($tableName, $uid, $fieldName, '', $deleted, $fieldRelations['itemArray']);
332 break;
333 case 'file_reference':
334 // not used (see getRelations()), but fallback to file
335 case 'file':
336 $this->createEntryData_fileRels($tableName, $uid, $fieldName, '', $deleted, $fieldRelations['newValueFiles']);
337 break;
338 case 'flex':
339 // DB references in FlexForms
340 if (is_array($fieldRelations['flexFormRels']['db'])) {
341 foreach ($fieldRelations['flexFormRels']['db'] as $flexPointer => $subList) {
342 $this->createEntryData_dbRels($tableName, $uid, $fieldName, $flexPointer, $deleted, $subList);
343 }
344 }
345 // File references in FlexForms
346 // @todo #65463 Test correct handling of file references in FlexForms
347 if (is_array($fieldRelations['flexFormRels']['file'])) {
348 foreach ($fieldRelations['flexFormRels']['file'] as $flexPointer => $subList) {
349 $this->createEntryData_fileRels($tableName, $uid, $fieldName, $flexPointer, $deleted, $subList);
350 }
351 }
352 // Soft references in FlexForms
353 // @todo #65464 Test correct handling of soft references in FlexForms
354 if (is_array($fieldRelations['flexFormRels']['softrefs'])) {
355 foreach ($fieldRelations['flexFormRels']['softrefs'] as $flexPointer => $subList) {
356 $this->createEntryData_softreferences($tableName, $uid, $fieldName, $flexPointer, $deleted, $subList['keys']);
357 }
358 }
359 break;
360 }
361 // Soft references in the field
362 if (is_array($fieldRelations['softrefs'])) {
363 $this->createEntryData_softreferences($tableName, $uid, $fieldName, '', $deleted, $fieldRelations['softrefs']['keys']);
364 }
365 }
366
367 return $this->relations;
368 }
369
370 /**
371 * Create array with field/value pairs ready to insert in database.
372 * The "hash" field is a fingerprint value across this table.
373 *
374 * @param string $table Tablename of source record (where reference is located)
375 * @param int $uid UID of source record (where reference is located)
376 * @param string $field Fieldname of source record (where reference is located)
377 * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in [field]
378 * @param int $deleted Whether record is deleted-flagged or not
379 * @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.
380 * @param int $ref_uid For database references; The UID of the record (zero "ref_table" is "_FILE" or "_STRING")
381 * @param string $ref_string For "_FILE" or "_STRING" references: The filepath (relative to PATH_site or absolute) or other string.
382 * @param int $sort The sorting order of references if many (the "group" or "select" TCA types). -1 if no sorting order is specified.
383 * @param string $softref_key If the reference is a soft reference, this is the soft reference parser key. Otherwise empty.
384 * @param string $softref_id Soft reference ID for key. Might be useful for replace operations.
385 * @return array Array record to insert into table.
386 */
387 public function createEntryData($table, $uid, $field, $flexPointer, $deleted, $ref_table, $ref_uid, $ref_string = '', $sort = -1, $softref_key = '', $softref_id = '') {
388 if (BackendUtility::isTableWorkspaceEnabled($table)) {
389 $element = BackendUtility::getRecord($table, $uid, 't3ver_wsid');
390 if ($element !== NULL && isset($element['t3ver_wsid']) && (int)$element['t3ver_wsid'] !== $this->getWorkspaceId()) {
391 //The given Element is ws-enabled but doesn't live in the selected workspace
392 // => don't add index as it's not actually there
393 return FALSE;
394 }
395 }
396 return array(
397 'tablename' => $table,
398 'recuid' => $uid,
399 'field' => $field,
400 'flexpointer' => $flexPointer,
401 'softref_key' => $softref_key,
402 'softref_id' => $softref_id,
403 'sorting' => $sort,
404 'deleted' => $deleted,
405 'workspace' => $this->getWorkspaceId(),
406 'ref_table' => $ref_table,
407 'ref_uid' => $ref_uid,
408 'ref_string' => $ref_string
409 );
410 }
411
412 /**
413 * Enter database references to ->relations array
414 *
415 * @param string $table Tablename of source record (where reference is located)
416 * @param int $uid UID of source record (where reference is located)
417 * @param string $fieldName Fieldname of source record (where reference is located)
418 * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in [field]
419 * @param int $deleted Whether record is deleted-flagged or not
420 * @param array $items Data array with database relations (table/id)
421 * @return void
422 */
423 public function createEntryData_dbRels($table, $uid, $fieldName, $flexPointer, $deleted, $items) {
424 foreach ($items as $sort => $i) {
425 $this->relations[] = $this->createEntryData($table, $uid, $fieldName, $flexPointer, $deleted, $i['table'], $i['id'], '', $sort);
426 }
427 }
428
429 /**
430 * Enter file references to ->relations array
431 *
432 * @param string $table Tablename of source record (where reference is located)
433 * @param int $uid UID of source record (where reference is located)
434 * @param string $fieldName Fieldname of source record (where reference is located)
435 * @param string $flexPointer Pointer to location inside FlexForm structure where reference is located in [field]
436 * @param int $deleted Whether record is deleted-flagged or not
437 * @param array $items Data array with file relations
438 * @return void
439 */
440 public function createEntryData_fileRels($table, $uid, $fieldName, $flexPointer, $deleted, $items) {
441 foreach ($items as $sort => $i) {
442 $filePath = $i['ID_absFile'];
443 if (GeneralUtility::isFirstPartOfStr($filePath, PATH_site)) {
444 $filePath = PathUtility::stripPathSitePrefix($filePath);
445 }
446 $this->relations[] = $this->createEntryData($table, $uid, $fieldName, $flexPointer, $deleted, '_FILE', 0, $filePath, $sort);
447 }
448 }
449
450 /**
451 * Enter softref references to ->relations array
452 *
453 * @param string $table Tablename of source record (where reference is located)
454 * @param int $uid UID of source record (where reference is located)
455 * @param string $fieldName Fieldname of source record (where reference is located)
456 * @param string $flexPointer Pointer to location inside FlexForm structure
457 * @param int $deleted
458 * @param array $keys Data array with soft reference keys
459 * @return void
460 */
461 public function createEntryData_softreferences($table, $uid, $fieldName, $flexPointer, $deleted, $keys) {
462 if (is_array($keys)) {
463 foreach ($keys as $spKey => $elements) {
464 if (is_array($elements)) {
465 foreach ($elements as $subKey => $el) {
466 if (is_array($el['subst'])) {
467 switch ((string)$el['subst']['type']) {
468 case 'db':
469 list($tableName, $recordId) = explode(':', $el['subst']['recordRef']);
470 $this->relations[] = $this->createEntryData($table, $uid, $fieldName, $flexPointer, $deleted, $tableName, $recordId, '', -1, $spKey, $subKey);
471 break;
472 case 'file_reference':
473 // not used (see getRelations()), but fallback to file
474 case 'file':
475 $this->relations[] = $this->createEntryData($table, $uid, $fieldName, $flexPointer, $deleted, '_FILE', 0, $el['subst']['relFileName'], -1, $spKey, $subKey);
476 break;
477 case 'string':
478 $this->relations[] = $this->createEntryData($table, $uid, $fieldName, $flexPointer, $deleted, '_STRING', 0, $el['subst']['tokenValue'], -1, $spKey, $subKey);
479 break;
480 }
481 }
482 }
483 }
484 }
485 }
486 }
487
488 /*******************************
489 *
490 * Get relations from table row
491 *
492 *******************************/
493
494 /**
495 * Returns relation information for a $table/$row-array
496 * Traverses all fields in input row which are configured in TCA/columns
497 * It looks for hard relations to files and records in the TCA types "select" and "group"
498 *
499 * @param string $table Table name
500 * @param array $row Row from table
501 * @param string $onlyField Specific field to fetch for.
502 * @return array Array with information about relations
503 * @see export_addRecord()
504 */
505 public function getRelations($table, $row, $onlyField = '') {
506 // Initialize:
507 $uid = $row['uid'];
508 $outRow = array();
509 foreach ($row as $field => $value) {
510 if (!isset(static::$nonRelationFields[$field]) && is_array($GLOBALS['TCA'][$table]['columns'][$field]) && (!$onlyField || $onlyField === $field)) {
511 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
512 // Add files
513 $resultsFromFiles = $this->getRelations_procFiles($value, $conf, $uid);
514 if (!empty($resultsFromFiles)) {
515 // We have to fill different arrays here depending on the result.
516 // internal_type file is still a relation of type file and
517 // since http://forge.typo3.org/issues/49538 internal_type file_reference
518 // is a database relation to a sys_file record
519 $fileResultsFromFiles = array();
520 $dbResultsFromFiles = array();
521 foreach ($resultsFromFiles as $resultFromFiles) {
522 if (isset($resultFromFiles['table']) && $resultFromFiles['table'] === 'sys_file') {
523 $dbResultsFromFiles[] = $resultFromFiles;
524 } else {
525 // Creates an entry for the field with all the files:
526 $fileResultsFromFiles[] = $resultFromFiles;
527 }
528 }
529 if (!empty($fileResultsFromFiles)) {
530 $outRow[$field] = array(
531 'type' => 'file',
532 'newValueFiles' => $fileResultsFromFiles
533 );
534 }
535 if (!empty($dbResultsFromFiles)) {
536 $outRow[$field] = array(
537 'type' => 'db',
538 'itemArray' => $dbResultsFromFiles
539 );
540 }
541 }
542 // Add a softref definition for link fields if the TCA does not specify one already
543 if ($conf['type'] === 'input' && isset($conf['wizards']['link']) && empty($conf['softref'])) {
544 $conf['softref'] = 'typolink';
545 }
546 // Add DB:
547 $resultsFromDatabase = $this->getRelations_procDB($value, $conf, $uid, $table, $field);
548 if (!empty($resultsFromDatabase)) {
549 // Create an entry for the field with all DB relations:
550 $outRow[$field] = array(
551 'type' => 'db',
552 'itemArray' => $resultsFromDatabase
553 );
554 }
555 // For "flex" fieldtypes we need to traverse the structure looking for file and db references of course!
556 if ($conf['type'] === 'flex') {
557 // Get current value array:
558 // 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()
559 $currentValueArray = GeneralUtility::xml2array($value);
560 // Traversing the XML structure, processing files:
561 if (is_array($currentValueArray)) {
562 $this->temp_flexRelations = array(
563 'db' => array(),
564 'file' => array(),
565 'softrefs' => array()
566 );
567 // Create and call iterator object:
568 $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
569 $flexFormTools->traverseFlexFormXMLData($table, $field, $row, $this, 'getRelations_flexFormCallBack');
570 // Create an entry for the field:
571 $outRow[$field] = array(
572 'type' => 'flex',
573 'flexFormRels' => $this->temp_flexRelations
574 );
575 }
576 }
577 // Soft References:
578 if ((string)$value !== '') {
579 $softRefValue = $value;
580 $softRefs = BackendUtility::explodeSoftRefParserList($conf['softref']);
581 if ($softRefs !== FALSE) {
582 foreach ($softRefs as $spKey => $spParams) {
583 $softRefObj = BackendUtility::softRefParserObj($spKey);
584 if (is_object($softRefObj)) {
585 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams);
586 if (is_array($resultArray)) {
587 $outRow[$field]['softrefs']['keys'][$spKey] = $resultArray['elements'];
588 if ((string)$resultArray['content'] !== '') {
589 $softRefValue = $resultArray['content'];
590 }
591 }
592 }
593 }
594 }
595 if (!empty($outRow[$field]['softrefs']) && (string)$value !== (string)$softRefValue && strpos($softRefValue, '{softref:') !== FALSE) {
596 $outRow[$field]['softrefs']['tokenizedContent'] = $softRefValue;
597 }
598 }
599 }
600 }
601 return $outRow;
602 }
603
604 /**
605 * Callback function for traversing the FlexForm structure in relation to finding file and DB references!
606 *
607 * @param array $dsArr Data structure for the current value
608 * @param mixed $dataValue Current value
609 * @param array $PA Additional configuration used in calling function
610 * @param string $structurePath Path of value in DS structure
611 * @param object $parentObject Object reference to caller (unused)
612 * @return void
613 * @see DataHandler::checkValue_flex_procInData_travDS(),FlexFormTools::traverseFlexFormXMLData()
614 */
615 public function getRelations_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, $parentObject) {
616 // Removing "data/" in the beginning of path (which points to location in data array)
617 $structurePath = substr($structurePath, 5) . '/';
618 $dsConf = $dsArr['TCEforms']['config'];
619 // Implode parameter values:
620 list($table, $uid, $field) = array(
621 $PA['table'],
622 $PA['uid'],
623 $PA['field']
624 );
625 // Add files
626 $resultsFromFiles = $this->getRelations_procFiles($dataValue, $dsConf, $uid);
627 if (!empty($resultsFromFiles)) {
628 // We have to fill different arrays here depending on the result.
629 // internal_type file is still a relation of type file and
630 // since http://forge.typo3.org/issues/49538 internal_type file_reference
631 // is a database relation to a sys_file record
632 $fileResultsFromFiles = array();
633 $dbResultsFromFiles = array();
634 foreach ($resultsFromFiles as $resultFromFiles) {
635 if (isset($resultFromFiles['table']) && $resultFromFiles['table'] === 'sys_file') {
636 $dbResultsFromFiles[] = $resultFromFiles;
637 } else {
638 $fileResultsFromFiles[] = $resultFromFiles;
639 }
640 }
641 if (!empty($fileResultsFromFiles)) {
642 $this->temp_flexRelations['file'][$structurePath] = $fileResultsFromFiles;
643 }
644 if (!empty($dbResultsFromFiles)) {
645 $this->temp_flexRelations['db'][$structurePath] = $dbResultsFromFiles;
646 }
647 }
648 // Add a softref definition for link fields if the TCA does not specify one already
649 if ($dsConf['type'] === 'input' && isset($dsConf['wizards']['link']) && empty($dsConf['softref'])) {
650 $dsConf['softref'] = 'typolink';
651 }
652 // Add DB:
653 $resultsFromDatabase = $this->getRelations_procDB($dataValue, $dsConf, $uid, $table, $field);
654 if (!empty($resultsFromDatabase)) {
655 // Create an entry for the field with all DB relations:
656 $this->temp_flexRelations['db'][$structurePath] = $resultsFromDatabase;
657 }
658 // Soft References:
659 if (is_array($dataValue) || (string)$dataValue !== '') {
660 $softRefValue = $dataValue;
661 $softRefs = BackendUtility::explodeSoftRefParserList($dsConf['softref']);
662 if ($softRefs !== FALSE) {
663 foreach ($softRefs as $spKey => $spParams) {
664 $softRefObj = BackendUtility::softRefParserObj($spKey);
665 if (is_object($softRefObj)) {
666 $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams, $structurePath);
667 if (is_array($resultArray) && is_array($resultArray['elements'])) {
668 $this->temp_flexRelations['softrefs'][$structurePath]['keys'][$spKey] = $resultArray['elements'];
669 if ((string)$resultArray['content'] !== '') {
670 $softRefValue = $resultArray['content'];
671 }
672 }
673 }
674 }
675 }
676 if (!empty($this->temp_flexRelations['softrefs']) && (string)$dataValue !== (string)$softRefValue) {
677 $this->temp_flexRelations['softrefs'][$structurePath]['tokenizedContent'] = $softRefValue;
678 }
679 }
680 }
681
682 /**
683 * Check field configuration if it is a file relation field and extract file relations if any
684 *
685 * @param string $value Field value
686 * @param array $conf Field configuration array of type "TCA/columns
687 * @param int $uid Field uid
688 * @return bool|array If field type is OK it will return an array with the files inside. Else FALSE
689 */
690 public function getRelations_procFiles($value, $conf, $uid) {
691 if ($conf['type'] !== 'group' || ($conf['internal_type'] !== 'file' && $conf['internal_type'] !== 'file_reference')) {
692 return FALSE;
693 }
694
695 // Collect file values in array:
696 if ($conf['MM']) {
697 $theFileValues = array();
698 $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
699 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
700 foreach ($dbAnalysis->itemArray as $someval) {
701 if ($someval['id']) {
702 $theFileValues[] = $someval['id'];
703 }
704 }
705 } else {
706 $theFileValues = explode(',', $value);
707 }
708 // Traverse the files and add them:
709 $uploadFolder = $conf['internal_type'] === 'file' ? $conf['uploadfolder'] : '';
710 $destinationFolder = $this->destPathFromUploadFolder($uploadFolder);
711 $newValueFiles = array();
712 foreach ($theFileValues as $file) {
713 if (trim($file)) {
714 $realFile = $destinationFolder . '/' . trim($file);
715 $newValueFile = array(
716 'filename' => basename($file),
717 'ID' => md5($realFile),
718 'ID_absFile' => $realFile
719 );
720 // Set sys_file and id for referenced files
721 if ($conf['internal_type'] === 'file_reference') {
722 try {
723 $file = ResourceFactory::getInstance()->retrieveFileOrFolderObject($file);
724 if ($file instanceof File || $file instanceof Folder) {
725 // For setting this as sys_file relation later, the keys filename, ID and ID_absFile
726 // have not to be included, because the are not evaluated for db relations.
727 $newValueFile = array(
728 'table' => 'sys_file',
729 'id' => $file->getUid()
730 );
731 }
732 } catch (\Exception $e) {
733
734 }
735 }
736 $newValueFiles[] = $newValueFile;
737 }
738 }
739 return $newValueFiles;
740 }
741
742 /**
743 * Check field configuration if it is a DB relation field and extract DB relations if any
744 *
745 * @param string $value Field value
746 * @param array $conf Field configuration array of type "TCA/columns
747 * @param int $uid Field uid
748 * @param string $table Table name
749 * @param string $field Field name
750 * @return array If field type is OK it will return an array with the database relations. Else FALSE
751 */
752 public function getRelations_procDB($value, $conf, $uid, $table = '', $field = '') {
753 // Get IRRE relations
754 if (empty($conf)) {
755 return FALSE;
756 } elseif ($conf['type'] === 'inline' && !empty($conf['foreign_table']) && empty($conf['MM'])) {
757 $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
758 $dbAnalysis->setUseLiveReferenceIds(FALSE);
759 $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
760 return $dbAnalysis->itemArray;
761 // DB record lists:
762 } elseif ($this->isDbReferenceField($conf)) {
763 $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'] . ',' . $conf['neg_foreign_table'];
764 if ($conf['MM_opposite_field']) {
765 return array();
766 }
767 $dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
768 $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
769 return $dbAnalysis->itemArray;
770 } elseif ($conf['type'] === 'inline' && $conf['foreign_table'] === 'sys_file_reference') {
771 // @todo It looks like this was never called before since isDbReferenceField also checks for type 'inline' and any 'foreign_table'
772 $files = $this->getDatabaseConnection()->exec_SELECTgetRows(
773 'uid_local',
774 'sys_file_reference',
775 'tablenames=\'' . $table . '\' AND fieldname=\'' . $field . '\' AND uid_foreign=' . $uid . ' AND deleted=0'
776 );
777 $fileArray = array();
778 if (!empty($files)) {
779 foreach ($files as $fileUid) {
780 $fileArray[] = array(
781 'table' => 'sys_file',
782 'id' => $fileUid['uid_local']
783 );
784 }
785 }
786 return $fileArray;
787 }
788 return FALSE;
789 }
790
791 /*******************************
792 *
793 * Setting values
794 *
795 *******************************/
796
797 /**
798 * Setting the value of a reference or removing it completely.
799 * Usage: For lowlevel clean up operations!
800 * WARNING: With this you can set values that are not allowed in the database since it will bypass all checks for validity!
801 * Hence it is targeted at clean-up operations. Please use DataHandler in the usual ways if you wish to manipulate references.
802 * Since this interface allows updates to soft reference values (which DataHandler does not directly) you may like to use it
803 * for that as an exception to the warning above.
804 * Notice; If you want to remove multiple references from the same field, you MUST start with the one having the highest
805 * sorting number. If you don't the removal of a reference with a lower number will recreate an index in which the remaining
806 * references in that field has new hash-keys due to new sorting numbers - and you will get errors for the remaining operations
807 * which cannot find the hash you feed it!
808 * To ensure proper working only admin-BE_USERS in live workspace should use this function
809 *
810 * @param string $hash 32-byte hash string identifying the record from sys_refindex which you wish to change the value for
811 * @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
812 * @param bool $returnDataArray Return $dataArray only, do not submit it to database.
813 * @param bool $bypassWorkspaceAdminCheck If set, it will bypass check for workspace-zero and admin user
814 * @return string|bool|array FALSE (=OK), error message string or array (if $returnDataArray is set!)
815 */
816 public function setReferenceValue($hash, $newValue, $returnDataArray = FALSE, $bypassWorkspaceAdminCheck = FALSE) {
817 $backendUser = $this->getBackendUser();
818 if ($backendUser->workspace === 0 && $backendUser->isAdmin() || $bypassWorkspaceAdminCheck) {
819 $databaseConnection = $this->getDatabaseConnection();
820
821 // Get current index from Database:
822 $referenceRecord = $databaseConnection->exec_SELECTgetSingleRow('*', 'sys_refindex', 'hash=' . $databaseConnection->fullQuoteStr($hash, 'sys_refindex'));
823 // Check if reference existed.
824 if (!is_array($referenceRecord)) {
825 return 'ERROR: No reference record with hash="' . $hash . '" was found!';
826 }
827
828 if (empty($GLOBALS['TCA'][$referenceRecord['tablename']])) {
829 return 'ERROR: Table "' . $referenceRecord['tablename'] . '" was not in TCA!';
830 }
831
832 // Get that record from database:
833 $record = $databaseConnection->exec_SELECTgetSingleRow('*', $referenceRecord['tablename'], 'uid=' . (int)$referenceRecord['recuid']);
834 if (is_array($record)) {
835 // Get relation for single field from record
836 $recordRelations = $this->getRelations($referenceRecord['tablename'], $record, $referenceRecord['field']);
837 if ($fieldRelation = $recordRelations[$referenceRecord['field']]) {
838 // Initialize data array that is to be sent to DataHandler afterwards:
839 $dataArray = array();
840 // Based on type
841 switch ((string)$fieldRelation['type']) {
842 case 'db':
843 $error = $this->setReferenceValue_dbRels($referenceRecord, $fieldRelation['itemArray'], $newValue, $dataArray);
844 if ($error) {
845 return $error;
846 }
847 break;
848 case 'file_reference':
849 // not used (see getRelations()), but fallback to file
850 case 'file':
851 $error = $this->setReferenceValue_fileRels($referenceRecord, $fieldRelation['newValueFiles'], $newValue, $dataArray);
852 if ($error) {
853 return $error;
854 }
855 break;
856 case 'flex':
857 // DB references in FlexForms
858 if (is_array($fieldRelation['flexFormRels']['db'][$referenceRecord['flexpointer']])) {
859 $error = $this->setReferenceValue_dbRels($referenceRecord, $fieldRelation['flexFormRels']['db'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
860 if ($error) {
861 return $error;
862 }
863 }
864 // File references in FlexForms
865 if (is_array($fieldRelation['flexFormRels']['file'][$referenceRecord['flexpointer']])) {
866 $error = $this->setReferenceValue_fileRels($referenceRecord, $fieldRelation['flexFormRels']['file'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
867 if ($error) {
868 return $error;
869 }
870 }
871 // Soft references in FlexForms
872 if ($referenceRecord['softref_key'] && is_array($fieldRelation['flexFormRels']['softrefs'][$referenceRecord['flexpointer']]['keys'][$referenceRecord['softref_key']])) {
873 $error = $this->setReferenceValue_softreferences($referenceRecord, $fieldRelation['flexFormRels']['softrefs'][$referenceRecord['flexpointer']], $newValue, $dataArray, $referenceRecord['flexpointer']);
874 if ($error) {
875 return $error;
876 }
877 }
878 break;
879 }
880 // Soft references in the field:
881 if ($referenceRecord['softref_key'] && is_array($fieldRelation['softrefs']['keys'][$referenceRecord['softref_key']])) {
882 $error = $this->setReferenceValue_softreferences($referenceRecord, $fieldRelation['softrefs'], $newValue, $dataArray);
883 if ($error) {
884 return $error;
885 }
886 }
887 // Data Array, now ready to be sent to DataHandler
888 if ($returnDataArray) {
889 return $dataArray;
890 } else {
891 // Execute CMD array:
892 $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
893 $dataHandler->stripslashes_values = FALSE;
894 $dataHandler->dontProcessTransformations = TRUE;
895 $dataHandler->bypassWorkspaceRestrictions = TRUE;
896 $dataHandler->bypassFileHandling = TRUE;
897 // Otherwise this cannot update things in deleted records...
898 $dataHandler->bypassAccessCheckForRecords = TRUE;
899 // Check has been done previously that there is a backend user which is Admin and also in live workspace
900 $dataHandler->start($dataArray, array());
901 $dataHandler->process_datamap();
902 // Return errors if any:
903 if (!empty($dataHandler->errorLog)) {
904 return LF . 'DataHandler:' . implode((LF . 'DataHandler:'), $dataHandler->errorLog);
905 }
906 }
907 }
908 }
909
910 } else {
911 return 'ERROR: BE_USER object is not admin OR not in workspace 0 (Live)';
912 }
913
914 return FALSE;
915 }
916
917 /**
918 * Setting a value for a reference for a DB field:
919 *
920 * @param array $refRec sys_refindex record
921 * @param array $itemArray Array of references from that field
922 * @param string $newValue Value to substitute current value with (or NULL to unset it)
923 * @param array $dataArray Data array in which the new value is set (passed by reference)
924 * @param string $flexPointer Flexform pointer, if in a flex form field.
925 * @return string Error message if any, otherwise FALSE = OK
926 */
927 public function setReferenceValue_dbRels($refRec, $itemArray, $newValue, &$dataArray, $flexPointer = '') {
928 if ((int)$itemArray[$refRec['sorting']]['id'] === (int)$refRec['ref_uid'] && (string)$itemArray[$refRec['sorting']]['table'] === (string)$refRec['ref_table']) {
929 // Setting or removing value:
930 // Remove value:
931 if ($newValue === NULL) {
932 unset($itemArray[$refRec['sorting']]);
933 } else {
934 list($itemArray[$refRec['sorting']]['table'], $itemArray[$refRec['sorting']]['id']) = explode(':', $newValue);
935 }
936 // Traverse and compile new list of records:
937 $saveValue = array();
938 foreach ($itemArray as $pair) {
939 $saveValue[] = $pair['table'] . '_' . $pair['id'];
940 }
941 // Set in data array:
942 if ($flexPointer) {
943 $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
944 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
945 $flexFormTools->setArrayValueByPath(substr($flexPointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
946 } else {
947 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
948 }
949 } else {
950 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'] . '"';
951 }
952
953 return FALSE;
954 }
955
956 /**
957 * Setting a value for a reference for a FILE field:
958 *
959 * @param array $refRec sys_refindex record
960 * @param array $itemArray Array of references from that field
961 * @param string $newValue Value to substitute current value with (or NULL to unset it)
962 * @param array $dataArray Data array in which the new value is set (passed by reference)
963 * @param string $flexPointer Flexform pointer, if in a flex form field.
964 * @return string Error message if any, otherwise FALSE = OK
965 */
966 public function setReferenceValue_fileRels($refRec, $itemArray, $newValue, &$dataArray, $flexPointer = '') {
967 $ID_absFile = PathUtility::stripPathSitePrefix($itemArray[$refRec['sorting']]['ID_absFile']);
968 if ($ID_absFile === (string)$refRec['ref_string'] && $refRec['ref_table'] === '_FILE') {
969 // Setting or removing value:
970 // Remove value:
971 if ($newValue === NULL) {
972 unset($itemArray[$refRec['sorting']]);
973 } else {
974 $itemArray[$refRec['sorting']]['filename'] = $newValue;
975 }
976 // Traverse and compile new list of records:
977 $saveValue = array();
978 foreach ($itemArray as $fileInfo) {
979 $saveValue[] = $fileInfo['filename'];
980 }
981 // Set in data array:
982 if ($flexPointer) {
983 $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
984 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
985 $flexFormTools->setArrayValueByPath(substr($flexPointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], implode(',', $saveValue));
986 } else {
987 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = implode(',', $saveValue);
988 }
989 } else {
990 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'] . '"';
991 }
992
993 return FALSE;
994 }
995
996 /**
997 * Setting a value for a soft reference token
998 *
999 * @param array $refRec sys_refindex record
1000 * @param array $softref Array of soft reference occurencies
1001 * @param string $newValue Value to substitute current value with
1002 * @param array $dataArray Data array in which the new value is set (passed by reference)
1003 * @param string $flexPointer Flexform pointer, if in a flex form field.
1004 * @return string Error message if any, otherwise FALSE = OK
1005 */
1006 public function setReferenceValue_softreferences($refRec, $softref, $newValue, &$dataArray, $flexPointer = '') {
1007 if (!is_array($softref['keys'][$refRec['softref_key']][$refRec['softref_id']])) {
1008 return 'ERROR: Soft reference parser key "' . $refRec['softref_key'] . '" or the index "' . $refRec['softref_id'] . '" was not found.';
1009 }
1010
1011 // Set new value:
1012 $softref['keys'][$refRec['softref_key']][$refRec['softref_id']]['subst']['tokenValue'] = '' . $newValue;
1013 // Traverse softreferences and replace in tokenized content to rebuild it with new value inside:
1014 foreach ($softref['keys'] as $sfIndexes) {
1015 foreach ($sfIndexes as $data) {
1016 $softref['tokenizedContent'] = str_replace('{softref:' . $data['subst']['tokenID'] . '}', $data['subst']['tokenValue'], $softref['tokenizedContent']);
1017 }
1018 }
1019 // Set in data array:
1020 if (!strstr($softref['tokenizedContent'], '{softref:')) {
1021 if ($flexPointer) {
1022 $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
1023 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'] = array();
1024 $flexFormTools->setArrayValueByPath(substr($flexPointer, 0, -1), $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']]['data'], $softref['tokenizedContent']);
1025 } else {
1026 $dataArray[$refRec['tablename']][$refRec['recuid']][$refRec['field']] = $softref['tokenizedContent'];
1027 }
1028 } else {
1029 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.)';
1030 }
1031
1032 return FALSE;
1033 }
1034
1035 /*******************************
1036 *
1037 * Helper functions
1038 *
1039 *******************************/
1040
1041 /**
1042 * Returns TRUE if the TCA/columns field type is a DB reference field
1043 *
1044 * @param array $configuration Config array for TCA/columns field
1045 * @return bool TRUE if DB reference field (group/db or select with foreign-table)
1046 */
1047 protected function isDbReferenceField(array $configuration) {
1048 return (
1049 ($configuration['type'] === 'group' && $configuration['internal_type'] === 'db')
1050 || (
1051 ($configuration['type'] === 'select' || $configuration['type'] === 'inline')
1052 && !empty($configuration['foreign_table'])
1053 )
1054 );
1055 }
1056
1057 /**
1058 * Returns TRUE if the TCA/columns field type is a reference field
1059 *
1060 * @param array $configuration Config array for TCA/columns field
1061 * @return bool TRUE if reference field
1062 */
1063 public function isReferenceField(array $configuration) {
1064 return (
1065 $this->isDbReferenceField($configuration)
1066 ||
1067 ($configuration['type'] === 'group' && ($configuration['internal_type'] === 'file' || $configuration['internal_type'] === 'file_reference')) // getRelations_procFiles
1068 ||
1069 ($configuration['type'] === 'input' && isset($configuration['wizards']['link'])) // getRelations_procDB
1070 ||
1071 $configuration['type'] === 'flex'
1072 ||
1073 isset($configuration['softref'])
1074 ||
1075 (
1076 // @deprecated global soft reference parsers are deprecated since TYPO3 CMS 7 and will be removed in TYPO3 CMS 8
1077 is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])
1078 && !empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])
1079 )
1080 );
1081 }
1082
1083 /**
1084 * Returns all fields of a table which could contain a relation
1085 *
1086 * @param string $tableName Name of the table
1087 * @return string Fields which could contain a relation
1088 */
1089 protected function fetchTableRelationFields($tableName) {
1090 $fields = array();
1091
1092 foreach ($GLOBALS['TCA'][$tableName]['columns'] as $field => $fieldDefinition) {
1093 if (is_array($fieldDefinition['config'])) {
1094 // Check for flex field
1095 if (isset($fieldDefinition['config']['type']) && $fieldDefinition['config']['type'] === 'flex') {
1096 // Fetch all fields if the is a field of type flex in the table definition because the complete row is passed to
1097 // BackendUtility::getFlexFormDS in the end and might be needed in ds_pointerField or $hookObj->getFlexFormDS_postProcessDS
1098 return '*';
1099 }
1100 // Only fetch this field if it can contain a reference
1101 if ($this->isReferenceField($fieldDefinition['config'])) {
1102 $fields[] = $field;
1103 }
1104 }
1105 }
1106
1107 return implode(',', $fields);
1108 }
1109
1110 /**
1111 * Returns destination path to an upload folder given by $folder
1112 *
1113 * @param string $folder Folder relative to PATH_site
1114 * @return string Input folder prefixed with PATH_site. No checking for existence is done. Output must be a folder without trailing slash.
1115 */
1116 public function destPathFromUploadFolder($folder) {
1117 if (!$folder) {
1118 return substr(PATH_site, 0, -1);
1119 }
1120 return PATH_site . $folder;
1121 }
1122
1123 /**
1124 * Sets error message in the internal error log
1125 *
1126 * @param string $msg Error message
1127 * @return void
1128 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1129 */
1130 public function error($msg) {
1131 GeneralUtility::logDeprecatedFunction();
1132 $this->errorLog[] = $msg;
1133 }
1134
1135 /**
1136 * Updating Index (External API)
1137 *
1138 * @param bool $testOnly If set, only a test
1139 * @param bool $cli_echo If set, output CLI status
1140 * @return array Header and body status content
1141 */
1142 public function updateIndex($testOnly, $cli_echo = FALSE) {
1143 $databaseConnection = $this->getDatabaseConnection();
1144 $errors = array();
1145 $tableNames = array();
1146 $recCount = 0;
1147 $tableCount = 0;
1148 $headerContent = $testOnly ? 'Reference Index being TESTED (nothing written, use "--refindex update" to update)' : 'Reference Index being Updated';
1149 if ($cli_echo) {
1150 echo '*******************************************' . LF . $headerContent . LF . '*******************************************' . LF;
1151 }
1152 // Traverse all tables:
1153 foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
1154 if (isset(static::$nonRelationTables[$tableName])) {
1155 continue;
1156 }
1157 // Traverse all records in tables, including deleted records:
1158 $fieldNames = (BackendUtility::isTableWorkspaceEnabled($tableName) ? 'uid,t3ver_wsid' : 'uid');
1159 $res = $databaseConnection->exec_SELECTquery($fieldNames, $tableName, '1=1');
1160 if ($databaseConnection->sql_error()) {
1161 // Table exists in $TCA but does not exist in the database
1162 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);
1163 continue;
1164 }
1165 $tableNames[] = $tableName;
1166 $tableCount++;
1167 $uidList = array(0);
1168 while ($record = $databaseConnection->sql_fetch_assoc($res)) {
1169 /** @var $refIndexObj ReferenceIndex */
1170 $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class);
1171 if (isset($record['t3ver_wsid'])) {
1172 $refIndexObj->setWorkspaceId($record['t3ver_wsid']);
1173 }
1174 $result = $refIndexObj->updateRefIndexTable($tableName, $record['uid'], $testOnly);
1175 $uidList[] = $record['uid'];
1176 $recCount++;
1177 if ($result['addedNodes'] || $result['deletedNodes']) {
1178 $error = 'Record ' . $tableName . ':' . $record['uid'] . ' had ' . $result['addedNodes'] . ' added indexes and ' . $result['deletedNodes'] . ' deleted indexes';
1179 $errors[] = $error;
1180 if ($cli_echo) {
1181 echo $error . LF;
1182 }
1183 }
1184 }
1185 $databaseConnection->sql_free_result($res);
1186
1187 // Searching lost indexes for this table:
1188 $where = 'tablename=' . $databaseConnection->fullQuoteStr($tableName, 'sys_refindex') . ' AND recuid NOT IN (' . implode(',', $uidList) . ')';
1189 $lostIndexes = $databaseConnection->exec_SELECTgetRows('hash', 'sys_refindex', $where);
1190 $lostIndexesCount = count($lostIndexes);
1191 if ($lostIndexesCount) {
1192 $error = 'Table ' . $tableName . ' has ' . $lostIndexesCount . ' lost indexes which are now deleted';
1193 $errors[] = $error;
1194 if ($cli_echo) {
1195 echo $error . LF;
1196 }
1197 if (!$testOnly) {
1198 $databaseConnection->exec_DELETEquery('sys_refindex', $where);
1199 }
1200 }
1201 }
1202 // Searching lost indexes for non-existing tables:
1203 $where = 'tablename NOT IN (' . implode(',', $databaseConnection->fullQuoteArray($tableNames, 'sys_refindex')) . ')';
1204 $lostTables = $databaseConnection->exec_SELECTgetRows('hash', 'sys_refindex', $where);
1205 $lostTablesCount = count($lostTables);
1206 if ($lostTablesCount) {
1207 $error = 'Index table hosted ' . $lostTablesCount . ' indexes for non-existing tables, now removed';
1208 $errors[] = $error;
1209 if ($cli_echo) {
1210 echo $error . LF;
1211 }
1212 if (!$testOnly) {
1213 $databaseConnection->exec_DELETEquery('sys_refindex', $where);
1214 }
1215 }
1216 $errorCount = count($errors);
1217 $recordsCheckedString = $recCount . ' records from ' . $tableCount . ' tables were checked/updated.' . LF;
1218 $flashMessage = GeneralUtility::makeInstance(
1219 FlashMessage::class,
1220 $errorCount ? implode('##LF##', $errors) : 'Index Integrity was perfect!',
1221 $recordsCheckedString,
1222 $errorCount ? FlashMessage::ERROR : FlashMessage::OK
1223 );
1224 $bodyContent = $flashMessage->render();
1225 if ($cli_echo) {
1226 echo $recordsCheckedString . ($errorCount ? 'Updates: ' . $errorCount : 'Index Integrity was perfect!') . LF;
1227 }
1228 if (!$testOnly) {
1229 $registry = GeneralUtility::makeInstance(Registry::class);
1230 $registry->set('core', 'sys_refindex_lastUpdate', $GLOBALS['EXEC_TIME']);
1231 }
1232 return array($headerContent, $bodyContent, $errorCount);
1233 }
1234
1235 /**
1236 * Return DatabaseConnection
1237 *
1238 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
1239 */
1240 protected function getDatabaseConnection() {
1241 return $GLOBALS['TYPO3_DB'];
1242 }
1243
1244 /**
1245 * Returns the current BE user.
1246 *
1247 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1248 */
1249 protected function getBackendUser() {
1250 return $GLOBALS['BE_USER'];
1251 }
1252
1253 }