DataMapProcessor.php 56 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
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\RelationHandler;
use TYPO3\CMS\Core\DataHandling\DataHandler;
25
use TYPO3\CMS\Core\Localization\LanguageService;
26
27
28
29
30
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Utility\StringUtility;

/**
31
 * This processor analyzes the provided data-map before actually being process
32
33
34
35
36
37
38
39
40
41
 * 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
 */
class DataMapProcessor
{
    /**
     * @var array
     */
52
53
54
55
56
57
    protected $allDataMap = [];

    /**
     * @var array
     */
    protected $modifiedDataMap = [];
58

59
60
61
62
63
    /**
     * @var array
     */
    protected $sanitizationMap = [];

64
65
66
67
68
69
70
71
    /**
     * @var BackendUserAuthentication
     */
    protected $backendUser;

    /**
     * @var DataMapItem[]
     */
72
73
74
75
76
77
    protected $allItems = [];

    /**
     * @var DataMapItem[]
     */
    protected $nextItems = [];
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

    /**
     * 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)
    {
101
102
        $this->allDataMap = $dataMap;
        $this->modifiedDataMap = $dataMap;
103
104
105
106
107
108
109
110
111
112
113
        $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()
    {
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        $iterations = 0;

        while (!empty($this->modifiedDataMap)) {
            $this->nextItems = [];
            foreach ($this->modifiedDataMap as $tableName => $idValues) {
                $this->collectItems($tableName, $idValues);
            }

            $this->modifiedDataMap = [];
            if (empty($this->nextItems)) {
                break;
            }

            if ($iterations++ === 0) {
                $this->sanitize($this->allItems);
            }
            $this->enrich($this->nextItems);
131
        }
132

133
        $this->allDataMap = $this->purgeDataMap($this->allDataMap);
134
        return $this->allDataMap;
135
136
    }

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    /**
     * Purges superfluous empty data-map sections.
     *
     * @param array $dataMap
     * @return array
     */
    protected function purgeDataMap(array $dataMap): array
    {
        foreach ($dataMap as $tableName => $idValues) {
            foreach ($idValues as $id => $values) {
                if (empty($values)) {
                    unset($dataMap[$tableName][$id]);
                }
            }
            if (empty($dataMap[$tableName])) {
                unset($dataMap[$tableName]);
            }
        }
        return $dataMap;
    }

158
159
160
161
162
163
164
165
    /**
     * Create data map items of all affected rows
     *
     * @param string $tableName
     * @param array $idValues
     */
    protected function collectItems(string $tableName, array $idValues)
    {
166
        if (!$this->isApplicable($tableName)) {
167
168
169
170
171
172
            return;
        }

        $fieldNames = [
            'uid' => 'uid',
            'l10n_state' => 'l10n_state',
173
174
            'language' => $GLOBALS['TCA'][$tableName]['ctrl']['languageField'],
            'parent' => $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'],
175
        ];
176
177
        if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['translationSource'])) {
            $fieldNames['source'] = $GLOBALS['TCA'][$tableName]['ctrl']['translationSource'];
178
179
        }

180
181
182
183
        $translationValues = $this->fetchTranslationValues(
            $tableName,
            $fieldNames,
            $this->filterNewItemIds(
184
                $tableName,
185
186
187
                $this->filterNumericIds(array_keys($idValues))
            )
        );
188
189

        $dependencies = $this->fetchDependencies(
190
191
            $tableName,
            $this->filterNewItemIds($tableName, array_keys($idValues))
192
193
        );

194
        foreach ($idValues as $id => $values) {
195
196
197
198
199
200
201
202
203
204
205
            $item = $this->findItem($tableName, $id);
            // build item if it has not been created in a previous iteration
            if ($item === null) {
                $recordValues = $translationValues[$id] ?? [];
                $item = DataMapItem::build(
                    $tableName,
                    $id,
                    $values,
                    $recordValues,
                    $fieldNames
                );
206

207
208
209
210
211
212
213
214
215
216
217
218
219
220
                // elements using "all language" cannot be localized
                if ($item->getLanguage() === -1) {
                    unset($item);
                    continue;
                }
                // 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]);
                }
221
            }
222
223
            // add item to $this->allItems and $this->nextItems
            $this->addNextItem($item);
224
225
226
227
        }
    }

    /**
228
     * Sanitizes the submitted data-map items and removes fields which are not
229
     * defined as custom and thus rely on either parent or source values.
230
231
     *
     * @param DataMapItem[] $items
232
     */
233
    protected function sanitize(array $items)
234
    {
235
236
        foreach (['directChild', 'grandChild'] as $type) {
            foreach ($this->filterItemsByType($type, $items) as $item) {
237
238
239
240
241
242
243
                $this->sanitizeTranslationItem($item);
            }
        }
    }

    /**
     * Handle synchronization of an item list
244
245
     *
     * @param DataMapItem[] $items
246
     */
