DataMapProcessor.php 40.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace TYPO3\CMS\Core\DataHandling\Localization;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
21
use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
22
23
24
25
26
27
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\RelationHandler;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Utility\StringUtility;
28
use TYPO3\CMS\Lang\LanguageService;
29
30
31
32
33
34
35
36
37
38
39
40
41

/**
 * This processor analyses the provided data-map before actually being process
 * in the calling DataHandler instance. Field names that are configured to have
 * "allowLanguageSynchronization" enabled are either synchronized from there
 * relative parent records (could be a default language record, or a l10n_source
 * record) or to their dependent records (in case a default language record or
 * nested records pointing upwards with l10n_source).
 *
 * Except inline relational record editing, all modifications are applied to
 * the data-map directly, which ensures proper history entries as a side-effect.
 * For inline relational record editing, this processor either triggers the copy
 * or localize actions by instantiation a new local DataHandler instance.
42
43
44
45
 *
 * Namings in this class:
 * + forTableName, forId always refers to dependencies data is provided *for*
 * + fromTableName, fromId always refers to ancestors data is retrieved *from*
46
47
48
49
50
51
52
53
 */
class DataMapProcessor
{
    /**
     * @var array
     */
    protected $dataMap = [];

54
55
56
57
58
    /**
     * @var array
     */
    protected $sanitizationMap = [];

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    /**
     * @var BackendUserAuthentication
     */
    protected $backendUser;

    /**
     * @var DataMapItem[]
     */
    protected $items = [];

    /**
     * Class generator
     *
     * @param array $dataMap The submitted data-map to be worked on
     * @param BackendUserAuthentication $backendUser Forwared backend-user scope
     * @return DataMapProcessor
     */
    public static function instance(array $dataMap, BackendUserAuthentication $backendUser)
    {
        return GeneralUtility::makeInstance(
            static::class,
            $dataMap,
            $backendUser
        );
    }

    /**
     * @param array $dataMap The submitted data-map to be worked on
     * @param BackendUserAuthentication $backendUser Forwared backend-user scope
     */
    public function __construct(array $dataMap, BackendUserAuthentication $backendUser)
    {
        $this->dataMap = $dataMap;
        $this->backendUser = $backendUser;
    }

    /**
     * Processes the submitted data-map and returns the sanitized and enriched
     * version depending on accordant localization states and dependencies.
     *
     * @return array
     */
    public function process()
    {
        foreach ($this->dataMap as $tableName => $idValues) {
            $this->collectItems($tableName, $idValues);
        }
106
107
108
109
        if (!empty($this->items)) {
            $this->sanitize();
            $this->enrich();
        }
110
111
112
113
114
115
116
117
118
119
120
        return $this->dataMap;
    }

    /**
     * Create data map items of all affected rows
     *
     * @param string $tableName
     * @param array $idValues
     */
    protected function collectItems(string $tableName, array $idValues)
    {
121
122
123
124
125
126
        $forTableName = $tableName;
        if ($forTableName === 'pages') {
            $forTableName = 'pages_language_overlay';
        }

        if (!$this->isApplicable($forTableName)) {
127
128
129
130
131
132
            return;
        }

        $fieldNames = [
            'uid' => 'uid',
            'l10n_state' => 'l10n_state',
133
134
            'language' => $GLOBALS['TCA'][$forTableName]['ctrl']['languageField'],
            'parent' => $GLOBALS['TCA'][$forTableName]['ctrl']['transOrigPointerField'],
135
        ];
136
137
        if (!empty($GLOBALS['TCA'][$forTableName]['ctrl']['translationSource'])) {
            $fieldNames['source'] = $GLOBALS['TCA'][$forTableName]['ctrl']['translationSource'];
138
139
        }

140
141
142
143
144
145
146
147
148
        $translationValues = [];
        // Fetching parent/source pointer values does not make sense for pages
        if ($tableName !== 'pages') {
            $translationValues = $this->fetchTranslationValues(
                $tableName,
                $fieldNames,
                $this->filterNumericIds(array_keys($idValues))
            );
        }
149
150

        $dependencies = $this->fetchDependencies(
151
            $forTableName,
152
153
154
            $this->filterNumericIds(array_keys($idValues))
        );

155
        foreach ($idValues as $id => $values) {
156
157
158
159
160
161
162
163
164
            $recordValues = $translationValues[$id] ?? [];
            $item = DataMapItem::build(
                $tableName,
                $id,
                $values,
                $recordValues,
                $fieldNames
            );

165
166
167
168
169
            // elements using "all language" cannot be localized
            if ($item->getLanguage() === -1) {
                unset($item);
                continue;
            }
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
            // must be any kind of localization and in connected mode
            if ($item->getLanguage() > 0 && empty($item->getParent())) {
                unset($item);
                continue;
            }
            // add dependencies
            if (!empty($dependencies[$id])) {
                $item->setDependencies($dependencies[$id]);
            }
            $this->items[$tableName . ':' . $id] = $item;
        }
    }

