DataMapProcessor.php 51.9 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
31
32
33
34
35
36
37
38
39
40
41
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Utility\StringUtility;

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

        return $this->allDataMap;
134
135
136
137
138
139
140
141
142
143
    }

    /**
     * Create data map items of all affected rows
     *
     * @param string $tableName
     * @param array $idValues
     */
    protected function collectItems(string $tableName, array $idValues)
    {
144
        if (!$this->isApplicable($tableName)) {
145
146
147
148
149
150
            return;
        }

        $fieldNames = [
            'uid' => 'uid',
            'l10n_state' => 'l10n_state',
151
152
            'language' => $GLOBALS['TCA'][$tableName]['ctrl']['languageField'],
            'parent' => $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'],
153
        ];
154
155
        if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['translationSource'])) {
            $fieldNames['source'] = $GLOBALS['TCA'][$tableName]['ctrl']['translationSource'];
156
157
        }

158
159
160
161
        $translationValues = $this->fetchTranslationValues(
            $tableName,
            $fieldNames,
            $this->filterNewItemIds(
162
                $tableName,
163
164
165
                $this->filterNumericIds(array_keys($idValues))
            )
        );
166
167

        $dependencies = $this->fetchDependencies(
168
169
            $tableName,
            $this->filterNewItemIds($tableName, array_keys($idValues))
170
171
        );

172
        foreach ($idValues as $id => $values) {
173
174
175
176
177
178
179
180
181
182
183
            $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
                );
184

185
186
187
188
189
190
191
192
193
194
195
196
197
198
                // 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]);
                }
199
            }
200
201
            // add item to $this->allItems and $this->nextItems
            $this->addNextItem($item);
202
203
204
205
206
207
        }
    }

    /**
     * Sanitizes the submitted data-map and removes fields which are not
     * defined as custom and thus rely on either parent or source values.
208
209
     *
     * @param DataMapItem[] $items
210
     */
211
    protected function sanitize(array $items)
212
    {
213
214
        foreach (['directChild', 'grandChild'] as $type) {
            foreach ($this->filterItemsByType($type, $items) as $item) {
215
216
217
218
219
220
221
                $this->sanitizeTranslationItem($item);
            }
        }
    }

    /**
     * Handle synchronization of an item list
222
223
     *
     * @param DataMapItem[] $items
224
     */
225
    protected function enrich(array $items)
226
    {
227
228
        foreach (['directChild', 'grandChild'] as $type) {
            foreach ($this->filterItemsByType($type, $items) as $item) {
229
230
231
232
233
234
235
236
237
                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);
            }
        }
238
        foreach ($this->filterItemsByType('parent', $items) as $item) {
239
240
241
242
243
244
245
246
247
248
249
250
251
            $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)
    {
252
253
254
255
256
257
258
        $fieldNames = [];
        foreach ($item->getApplicableScopes() as $scope) {
            $fieldNames = array_merge(
                $fieldNames,
                $this->getFieldNamesForItemScope($item, $scope, !$item->isNew())
            );
        }
259
260
261
262

        $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(
263
            $this->allDataMap[$item->getTableName()][$item->getId()],
264
265
            $fieldNameMap
        );
266
        // remove fields, that are submitted in data-map, but not defined as custom
267
268
        $this->allDataMap[$item->getTableName()][$item->getId()] = array_diff_key(
            $this->allDataMap[$item->getTableName()][$item->getId()],
269
            $fieldNameMap
270
271
272
273
274
275
276
277
        );
    }

    /**
     * Synchronize a single item
     *
     * @param DataMapItem $item
     * @param array $fieldNames
278
     * @param string|int $fromId
279
     */
280
    protected function synchronizeTranslationItem(DataMapItem $item, array $fieldNames, $fromId)
281
282
283
284
    {
        if (empty($fieldNames)) {
            return;
        }
285

286
        $fieldNameList = 'uid,' . implode(',', $fieldNames);
287
288
289
290

        $fromRecord = ['uid' => $fromId];
        if (MathUtility::canBeInterpretedAsInteger($fromId)) {
            $fromRecord = BackendUtility::getRecordWSOL(
291
                $item->getTableName(),
292
293
294
295
296
                $fromId,
                $fieldNameList
            );
        }

297
298
299
300
301
302
303
304
        $forRecord = [];
        if (!$item->isNew()) {
            $forRecord = BackendUtility::getRecordWSOL(
                $item->getTableName(),
                $item->getId(),
                $fieldNameList
            );
        }
305

306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        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)
    {
324
        foreach ([DataMapItem::SCOPE_PARENT, DataMapItem::SCOPE_SOURCE] as $scope) {
325
326
327
328
329
330
331
332
333
            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;
                }
334
335
336
337
338
339
340
341
342
343
344
345
                foreach ([$scope, DataMapItem::SCOPE_EXCLUDE] as $dependentScope) {
                    $fieldNames = $this->getFieldNamesForItemScope(
                        $dependentItem,
                        $dependentScope,
                        false
                    );
                    $this->synchronizeTranslationItem(
                        $dependentItem,
                        $fieldNames,
                        $item->getId()
                    );
                }
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
            }
        }
    }

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