247
    protected function enrich(array $items)
248
    {
249
250
        foreach (['directChild', 'grandChild'] as $type) {
            foreach ($this->filterItemsByType($type, $items) as $item) {
251
252
253
254
255
256
257
258
259
                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);
            }
        }
260
        foreach ($this->filterItemsByType('parent', $items) as $item) {
261
262
263
264
265
266
267
268
269
270
271
272
273
            $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)
    {
274
275
276
277
        $fieldNames = [];
        foreach ($item->getApplicableScopes() as $scope) {
            $fieldNames = array_merge(
                $fieldNames,
278
                $this->getFieldNamesForItemScope($item, $scope, false)
279
280
            );
        }
281
282
283
284

        $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(
285
            $this->allDataMap[$item->getTableName()][$item->getId()],
286
287
            $fieldNameMap
        );
288
        // remove fields, that are submitted in data-map, but not defined as custom
289
290
        $this->allDataMap[$item->getTableName()][$item->getId()] = array_diff_key(
            $this->allDataMap[$item->getTableName()][$item->getId()],
291
            $fieldNameMap
292
293
294
295
296
297
298
299
        );
    }

    /**
     * Synchronize a single item
     *
     * @param DataMapItem $item
     * @param array $fieldNames
300
     * @param string|int $fromId
301
     */
302
    protected function synchronizeTranslationItem(DataMapItem $item, array $fieldNames, $fromId)
