DataHandler.php 473 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * 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.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
Christian Kuhn's avatar
Christian Kuhn committed
15

16
17
namespace TYPO3\CMS\Core\DataHandling;

18
use Doctrine\DBAL\Exception as DBALException;
19
use Doctrine\DBAL\Platforms\PostgreSQL94Platform as PostgreSQLPlatform;
20
use Doctrine\DBAL\Types\IntegerType;
21
22
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
23
use TYPO3\CMS\Backend\Utility\BackendUtility;
24
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
25
use TYPO3\CMS\Core\Cache\CacheManager;
26
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
27
28
29
30
31
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidIdentifierException;
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowException;
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowLoopException;
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowRootException;
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidPointerFieldValueException;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
32
use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
33
use TYPO3\CMS\Core\Configuration\Richtext;
34
35
use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException;
use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;
36
use TYPO3\CMS\Core\Database\Connection;
37
use TYPO3\CMS\Core\Database\ConnectionPool;
38
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
39
use TYPO3\CMS\Core\Database\Query\QueryHelper;
40
41
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
42
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
43
use TYPO3\CMS\Core\Database\RelationHandler;
44
use TYPO3\CMS\Core\DataHandling\History\RecordHistoryStore;
45
use TYPO3\CMS\Core\DataHandling\Localization\DataMapProcessor;
46
use TYPO3\CMS\Core\DataHandling\Model\CorrelationId;
47
use TYPO3\CMS\Core\DataHandling\Model\RecordStateFactory;
48
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
Christian Kuhn's avatar
Christian Kuhn committed
49
use TYPO3\CMS\Core\Html\RteHtmlParser;
50
51
use TYPO3\CMS\Core\LinkHandling\Exception\UnknownLinkHandlerException;
use TYPO3\CMS\Core\LinkHandling\LinkService;
52
use TYPO3\CMS\Core\LinkHandling\TypoLinkCodecService;
53
use TYPO3\CMS\Core\Localization\LanguageService;
54
use TYPO3\CMS\Core\Log\LogDataTrait;
55
use TYPO3\CMS\Core\Messaging\FlashMessage;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
56
57
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Resource\ResourceFactory;
58
use TYPO3\CMS\Core\Service\OpcodeCacheService;
59
60
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
use TYPO3\CMS\Core\Site\SiteFinder;
61
62
63
64
use TYPO3\CMS\Core\SysLog\Action\Cache as SystemLogCacheAction;
use TYPO3\CMS\Core\SysLog\Action\Database as SystemLogDatabaseAction;
use TYPO3\CMS\Core\SysLog\Error as SystemLogErrorClassification;
use TYPO3\CMS\Core\SysLog\Type as SystemLogType;
65
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
66
use TYPO3\CMS\Core\Utility\ArrayUtility;
67
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
68
use TYPO3\CMS\Core\Utility\GeneralUtility;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
69
use TYPO3\CMS\Core\Utility\MathUtility;
70
use TYPO3\CMS\Core\Utility\StringUtility;
71
use TYPO3\CMS\Core\Versioning\VersionState;
72

73
/**
74
75
 * The main data handler class which takes care of correctly updating and inserting records.
 * This class was formerly known as TCEmain.
76
77
 *
 * This is the TYPO3 Core Engine class for manipulation of the database
78
 * This class is used by eg. the tce_db BE route (SimpleDataHandlerController) which provides an interface for POST forms to this class.
79
80
81
82
83
 *
 * Dependencies:
 * - $GLOBALS['TCA'] must exist
 * - $GLOBALS['LANG'] must exist
 *
84
 * Also see document 'TYPO3 Core API' for details.
85
 */
86
class DataHandler implements LoggerAwareInterface
87
{
88
    use LogDataTrait;
89
90
    use LoggerAwareTrait;

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    // *********************
    // Public variables you can configure before using the class:
    // *********************
    /**
     * If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the
     * log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
     *
     * @var bool
     */
    public $storeLogMessages = true;

    /**
     * If TRUE, actions are logged to sys_log.
     *
     * @var bool
     */
    public $enableLogging = true;

    /**
     * If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new
     * bunch of records.
     *
     * @var bool
     */
    public $reverseOrder = false;

    /**
     * If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array
     * is similar, it's not saved then.
     *
     * @var bool
122
     * @internal should only be used from within TYPO3 Core
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
     */
    public $checkSimilar = true;

    /**
     * This will read the record after having updated or inserted it. If anything is not properly submitted an error
     * is written to the log. This feature consumes extra time by selecting records
     *
     * @var bool
     */
    public $checkStoredRecords = true;

    /**
     * If set, values '' and 0 will equal each other when the stored records are checked.
     *
     * @var bool
     */
    public $checkStoredRecords_loose = true;

    /**
     * If set, then the 'hideAtCopy' flag for tables will be ignored.
     *
     * @var bool
     */
    public $neverHideAtCopy = false;

    /**
     * If set, then the TCE class has been instantiated during an import action of a T3D
     *
     * @var bool
     */
    public $isImporting = false;

    /**
     * If set, then transformations are NOT performed on the input.
     *
     * @var bool
     */
    public $dontProcessTransformations = false;

162
163
164
165
166
167
168
169
170
    /**
     * Will distinguish between translations (with parent) and localizations (without parent) while still using the same methods to copy the records
     * TRUE: translation of a record connected to the default language
     * FALSE: localization of a record without connection to the default language
     *
     * @var bool
     */
    protected $useTransOrigPointerField = true;

171
    /**
172
     * If TRUE, workspace restrictions are bypassed on edit and create actions (process_datamap()).
173
174
175
     * YOU MUST KNOW what you do if you use this feature!
     *
     * @var bool
176
     * @internal should only be used from within TYPO3 Core
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
     */
    public $bypassWorkspaceRestrictions = false;

    /**
     * If TRUE, access check, check for deleted etc. for records is bypassed.
     * YOU MUST KNOW what you are doing if you use this feature!
     *
     * @var bool
     */
    public $bypassAccessCheckForRecords = false;

    /**
     * Comma-separated list. This list of tables decides which tables will be copied. If empty then none will.
     * If '*' then all will (that the user has permission to of course)
     *
     * @var string
193
     * @internal should only be used from within TYPO3 Core
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
     */
    public $copyWhichTables = '*';

    /**
     * If 0 then branch is NOT copied.
     * If 1 then pages on the 1st level is copied.
     * If 2 then pages on the second level is copied ... and so on
     *
     * @var int
     */
    public $copyTree = 0;

    /**
     * [table][fields]=value: New records are created with default values and you can set this array on the
     * form $defaultValues[$table][$field] = $value to override the default values fetched from TCA.
     * If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array
     * (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
     *
     * @var array
213
     * @internal should only be used from within TYPO3 Core
214
     */
215
    public $defaultValues = [];
216
217
218
219
220
221
222

    /**
     * [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to
     * override the incoming data. You must set this externally. You must make sure the fields in this array are also
     * found in the table, because it's not checked. All columns can be set by this array!
     *
     * @var array
223
     * @internal should only be used from within TYPO3 Core
224
     */
225
    public $overrideValues = [];
226
227
228
229
230
231
232

    /**
     * If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated.
     * You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1.
     * Then an empty checkbox will disable the field.
     *
     * @var array
233
     * @internal should only be used from within TYPO3 Core
234
     */
235
    public $data_disableFields = [];
236
237
238
239
240
241
242
243
244
245

    /**
     * Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option
     * since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set
     * it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete).
     * The option is used for import of T3D files when synchronizing between two mirrored servers.
     * As a security measure this feature is available only for Admin Users (for now)
     *
     * @var array
     */
246
    public $suggestedInsertUids = [];
247
248
249
250
251
252

    /**
     * Object. Call back object for FlexForm traversal. Useful when external classes wants to use the
     * iteration functions inside DataHandler for traversing a FlexForm structure.
     *
     * @var object
253
     * @internal should only be used from within TYPO3 Core
254
255
256
     */
    public $callBackObj;

257
258
259
    /**
     * A string which can be used as correlationId for RecordHistory entries.
     * The string can later be used to rollback multiple changes at once.
260
261
     *
     * @var CorrelationId|null
262
263
264
     */
    protected $correlationId;

265
266
267
268
269
270
    // *********************
    // Internal variables (mapping arrays) which can be used (read-only) from outside
    // *********************
    /**
     * Contains mapping of auto-versionized records.
     *
271
     * @var array<string, array<int, string>>
272
     * @internal should only be used from within TYPO3 Core
273
     */
274
    public $autoVersionIdMap = [];
275
276
277
278
279
280

    /**
     * When new elements are created, this array contains a map between their "NEW..." string IDs and the eventual UID they got when stored in database
     *
     * @var array
     */
281
    public $substNEWwithIDs = [];
282
283
284
285
286

    /**
     * Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
     *
     * @var array
287
     * @internal should only be used from within TYPO3 Core
288
     */
289
    public $substNEWwithIDs_table = [];
290
291
292
293
294

    /**
     * Holds the tables and there the ids of newly created child records from IRRE
     *
     * @var array
295
     * @internal should only be used from within TYPO3 Core
296
     */
297
    public $newRelatedIDs = [];
298
299

    /**
300
     * This array is the sum of all copying operations in this class.
301
302
     *
     * @var array
303
     * @internal should only be used from within TYPO3 Core
304
     */
305
    public $copyMappingArray_merged = [];
306

307
308
309
310
311
312
313
    /**
     * Per-table array with UIDs that have been deleted.
     *
     * @var array
     */
    protected $deletedRecords = [];

314
315
316
317
    /**
     * Errors are collected in this variable.
     *
     * @var array
318
     * @internal should only be used from within TYPO3 Core
319
     */
320
    public $errorLog = [];
321
322
323
324
325
326

    /**
     * Fields from the pages-table for which changes will trigger a pagetree refresh
     *
     * @var array
     */
327
    public $pagetreeRefreshFieldsFromPages = ['pid', 'sorting', 'deleted', 'hidden', 'title', 'doktype', 'is_siteroot', 'fe_group', 'nav_hide', 'nav_title', 'module', 'starttime', 'endtime', 'content_from_pid', 'extendToSubpages'];
328
329
330
331
332

    /**
     * Indicates whether the pagetree needs a refresh because of important changes
     *
     * @var bool
333
     * @internal should only be used from within TYPO3 Core
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
     */
    public $pagetreeNeedsRefresh = false;

    // *********************
    // Internal Variables, do not touch.
    // *********************

    // Variables set in init() function:

    /**
     * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
     *
     * @var BackendUserAuthentication
     */
    public $BE_USER;

    /**
     * Will be set to uid of be_user executing this script
     *
     * @var int
354
     * @internal should only be used from within TYPO3 Core
355
356
357
358
359
360
361
     */
    public $userid;

    /**
     * Will be set to username of be_user executing this script
     *
     * @var string
362
     * @internal should only be used from within TYPO3 Core
363
364
365
366
367
368
369
     */
    public $username;

    /**
     * Will be set if user is admin
     *
     * @var bool
370
     * @internal should only be used from within TYPO3 Core
371
372
373
     */
    public $admin;

374
375
376
377
378
    /**
     * @var PagePermissionAssembler
     */
    protected $pagePermissionAssembler;

379
380
381
382
383
    /**
     * The list of <table>-<fields> that cannot be edited by user. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
     *
     * @var array
     */
384
    protected $excludedTablesAndFields = [];
385
386
387
388
389
390
391

    /**
     * Data submitted from the form view, used to control behaviours,
     * e.g. this is used to activate/deactivate fields and thus store NULL values
     *
     * @var array
     */
392
    protected $control = [];
393
394
395
396

    /**
     * Set with incoming data array
     *
397
     * @var array<int|string, array<int|string, array>>
398
     */
399
    public $datamap = [];
400
401
402
403

    /**
     * Set with incoming cmd array
     *
404
     * @var array<string, array<int|string, array>>
405
     */
406
    public $cmdmap = [];
407
408
409
410
411
412

    /**
     * List of changed old record ids to new records ids
     *
     * @var array
     */
413
    protected $mmHistoryRecords = [];
414
415
416
417
418
419

    /**
     * List of changed old record ids to new records ids
     *
     * @var array
     */
420
    protected $historyRecords = [];
421
422
423
424

    // Internal static:

    /**
425
426
427
     * The interval between sorting numbers used with tables with a 'sorting' field defined.
     *
     * Min 1, should be power of 2
428
429
     *
     * @var int
430
     * @internal should only be used from within TYPO3 Core
431
432
433
434
435
436
437
438
439
     */
    public $sortIntervals = 256;

    // Internal caching arrays
    /**
     * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
     *
     * @var array
     */
440
    protected $recInsertAccessCache = [];
441
442
443
444
445
446

    /**
     * Caching array for check of whether records are in a webmount
     *
     * @var array
     */
447
    protected $isRecordInWebMount_Cache = [];
448
449
450
451
452
453

    /**
     * Caching array for page ids in webmounts
     *
     * @var array
     */
454
    protected $isInWebMount_Cache = [];
455
456
457
458

    /**
     * Used for caching page records in pageInfo()
     *
459
     * @var array<int, array<string, array>>
460
     */
461
    protected $pageCache = [];
462
463
464
465
466
467

    // Other arrays:
    /**
     * For accumulation of MM relations that must be written after new records are created.
     *
     * @var array
468
     * @internal
469
     */
470
    public $dbAnalysisStore = [];
471
472
473
474

    /**
     * Used for tracking references that might need correction after operations
     *
475
     * @var array<string, array<int, array>>
476
     * @internal
477
     */
478
    public $registerDBList = [];
479
480
481
482
483

    /**
     * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
     *
     * @var array
484
     * @internal
485
     */
486
    public $registerDBPids = [];
487
488
489
490
491
492
493
494
495

    /**
     * Used by the copy action to track the ids of new pages so subpages are correctly inserted!
     * THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE!
     * Read from copyMappingArray_merged instead which is accumulating this information.
     *
     * NOTE: This is used by some outside scripts (e.g. hooks), as the results in $copyMappingArray_merged
     * are only available after an action has been completed.
     *
496
     * @var array<string, array>
497
     * @internal
498
     */
499
    public $copyMappingArray = [];
500
501
502
503
504

    /**
     * Array used for remapping uids and values at the end of process_datamap
     *
     * @var array
505
     * @internal
506
     */
507
    public $remapStack = [];
508
509
510
511
512
513

    /**
     * Array used for remapping uids and values at the end of process_datamap
     * (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
     *
     * @var array
514
     * @internal
515
     */
516
    public $remapStackRecords = [];
517
518
519
520
521
522

    /**
     * Array used for checking whether new children need to be remapped
     *
     * @var array
     */
523
    protected $remapStackChildIds = [];
524
525
526
527
528
529

    /**
     * Array used for executing addition actions after remapping happened (set processRemapStack())
     *
     * @var array
     */
530
    protected $remapStackActions = [];
531
532

    /**
533
534
535
536
537
     * Registry object to gather reference index update requests and perform updates after
     * main processing has been done. The first call to start() instantiates this object.
     * Recursive sub instances receive this instance via __construct().
     * The final update() call is done at the end of process_cmdmap() or process_datamap()
     * in the outer most instance.
538
     *
539
     * @var ReferenceIndexUpdater
540
     */
541
    protected $referenceIndexUpdater;
542
543
544
545
546
547
548

    // Various

    /**
     * Set to "currentRecord" during checking of values.
     *
     * @var array
549
     * @internal
550
     */
551
    public $checkValue_currentRecord = [];
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570

    /**
     * Disable delete clause
     *
     * @var bool
     */
    protected $disableDeleteClause = false;

    /**
     * @var array
     */
    protected $checkModifyAccessListHookObjects;

    /**
     * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
     * This object instantiates itself on versioning and localization ...
     *
     * @var \TYPO3\CMS\Core\DataHandling\DataHandler
     */
571
    protected $outerMostInstance;
572
573
574
575
576
577

    /**
     * Internal cache for collecting records that should trigger cache clearing
     *
     * @var array
     */
578
    protected static $recordsToClearCacheFor = [];
579

580
581
582
583
584
585
    /**
     * Internal cache for pids of records which were deleted. It's not possible
     * to retrieve the parent folder/page at a later stage
     *
     * @var array
     */
586
    protected static $recordPidsForDeletedRecords = [];
587

588
589
590
    /**
     * Runtime Cache to store and retrieve data computed for a single request
     *
591
     * @var FrontendInterface
592
     */
593
    protected $runtimeCache;
594
595
596
597
598
599
600
601
602

    /**
     * Prefix for the cache entries of nested element calls since the runtimeCache has a global scope.
     *
     * @var string
     */
    protected $cachePrefixNestedElementCalls = 'core-datahandler-nestedElementCalls-';

    /**
603
     * Sets up the data handler cache and some additional options, the main logic is done in the start() method.
604
605
     *
     * @param ReferenceIndexUpdater|null $referenceIndexUpdater Hand over from outer most instance to sub instances
606
     */
607
    public function __construct(ReferenceIndexUpdater $referenceIndexUpdater = null)
608
    {
609
610
        $this->checkStoredRecords = (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecords'];
        $this->checkStoredRecords_loose = (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecordsLoose'];
611
        $this->runtimeCache = $this->getRuntimeCache();
612
        $this->pagePermissionAssembler = GeneralUtility::makeInstance(PagePermissionAssembler::class, $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions']);
613
614
615
616
617
618
        if ($referenceIndexUpdater === null) {
            // Create ReferenceIndexUpdater object. This should only happen on outer most instance,
            // sub instances should receive the reference index updater from a parent.
            $referenceIndexUpdater = GeneralUtility::makeInstance(ReferenceIndexUpdater::class);
        }
        $this->referenceIndexUpdater = $referenceIndexUpdater;
619
620
621
622
    }

    /**
     * @param array $control
623
     * @internal
624
625
626
627
628
629
630
631
632
633
634
635
636
     */
    public function setControl(array $control)
    {
        $this->control = $control;
    }

    /**
     * Initializing.
     * For details, see 'TYPO3 Core API' document.
     * This function does not start the processing of data, but merely initializes the object
     *
     * @param array $data Data to be modified or inserted in the database
     * @param array $cmd Commands to copy, move, delete, localize, versionize records.
637
     * @param BackendUserAuthentication|null $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
638
639
640
641
642
     */
    public function start($data, $cmd, $altUserObject = null)
    {
        // Initializing BE_USER
        $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
643
644
645
        $this->userid = $this->BE_USER->user['uid'] ?? 0;
        $this->username = $this->BE_USER->user['username'] ?? '';
        $this->admin = $this->BE_USER->user['admin'] ?? false;
646

647
648
649
650
651
        // set correlation id for each new set of data or commands
        $this->correlationId = CorrelationId::forScope(
            md5(StringUtility::getUniqueId(self::class))
        );

652
        // Get default values from user TSconfig
653
654
655
656
657
        $tcaDefaultOverride = $this->BE_USER->getTSConfig()['TCAdefaults.'] ?? null;
        if (is_array($tcaDefaultOverride)) {
            $this->setDefaultsFromUserTS($tcaDefaultOverride);
        }

658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
        // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
        if (!$this->admin) {
            $this->excludedTablesAndFields = array_flip($this->getExcludeListArray());
        }
        // Setting the data and cmd arrays
        if (is_array($data)) {
            reset($data);
            $this->datamap = $data;
        }
        if (is_array($cmd)) {
            reset($cmd);
            $this->cmdmap = $cmd;
        }
    }

    /**
     * Function that can mirror input values in datamap-array to other uid numbers.
     * Example: $mirror[table][11] = '22,33' will look for content in $this->datamap[table][11] and copy it to $this->datamap[table][22] and $this->datamap[table][33]
     *
     * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
678
     * @internal
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
     */
    public function setMirror($mirror)
    {
        if (!is_array($mirror)) {
            return;
        }

        foreach ($mirror as $table => $uid_array) {
            if (!isset($this->datamap[$table])) {
                continue;
            }

            foreach ($uid_array as $id => $uidList) {
                if (!isset($this->datamap[$table][$id])) {
                    continue;
                }

                $theIdsInArray = GeneralUtility::trimExplode(',', $uidList, true);
                foreach ($theIdsInArray as $copyToUid) {
                    $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
                }
            }
        }
    }

    /**
     * Initializes default values coming from User TSconfig
     *
     * @param array $userTS User TSconfig array
708
     * @internal should only be used from within DataHandler
709
710
711
712
713
714
715
716
     */
    public function setDefaultsFromUserTS($userTS)
    {
        if (!is_array($userTS)) {
            return;
        }

        foreach ($userTS as $k => $v) {
717
            $k = mb_substr($k, 0, -1);
718
719
720
721
            if (!$k || !is_array($v) || !isset($GLOBALS['TCA'][$k])) {
                continue;
            }

722
            if (is_array($this->defaultValues[$k] ?? false)) {
723
724
725
726
727
728
729
                $this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
            } else {
                $this->defaultValues[$k] = $v;
            }
        }
    }

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
    /**
     * When a new record is created, all values that haven't been set but are set via PageTSconfig / UserTSconfig
     * get applied here.
     *
     * This is only executed for new records. The most important part is that the pageTS of the actual resolved $pid
     * is taken, and a new field array with empty defaults is set again.
     *
     * @param string $table
     * @param int $pageId
     * @param array $prepopulatedFieldArray
     * @return array
     */
    protected function applyDefaultsForFieldArray(string $table, int $pageId, array $prepopulatedFieldArray): array
    {
        // First set TCAdefaults respecting the given PageID
        $tcaDefaults = BackendUtility::getPagesTSconfig($pageId)['TCAdefaults.'] ?? null;
        // Re-apply $this->defaultValues settings
        $this->setDefaultsFromUserTS($tcaDefaults);
        $cleanFieldArray = $this->newFieldArray($table);
        if (isset($prepopulatedFieldArray['pid'])) {
            $cleanFieldArray['pid'] = $prepopulatedFieldArray['pid'];
        }
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? null;
        if ($sortColumn !== null && isset($prepopulatedFieldArray[$sortColumn])) {
            $cleanFieldArray[$sortColumn] = $prepopulatedFieldArray[$sortColumn];
        }
        return $cleanFieldArray;
    }

759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
    /*********************************************
     *
     * HOOKS
     *
     *********************************************/
    /**
     * Hook: processDatamap_afterDatabaseOperations
     * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
     *
     * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
     * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
     *
     * @param array $hookObjectsArr (reference) Array with hook objects
     * @param string $status (reference) Status of the current operation, 'new' or 'update
     * @param string $table (reference) The table currently processing data for
     * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
     * @param array $fieldArray (reference) The field array of a record
776
     * @internal should only be used from within DataHandler
777
778
779
780
781
782
783
784
785
786
787
     */
    public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray)
    {
        // Process hook directly:
        if (!isset($this->remapStackRecords[$table][$id])) {
            foreach ($hookObjectsArr as $hookObj) {
                if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
                    $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
                }
            }
        } else {
788
            $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = [
789
790
                'status' => $status,
                'fieldArray' => $fieldArray,
791
                'hookObjectsArr' => $hookObjectsArr,
792
            ];
793
794
795
796
797
798
799
800
801
802
803
804
805
        }
    }

    /**
     * Gets the 'checkModifyAccessList' hook objects.
     * The first call initializes the accordant objects.
     *
     * @return array The 'checkModifyAccessList' hook objects (if any)
     * @throws \UnexpectedValueException
     */
    protected function getCheckModifyAccessListHookObjects()
    {
        if (!isset($this->checkModifyAccessListHookObjects)) {
806
            $this->checkModifyAccessListHookObjects = [];
807
808
809
810
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] ?? [] as $className) {
                $hookObject = GeneralUtility::makeInstance($className);
                if (!$hookObject instanceof DataHandlerCheckModifyAccessListHookInterface) {
                    throw new \UnexpectedValueException($className . ' must implement interface ' . DataHandlerCheckModifyAccessListHookInterface::class, 1251892472);
811
                }
812
                $this->checkModifyAccessListHookObjects[] = $hookObject;
813
814
815
816
817
818
819
820
821
822
823
824
825
826
            }
        }
        return $this->checkModifyAccessListHookObjects;
    }

    /*********************************************
     *
     * PROCESSING DATA
     *
     *********************************************/
    /**
     * Processing the data-array
     * Call this function to process the data-array set by start()
     *
827
     * @return bool|void
828
829
830
831
832
833
     */
    public function process_datamap()
    {
        $this->controlActiveElements();

        // Keep versionized(!) relations here locally:
834
        $registerDBList = [];
835
836
837
        $this->registerElementsToBeDeleted();
        $this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
        // Editing frozen:
838
        if ($this->BE_USER->workspace !== 0 && ($this->BE_USER->workspaceRec['freeze'] ?? false)) {
839
            $this->log('sys_workspace', $this->BE_USER->workspace, SystemLogDatabaseAction::VERSIONIZE, 0, SystemLogErrorClassification::USER_ERROR, 'All editing in this workspace has been frozen');
840
841
842
            return false;
        }
        // First prepare user defined objects (if any) for hooks which extend this function:
843
        $hookObjectsArr = [];
844
845
846
847
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] ?? [] as $className) {
            $hookObject = GeneralUtility::makeInstance($className);
            if (method_exists($hookObject, 'processDatamap_beforeStart')) {
                $hookObject->processDatamap_beforeStart($this);
848
            }
849
            $hookObjectsArr[] = $hookObject;
850
        }