    /**
     * Sanitizes the submitted data-map and removes fields which are not
     * defined as custom and thus rely on either parent or source values.
     */
    protected function sanitize()
    {
        foreach (['grandChild', 'directChild'] as $type) {
            foreach ($this->filterItemsByType($type) as $item) {
                $this->sanitizeTranslationItem($item);
            }
        }
    }

    /**
     * Handle synchronization of an item list
     */
    protected function enrich()
    {
        foreach (['grandChild', 'directChild'] as $type) {
            foreach ($this->filterItemsByType($type) as $item) {
                foreach ($item->getApplicableScopes() as $scope) {
                    $fromId = $item->getIdForScope($scope);
                    $fieldNames = $this->getFieldNamesForItemScope($item, $scope, !$item->isNew());
                    $this->synchronizeTranslationItem($item, $fieldNames, $fromId);
                }
                $this->populateTranslationItem($item);
                $this->finishTranslationItem($item);
            }
        }
        foreach ($this->filterItemsByType('parent') as $item) {
            $this->populateTranslationItem($item);
        }
    }

    /**
     * Sanitizes the submitted data-map for a particular item and removes
     * fields which are not defined as custom and thus rely on either parent
     * or source values.
     *
     * @param DataMapItem $item
     */
    protected function sanitizeTranslationItem(DataMapItem $item)
    {
        $fieldNames = array_merge(
            $this->getFieldNamesForItemScope($item, DataMapItem::SCOPE_PARENT, !$item->isNew()),
            $this->getFieldNamesForItemScope($item, DataMapItem::SCOPE_SOURCE, !$item->isNew())
        );
230
231
232
233
234
235
236

        $fieldNameMap = array_combine($fieldNames, $fieldNames);
        // separate fields, that are submitted in data-map, but not defined as custom
        $this->sanitizationMap[$item->getTableName()][$item->getId()] = array_intersect_key(
            $this->dataMap[$item->getTableName()][$item->getId()],
            $fieldNameMap
        );
237
238
239
        // remove fields, that are submitted in data-map, but not defined as custom
        $this->dataMap[$item->getTableName()][$item->getId()] = array_diff_key(
            $this->dataMap[$item->getTableName()][$item->getId()],
240
            $fieldNameMap
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
        );
    }

    /**
     * Synchronize a single item
     *
     * @param DataMapItem $item
     * @param array $fieldNames
     * @param int $fromId
     */
    protected function synchronizeTranslationItem(DataMapItem $item, array $fieldNames, int $fromId)
    {
        if (empty($fieldNames)) {
            return;
        }
        $fieldNameList = 'uid,' . implode(',', $fieldNames);
        $fromRecord = BackendUtility::getRecordWSOL(
            $item->getFromTableName(),
            $fromId,
            $fieldNameList
        );
        $forRecord = [];
        if (!$item->isNew()) {
            $forRecord = BackendUtility::getRecordWSOL(
                $item->getTableName(),
                $item->getId(),
                $fieldNameList
            );
        }
        foreach ($fieldNames as $fieldName) {
            $this->synchronizeFieldValues(
                $item,
                $fieldName,
                $fromRecord,
                $forRecord
            );
        }
    }

    /**
     * Populates values downwards, either from a parent language item or
     * a source language item to an accordant dependent translation item.
     *
     * @param DataMapItem $item
     */
    protected function populateTranslationItem(DataMapItem $item)
    {
        if ($item->isNew()) {
            return;
        }

        foreach ([State::STATE_PARENT, State::STATE_SOURCE] as $scope) {
            foreach ($item->findDependencies($scope) as $dependentItem) {
                // use suggested item, if it was submitted in data-map
                $suggestedDependentItem = $this->findItem(
                    $dependentItem->getTableName(),
                    $dependentItem->getId()
                );
                if ($suggestedDependentItem !== null) {
                    $dependentItem = $suggestedDependentItem;
                }
                $fieldNames = $this->getFieldNamesForItemScope(
                    $dependentItem,
                    $scope,
                    false
                );
                $this->synchronizeTranslationItem(
                    $dependentItem,
                    $fieldNames,
                    $item->getId()
                );
            }
        }
    }

    /**
     * Finishes a translation item by updating states to be persisted.
     *
     * @param DataMapItem $item
     */
    protected function finishTranslationItem(DataMapItem $item)
    {
        if (
            $item->isParentType()
            || !State::isApplicable($item->getTableName())
        ) {
            return;
        }

        $this->dataMap[$item->getTableName()][$item->getId()]['l10n_state'] = $item->getState()->export();
    }

    /**
     * Synchronize simple values like text and similar
     *
     * @param DataMapItem $item
     * @param string $fieldName
     * @param array $fromRecord
     * @param array $forRecord
     */
    protected function synchronizeFieldValues(DataMapItem $item, string $fieldName, array $fromRecord, array $forRecord)
    {
        // skip if this field has been processed already, assumed that proper sanitation happened
        if (!empty($this->dataMap[$item->getTableName()][$item->getId()][$fieldName])) {
            return;
        }

        $fromId = $fromRecord['uid'];
        $fromValue = $this->dataMap[$item->getFromTableName()][$fromId][$fieldName] ?? $fromRecord[$fieldName];

        // plain values
        if (!$this->isRelationField($item->getFromTableName(), $fieldName)) {
            $this->dataMap[$item->getTableName()][$item->getId()][$fieldName] = $fromValue;
        // direct relational values
        } elseif (!$this->isInlineRelationField($item->getFromTableName(), $fieldName)) {
            $this->synchronizeDirectRelations($item, $fieldName, $fromRecord);
        // inline relational values
        } else {
            $this->synchronizeInlineRelations($item, $fieldName, $fromRecord, $forRecord);
        }
    }

    /**
     * Synchronize select and group field localizations
     *
     * @param DataMapItem $item
     * @param string $fieldName
     * @param array $fromRecord
     */
    protected function synchronizeDirectRelations(DataMapItem $item, string $fieldName, array $fromRecord)
    {
        $fromId = $fromRecord['uid'];
        $fromValue = $this->dataMap[$item->getFromTableName()][$fromId][$fieldName] ?? $fromRecord[$fieldName];
        $configuration = $GLOBALS['TCA'][$item->getFromTableName()]['columns'][$fieldName];

        // non-MM relations are stored as comma separated values, just use them
        // if values are available in data-map already, just use them as well
        if (
            empty($configuration['config']['MM'])
            || isset($this->dataMap[$item->getFromTableName()][$fromId][$fieldName])
            || ($configuration['config']['special'] ?? null) === 'languages'
        ) {
            $this->dataMap[$item->getTableName()][$item->getId()][$fieldName] = $fromValue;
            return;
        }

        // fetch MM relations from storage
        $type = $configuration['config']['type'];
        $manyToManyTable = $configuration['config']['MM'];
        if ($type === 'group' && $configuration['config']['internal_type'] === 'db') {
            $tableNames = trim($configuration['config']['allowed'] ?? '');
        } elseif ($configuration['config']['type'] === 'select') {
            $tableNames = ($configuration['foreign_table'] ?? '');
        } else {
            return;
        }

        $relationHandler = $this->createRelationHandler();
        $relationHandler->start(
            '',
            $tableNames,
            $manyToManyTable,
            $fromId,
            $item->getFromTableName(),
            $configuration['config']
        );

        // provide list of relations, optionally prepended with table name
        // e.g. "13,19,23" or "tt_content_27,tx_extension_items_28"
        $this->dataMap[$item->getTableName()][$item->getId()][$fieldName] = implode(
            ',',
            $relationHandler->getValueArray()
        );
    }

    /**
     * Handle synchonization of inline relations
     *
     * @param DataMapItem $item
     * @param string $fieldName
     * @param array $fromRecord
     * @param array $forRecord
423
     * @throws \RuntimeException
424
425
426
427
428
     */
    protected function synchronizeInlineRelations(DataMapItem $item, string $fieldName, array $fromRecord, array $forRecord)
    {
        $fromId = $fromRecord['uid'];
        $configuration = $GLOBALS['TCA'][$item->getFromTableName()]['columns'][$fieldName];
429
        $isLocalizationModeExclude = ($configuration['l10n_mode'] ?? null) === 'exclude';
430
431
432
        $foreignTableName = $configuration['config']['foreign_table'];
        $manyToManyTable = ($configuration['config']['MM'] ?? '');

433
434
435
436
437
438
        $fieldNames = [
            'language' => ($GLOBALS['TCA'][$foreignTableName]['ctrl']['languageField'] ?? null),
            'parent' => ($GLOBALS['TCA'][$foreignTableName]['ctrl']['transOrigPointerField'] ?? null),
            'source' => ($GLOBALS['TCA'][$foreignTableName]['ctrl']['translationSource'] ?? null),
        ];
        $isTranslatable = (!empty($fieldNames['language']) && !empty($fieldNames['parent']));
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488

        // determine suggested elements of either translation parent or source record
        // from data-map, in case the accordant language parent/source record was modified
        if (isset($this->dataMap[$item->getFromTableName()][$fromId][$fieldName])) {
            $suggestedAncestorIds = GeneralUtility::trimExplode(
                ',',
                $this->dataMap[$item->getFromTableName()][$fromId][$fieldName],
                true
            );
        // determine suggested elements of either translation parent or source record from storage
        } else {
            $relationHandler = $this->createRelationHandler();
            $relationHandler->start(
                $fromRecord[$fieldName],
                $foreignTableName,
                $manyToManyTable,
                $fromId,
                $item->getFromTableName(),
                $configuration['config']
            );
            $suggestedAncestorIds = $this->mapRelationItemId($relationHandler->itemArray);
        }
        // determine persisted elements for the current data-map item
        $relationHandler = $this->createRelationHandler();
        $relationHandler->start(
            $forRecord[$fieldName] ?? '',
            $foreignTableName,
            $manyToManyTable,
            $item->getId(),
            $item->getTableName(),
            $configuration['config']
        );
        $persistedIds = $this->mapRelationItemId($relationHandler->itemArray);
        // The dependent ID map points from language parent/source record to
        // localization, thus keys: parents/sources & values: localizations
        $dependentIdMap = $this->fetchDependentIdMap($foreignTableName, $suggestedAncestorIds);
        // filter incomplete structures - this is a drawback of DataHandler's remap stack, since
        // just created IRRE translations still belong to the language parent - filter them out
        $suggestedAncestorIds = array_diff($suggestedAncestorIds, array_values($dependentIdMap));
        // compile element differences to be resolved
        // remove elements that are persisted at the language translation, but not required anymore
        $removeIds = array_diff($persistedIds, array_values($dependentIdMap));
        // remove elements that are persisted at the language parent/source, but not required anymore
        $removeAncestorIds = array_diff(array_keys($dependentIdMap), $suggestedAncestorIds);
        // missing elements that are persisted at the language parent/source, but not translated yet
        $missingAncestorIds = array_diff($suggestedAncestorIds, array_keys($dependentIdMap));
        // persisted elements that should be copied or localized
        $createAncestorIds = $this->filterNumericIds($missingAncestorIds, true);
        // non-persisted elements that should be duplicated in data-map directly
        $populateAncestorIds = $this->filterNumericIds($missingAncestorIds, false);
489
490
        // this desired state map defines the final result of child elements in their parent translation
        $desiredIdMap = array_combine($suggestedAncestorIds, $suggestedAncestorIds);
491
492
        // update existing translations in the desired state map
        foreach ($dependentIdMap as $ancestorId => $translationId) {
493
494
            if (isset($desiredIdMap[$ancestorId])) {
                $desiredIdMap[$ancestorId] = $translationId;
495
496
497
498
499
500
            }
        }
        // nothing to synchronize, but element order could have been changed
        if (empty($removeAncestorIds) && empty($missingAncestorIds)) {
            $this->dataMap[$item->getTableName()][$item->getId()][$fieldName] = implode(
                ',',
501
                array_values($desiredIdMap)
502
503
504
            );
            return;
        }
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
        // In case only missing elements shall be created, re-use previously sanitized
        // values IF child table cannot be translated, the relation parent item is new
        // and the count of missing relations equals the count of previously sanitized
        // relations. This is caused during copy processes, when the child relations
        // already have been cloned in DataHandler::copyRecord_procBasedOnFieldType()
        // without the possibility to resolve the initial connections at this point.
        // Otherwise child relations would superfluously be duplicated again here.
        // @todo Invalid manually injected child relations cannot be determined here
        $sanitizedValue = $this->sanitizationMap[$item->getTableName()][$item->getId()][$fieldName] ?? null;
        if (!empty($missingAncestorIds) && $item->isNew()
            && $sanitizedValue !== null && !$isTranslatable
            && count(GeneralUtility::trimExplode(',', $sanitizedValue)) === count($missingAncestorIds)
        ) {
            $this->dataMap[$item->getTableName()][$item->getId()][$fieldName] = $sanitizedValue;
            return;
        }
521
522
523
524
525
526
527
528
529
530
531

        $localCommandMap = [];
        foreach ($removeIds as $removeId) {
            $localCommandMap[$foreignTableName][$removeId]['delete'] = true;
        }
        foreach ($removeAncestorIds as $removeAncestorId) {
            $removeId = $dependentIdMap[$removeAncestorId];
            $localCommandMap[$foreignTableName][$removeId]['delete'] = true;
        }
        foreach ($createAncestorIds as $createAncestorId) {
            // if child table is not aware of localization, just copy
532
533
            if ($isLocalizationModeExclude || !$isTranslatable) {
                $localCommandMap[$foreignTableName][$createAncestorId]['copy'] = -$createAncestorId;
534
535
536
537
538
539
540
541
542
543
544
545
            // otherwise, trigger the localization process
            } else {
                $localCommandMap[$foreignTableName][$createAncestorId]['localize'] = $item->getLanguage();
            }
        }
        // execute copy, localize and delete actions on persisted child records
        if (!empty($localCommandMap)) {
            $localDataHandler = GeneralUtility::makeInstance(DataHandler::class);
            $localDataHandler->start([], $localCommandMap, $this->backendUser);
            $localDataHandler->process_cmdmap();
            // update copied or localized ids
            foreach ($createAncestorIds as $createAncestorId) {
546
                if (empty($localDataHandler->copyMappingArray_merged[$foreignTableName][$createAncestorId])) {
547
548
549
550
551
552
553
554
                    $additionalInformation = '';
                    if (!empty($localDataHandler->errorLog)) {
                        $additionalInformation = ', reason "'
                        . implode(', ', $localDataHandler->errorLog) . '"';
                    }
                    throw new \RuntimeException(
                        'Child record was not processed' . $additionalInformation,
                        1486233164);
555
                }
556
                $newLocalizationId = $localDataHandler->copyMappingArray_merged[$foreignTableName][$createAncestorId];
557
                $newLocalizationId = $localDataHandler->getAutoVersionId($foreignTableName, $newLocalizationId) ?? $newLocalizationId;
558
                $desiredIdMap[$createAncestorId] = $newLocalizationId;
559
560
561
562
            }
        }
        // populate new child records in data-map
        if (!empty($populateAncestorIds)) {
563
            foreach ($populateAncestorIds as $populateAncestorId) {
564
                $newLocalizationId = StringUtility::getUniqueId('NEW');
565
566
567
568
569
570
571
                $desiredIdMap[$populateAncestorId] = $newLocalizationId;
                $this->dataMap[$foreignTableName][$newLocalizationId] = $this->duplicateFromDataMap(
                    $foreignTableName,
                    $populateAncestorId,
                    $item->getLanguage(),
                    $fieldNames
                );
572
573
574
575
576
            }
        }
        // update inline parent field references - required to update pointer fields
        $this->dataMap[$item->getTableName()][$item->getId()][$fieldName] = implode(
            ',',
577
            array_values($desiredIdMap)
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
        );
    }