303
304
305
306
    {
        if (empty($fieldNames)) {
            return;
        }
307

308
        $fieldNameList = 'uid,' . implode(',', $fieldNames);
309
310
311
312

        $fromRecord = ['uid' => $fromId];
        if (MathUtility::canBeInterpretedAsInteger($fromId)) {
            $fromRecord = BackendUtility::getRecordWSOL(
313
                $item->getTableName(),
314
315
316
317
318
                $fromId,
                $fieldNameList
            );
        }

319
320
321
322
323
324
325
326
        $forRecord = [];
        if (!$item->isNew()) {
            $forRecord = BackendUtility::getRecordWSOL(
                $item->getTableName(),
                $item->getId(),
                $fieldNameList
            );
        }
327

328
329
330
331
332
333
334
335
336
        if (is_array($fromRecord) && is_array($forRecord)) {
            foreach ($fieldNames as $fieldName) {
                $this->synchronizeFieldValues(
                    $item,
                    $fieldName,
                    $fromRecord,
                    $forRecord
                );
            }
337
338
339
340
341
342
343
344
345
346
347
        }
    }

    /**
     * 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)
    {
348
        foreach ([DataMapItem::SCOPE_PARENT, DataMapItem::SCOPE_SOURCE] as $scope) {
349
350
351
352
353
354
355
356
357
            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;
                }
358
359
360
361
362
363
364
365
366
367
368
369
                foreach ([$scope, DataMapItem::SCOPE_EXCLUDE] as $dependentScope) {
                    $fieldNames = $this->getFieldNamesForItemScope(
                        $dependentItem,
                        $dependentScope,
                        false
                    );
                    $this->synchronizeTranslationItem(
                        $dependentItem,
                        $fieldNames,
                        $item->getId()
                    );
                }
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
            }
        }
    }

    /**
     * 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;
        }

388
        $this->allDataMap[$item->getTableName()][$item->getId()]['l10n_state'] = $item->getState()->export();
389
390
391
392
393
394
395
396
397
398
399
400
401
    }

    /**
     * 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
402
        if ($this->isSetInDataMap($item->getTableName(), $item->getId(), $fieldName)) {
403
404
405
406
            return;
        }

        $fromId = $fromRecord['uid'];
407
        // retrieve value from in-memory data-map
408
409
        if ($this->isSetInDataMap($item->getTableName(), $fromId, $fieldName)) {
            $fromValue = $this->allDataMap[$item->getTableName()][$fromId][$fieldName];
410
        } elseif (array_key_exists($fieldName, $fromRecord)) {
411
            // retrieve value from record
412
            $fromValue = $fromRecord[$fieldName];
413
        } else {
414
            // otherwise abort synchronization
415
            return;
416
        }
417
418

        // plain values
419
        if (!$this->isRelationField($item->getTableName(), $fieldName)) {
420
421
422
423
424
            $this->modifyDataMap(
                $item->getTableName(),
                $item->getId(),
                [$fieldName => $fromValue]
            );
425
        } elseif (!$this->isInlineRelationField($item->getTableName(), $fieldName)) {
426
            // direct relational values
427
428
            $this->synchronizeDirectRelations($item, $fieldName, $fromRecord);
        } else {
429
            // inline relational values
430
431
432
433
434
435
436
437
438
439
440
441
442
            $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)
    {
443
        $configuration = $GLOBALS['TCA'][$item->getTableName()]['columns'][$fieldName];
444
        $isSpecialLanguageField = ($configuration['config']['special'] ?? null) === 'languages';
445

446
        $fromId = $fromRecord['uid'];
447
448
        if ($this->isSetInDataMap($item->getTableName(), $fromId, $fieldName)) {
            $fromValue = $this->allDataMap[$item->getTableName()][$fromId][$fieldName];
449
450
451
452
        } else {
            $fromValue = $fromRecord[$fieldName];
        }

453
454
455
456
        // 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'])
457
            || $this->isSetInDataMap($item->getTableName(), $fromId, $fieldName)
458
            || $isSpecialLanguageField
459
        ) {
460
461
462
463
464
            $this->modifyDataMap(
                $item->getTableName(),
                $item->getId(),
                [$fieldName => $fromValue]
            );
465
466
            return;
        }
467
468
469
470
        // resolve the language special table name
        if ($isSpecialLanguageField) {
            $specialTableName = 'sys_language';
        }
471
472
473
474
475
476
        // 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') {
477
            $tableNames = ($specialTableName ?? $configuration['config']['foreign_table'] ?? '');
478
479
480
481
482
483
484
485
486
487
        } else {
            return;
        }

        $relationHandler = $this->createRelationHandler();
        $relationHandler->start(
            '',
            $tableNames,
            $manyToManyTable,
            $fromId,
488
            $item->getTableName(),
489
490
491
492
493
            $configuration['config']
        );

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

    /**
502
503
504
505
     * Handle synchronization of inline relations.
     * Inline Relational Record Editong ("IRRE") always is modelled as 1:n composite relation - which means that
     * direct(!) children cannot exist without their parent. Removing a relative parent results in cascaded removal
     * of all direct(!) children as well.
506
507
508
509
510
     *
     * @param DataMapItem $item
     * @param string $fieldName
     * @param array $fromRecord
     * @param array $forRecord
511
     * @throws \RuntimeException
512
513
514
     */
    protected function synchronizeInlineRelations(DataMapItem $item, string $fieldName, array $fromRecord, array $forRecord)
    {
515
        $configuration = $GLOBALS['TCA'][$item->getTableName()]['columns'][$fieldName];
516
        $isLocalizationModeExclude = ($configuration['l10n_mode'] ?? null) === 'exclude';
517
518
        $foreignTableName = $configuration['config']['foreign_table'];

519
        $fieldNames = [
520
521
522
            'language' => $GLOBALS['TCA'][$foreignTableName]['ctrl']['languageField'] ?? null,
            'parent' => $GLOBALS['TCA'][$foreignTableName]['ctrl']['transOrigPointerField'] ?? null,
            'source' => $GLOBALS['TCA'][$foreignTableName]['ctrl']['translationSource'] ?? null,
523
524
        ];
        $isTranslatable = (!empty($fieldNames['language']) && !empty($fieldNames['parent']));
525
        $isLocalized = !empty($item->getLanguage());
526

527
528
529
530
531
532
533
534
535
        $suggestedAncestorIds = $this->resolveSuggestedInlineRelations(
            $item,
            $fieldName,
            $fromRecord
        );
        $persistedIds = $this->resolvePersistedInlineRelations(
            $item,
            $fieldName,
            $forRecord
536
        );
537

538
539
        // The dependent ID map points from language parent/source record to
        // localization, thus keys: parents/sources & values: localizations
540
        $dependentIdMap = $this->fetchDependentIdMap($foreignTableName, $suggestedAncestorIds, $item->getLanguage());
541
542
543
544
545
546
547
548
549
550
551
        // 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
552
        $createAncestorIds = $this->filterNumericIds($missingAncestorIds);
553
        // non-persisted elements that should be duplicated in data-map directly
554
        $populateAncestorIds = array_diff($missingAncestorIds, $createAncestorIds);
555
556
        // this desired state map defines the final result of child elements in their parent translation
        $desiredIdMap = array_combine($suggestedAncestorIds, $suggestedAncestorIds);
557
558
        // update existing translations in the desired state map
        foreach ($dependentIdMap as $ancestorId => $translationId) {
559
560
            if (isset($desiredIdMap[$ancestorId])) {
                $desiredIdMap[$ancestorId] = $translationId;
561
562
            }
        }
563
        // no children to be synchronized, but element order could have been changed
564
        if (empty($removeAncestorIds) && empty($missingAncestorIds)) {
565
566
567
568
            $this->modifyDataMap(
                $item->getTableName(),
                $item->getId(),
                [$fieldName => implode(',', array_values($desiredIdMap))]
569
570
571
            );
            return;
        }
572
        // In case only missing elements shall be created, re-use previously sanitized
573
574
575
        // values IF 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
576
577
578
579
580
        // 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;
581
582
        if (
            !empty($missingAncestorIds) && $item->isNew() && $sanitizedValue !== null
583
            && count(GeneralUtility::trimExplode(',', $sanitizedValue, true)) === count($missingAncestorIds)
584
        ) {
585
586
587
588
589
            $this->modifyDataMap(
                $item->getTableName(),
                $item->getId(),
                [$fieldName => $sanitizedValue]
            );
590
591
            return;
        }
592
593
594
595
596
597
598
599
600
601
602

        $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
603
            if ($isLocalizationModeExclude || !$isTranslatable) {
604
605
606
607
                $localCommandMap[$foreignTableName][$createAncestorId]['copy'] = [
                    'target' => -$createAncestorId,
                    'ignoreLocalization' => true,
                ];
608
            } else {
609
                // otherwise, trigger the localization process
610
611
612
613
614
615
616
617
618
619
                $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) {
620
                if (empty($localDataHandler->copyMappingArray_merged[$foreignTableName][$createAncestorId])) {
621
622
623
624
625
626
627
                    $additionalInformation = '';
                    if (!empty($localDataHandler->errorLog)) {
                        $additionalInformation = ', reason "'
                        . implode(', ', $localDataHandler->errorLog) . '"';
                    }
                    throw new \RuntimeException(
                        'Child record was not processed' . $additionalInformation,
628
629
                        1486233164
                    );
630
                }
631
                $newLocalizationId = $localDataHandler->copyMappingArray_merged[$foreignTableName][$createAncestorId];
632
                $newLocalizationId = $localDataHandler->getAutoVersionId($foreignTableName, $newLocalizationId) ?? $newLocalizationId;
633
                $desiredIdMap[$createAncestorId] = $newLocalizationId;
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
                // apply localization references to l10n_mode=exclude children
                // (without keeping their reference to their origin, synchronization is not possible)
                if ($isLocalizationModeExclude && $isTranslatable && $isLocalized) {
                    $adjustCopiedValues = $this->applyLocalizationReferences(
                        $foreignTableName,
                        $createAncestorId,
                        $item->getLanguage(),
                        $fieldNames,
                        []
                    );
                    $this->modifyDataMap(
                        $foreignTableName,
                        $newLocalizationId,
                        $adjustCopiedValues
                    );
                }
650
651
652
653
            }
        }
        // populate new child records in data-map
        if (!empty($populateAncestorIds)) {
654
            foreach ($populateAncestorIds as $populateAncestorId) {
655
                $newLocalizationId = StringUtility::getUniqueId('NEW');
656
                $desiredIdMap[$populateAncestorId] = $newLocalizationId;
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
                $duplicatedValues = $this->allDataMap[$foreignTableName][$populateAncestorId] ?? [];
                // applies localization references to given raw data-map item
                if ($isTranslatable && $isLocalized) {
                    $duplicatedValues = $this->applyLocalizationReferences(
                        $foreignTableName,
                        $populateAncestorId,
                        $item->getLanguage(),
                        $fieldNames,
                        $duplicatedValues
                    );
                }
                // prefixes language title if applicable for the accordant field name in raw data-map item
                if ($isTranslatable && $isLocalized && !$isLocalizationModeExclude) {
                    $duplicatedValues = $this->prefixLanguageTitle(
                        $foreignTableName,
                        $populateAncestorId,
                        $item->getLanguage(),
                        $duplicatedValues
                    );
                }
677
                $this->modifyDataMap(
678
                    $foreignTableName,
679
                    $newLocalizationId,
680
                    $duplicatedValues
681
                );
682
683
684
            }
        }
        // update inline parent field references - required to update pointer fields
685
686
687
688
689
690
691
        $this->modifyDataMap(
            $item->getTableName(),
            $item->getId(),
            [$fieldName => implode(',', array_values($desiredIdMap))]
        );
    }

692
693
694
695
696
697
698
699
700
701
702
703
704
705
    /**
     * Determines suggest inline relations of either translation parent or
     * source record from data-map or storage in case records have been
     * persisted already.
     *
     * @param DataMapItem $item
     * @param string $fieldName
     * @param array $fromRecord
     * @return int[]|string[]
     */
    protected function resolveSuggestedInlineRelations(DataMapItem $item, string $fieldName, array $fromRecord): array
    {
        $suggestedAncestorIds = [];
        $fromId = $fromRecord['uid'];
706
        $configuration = $GLOBALS['TCA'][$item->getTableName()]['columns'][$fieldName];
707
708
709
710
711
        $foreignTableName = $configuration['config']['foreign_table'];
        $manyToManyTable = ($configuration['config']['MM'] ?? '');

        // determine suggested elements of either translation parent or source record
        // from data-map, in case the accordant language parent/source record was modified
712
        if ($this->isSetInDataMap($item->getTableName(), $fromId, $fieldName)) {
713
714
            $suggestedAncestorIds = GeneralUtility::trimExplode(
                ',',
715
                $this->allDataMap[$item->getTableName()][$fromId][$fieldName],
716
717
718
                true
            );
        } elseif (MathUtility::canBeInterpretedAsInteger($fromId)) {
719
            // determine suggested elements of either translation parent or source record from storage
720
721
722
723
724
725
            $relationHandler = $this->createRelationHandler();
            $relationHandler->start(
                $fromRecord[$fieldName],
                $foreignTableName,
                $manyToManyTable,
                $fromId,
726
                $item->getTableName(),
727
728
729
730
731
                $configuration['config']
            );
            $suggestedAncestorIds = $this->mapRelationItemId($relationHandler->itemArray);
        }

732
        return array_filter($suggestedAncestorIds);
733
734
735
736
737
738
739
740
741
742
743
744
745
    }

    /**
     * Determine persisted inline relations for current data-map-item.
     *
     * @param DataMapItem $item
     * @param string $fieldName
     * @param array $forRecord
     * @return int[]
     */
    private function resolvePersistedInlineRelations(DataMapItem $item, string $fieldName, array $forRecord): array
    {
        $persistedIds = [];
746
        $configuration = $GLOBALS['TCA'][$item->getTableName()]['columns'][$fieldName];
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
        $foreignTableName = $configuration['config']['foreign_table'];
        $manyToManyTable = ($configuration['config']['MM'] ?? '');

        // determine persisted elements for the current data-map item
        if (!$item->isNew()) {
            $relationHandler = $this->createRelationHandler();
            $relationHandler->start(
                $forRecord[$fieldName] ?? '',
                $foreignTableName,
                $manyToManyTable,
                $item->getId(),
                $item->getTableName(),
                $configuration['config']
            );
            $persistedIds = $this->mapRelationItemId($relationHandler->itemArray);
        }

764
        return array_filter($persistedIds);
765
766
    }