364
        $this->allDataMap[$item->getTableName()][$item->getId()]['l10n_state'] = $item->getState()->export();
365
366
367
368
369
370
371
372
373
374
375
376
377
    }

    /**
     * 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
378
        if ($this->isSetInDataMap($item->getTableName(), $item->getId(), $fieldName)) {
379
380
381
382
            return;
        }

        $fromId = $fromRecord['uid'];
383
        // retrieve value from in-memory data-map
384
385
        if ($this->isSetInDataMap($item->getTableName(), $fromId, $fieldName)) {
            $fromValue = $this->allDataMap[$item->getTableName()][$fromId][$fieldName];
386
        } elseif (array_key_exists($fieldName, $fromRecord)) {
387
            // retrieve value from record
388
            $fromValue = $fromRecord[$fieldName];
389
        } else {
390
            // otherwise abort synchronization
391
            return;
392
        }
393
394

        // plain values
395
        if (!$this->isRelationField($item->getTableName(), $fieldName)) {
396
397
398
399
400
            $this->modifyDataMap(
                $item->getTableName(),
                $item->getId(),
                [$fieldName => $fromValue]
            );
401
        } elseif (!$this->isInlineRelationField($item->getTableName(), $fieldName)) {
402
            // direct relational values
403
404
            $this->synchronizeDirectRelations($item, $fieldName, $fromRecord);
        } else {
405
            // inline relational values
406
407
408
409
410
411
412
413
414
415
416
417
418
            $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)
    {
419
        $configuration = $GLOBALS['TCA'][$item->getTableName()]['columns'][$fieldName];
420
        $isSpecialLanguageField = ($configuration['config']['special'] ?? null) === 'languages';
421

422
        $fromId = $fromRecord['uid'];
423
424
        if ($this->isSetInDataMap($item->getTableName(), $fromId, $fieldName)) {
            $fromValue = $this->allDataMap[$item->getTableName()][$fromId][$fieldName];
425
426
427
428
        } else {
            $fromValue = $fromRecord[$fieldName];
        }

429
430
431
432
        // 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'])
433
            || $this->isSetInDataMap($item->getTableName(), $fromId, $fieldName)
434
            || $isSpecialLanguageField
435
        ) {
436
437
438
439
440
            $this->modifyDataMap(
                $item->getTableName(),
                $item->getId(),
                [$fieldName => $fromValue]
            );
441
442
            return;
        }
443
444
445
446
        // resolve the language special table name
        if ($isSpecialLanguageField) {
            $specialTableName = 'sys_language';
        }
447
448
449
450
451
452
        // 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') {
453
            $tableNames = ($specialTableName ?? $configuration['config']['foreign_table'] ?? '');
454
455
456
457
458
459
460
461
462
463
        } else {
            return;
        }

        $relationHandler = $this->createRelationHandler();
        $relationHandler->start(
            '',
            $tableNames,
            $manyToManyTable,
            $fromId,
464
            $item->getTableName(),
465
466
467
468
469
            $configuration['config']
        );

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

    /**
478
     * Handle synchronization of inline relations
479
480
481
482
483
     *
     * @param DataMapItem $item
     * @param string $fieldName
     * @param array $fromRecord
     * @param array $forRecord
484
     * @throws \RuntimeException
485
486
487
     */
    protected function synchronizeInlineRelations(DataMapItem $item, string $fieldName, array $fromRecord, array $forRecord)
    {
488
        $configuration = $GLOBALS['TCA'][$item->getTableName()]['columns'][$fieldName];
489
        $isLocalizationModeExclude = ($configuration['l10n_mode'] ?? null) === 'exclude';
490
491
        $foreignTableName = $configuration['config']['foreign_table'];

492
493
494
495
496
497
        $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']));
498

499
500
501
502
503
504
505
506
507
        $suggestedAncestorIds = $this->resolveSuggestedInlineRelations(
            $item,
            $fieldName,
            $fromRecord
        );
        $persistedIds = $this->resolvePersistedInlineRelations(
            $item,
            $fieldName,
            $forRecord
508
        );
509

510
511
        // The dependent ID map points from language parent/source record to
        // localization, thus keys: parents/sources & values: localizations
512
        $dependentIdMap = $this->fetchDependentIdMap($foreignTableName, $suggestedAncestorIds, $item->getLanguage());
513
514
515
516
517
518
519
520
521
522
523
524
525
526
        // 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);
527
528
        // this desired state map defines the final result of child elements in their parent translation
        $desiredIdMap = array_combine($suggestedAncestorIds, $suggestedAncestorIds);
529
530
        // update existing translations in the desired state map
        foreach ($dependentIdMap as $ancestorId => $translationId) {
531
532
            if (isset($desiredIdMap[$ancestorId])) {
                $desiredIdMap[$ancestorId] = $translationId;
533
534
            }
        }
535
        // no children to be synchronized, but element order could have been changed
536
        if (empty($removeAncestorIds) && empty($missingAncestorIds)) {
537
538
539
540
            $this->modifyDataMap(
                $item->getTableName(),
                $item->getId(),
                [$fieldName => implode(',', array_values($desiredIdMap))]
541
542
543
            );
            return;
        }
544
        // In case only missing elements shall be created, re-use previously sanitized
545
546
547
        // 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
548
549
550
551
552
        // 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;
553
554
        if (
            !empty($missingAncestorIds) && $item->isNew() && $sanitizedValue !== null
555
            && count(GeneralUtility::trimExplode(',', $sanitizedValue, true)) === count($missingAncestorIds)
556
        ) {
557
558
559
560
561
            $this->modifyDataMap(
                $item->getTableName(),
                $item->getId(),
                [$fieldName => $sanitizedValue]
            );
562
563
            return;
        }
564
565
566
567
568
569
570
571
572
573
574

        $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
575
576
            if ($isLocalizationModeExclude || !$isTranslatable) {
                $localCommandMap[$foreignTableName][$createAncestorId]['copy'] = -$createAncestorId;
577
            } else {
578
                // otherwise, trigger the localization process
579
580
581
582
583
584
585
586
587
588
                $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) {
589
                if (empty($localDataHandler->copyMappingArray_merged[$foreignTableName][$createAncestorId])) {
590
591
592
593
594
595
596
                    $additionalInformation = '';
                    if (!empty($localDataHandler->errorLog)) {
                        $additionalInformation = ', reason "'
                        . implode(', ', $localDataHandler->errorLog) . '"';
                    }
                    throw new \RuntimeException(
                        'Child record was not processed' . $additionalInformation,
597
598
                        1486233164
                    );
599
                }
600
                $newLocalizationId = $localDataHandler->copyMappingArray_merged[$foreignTableName][$createAncestorId];
601
                $newLocalizationId = $localDataHandler->getAutoVersionId($foreignTableName, $newLocalizationId) ?? $newLocalizationId;
602
                $desiredIdMap[$createAncestorId] = $newLocalizationId;
603
604
605
606
            }
        }
        // populate new child records in data-map
        if (!empty($populateAncestorIds)) {
607
            foreach ($populateAncestorIds as $populateAncestorId) {
608
                $newLocalizationId = StringUtility::getUniqueId('NEW');
609
                $desiredIdMap[$populateAncestorId] = $newLocalizationId;
610
611
612
613
614
615
616
                $duplicatedValues = $this->duplicateFromDataMap(
                    $foreignTableName,
                    $populateAncestorId,
                    $item->getLanguage(),
                    $fieldNames,
                    !$isLocalizationModeExclude && $isTranslatable
                );
617
                $this->modifyDataMap(
618
                    $foreignTableName,
619
                    $newLocalizationId,
620
                    $duplicatedValues
621
                );
622
623
624
            }
        }
        // update inline parent field references - required to update pointer fields