    /**
     * Fetches translation related field values for the items submitted in
     * the data-map. That's why further adjustment for the tables pages vs.
     * pages_language_overlay is not required.
     *
     * @param string $tableName
     * @param array $fieldNames
     * @param array $ids
     * @return array
     */
    protected function fetchTranslationValues(string $tableName, array $fieldNames, array $ids)
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()
            ->removeAll()
597
598
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, $this->backendUser->workspace, false));
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
        $statement = $queryBuilder
            ->select(...array_values($fieldNames))
            ->from($tableName)
            ->where(
                $queryBuilder->expr()->in(
                    'uid',
                    $queryBuilder->createNamedParameter($ids, Connection::PARAM_INT_ARRAY)
                )
            )
            ->execute();

        $translationValues = [];
        foreach ($statement as $record) {
            $translationValues[$record['uid']] = $record;
        }
        return $translationValues;
    }

    /**
618
     * Fetches translation dependencies for a given parent/source record ids.
619
620
621
622
623
624
625
626
627
628
629
     *
     * @param string $tableName
     * @param array $ids
     * @return DataMapItem[][]
     */
    protected function fetchDependencies(string $tableName, array $ids)
    {
        if ($tableName === 'pages') {
            $tableName = 'pages_language_overlay';
        }

630
631
632
633
        if (!BackendUtility::isTableLocalizable($tableName)) {
            return [];
        }

634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
        $fieldNames = [
            'uid' => 'uid',
            'l10n_state' => 'l10n_state',
            'language' => $GLOBALS['TCA'][$tableName]['ctrl']['languageField'],
            'parent' => $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'],
        ];
        if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['translationSource'])) {
            $fieldNames['source'] = $GLOBALS['TCA'][$tableName]['ctrl']['translationSource'];
        }

        $dependentElements = $this->fetchDependentElements($tableName, $ids, $fieldNames);

        $dependencyMap = [];
        foreach ($dependentElements as $dependentElement) {
            $dependentItem = DataMapItem::build(
                $tableName,
                $dependentElement['uid'],
                [],
                $dependentElement,
                $fieldNames
            );

            if ($dependentItem->isDirectChildType()) {
                $dependencyMap[$dependentItem->getParent()][State::STATE_PARENT][] = $dependentItem;
            }
            if ($dependentItem->isGrandChildType()) {
660
                $dependencyMap[$dependentItem->getParent()][State::STATE_PARENT][] = $dependentItem;
661
662
663
664
665
666
667
                $dependencyMap[$dependentItem->getSource()][State::STATE_SOURCE][] = $dependentItem;
            }
        }
        return $dependencyMap;
    }

    /**
668
669
670
     * Fetches dependent records that depend on given record id's in in either
     * their parent or source field for translatable tables or their origin
     * field for non-translatable tables and creates an id mapping.
671
672
673
674
675
676
677
678
679
680
681
     *
     * @param string $tableName
     * @param array $ids
     * @return array
     */
    protected function fetchDependentIdMap(string $tableName, array $ids)
    {
        if ($tableName === 'pages') {
            $tableName = 'pages_language_overlay';
        }

682
683
684
685
        $isTranslatable = BackendUtility::isTableLocalizable($tableName);
        $originFieldName = ($GLOBALS['TCA'][$tableName]['ctrl']['origUid'] ?? null);

        if (!$isTranslatable && $originFieldName === null) {
686
687
688
            return [];
        }

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        if ($isTranslatable) {
            $fieldNames = [
                'uid' => 'uid',
                'l10n_state' => 'l10n_state',
                'language' => $GLOBALS['TCA'][$tableName]['ctrl']['languageField'],
                'parent' => $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'],
            ];
            if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['translationSource'])) {
                $fieldNames['source'] = $GLOBALS['TCA'][$tableName]['ctrl']['translationSource'];
            }
        } else {
            $fieldNames = [
                'uid' => 'uid',
                'origin' => $originFieldName,
            ];
704
705
706
707
708
709
        }

        $dependentElements = $this->fetchDependentElements($tableName, $ids, $fieldNames);

        $dependentIdMap = [];
        foreach ($dependentElements as $dependentElement) {
710
711
712
713
            $dependentId = $dependentElement['uid'];
            // implicit: use origin pointer if table cannot be translated
            if (!$isTranslatable) {
                $dependentIdMap[$dependentElement[$fieldNames['origin']]] = $dependentId;
714
            // implicit: having source value different to parent value, use source pointer
715
            } elseif (
716
717
718
                !empty($fieldNames['source'])
                && $dependentElement[$fieldNames['source']] !== $dependentElement[$fieldNames['parent']]
            ) {
719
                $dependentIdMap[$dependentElement[$fieldNames['source']]] = $dependentId;
720
721
            // implicit: otherwise, use parent pointer
            } else {
722
                $dependentIdMap[$dependentElement[$fieldNames['parent']]] = $dependentId;
723
724
725
726
727
728
            }
        }
        return $dependentIdMap;
    }

    /**
729
730
731
     * Fetch all elements that depend on given record id's in either their
     * parent or source field for translatable tables or their origin field
     * for non-translatable tables.
732
733
734
     *
     * @param string $tableName
     * @param array $ids
735
     * @param array $fieldNames
736
     * @return array
737
     * @throws \InvalidArgumentException
738
739
740
     */
    protected function fetchDependentElements(string $tableName, array $ids, array $fieldNames)
    {
741
742
        $ids = $this->filterNumericIds($ids, true);

743
744
745
746
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()
            ->removeAll()
747
748
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, $this->backendUser->workspace, false));
749

750
        $zeroParameter = $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT);
751
        $ids = array_filter($ids, [MathUtility::class, 'canBeInterpretedAsInteger']);
752
753
        $idsParameter = $queryBuilder->createNamedParameter($ids, Connection::PARAM_INT_ARRAY);

754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
        // fetch by language dependency
        if (!empty($fieldNames['language']) && !empty($fieldNames['parent'])) {
            $ancestorPredicates = [
                $queryBuilder->expr()->in(
                    $fieldNames['parent'],
                    $idsParameter
                )
            ];
            if (!empty($fieldNames['source'])) {
                $ancestorPredicates[] = $queryBuilder->expr()->in(
                    $fieldNames['source'],
                    $idsParameter
                );
            }
            $predicates = [
769
770
771
                // must be any kind of localization
                $queryBuilder->expr()->gt(
                    $fieldNames['language'],
772
                    $zeroParameter
773
774
775
776
                ),
                // must be in connected mode
                $queryBuilder->expr()->gt(
                    $fieldNames['parent'],
777
                    $zeroParameter
778
779
                ),
                // any parent or source pointers
780
781
782
783
784
                $queryBuilder->expr()->orX(...$ancestorPredicates),
            ];
        // fetch by origin dependency ("copied from")
        } elseif (!empty($fieldNames['origin'])) {
            $predicates = [
785
                $queryBuilder->expr()->in(
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
                    $fieldNames['origin'],
                    $idsParameter
                )
            ];
        // otherwise: stop execution
        } else {
            throw new \InvalidArgumentException(
                'Invalid combination of query field names given',
                1487192370
            );
        }

        $statement = $queryBuilder
            ->select(...array_values($fieldNames))
            ->from($tableName)
            ->andWhere(...$predicates)
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
            ->execute();

        $dependentElements = [];
        foreach ($statement as $record) {
            $dependentElements[] = $record;
        }
        return $dependentElements;
    }

    /**
     * Return array of data map items that are of given type
     *
     * @param string $type
     * @return DataMapItem[]
     */
    protected function filterItemsByType(string $type)
    {
        return array_filter(
            $this->items,
821
            function (DataMapItem $item) use ($type) {
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
                return $item->getType() === $type;
            }
        );
    }

    /**
     * Return only id's that are integer - so no NEW...
     *
     * @param array $ids
     * @param bool $numeric
     * @return array
     */
    protected function filterNumericIds(array $ids, bool $numeric = true)
    {
        return array_filter(
            $ids,
838
            function ($id) use ($numeric) {
839
840
841
842
843
844
845
846
847
848
849
850
851
852
                return MathUtility::canBeInterpretedAsInteger($id) === $numeric;
            }
        );
    }

    /**
     * Flatten array
     *
     * @param array $relationItems
     * @return string[]
     */
    protected function mapRelationItemId(array $relationItems)
    {
        return array_map(
853
            function (array $relationItem) {
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
                return (string)$relationItem['id'];
            },
            $relationItems
        );
    }

    /**
     * See if an items is in item list and return it
     *
     * @param string $tableName
     * @param string|int $id
     * @return null|DataMapItem
     */
    protected function findItem(string $tableName, $id)
    {
        return $this->items[$tableName . ':' . $id] ?? null;
    }

872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
    /**
     * Duplicates an item from data-map and prefixed language title,
     * if applicable for the accordant field name.
     *
     * @param string $tableName
     * @param string|int $id
     * @param int $language
     * @param array $fieldNames
     * @return array
     */
    protected function duplicateFromDataMap(string $tableName, $id, int $language, array $fieldNames)
    {
        $data = $this->dataMap[$tableName][$id];
        $isTranslatable = (!empty($fieldNames['language']) && !empty($fieldNames['parent']));

        if (empty($language) || !$isTranslatable) {
            return $data;
        }

        $data[$fieldNames['language']] = $language;
        // @todo Only $id used in TCA type 'select' is resolved in DataHandler's remapStack
        $data[$fieldNames['parent']] = $id;
        if (!empty($fieldNames['source'])) {
            // @todo Not sure, whether $id is resolved in DataHandler's remapStack
            $data[$fieldNames['source']] = $id;
        }

        $prefixFieldNames = array_intersect(
            array_keys($data),
            $this->getPrefixLanguageTitleFieldNames($tableName)
        );
        if (empty($prefixFieldNames)) {
            return $data;
        }

        $languageService = $this->getLanguageService();
        $languageRecord = BackendUtility::getRecord('sys_language', $language, 'title');
        list($pageId) = BackendUtility::getTSCpid($tableName, $id, $data['pid'] ?? null);

        $TSconfig =  $this->backendUser->getTSConfig(
            'TCEMAIN',
            BackendUtility::getPagesTSconfig($pageId)
        );
        if (!empty($TSconfig['translateToMessage'])) {
            $prefix = $TSconfig['translateToMessage'];
            if ($languageService !== null) {
                $prefix = $languageService->sL($prefix);
            }
            $prefix = sprintf($prefix, $languageRecord['title']);
        }
        if (empty($prefix)) {
            $prefix = 'Translate to ' . $languageRecord['title'] . ':';
        }

        foreach ($prefixFieldNames as $prefixFieldName) {
            // @todo The hook in DataHandler is not applied here
            $data[$prefixFieldName] = '[' . $prefix . '] ' . $data[$prefixFieldName];
        }

        return $data;
    }

934
935
936
937
938
    /**
     * Field names we have to deal with
     *
     * @param DataMapItem $item
     * @param string $scope
939
     * @param bool $modified
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
     * @return string[]
     */
    protected function getFieldNamesForItemScope(
        DataMapItem $item,
        string $scope,
        bool $modified
    ) {
        if (
            $scope === DataMapItem::SCOPE_PARENT
            || $scope === DataMapItem::SCOPE_SOURCE
        ) {
            if (!State::isApplicable($item->getTableName())) {
                return [];
            }
            return $item->getState()->filterFieldNames($scope, $modified);
        }
        if ($scope === DataMapItem::SCOPE_EXCLUDE) {
            return $this->getLocalizationModeExcludeFieldNames(
                $item->getTableName()
            );
        }
        return [];
    }

    /**
     * Field names of TCA table with columns having l10n_mode=exclude
     *
     * @param string $tableName
     * @return string[]
     */
    protected function getLocalizationModeExcludeFieldNames(string $tableName)
    {
        $localizationExcludeFieldNames = [];
        if (empty($GLOBALS['TCA'][$tableName]['columns'])) {
            return $localizationExcludeFieldNames;
        }

        foreach ($GLOBALS['TCA'][$tableName]['columns'] as $fieldName => $configuration) {
            if (($configuration['l10n_mode'] ?? null) === 'exclude') {
                $localizationExcludeFieldNames[] = $fieldName;
            }
        }

        return $localizationExcludeFieldNames;
    }

986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    /**
     * Field names of TCA table with columns having l10n_mode=prefixLangTitle
     *
     * @param string $tableName
     * @return array
     */
    protected function getPrefixLanguageTitleFieldNames(string $tableName)
    {
        if ($tableName === 'pages') {
            $tableName = 'pages_language_overlay';
        }

        $prefixLanguageTitleFieldNames = [];
        if (empty($GLOBALS['TCA'][$tableName]['columns'])) {
            return $prefixLanguageTitleFieldNames;