767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
    /**
     * Determines whether a combination of table name, id and field name is
     * set in data-map. This method considers null values as well, that would
     * not be considered by a plain isset() invocation.
     *
     * @param string $tableName
     * @param string|int $id
     * @param string $fieldName
     * @return bool
     */
    protected function isSetInDataMap(string $tableName, $id, string $fieldName)
    {
        return
            // directly look-up field name
            isset($this->allDataMap[$tableName][$id][$fieldName])
            // check existence of field name as key for null values
            || isset($this->allDataMap[$tableName][$id])
            && is_array($this->allDataMap[$tableName][$id])
            && array_key_exists($fieldName, $this->allDataMap[$tableName][$id]);
    }

788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
    /**
     * Applies modifications to the data-map, calling this method is essential
     * to determine new data-map items to be process for synchronizing chained
     * record localizations.
     *
     * @param string $tableName
     * @param string|int $id
     * @param array $values
     * @throws \RuntimeException
     */
    protected function modifyDataMap(string $tableName, $id, array $values)
    {
        // avoid superfluous iterations by data-map changes with values
        // that actually have not been changed and were available already
        $sameValues = array_intersect_assoc(
            $this->allDataMap[$tableName][$id] ?? [],
            $values
        );
        if (!empty($sameValues)) {
            $fieldNames = implode(', ', array_keys($sameValues));
            throw new \RuntimeException(
                sprintf(
                    'Issued data-map change for table %s with same values '
                    . 'for these fields names %s',
                    $tableName,
                    $fieldNames
                ),
                1488634845
            );
        }

        $this->modifiedDataMap[$tableName][$id] = array_merge(
            $this->modifiedDataMap[$tableName][$id] ?? [],
            $values
        );
        $this->allDataMap[$tableName][$id] = array_merge(
            $this->allDataMap[$tableName][$id] ?? [],
            $values
826
827
828
        );
    }

829
830
831
832
833
834
835
836
837
838
839
840
    /**
     * @param DataMapItem $item
     */
    protected function addNextItem(DataMapItem $item)
    {
        $identifier = $item->getTableName() . ':' . $item->getId();
        if (!isset($this->allItems[$identifier])) {
            $this->allItems[$identifier] = $item;
        }
        $this->nextItems[$identifier] = $item;
    }

841
842
    /**
     * Fetches translation related field values for the items submitted in
843
     * the data-map.
844
845
846
847
848
849
850
851
852
853
854
855
     *
     * @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()
856
857
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, $this->backendUser->workspace, false));
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
        $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;
    }

    /**
877
     * Fetches translation dependencies for a given parent/source record ids.
878
     *
879
880
881
882
883
884
885
886
887
888
     * Existing records in database:
     * + [uid:5, l10n_parent=0, l10n_source=0, sys_language_uid=0]
     * + [uid:6, l10n_parent=5, l10n_source=5, sys_language_uid=1]
     * + [uid:7, l10n_parent=5, l10n_source=6, sys_language_uid=2]
     *
     * Input $ids and their results:
     * + [5]   -> [DataMapItem(6), DataMapItem(7)] # since 5 is parent/source
     * + [6]   -> [DataMapItem(7)]                 # since 6 is source
     * + [7]   -> []                               # since there's nothing
     *
889
     * @param string $tableName
890
     * @param int[]|string[] $ids
891
892
893
894
     * @return DataMapItem[][]
     */
    protected function fetchDependencies(string $tableName, array $ids)
    {
895
896
897
898
        if (!BackendUtility::isTableLocalizable($tableName)) {
            return [];
        }

899
900
901
902
903
904
905
906
907
        $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'];
        }
908
909
        $fieldNamesMap = array_combine($fieldNames, $fieldNames);

910
911
        $persistedIds = $this->filterNumericIds($ids);
        $createdIds = array_diff($ids, $persistedIds);
912
        $dependentElements = $this->fetchDependentElements($tableName, $persistedIds, $fieldNames);
913

914
915
916
917
918
919
920
921
922
923
        foreach ($createdIds as $createdId) {
            $data = $this->allDataMap[$tableName][$createdId] ?? null;
            if ($data === null) {
                continue;
            }
            $dependentElements[] = array_merge(
                ['uid' => $createdId],
                array_intersect_key($data, $fieldNamesMap)
            );
        }
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938

        $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()) {
939
                $dependencyMap[$dependentItem->getParent()][State::STATE_PARENT][] = $dependentItem;
940
941
942
943
944
945
946
                $dependencyMap[$dependentItem->getSource()][State::STATE_SOURCE][] = $dependentItem;
            }
        }
        return $dependencyMap;
    }

    /**
947
948
949
     * 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.
950
     *
951
952
953
954
955
956
957
958
959
960
961
962
963
964
     * This method expands the search criteria by expanding to ancestors.
     *
     * Existing records in database:
     * + [uid:5, l10n_parent=0, l10n_source=0, sys_language_uid=0]
     * + [uid:6, l10n_parent=5, l10n_source=5, sys_language_uid=1]
     * + [uid:7, l10n_parent=5, l10n_source=6, sys_language_uid=2]
     *
     * Input $ids and $desiredLanguage and their results:
     * + $ids=[5], $lang=1 -> [5 => 6] # since 5 is source of 6
     * + $ids=[5], $lang=2 -> []       # since 5 is parent of 7, but different language
     * + $ids=[6], $lang=1 -> []       # since there's nothing
     * + $ids=[6], $lang=2 -> [6 => 7] # since 6 has source 5, which is ancestor of 7
     * + $ids=[7], $lang=* -> []       # since there's nothing
     *
965
966
     * @param string $tableName
     * @param array $ids
967
     * @param int $desiredLanguage
968
969
     * @return array
     */
970
    protected function fetchDependentIdMap(string $tableName, array $ids, int $desiredLanguage)
971
    {
972
        $ids = $this->filterNumericIds($ids);
973
974
975
976
        $isTranslatable = BackendUtility::isTableLocalizable($tableName);
        $originFieldName = ($GLOBALS['TCA'][$tableName]['ctrl']['origUid'] ?? null);

        if (!$isTranslatable && $originFieldName === null) {
977
            // @todo Possibly throw an error, since pointing to original entity is not possible (via origin/parent)
978
979
980
            return [];
        }

981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
        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,
            ];
996
997
        }

998
999
1000
1001
1002
1003
1004
1005
1006
        $fetchIds = $ids;
        if ($isTranslatable) {
            // expand search criteria via parent and source elements
            $translationValues = $this->fetchTranslationValues($tableName, $fieldNames, $ids);
            $ancestorIdMap = $this->buildElementAncestorIdMap($fieldNames, $translationValues);
            $fetchIds = array_unique(array_merge($ids, array_keys($ancestorIdMap)));
        }

        $dependentElements = $this->fetchDependentElements($tableName, $fetchIds, $fieldNames);
1007
1008
1009

        $dependentIdMap = [];
        foreach ($dependentElements as $dependentElement) {
1010
1011
1012
            $dependentId = $dependentElement['uid'];
            // implicit: use origin pointer if table cannot be translated
            if (!$isTranslatable) {
1013
                $ancestorId = (int)$dependentElement[$fieldNames['origin']];
1014
            // only consider element if it reflects the desired language
1015
1016
            } elseif ((int)$dependentElement[$fieldNames['language']] === $desiredLanguage) {
                $ancestorId = $this->resolveAncestorId($fieldNames, $dependentElement);
1017
            } else {
1018
                // otherwise skip the element completely
1019
1020
1021
                continue;
            }
            // only keep ancestors that were initially requested before expanding
1022
            if (in_array($ancestorId, $ids, true)) {
1023
1024
                $dependentIdMap[$ancestorId] = $dependentId;
            } elseif (!empty($ancestorIdMap[$ancestorId])) {
1025
                // resolve from previously expanded search criteria
1026
1027
1028
1029
1030
1031
1032
1033
                $possibleChainedIds = array_intersect(
                    $ids,
                    $ancestorIdMap[$ancestorId]
                );
                if (!empty($possibleChainedIds)) {
                    $ancestorId = $possibleChainedIds[0];
                    $dependentIdMap[$ancestorId] = $dependentId;
                }
1034
1035
1036
1037
1038
1039
            }
        }
        return $dependentIdMap;
    }

    /**
1040
1041
1042
     * 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.
1043
1044
1045
     *
     * @param string $tableName
     * @param array $ids
1046
     * @param array $fieldNames
1047
     * @return array
1048
     * @throws \InvalidArgumentException
1049
1050
1051
1052
1053
1054
1055
     */
    protected function fetchDependentElements(string $tableName, array $ids, array $fieldNames)
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()
            ->removeAll()
1056
1057
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, $this->backendUser->workspace, false));
1058

1059
        $zeroParameter = $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT);
1060
        $ids = $this->filterNumericIds($ids);
1061
1062
        $idsParameter = $queryBuilder->createNamedParameter($ids, Connection::PARAM_INT_ARRAY);

1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
        // 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 = [
1078
1079
1080
                // must be any kind of localization
                $queryBuilder->expr()->gt(
                    $fieldNames['language'],
1081
                    $zeroParameter
1082
1083
1084
1085
                ),
                // must be in connected mode
                $queryBuilder->expr()->gt(
                    $fieldNames['parent'],
1086
                    $zeroParameter
1087
1088
                ),
                // any parent or source pointers
1089
1090
1091
                $queryBuilder->expr()->orX(...$ancestorPredicates),
            ];
        } elseif (!empty($fieldNames['origin'])) {
1092
            // fetch by origin dependency ("copied from")
1093
            $predicates = [
1094
                $queryBuilder->expr()->in(
1095
1096
1097
1098
1099
                    $fieldNames['origin'],
                    $idsParameter
                )
            ];
        } else {
1100
            // otherwise: stop execution
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
            throw new \InvalidArgumentException(
                'Invalid combination of query field names given',
                1487192370
            );
        }

        $statement = $queryBuilder
            ->select(...array_values($fieldNames))
            ->from($tableName)
            ->andWhere(...$predicates)
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
            ->execute();

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

    /**
     * Return array of data map items that are of given type
     *
     * @param string $type
1124
     * @param DataMapItem[] $items
1125
1126
     * @return DataMapItem[]
     */
1127
    protected function filterItemsByType(string $type, array $items)
1128
1129
    {
        return array_filter(
1130
            $items,
1131
            function (DataMapItem $item) use ($type) {
1132
1133
1134
1135
1136
1137
                return $item->getType() === $type;
            }
        );
    }

    /**
1138
     * Return only ids that are integer - so no "NEW..." values
1139
     *
1140
     * @param string[]|int[] $ids
1141
     * @return int[]
1142
     */
1143
    protected function filterNumericIds(array $ids)
1144
    {
1145
        $ids = array_filter(
1146
            $ids,
1147
1148
            function ($id) {
                return MathUtility::canBeInterpretedAsInteger($id);
1149
1150
            }
        );
1151
        return array_map('intval', $ids);
1152
1153
    }

1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
    /**
     * Return only ids that don't have an item equivalent in $this->allItems.
     *
     * @param string $tableName
     * @param int[] $ids
     * @return array
     */
    protected function filterNewItemIds(string $tableName, array $ids)
    {
        return array_filter(
            $ids,
            function ($id) use ($tableName) {
                return $this->findItem($tableName, $id) === null;
            }
        );
    }

1171
1172
1173
1174
1175
1176
1177
1178
1179
    /**
     * Flatten array
     *
     * @param array $relationItems
     * @return string[]
     */
    protected function mapRelationItemId(array $relationItems)
    {
        return array_map(
1180
            function (array $relationItem) {
1181
                return (int)$relationItem['id'];
1182
1183
1184
1185
1186
            },
            $relationItems
        );
    }

1187
    /**
1188
1189
1190
     * @param array<string, string> $fieldNames
     * @param array<string, mixed> $element
     * @return int|null either a (non-empty) ancestor uid, or `null` if unresolved
1191
1192
1193
     */
    protected function resolveAncestorId(array $fieldNames, array $element)
    {
1194
1195
1196
1197
        $sourceName = $fieldNames['source'] ?? null;
        if ($sourceName !== null && !empty($element[$sourceName])) {
            // implicit: use source pointer if given (not empty)
            return (int)$element[$sourceName];
1198
        }
1199
1200
1201
1202
        $parentName = $fieldNames['parent'] ?? null;
        if ($parentName !== null && !empty($element[$parentName])) {
            // implicit: use parent pointer if given (not empty)
            return (int)$element[$parentName];
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
        }
        return null;
    }

    /**
     * Builds a map from ancestor ids to accordant localization dependents.
     *
     * The result of e.g. [5 => [6, 7]] refers to ids 6 and 7 being dependents
     * (either used in parent or source field) of the ancestor with id 5.
     *
     * @param array $fieldNames
     * @param array $elements
     * @return array
     */
    protected function buildElementAncestorIdMap(array $fieldNames, array $elements)
    {
        $ancestorIdMap = [];
        foreach ($elements as $element) {
            $ancestorId = $this->resolveAncestorId($fieldNames, $element);
            if ($ancestorId !== null) {
                $ancestorIdMap[$ancestorId][] = (int)$element['uid'];
            }
        }
        return $ancestorIdMap;
    }

1229
1230
1231
1232
1233
    /**
     * See if an items is in item list and return it
     *
     * @param string $tableName
     * @param string|int $id
1234
     * @return DataMapItem|null
1235
1236
1237
     */
    protected function findItem(string $tableName, $id)
    {
1238
        return $this->allItems[$tableName . ':' . $id] ?? null;
1239
1240
    }

1241
    /**
1242
     * Duplicates an item from data-map and prefixes language title,
1243
1244
1245
     * if applicable for the accordant field name.
     *
     * @param string $tableName
1246
     * @param string|int $fromId
1247
1248
     * @param int $language
     * @param array $fieldNames
1249
     * @param bool $localize
1250
     * @return array
1251
     * @deprecated Not used anymore, split into applyLocalizationReferences() and prefixLanguageTitle()
1252
     */
1253
    protected function duplicateFromDataMap(string $tableName, $fromId, int $language, array $fieldNames, bool $localize): array
1254
    {
1255
1256
        $data = $this->allDataMap[$tableName][$fromId] ?? [];
        // just return if localization cannot be applied
1257
        if (empty($language) || !$localize) {
1258
1259
            return $data;
        }
1260
1261
1262
1263
        $data = $this->applyLocalizationReferences($tableName, $fromId, $language, $fieldNames, $data);
        $data = $this->prefixLanguageTitle($tableName, $fromId, $language, $data);
        return $data;
    }
1264

1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
    /**
     * Applies localization references to given raw data-map item.
     *
     * @param string $tableName
     * @param string|int $fromId
     * @param int $language
     * @param array $fieldNames
     * @param array $data
     * @return array
     */
    protected function applyLocalizationReferences(string $tableName, $fromId, int $language, array $fieldNames, array $data): array
    {
        // just return if localization cannot be applied
        if (empty($language)) {
            return $data;
        }

        // apply `languageField`, e.g. `sys_language_uid`
1283
        $data[$fieldNames['language']] = $language;
1284
        // apply `transOrigPointerField`, e.g. `l10n_parent`
1285
1286
1287
1288
        if (empty($data[$fieldNames['parent']])) {
            // @todo Only $id used in TCA type 'select' is resolved in DataHandler's remapStack
            $data[$fieldNames['parent']] = $fromId;
        }
1289
        // apply `translationSource`, e.g. `l10n_source`
1290
1291
        if (!empty($fieldNames['source'])) {
            // @todo Not sure, whether $id is resolved in DataHandler's remapStack
1292
            $data[$fieldNames['source']] = $fromId;
1293
        }
1294
1295
1296
1297
        // unset field names that are expected to be handled in this processor
        foreach ($this->getFieldNamesToBeHandled($tableName) as $fieldName) {
            unset($data[$fieldName]);
        }
1298

1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
        return $data;
    }

    /**
     * Prefixes language title if applicable for the accordant field name in raw data-map item.
     *
     * @param string $tableName
     * @param $fromId
     * @param int $language
     * @param array $data
     * @return array
     */
    protected function prefixLanguageTitle(string $tableName, $fromId, int $language, array $data): array
    {
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
        $prefixFieldNames = array_intersect(
            array_keys($data),
            $this->getPrefixLanguageTitleFieldNames($tableName)
        );
        if (empty($prefixFieldNames)) {
            return $data;
        }

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

1325
1326
1327
        $tsConfigTranslateToMessage = BackendUtility::getPagesTSconfig($pageId)['TCEMAIN.']['translateToMessage'] ?? '';
        if (!empty($tsConfigTranslateToMessage)) {
            $prefix = $tsConfigTranslateToMessage;
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
            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;
    }

1345
1346
1347
1348
1349
    /**
     * Field names we have to deal with
     *
     * @param DataMapItem $item
     * @param string $scope
1350
     * @param bool $modified
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
     * @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) {
1389
1390
1391
            if (($configuration['l10n_mode'] ?? null) === 'exclude'
                && ($configuration['config']['typ