625
626
627
628
629
630
631
        $this->modifyDataMap(
            $item->getTableName(),
            $item->getId(),
            [$fieldName => implode(',', array_values($desiredIdMap))]
        );
    }

632
633
634
635
636
637
638
639
640
641
642
643
644
645
    /**
     * 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'];
646
        $configuration = $GLOBALS['TCA'][$item->getTableName()]['columns'][$fieldName];
647
648
649
650
651
        $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
652
        if ($this->isSetInDataMap($item->getTableName(), $fromId, $fieldName)) {
653
654
            $suggestedAncestorIds = GeneralUtility::trimExplode(
                ',',
655
                $this->allDataMap[$item->getTableName()][$fromId][$fieldName],
656
657
658
                true
            );
        } elseif (MathUtility::canBeInterpretedAsInteger($fromId)) {
659
            // determine suggested elements of either translation parent or source record from storage
660
661
662
663
664
665
            $relationHandler = $this->createRelationHandler();
            $relationHandler->start(
                $fromRecord[$fieldName],
                $foreignTableName,
                $manyToManyTable,
                $fromId,
666
                $item->getTableName(),
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
                $configuration['config']
            );
            $suggestedAncestorIds = $this->mapRelationItemId($relationHandler->itemArray);
        }

        return $suggestedAncestorIds;
    }

    /**
     * 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 = [];
686
        $configuration = $GLOBALS['TCA'][$item->getTableName()]['columns'][$fieldName];
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
        $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);
        }

        return $persistedIds;
    }

707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
    /**
     * 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]);
    }

728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
    /**
     * 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
766
767
768
        );
    }

769
770
771
772
773
774
775
776
777
778
779
780
    /**
     * @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;
    }

781
782
    /**
     * Fetches translation related field values for the items submitted in
783
     * the data-map.
784
785
786
787
788
789
790
791
792
793
794
795
     *
     * @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()
796
797
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, $this->backendUser->workspace, false));
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
        $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;
    }

    /**
817
     * Fetches translation dependencies for a given parent/source record ids.
818
     *
819
820
821
822
823
824
825
826
827
828
     * 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
     *
829
     * @param string $tableName
830
     * @param int[]|string[] $ids
831
832
833
834
     * @return DataMapItem[][]
     */
    protected function fetchDependencies(string $tableName, array $ids)
    {
835
836
837
838
        if (!BackendUtility::isTableLocalizable($tableName)) {
            return [];
        }

839
840
841
842
843
844
845
846
847
        $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'];
        }