851
        // Pre-process data-map and synchronize localization states
852
        $this->datamap = GeneralUtility::makeInstance(SlugEnricher::class)->enrichDataMap($this->datamap);
853
        $this->datamap = DataMapProcessor::instance($this->datamap, $this->BE_USER, $this->referenceIndexUpdater)->process();
854
        // Organize tables so that the pages-table is always processed first. This is required if you want to make sure that content pointing to a new page will be created.
855
        $orderOfTables = [];
856
857
858
859
860
861
862
863
864
865
866
867
868
        // Set pages first.
        if (isset($this->datamap['pages'])) {
            $orderOfTables[] = 'pages';
        }
        $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
        // Process the tables...
        foreach ($orderOfTables as $table) {
            // Check if
            //	   - table is set in $GLOBALS['TCA'],
            //	   - table is NOT readOnly
            //	   - the table is set with content in the data-array (if not, there's nothing to process...)
            //	   - permissions for tableaccess OK
            $modifyAccessList = $this->checkModifyAccessList($table);
869
            if (!$modifyAccessList) {
870
                $this->log($table, 0, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify table "{table}" without permission', 1, ['table' => $table]);
871
872
873
874
875
876
            }
            if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->datamap[$table]) || !$modifyAccessList) {
                continue;
            }

            if ($this->reverseOrder) {
877
                $this->datamap[$table] = array_reverse($this->datamap[$table], true);
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
            }
            // For each record from the table, do:
            // $id is the record uid, may be a string if new records...
            // $incomingFieldArray is the array of fields
            foreach ($this->datamap[$table] as $id => $incomingFieldArray) {
                if (!is_array($incomingFieldArray)) {
                    continue;
                }
                $theRealPid = null;

                // Hook: processDatamap_preProcessFieldArray
                foreach ($hookObjectsArr as $hookObj) {
                    if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
                        $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
                    }
                }
                // ******************************
                // Checking access to the record
                // ******************************
                $createNewVersion = false;
                $old_pid_value = '';
                // Is it a new record? (Then Id is a string)
                if (!MathUtility::canBeInterpretedAsInteger($id)) {
901
                    // Get a fieldArray with tca default values
902
903
904
905
906
                    $fieldArray = $this->newFieldArray($table);
                    // A pid must be set for new records.
                    if (isset($incomingFieldArray['pid'])) {
                        $pid_value = $incomingFieldArray['pid'];
                        // Checking and finding numerical pid, it may be a string-reference to another value
907
                        $canProceed = true;
908
                        // If a NEW... id
909
                        if (str_contains($pid_value, 'NEW')) {
910
911
912
913
914
915
916
917
918
919
920
921
922
                            if ($pid_value[0] === '-') {
                                $negFlag = -1;
                                $pid_value = substr($pid_value, 1);
                            } else {
                                $negFlag = 1;
                            }
                            // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
                            if (isset($this->substNEWwithIDs[$pid_value])) {
                                if ($negFlag === 1) {
                                    $old_pid_value = $this->substNEWwithIDs[$pid_value];
                                }
                                $pid_value = (int)($negFlag * $this->substNEWwithIDs[$pid_value]);
                            } else {
923
                                $canProceed = false;
924
925
926
                            }
                        }
                        $pid_value = (int)$pid_value;
927
928
                        if ($canProceed) {
                            $fieldArray = $this->resolveSortingAndPidForNewRecord($table, $pid_value, $fieldArray);
929
930
931
                        }
                    }
                    $theRealPid = $fieldArray['pid'];
932
933
                    // Checks if records can be inserted on this $pid.
                    // If this is a page translation, the check needs to be done for the l10n_parent record
934
935
936
937
938
939
940
                    $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? null;
                    $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? null;
                    if ($table === 'pages'
                        && $languageField && isset($incomingFieldArray[$languageField]) && $incomingFieldArray[$languageField] > 0
                        && $transOrigPointerField && isset($incomingFieldArray[$transOrigPointerField]) && $incomingFieldArray[$transOrigPointerField] > 0
                    ) {
                        $recordAccess = $this->checkRecordInsertAccess($table, $incomingFieldArray[$transOrigPointerField]);
941
942
943
944
                    } else {
                        $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
                    }
                    if ($recordAccess) {
945
                        $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray, $theRealPid);
946
947
                        $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, true);
                        if (!$recordAccess) {
948
                            $this->log($table, 0, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::USER_ERROR, 'recordEditAccessInternals() check failed [{reason}]', -1, ['reason' => $this->BE_USER->errorMsg]);
949
950
951
952
953
954
955
                        } elseif (!$this->bypassWorkspaceRestrictions && !$this->BE_USER->workspaceAllowsLiveEditingInTable($table)) {
                            // If LIVE records cannot be created due to workspace restrictions, prepare creation of placeholder-record
                            // So, if no live records were allowed in the current workspace, we have to create a new version of this record
                            if (BackendUtility::isTableWorkspaceEnabled($table)) {
                                $createNewVersion = true;
                            } else {
                                $recordAccess = false;
956
                                $this->log($table, 0, SystemLogDatabaseAction::VERSIONIZE, 0, SystemLogErrorClassification::USER_ERROR, 'Record could not be created in this workspace');
957
958
959
960
961
962
963
                            }
                        }
                    }
                    // Yes new record, change $record_status to 'insert'
                    $status = 'new';
                } else {
                    // Nope... $id is a number
964
                    $id = (int)$id;
965
                    $fieldArray = [];
966
967
968
969
                    $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
                    if (!$recordAccess) {
                        if ($this->enableLogging) {
                            $propArr = $this->getRecordProperties($table, $id);
970
                            $this->log($table, $id, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify record "{title}" ({table}:{uid}) without permission or non-existing page', 2, ['title' => $propArr['header'], 'table' => $table, 'uid' => $id], $propArr['event_pid']);
971
972
973
974
975
976
                        }
                        continue;
                    }
                    // Next check of the record permissions (internals)
                    $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
                    if (!$recordAccess) {
977
                        $this->log($table, $id, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'recordEditAccessInternals() check failed [{reason}]', -1, ['reason' => $this->BE_USER->errorMsg]);
978
979
                    } else {
                        // Here we fetch the PID of the record that we point to...
980
                        $tempdata = $this->recordInfo($table, $id, 'pid' . (BackendUtility::isTableWorkspaceEnabled($table) ? ',t3ver_oid,t3ver_wsid,t3ver_stage' : ''));
981
                        $theRealPid = $tempdata['pid'] ?? null;
982
983
                        // Use the new id of the versionized record we're trying to write to:
                        // (This record is a child record of a parent and has already been versionized.)
984
                        if (!empty($this->autoVersionIdMap[$table][$id])) {
985
986
987
988
989
990
                            // For the reason that creating a new version of this record, automatically
                            // created related child records (e.g. "IRRE"), update the accordant field:
                            $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
                            // Use the new id of the copied/versionized record:
                            $id = $this->autoVersionIdMap[$table][$id];
                            $recordAccess = true;
991
                        } elseif (!$this->bypassWorkspaceRestrictions && $tempdata && ($errorCode = $this->workspaceCannotEditRecord($table, $tempdata))) {
992
993
994
                            $recordAccess = false;
                            // Versioning is required and it must be offline version!
                            // Check if there already is a workspace version
995
996
997
                            $workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid,t3ver_oid');
                            if ($workspaceVersion) {
                                $id = $workspaceVersion['uid'];
998
                                $recordAccess = true;
999
                            } elseif ($this->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1000
1001
1002
                                // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
                                $this->pagetreeNeedsRefresh = true;

1003
                                /** @var DataHandler $tce */
1004
                                $tce = GeneralUtility::makeInstance(__CLASS__, $this->referenceIndexUpdater);
1005
                                $tce->enableLogging = $this->enableLogging;
1006
                                // Setting up command for creating a new version of the record:
1007
1008
                                $cmd = [];
                                $cmd[$table][$id]['version'] = [
1009
                                    'action' => 'new',
1010
                                    // Default is to create a version of the individual records
1011
                                    'label' => 'Auto-created for WS #' . $this->BE_USER->workspace,
1012
                                ];
1013
                                $tce->start([], $cmd, $this->BE_USER);
1014
1015
1016
                                $tce->process_cmdmap();
                                $this->errorLog = array_merge($this->errorLog, $tce->errorLog);
                                // If copying was successful, share the new uids (also of related children):
1017
                                if (!empty($tce->copyMappingArray[$table][$id])) {
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
                                    foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
                                        foreach ($origIdArray as $origId => $newId) {
                                            $this->autoVersionIdMap[$origTable][$origId] = $newId;
                                        }
                                    }
                                    // Update registerDBList, that holds the copied relations to child records:
                                    $registerDBList = array_merge($registerDBList, $tce->registerDBList);
                                    // For the reason that creating a new version of this record, automatically
                                    // created related child records (e.g. "IRRE"), update the accordant field:
                                    $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
                                    // Use the new id of the copied/versionized record:
                                    $id = $this->autoVersionIdMap[$table][$id];
                                    $recordAccess = true;
1031
                                } else {
1032
                                    $this->log($table, $id, SystemLogDatabaseAction::VERSIONIZE, 0, SystemLogErrorClassification::USER_ERROR, 'Could not be edited in offline workspace in the branch where found ({reason}). Auto-creation of version failed', -1, ['reason' => $errorCode]);
1033
                                }
1034
                            } else {
1035
                                $this->log($table, $id, SystemLogDatabaseAction::VERSIONIZE, 0, SystemLogErrorClassification::USER_ERROR, 'Could not be edited in offline workspace in the branch where found ({reason}). Auto-creation of version not allowed in workspace', -1, ['reason' => $errorCode]);
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
                            }
                        }
                    }
                    // The default is 'update'
                    $status = 'update';
                }
                // If access was granted above, proceed to create or update record:
                if (!$recordAccess) {
                    continue;
                }

                // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1048
                [$tscPID] = BackendUtility::getTSCpid($table, $id, $old_pid_value ?: ($fieldArray['pid'] ?? 0));
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
                if ($status === 'new') {
                    // Apply TCAdefaults from pageTS
                    $fieldArray = $this->applyDefaultsForFieldArray($table, (int)$tscPID, $fieldArray);
                    // Apply page permissions as well
                    if ($table === 'pages') {
                        $fieldArray = $this->pagePermissionAssembler->applyDefaults(
                            $fieldArray,
                            (int)$tscPID,
                            (int)$this->userid,
                            (int)$this->BE_USER->firstMainGroup
                        );
                    }
1061
1062
1063
1064
1065
                    // Ensure that the default values, that are stored in the $fieldArray (built from internal default values)
                    // Are also placed inside the incomingFieldArray, so this is checked in "fillInFieldArray" and
                    // all default values are also checked for validity
                    // This allows to set TCAdefaults (for example) without having to use FormEngine to have the fields available first.
                    $incomingFieldArray = array_replace_recursive($fieldArray, $incomingFieldArray);
1066
1067
1068
                }
                // Processing of all fields in incomingFieldArray and setting them in $fieldArray
                $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1069
                // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations to field!
1070
1071
1072
1073
                // Forcing some values unto field array:
                // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
                $fieldArray = $this->overrideFieldArray($table, $fieldArray);
                // Setting system fields
1074
                if ($status === 'new') {
1075
                    if ($GLOBALS['TCA'][$table]['ctrl']['crdate'] ?? false) {
1076
1077
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
                    }
1078
                    if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id'] ?? false) {
1079
1080
1081
1082
1083
1084
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
                    }
                } elseif ($this->checkSimilar) {
                    // Removing fields which are equal to the current value:
                    $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
                }
1085
                if (($GLOBALS['TCA'][$table]['ctrl']['tstamp'] ?? false) && !empty($fieldArray)) {
1086
1087
1088
                    $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
                }
                // Set stage to "Editing" to make sure we restart the workflow
1089
                if (BackendUtility::isTableWorkspaceEnabled($table)) {
1090
1091
1092
1093
1094
1095
1096
1097
1098
                    $fieldArray['t3ver_stage'] = 0;
                }
                // Hook: processDatamap_postProcessFieldArray
                foreach ($hookObjectsArr as $hookObj) {
                    if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
                        $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
                    }
                }
                // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1099
                // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already
1100
                if (is_array($fieldArray)) {
1101
                    if ($status === 'new') {
1102
1103
1104
1105
1106
                        if ($table === 'pages') {
                            // for new pages always a refresh is needed
                            $this->pagetreeNeedsRefresh = true;
                        }

1107
                        // This creates a version of the record, instead of adding it to the live workspace
1108
1109
1110
                        if ($createNewVersion) {
                            // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
                            $this->pagetreeNeedsRefresh = true;
1111
                            $fieldArray['pid'] = $theRealPid;
1112
1113
1114
                            $fieldArray['t3ver_oid'] = 0;
                            // Setting state for version (so it can know it is currently a new version...)
                            $fieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER);
1115
                            $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1116
1117
1118
                            $this->insertDB($table, $id, $fieldArray, true, (int)($incomingFieldArray['uid'] ?? 0));
                            // Hold auto-versionized ids of placeholders
                            $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $this->substNEWwithIDs[$id];
1119
                        } else {
1120
                            $this->insertDB($table, $id, $fieldArray, false, (int)($incomingFieldArray['uid'] ?? 0));
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
                        }
                    } else {
                        if ($table === 'pages') {
                            // only a certain number of fields needs to be checked for updates
                            // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
                            $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages, array_keys($fieldArray));
                            if (!empty($fieldsToCheck)) {
                                $this->pagetreeNeedsRefresh = true;
                            }
                        }
                        $this->updateDB($table, $id, $fieldArray);
                    }
                }
                // Hook: processDatamap_afterDatabaseOperations
                // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
                // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
                $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
            }
        }
        // Process the stack of relations to remap/correct
        $this->processRemapStack();
        $this->dbAnalysisStoreExec();
        // Hook: processDatamap_afterAllOperations
        // Note: When this hook gets called, all operations on the submitted data have been finished.
        foreach ($hookObjectsArr as $hookObj) {
            if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
                $hookObj->processDatamap_afterAllOperations($this);
            }
        }
1150

1151
        if ($this->isOuterMostInstance()) {
1152
            $this->referenceIndexUpdater->update();
1153
1154
1155
1156
1157
            $this->processClearCacheQueue();
            $this->resetElementsToBeDeleted();
        }
    }

1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
    /**
     * Sets the "sorting" DB field and the "pid" field of an incoming record that should be added (NEW1234)
     * depending on the record that should be added or where it should be added.
     *
     * This method is called from process_datamap()
     *
     * @param string $table the table name of the record to insert
     * @param int $pid the real PID (numeric) where the record should be
     * @param array $fieldArray field+value pairs to add
     * @return array the modified field array
     */
    protected function resolveSortingAndPidForNewRecord(string $table, int $pid, array $fieldArray): array
    {
1171
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
1172
1173
        // Points to a page on which to insert the element, possibly in the top of the page
        if ($pid >= 0) {
1174
            // Ensure that the "pid" is not a translated page ID, but the default page ID
1175
            $pid = $this->getDefaultLanguagePageId($pid);
1176
1177
1178
            // The numerical pid is inserted in the data array
            $fieldArray['pid'] = $pid;
            // If this table is sorted we better find the top sorting number
1179
1180
            if ($sortColumn) {
                $fieldArray[$sortColumn] = $this->getSortNumber($table, 0, $pid);
1181
            }
1182
        } elseif ($sortColumn) {
1183
1184
1185
1186
1187
            // Points to another record before itself
            // If this table is sorted we better find the top sorting number
            // Because $pid is < 0, getSortNumber() returns an array
            $sortingInfo = $this->getSortNumber($table, 0, $pid);
            $fieldArray['pid'] = $sortingInfo['pid'];
1188
            $fieldArray[$sortColumn] = $sortingInfo['sortNumber'];
1189
1190
1191
        } else {
            // Here we fetch the PID of the record that we point to
            $record = $this->recordInfo($table, abs($pid), 'pid');
1192
            // Ensure that the "pid" is not a translated page ID, but the default page ID
1193
            $fieldArray['pid'] = $this->getDefaultLanguagePageId($record['pid']);
1194
1195
1196
1197
        }
        return $fieldArray;
    }

1198