DataHandler.php 436 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\DBALException;
19
use Doctrine\DBAL\Driver\Statement;
20
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
21
use Doctrine\DBAL\Platforms\SQLServerPlatform;
22
use Doctrine\DBAL\Types\IntegerType;
23
24
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
25
use TYPO3\CMS\Backend\Utility\BackendUtility;
26
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
27
use TYPO3\CMS\Core\Cache\CacheManager;
28
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
29
30
31
32
33
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
34
use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
35
use TYPO3\CMS\Core\Configuration\Richtext;
36
37
use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException;
use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;
38
use TYPO3\CMS\Core\Database\Connection;
39
use TYPO3\CMS\Core\Database\ConnectionPool;
40
use TYPO3\CMS\Core\Database\Query\QueryHelper;
41
use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
42
43
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
44
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
45
46
use TYPO3\CMS\Core\Database\ReferenceIndex;
use TYPO3\CMS\Core\Database\RelationHandler;
47
use TYPO3\CMS\Core\DataHandling\History\RecordHistoryStore;
48
use TYPO3\CMS\Core\DataHandling\Localization\DataMapProcessor;
49
use TYPO3\CMS\Core\DataHandling\Model\CorrelationId;
50
use TYPO3\CMS\Core\DataHandling\Model\RecordStateFactory;
Christian Kuhn's avatar
Christian Kuhn committed
51
use TYPO3\CMS\Core\Html\RteHtmlParser;
52
use TYPO3\CMS\Core\Localization\LanguageService;
53
use TYPO3\CMS\Core\Messaging\FlashMessage;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
54
55
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Resource\ResourceFactory;
56
use TYPO3\CMS\Core\Service\OpcodeCacheService;
57
58
59
60
61
use TYPO3\CMS\Core\SysLog\Action as SystemLogGenericAction;
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;
62
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
63
use TYPO3\CMS\Core\Utility\ArrayUtility;
64
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
65
use TYPO3\CMS\Core\Utility\GeneralUtility;
66
use TYPO3\CMS\Core\Utility\HttpUtility;
Sebastian Michaelsen's avatar
Sebastian Michaelsen committed
67
use TYPO3\CMS\Core\Utility\MathUtility;
68
use TYPO3\CMS\Core\Utility\StringUtility;
69
use TYPO3\CMS\Core\Versioning\VersionState;
70

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

88
89
90
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
    // *********************
    // 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
119
     * @internal should only be used from within TYPO3 Core
120
121
122
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
162
163
164
165
166
     */
    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 this is set, then a page is deleted by deleting the whole branch under it (user must have
     * delete permissions to it all). If not set, then the page is deleted ONLY if it has no branch.
     *
     * @var bool
     */
    public $deleteTree = false;

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

167
168
169
170
171
172
173
174
175
    /**
     * 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;

176
    /**
177
     * If TRUE, workspace restrictions are bypassed on edit and create actions (process_datamap()).
178
179
180
     * YOU MUST KNOW what you do if you use this feature!
     *
     * @var bool
181
     * @internal should only be used from within TYPO3 Core
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
     */
    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
198
     * @internal should only be used from within TYPO3 Core
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
     */
    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
218
     * @internal should only be used from within TYPO3 Core
219
     */
220
    public $defaultValues = [];
221
222
223
224
225
226
227

    /**
     * [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
228
     * @internal should only be used from within TYPO3 Core
229
     */
230
    public $overrideValues = [];
231
232
233
234
235
236
237

    /**
     * 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
238
     * @internal should only be used from within TYPO3 Core
239
     */
240
    public $data_disableFields = [];
241
242
243
244
245
246
247
248
249
250

    /**
     * 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
     */
251
    public $suggestedInsertUids = [];
252
253
254
255
256
257

    /**
     * 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
258
     * @internal should only be used from within TYPO3 Core
259
260
261
     */
    public $callBackObj;

262
263
264
    /**
     * A string which can be used as correlationId for RecordHistory entries.
     * The string can later be used to rollback multiple changes at once.
265
266
     *
     * @var CorrelationId|null
267
268
269
     */
    protected $correlationId;

270
271
272
273
274
275
276
    // *********************
    // Internal variables (mapping arrays) which can be used (read-only) from outside
    // *********************
    /**
     * Contains mapping of auto-versionized records.
     *
     * @var array
277
     * @internal should only be used from within TYPO3 Core
278
     */
279
    public $autoVersionIdMap = [];
280
281
282
283
284
285

    /**
     * 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
     */
286
    public $substNEWwithIDs = [];
287
288
289
290
291

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

    /**
     * Holds the tables and there the ids of newly created child records from IRRE
     *
     * @var array
300
     * @internal should only be used from within TYPO3 Core
301
     */
302
    public $newRelatedIDs = [];
303
304

    /**
305
     * This array is the sum of all copying operations in this class.
306
307
     *
     * @var array
308
     * @internal should only be used from within TYPO3 Core
309
     */
310
    public $copyMappingArray_merged = [];
311

312
313
314
315
316
317
318
    /**
     * Per-table array with UIDs that have been deleted.
     *
     * @var array
     */
    protected $deletedRecords = [];

319
320
321
322
    /**
     * Errors are collected in this variable.
     *
     * @var array
323
     * @internal should only be used from within TYPO3 Core
324
     */
325
    public $errorLog = [];
326
327
328
329
330
331

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

    /**
     * Indicates whether the pagetree needs a refresh because of important changes
     *
     * @var bool
338
     * @internal should only be used from within TYPO3 Core
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
     */
    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
359
     * @internal should only be used from within TYPO3 Core
360
361
362
363
364
365
366
     */
    public $userid;

    /**
     * Will be set to username of be_user executing this script
     *
     * @var string
367
     * @internal should only be used from within TYPO3 Core
368
369
370
371
372
373
374
     */
    public $username;

    /**
     * Will be set if user is admin
     *
     * @var bool
375
     * @internal should only be used from within TYPO3 Core
376
377
378
     */
    public $admin;

379
380
381
382
383
    /**
     * @var PagePermissionAssembler
     */
    protected $pagePermissionAssembler;

384
385
386
387
388
    /**
     * 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
     */
389
    protected $excludedTablesAndFields = [];
390
391
392
393
394
395
396

    /**
     * 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
     */
397
    protected $control = [];
398
399
400
401
402
403

    /**
     * Set with incoming data array
     *
     * @var array
     */
404
    public $datamap = [];
405
406
407
408
409
410

    /**
     * Set with incoming cmd array
     *
     * @var array
     */
411
    public $cmdmap = [];
412
413
414
415
416
417

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

    /**
     * List of changed old record ids to new records ids
     *
     * @var array
     */
425
    protected $historyRecords = [];
426
427
428
429

    // Internal static:

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

    // Internal caching arrays
    /**
     * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
     *
     * @var array
     */
445
    protected $recInsertAccessCache = [];
446
447
448
449
450
451

    /**
     * Caching array for check of whether records are in a webmount
     *
     * @var array
     */
452
    protected $isRecordInWebMount_Cache = [];
453
454
455
456
457
458

    /**
     * Caching array for page ids in webmounts
     *
     * @var array
     */
459
    protected $isInWebMount_Cache = [];
460
461
462
463
464
465

    /**
     * Used for caching page records in pageInfo()
     *
     * @var array
     */
466
    protected $pageCache = [];
467
468
469
470
471
472

    // Other arrays:
    /**
     * For accumulation of MM relations that must be written after new records are created.
     *
     * @var array
473
     * @internal
474
     */
475
    public $dbAnalysisStore = [];
476
477
478
479
480

    /**
     * Used for tracking references that might need correction after operations
     *
     * @var array
481
     * @internal
482
     */
483
    public $registerDBList = [];
484
485
486
487
488

    /**
     * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
     *
     * @var array
489
     * @internal
490
     */
491
    public $registerDBPids = [];
492
493
494
495
496
497
498
499
500
501

    /**
     * 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.
     *
     * @var array
502
     * @internal
503
     */
504
    public $copyMappingArray = [];
505
506
507
508
509

    /**
     * Array used for remapping uids and values at the end of process_datamap
     *
     * @var array
510
     * @internal
511
     */
512
    public $remapStack = [];
513
514
515
516
517
518

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

    /**
     * Array used for checking whether new children need to be remapped
     *
     * @var array
     */
528
    protected $remapStackChildIds = [];
529
530
531
532
533
534

    /**
     * Array used for executing addition actions after remapping happened (set processRemapStack())
     *
     * @var array
     */
535
    protected $remapStackActions = [];
536
537
538
539
540
541

    /**
     * Array used for executing post-processing on the reference index
     *
     * @var array
     */
542
    protected $remapStackRefIndex = [];
543
544
545
546
547

    /**
     * Array used for additional calls to $this->updateRefIndex
     *
     * @var array
548
     * @internal
549
     */
550
    public $updateRefIndexStack = [];
551
552
553
554
555

    /**
     * Tells, that this DataHandler instance was called from \TYPO3\CMS\Impext\ImportExport.
     * This variable is set by \TYPO3\CMS\Impext\ImportExport
     *
556
     * @var bool
557
     * @internal only used within TYPO3 Core
558
559
560
561
562
563
564
565
566
     */
    public $callFromImpExp = false;

    // Various

    /**
     * Set to "currentRecord" during checking of values.
     *
     * @var array
567
     * @internal
568
     */
569
    public $checkValue_currentRecord = [];
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593

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

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

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

    /**
     * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
     * This object instantiates itself on versioning and localization ...
     *
     * @var \TYPO3\CMS\Core\DataHandling\DataHandler
     */
594
    protected $outerMostInstance;
595
596
597
598
599
600

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

603
604
605
606
607
608
    /**
     * 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
     */
609
    protected static $recordPidsForDeletedRecords = [];
610

611
612
613
    /**
     * Runtime Cache to store and retrieve data computed for a single request
     *
614
     * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
615
     */
616
    protected $runtimeCache;
617
618
619
620
621
622
623
624
625

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

    /**
626
     * Sets up the data handler cache and some additional options, the main logic is done in the start() method.
627
628
629
     */
    public function __construct()
    {
630
631
        $this->checkStoredRecords = (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecords'];
        $this->checkStoredRecords_loose = (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecordsLoose'];
632
        $this->runtimeCache = $this->getRuntimeCache();
633
        $this->pagePermissionAssembler = GeneralUtility::makeInstance(PagePermissionAssembler::class, $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions']);
634
635
636
637
    }

    /**
     * @param array $control
638
     * @internal
639
640
641
642
643
644
645
646
647
648
649
650
651
     */
    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.
652
     * @param BackendUserAuthentication|null $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
653
654
655
656
657
     */
    public function start($data, $cmd, $altUserObject = null)
    {
        // Initializing BE_USER
        $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
658
659
660
661
        $this->userid = $this->BE_USER->user['uid'] ?? 0;
        $this->username = $this->BE_USER->user['username'] ?? '';
        $this->admin = $this->BE_USER->user['admin'] ?? false;
        if ($this->BE_USER->uc['recursiveDelete'] ?? false) {
662
663
            $this->deleteTree = 1;
        }
664

665
666
667
668
669
        // set correlation id for each new set of data or commands
        $this->correlationId = CorrelationId::forScope(
            md5(StringUtility::getUniqueId(self::class))
        );

670
        // Get default values from user TSconfig
671
672
673
674
675
        $tcaDefaultOverride = $this->BE_USER->getTSConfig()['TCAdefaults.'] ?? null;
        if (is_array($tcaDefaultOverride)) {
            $this->setDefaultsFromUserTS($tcaDefaultOverride);
        }

676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
        // 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!]
696
     * @internal
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
     */
    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
726
     * @internal should only be used from within DataHandler
727
728
729
730
731
732
733
734
     */
    public function setDefaultsFromUserTS($userTS)
    {
        if (!is_array($userTS)) {
            return;
        }

        foreach ($userTS as $k => $v) {
735
            $k = mb_substr($k, 0, -1);
736
737
738
739
740
741
742
743
744
745
746
747
            if (!$k || !is_array($v) || !isset($GLOBALS['TCA'][$k])) {
                continue;
            }

            if (is_array($this->defaultValues[$k])) {
                $this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
            } else {
                $this->defaultValues[$k] = $v;
            }
        }
    }

748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
    /**
     * 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;
    }

777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
    /*********************************************
     *
     * 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
794
     * @internal should only be used from within DataHandler
795
796
797
798
799
800
801
802
803
804
805
     */
    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 {
806
            $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = [
807
808
809
                'status' => $status,
                'fieldArray' => $fieldArray,
                'hookObjectsArr' => $hookObjectsArr
810
            ];
811
812
813
814
815
816
817
818
819
820
821
822
823
        }
    }

    /**
     * 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)) {
824
            $this->checkModifyAccessListHookObjects = [];
825
826
827
828
            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);
829
                }
830
                $this->checkModifyAccessListHookObjects[] = $hookObject;
831
832
833
834
835
836
837
838
839
840
841
842
843
844
            }
        }
        return $this->checkModifyAccessListHookObjects;
    }

    /*********************************************
     *
     * PROCESSING DATA
     *
     *********************************************/
    /**
     * Processing the data-array
     * Call this function to process the data-array set by start()
     *
845
     * @return bool|void
846
847
848
849
850
851
     */
    public function process_datamap()
    {
        $this->controlActiveElements();

        // Keep versionized(!) relations here locally:
852
        $registerDBList = [];
853
854
855
856
        $this->registerElementsToBeDeleted();
        $this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
        // Editing frozen:
        if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
857
            $this->newlog('All editing in this workspace has been frozen!', SystemLogErrorClassification::USER_ERROR);
858
859
860
            return false;
        }
        // First prepare user defined objects (if any) for hooks which extend this function:
861
        $hookObjectsArr = [];
862
863
864
865
        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);
866
            }
867
            $hookObjectsArr[] = $hookObject;
868
        }
869
        // Pre-process data-map and synchronize localization states
870
        $this->datamap = GeneralUtility::makeInstance(SlugEnricher::class)->enrichDataMap($this->datamap);
871
        $this->datamap = DataMapProcessor::instance($this->datamap, $this->BE_USER)->process();
872
        // 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.
873
        $orderOfTables = [];
874
875
876
877
878
879
880
881
882
883
884
885
886
        // 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);
887
            if (!$modifyAccessList) {
888
                $this->log($table, 0, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
            }
            if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->datamap[$table]) || !$modifyAccessList) {
                continue;
            }

            if ($this->reverseOrder) {
                $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
            }
            // 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;
                $recordAccess = false;
                $old_pid_value = '';
                // Is it a new record? (Then Id is a string)
                if (!MathUtility::canBeInterpretedAsInteger($id)) {
920
                    // Get a fieldArray with tca default values
921
922
923
924
925
                    $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
926
                        $canProceed = true;
927
                        // If a NEW... id
928
                        if (strpos($pid_value, 'NEW') !== false) {
929
930
931
932
933
934
935
936
937
938
939
940
941
                            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 {
942
                                $canProceed = false;
943
944
945
                            }
                        }
                        $pid_value = (int)$pid_value;
946
947
                        if ($canProceed) {
                            $fieldArray = $this->resolveSortingAndPidForNewRecord($table, $pid_value, $fieldArray);
948
949
950
                        }
                    }
                    $theRealPid = $fieldArray['pid'];
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
                    // 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
                    if ($table === 'pages' && $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0 && $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0) {
                        $recordAccess = $this->checkRecordInsertAccess($table, $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
                    } else {
                        $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
                    }
                    if ($recordAccess) {
                        $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
                        $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, true);
                        if (!$recordAccess) {
                            $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', SystemLogErrorClassification::USER_ERROR);
                        } 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;
                                $this->newlog('Record could not be created in this workspace', SystemLogErrorClassification::USER_ERROR);
971
972
973
974
975
976
977
                            }
                        }
                    }
                    // Yes new record, change $record_status to 'insert'
                    $status = 'new';
                } else {
                    // Nope... $id is a number
978
                    $fieldArray = [];
979
980
981
982
                    $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
                    if (!$recordAccess) {
                        if ($this->enableLogging) {
                            $propArr = $this->getRecordProperties($table, $id);
983
                            $this->log($table, $id, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify record \'%s\' (%s) without permission. Or non-existing page.', 2, [$propArr['header'], $table . ':' . $id], $propArr['event_pid']);
984
985
986
987
988
989
                        }
                        continue;
                    }
                    // Next check of the record permissions (internals)
                    $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
                    if (!$recordAccess) {
990
                        $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', SystemLogErrorClassification::USER_ERROR);
991
992
                    } else {
                        // Here we fetch the PID of the record that we point to...
993
                        $tempdata = $this->recordInfo($table, $id, 'pid' . (BackendUtility::isTableWorkspaceEnabled($table) ? ',t3ver_oid,t3ver_wsid,t3ver_stage' : ''));
994
                        $theRealPid = $tempdata['pid'] ?? null;
995
996
                        // 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.)
997
                        if (!empty($this->autoVersionIdMap[$table][$id])) {
998
999
1000
                            // 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);