848
849
        $fieldNamesMap = array_combine($fieldNames, $fieldNames);

850
851
        $persistedIds = $this->filterNumericIds($ids, true);
        $createdIds = $this->filterNumericIds($ids, false);
852
        $dependentElements = $this->fetchDependentElements($tableName, $persistedIds, $fieldNames);
853

854
855
856
857
858
859
860
861
862
863
        foreach ($createdIds as $createdId) {
            $data = $this->allDataMap[$tableName][$createdId] ?? null;
            if ($data === null) {
                continue;
            }
            $dependentElements[] = array_merge(
                ['uid' => $createdId],
                array_intersect_key($data, $fieldNamesMap)
            );
        }
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

        $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()) {
879
                $dependencyMap[$dependentItem->getParent()][State::STATE_PARENT][] = $dependentItem;
880
881
882
883
884
885
886
                $dependencyMap[$dependentItem->getSource()][State::STATE_SOURCE][] = $dependentItem;
            }
        }
        return $dependencyMap;
    }

    /**
887
888
889
     * 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.
890
     *
891
892
893
894
895
896
897
898
899
900
901
902
903
904
     * 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
     *
905
906
     * @param string $tableName
     * @param array $ids
907
     * @param int $desiredLanguage
908
909
     * @return array
     */
910
    protected function fetchDependentIdMap(string $tableName, array $ids, int $desiredLanguage)
911
    {
912
        $ids = $this->filterNumericIds($ids, true);
913
914
915
916
        $isTranslatable = BackendUtility::isTableLocalizable($tableName);
        $originFieldName = ($GLOBALS['TCA'][$tableName]['ctrl']['origUid'] ?? null);

        if (!$isTranslatable && $originFieldName === null) {
917
918
919
            return [];
        }

920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
        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,
            ];
935
936
        }

937
938
939
940
941
942
943
944
945
        $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);
946
947
948

        $dependentIdMap = [];
        foreach ($dependentElements as $dependentElement) {
949
950
951
            $dependentId = $dependentElement['uid'];
            // implicit: use origin pointer if table cannot be translated
            if (!$isTranslatable) {
952
                $ancestorId = (int)$dependentElement[$fieldNames['origin']];
953
                // only consider element if it reflects the desired language
954
955
            } elseif ((int)$dependentElement[$fieldNames['language']] === $desiredLanguage) {
                $ancestorId = $this->resolveAncestorId($fieldNames, $dependentElement);
956
            } else {
957
                // otherwise skip the element completely
958
959
960
961
962
963
                continue;
            }
            // only keep ancestors that were initially requested before expanding
            if (in_array($ancestorId, $ids)) {
                $dependentIdMap[$ancestorId] = $dependentId;
            } elseif (!empty($ancestorIdMap[$ancestorId])) {
964
                // resolve from previously expanded search criteria
965
966
967
968
969
970
971
972
                $possibleChainedIds = array_intersect(
                    $ids,
                    $ancestorIdMap[$ancestorId]
                );
                if (!empty($possibleChainedIds)) {
                    $ancestorId = $possibleChainedIds[0];
                    $dependentIdMap[$ancestorId] = $dependentId;
                }
973
974
975
976
977
978
            }
        }
        return $dependentIdMap;
    }

    /**
979
980
981
     * 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.
982
983
984
     *
     * @param string $tableName
     * @param array $ids
985
     * @param array $fieldNames
986
     * @return array
987
     * @throws \InvalidArgumentException
988
989
990
     */
    protected function fetchDependentElements(string $tableName, array $ids, array $fieldNames)
    {
991
992
        $ids = $this->filterNumericIds($ids, true);

993
994
995
996
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()
            ->removeAll()
997
998
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, $this->backendUser->workspace, false));
999

1000
        $zeroParameter = $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT);