Passed
Push — master ( 03f78e...954a3f )
by
unknown
12:06
created

DataHandler::getUnique()   B

Complexity

Conditions 9
Paths 14

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 19
nc 14
nop 5
dl 0
loc 35
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Core\DataHandling;
17
18
use Doctrine\DBAL\Driver\Statement;
19
use Doctrine\DBAL\Exception as DBALException;
20
use Doctrine\DBAL\Platforms\PostgreSQL94Platform as PostgreSqlPlatform;
21
use Doctrine\DBAL\Platforms\SQLServer2012Platform as SQLServerPlatform;
22
use Doctrine\DBAL\Types\IntegerType;
23
use Psr\Log\LoggerAwareInterface;
24
use Psr\Log\LoggerAwareTrait;
25
use TYPO3\CMS\Backend\Utility\BackendUtility;
26
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
27
use TYPO3\CMS\Core\Cache\CacheManager;
28
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
29
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidIdentifierException;
30
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowException;
31
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowLoopException;
32
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowRootException;
33
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidPointerFieldValueException;
34
use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
35
use TYPO3\CMS\Core\Configuration\Richtext;
36
use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException;
37
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\DeletedRestriction;
42
use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
43
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
44
use TYPO3\CMS\Core\Database\RelationHandler;
45
use TYPO3\CMS\Core\DataHandling\History\RecordHistoryStore;
46
use TYPO3\CMS\Core\DataHandling\Localization\DataMapProcessor;
47
use TYPO3\CMS\Core\DataHandling\Model\CorrelationId;
48
use TYPO3\CMS\Core\DataHandling\Model\RecordStateFactory;
49
use TYPO3\CMS\Core\Html\RteHtmlParser;
50
use TYPO3\CMS\Core\Localization\LanguageService;
51
use TYPO3\CMS\Core\Messaging\FlashMessage;
52
use TYPO3\CMS\Core\Messaging\FlashMessageService;
53
use TYPO3\CMS\Core\Resource\ResourceFactory;
54
use TYPO3\CMS\Core\Service\OpcodeCacheService;
55
use TYPO3\CMS\Core\SysLog\Action as SystemLogGenericAction;
56
use TYPO3\CMS\Core\SysLog\Action\Cache as SystemLogCacheAction;
57
use TYPO3\CMS\Core\SysLog\Action\Database as SystemLogDatabaseAction;
58
use TYPO3\CMS\Core\SysLog\Error as SystemLogErrorClassification;
59
use TYPO3\CMS\Core\SysLog\Type as SystemLogType;
60
use TYPO3\CMS\Core\Type\Bitmask\Permission;
61
use TYPO3\CMS\Core\Utility\ArrayUtility;
62
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
63
use TYPO3\CMS\Core\Utility\GeneralUtility;
64
use TYPO3\CMS\Core\Utility\HttpUtility;
65
use TYPO3\CMS\Core\Utility\MathUtility;
66
use TYPO3\CMS\Core\Utility\StringUtility;
67
use TYPO3\CMS\Core\Versioning\VersionState;
68
69
/**
70
 * The main data handler class which takes care of correctly updating and inserting records.
71
 * This class was formerly known as TCEmain.
72
 *
73
 * This is the TYPO3 Core Engine class for manipulation of the database
74
 * This class is used by eg. the tce_db BE route (SimpleDataHandlerController) which provides an interface for POST forms to this class.
75
 *
76
 * Dependencies:
77
 * - $GLOBALS['TCA'] must exist
78
 * - $GLOBALS['LANG'] must exist
79
 *
80
 * Also see document 'TYPO3 Core API' for details.
81
 */
82
class DataHandler implements LoggerAwareInterface
83
{
84
    use LoggerAwareTrait;
85
86
    // *********************
87
    // Public variables you can configure before using the class:
88
    // *********************
89
    /**
90
     * If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the
91
     * log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
92
     *
93
     * @var bool
94
     */
95
    public $storeLogMessages = true;
96
97
    /**
98
     * If TRUE, actions are logged to sys_log.
99
     *
100
     * @var bool
101
     */
102
    public $enableLogging = true;
103
104
    /**
105
     * If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new
106
     * bunch of records.
107
     *
108
     * @var bool
109
     */
110
    public $reverseOrder = false;
111
112
    /**
113
     * If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array
114
     * is similar, it's not saved then.
115
     *
116
     * @var bool
117
     * @internal should only be used from within TYPO3 Core
118
     */
119
    public $checkSimilar = true;
120
121
    /**
122
     * This will read the record after having updated or inserted it. If anything is not properly submitted an error
123
     * is written to the log. This feature consumes extra time by selecting records
124
     *
125
     * @var bool
126
     */
127
    public $checkStoredRecords = true;
128
129
    /**
130
     * If set, values '' and 0 will equal each other when the stored records are checked.
131
     *
132
     * @var bool
133
     */
134
    public $checkStoredRecords_loose = true;
135
136
    /**
137
     * If set, then the 'hideAtCopy' flag for tables will be ignored.
138
     *
139
     * @var bool
140
     */
141
    public $neverHideAtCopy = false;
142
143
    /**
144
     * If set, then the TCE class has been instantiated during an import action of a T3D
145
     *
146
     * @var bool
147
     */
148
    public $isImporting = false;
149
150
    /**
151
     * If set, then transformations are NOT performed on the input.
152
     *
153
     * @var bool
154
     */
155
    public $dontProcessTransformations = false;
156
157
    /**
158
     * Will distinguish between translations (with parent) and localizations (without parent) while still using the same methods to copy the records
159
     * TRUE: translation of a record connected to the default language
160
     * FALSE: localization of a record without connection to the default language
161
     *
162
     * @var bool
163
     */
164
    protected $useTransOrigPointerField = true;
165
166
    /**
167
     * If TRUE, workspace restrictions are bypassed on edit and create actions (process_datamap()).
168
     * YOU MUST KNOW what you do if you use this feature!
169
     *
170
     * @var bool
171
     * @internal should only be used from within TYPO3 Core
172
     */
173
    public $bypassWorkspaceRestrictions = false;
174
175
    /**
176
     * If TRUE, access check, check for deleted etc. for records is bypassed.
177
     * YOU MUST KNOW what you are doing if you use this feature!
178
     *
179
     * @var bool
180
     */
181
    public $bypassAccessCheckForRecords = false;
182
183
    /**
184
     * Comma-separated list. This list of tables decides which tables will be copied. If empty then none will.
185
     * If '*' then all will (that the user has permission to of course)
186
     *
187
     * @var string
188
     * @internal should only be used from within TYPO3 Core
189
     */
190
    public $copyWhichTables = '*';
191
192
    /**
193
     * If 0 then branch is NOT copied.
194
     * If 1 then pages on the 1st level is copied.
195
     * If 2 then pages on the second level is copied ... and so on
196
     *
197
     * @var int
198
     */
199
    public $copyTree = 0;
200
201
    /**
202
     * [table][fields]=value: New records are created with default values and you can set this array on the
203
     * form $defaultValues[$table][$field] = $value to override the default values fetched from TCA.
204
     * If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array
205
     * (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
206
     *
207
     * @var array
208
     * @internal should only be used from within TYPO3 Core
209
     */
210
    public $defaultValues = [];
211
212
    /**
213
     * [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to
214
     * override the incoming data. You must set this externally. You must make sure the fields in this array are also
215
     * found in the table, because it's not checked. All columns can be set by this array!
216
     *
217
     * @var array
218
     * @internal should only be used from within TYPO3 Core
219
     */
220
    public $overrideValues = [];
221
222
    /**
223
     * If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated.
224
     * You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1.
225
     * Then an empty checkbox will disable the field.
226
     *
227
     * @var array
228
     * @internal should only be used from within TYPO3 Core
229
     */
230
    public $data_disableFields = [];
231
232
    /**
233
     * Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option
234
     * since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set
235
     * it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete).
236
     * The option is used for import of T3D files when synchronizing between two mirrored servers.
237
     * As a security measure this feature is available only for Admin Users (for now)
238
     *
239
     * @var array
240
     */
241
    public $suggestedInsertUids = [];
242
243
    /**
244
     * Object. Call back object for FlexForm traversal. Useful when external classes wants to use the
245
     * iteration functions inside DataHandler for traversing a FlexForm structure.
246
     *
247
     * @var object
248
     * @internal should only be used from within TYPO3 Core
249
     */
250
    public $callBackObj;
251
252
    /**
253
     * A string which can be used as correlationId for RecordHistory entries.
254
     * The string can later be used to rollback multiple changes at once.
255
     *
256
     * @var CorrelationId|null
257
     */
258
    protected $correlationId;
259
260
    // *********************
261
    // Internal variables (mapping arrays) which can be used (read-only) from outside
262
    // *********************
263
    /**
264
     * Contains mapping of auto-versionized records.
265
     *
266
     * @var array<string, array<int, string>>
267
     * @internal should only be used from within TYPO3 Core
268
     */
269
    public $autoVersionIdMap = [];
270
271
    /**
272
     * 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
273
     *
274
     * @var array
275
     */
276
    public $substNEWwithIDs = [];
277
278
    /**
279
     * Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
280
     *
281
     * @var array
282
     * @internal should only be used from within TYPO3 Core
283
     */
284
    public $substNEWwithIDs_table = [];
285
286
    /**
287
     * Holds the tables and there the ids of newly created child records from IRRE
288
     *
289
     * @var array
290
     * @internal should only be used from within TYPO3 Core
291
     */
292
    public $newRelatedIDs = [];
293
294
    /**
295
     * This array is the sum of all copying operations in this class.
296
     *
297
     * @var array
298
     * @internal should only be used from within TYPO3 Core
299
     */
300
    public $copyMappingArray_merged = [];
301
302
    /**
303
     * Per-table array with UIDs that have been deleted.
304
     *
305
     * @var array
306
     */
307
    protected $deletedRecords = [];
308
309
    /**
310
     * Errors are collected in this variable.
311
     *
312
     * @var array
313
     * @internal should only be used from within TYPO3 Core
314
     */
315
    public $errorLog = [];
316
317
    /**
318
     * Fields from the pages-table for which changes will trigger a pagetree refresh
319
     *
320
     * @var array
321
     */
322
    public $pagetreeRefreshFieldsFromPages = ['pid', 'sorting', 'deleted', 'hidden', 'title', 'doktype', 'is_siteroot', 'fe_group', 'nav_hide', 'nav_title', 'module', 'starttime', 'endtime', 'content_from_pid', 'extendToSubpages'];
323
324
    /**
325
     * Indicates whether the pagetree needs a refresh because of important changes
326
     *
327
     * @var bool
328
     * @internal should only be used from within TYPO3 Core
329
     */
330
    public $pagetreeNeedsRefresh = false;
331
332
    // *********************
333
    // Internal Variables, do not touch.
334
    // *********************
335
336
    // Variables set in init() function:
337
338
    /**
339
     * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
340
     *
341
     * @var BackendUserAuthentication
342
     */
343
    public $BE_USER;
344
345
    /**
346
     * Will be set to uid of be_user executing this script
347
     *
348
     * @var int
349
     * @internal should only be used from within TYPO3 Core
350
     */
351
    public $userid;
352
353
    /**
354
     * Will be set to username of be_user executing this script
355
     *
356
     * @var string
357
     * @internal should only be used from within TYPO3 Core
358
     */
359
    public $username;
360
361
    /**
362
     * Will be set if user is admin
363
     *
364
     * @var bool
365
     * @internal should only be used from within TYPO3 Core
366
     */
367
    public $admin;
368
369
    /**
370
     * @var PagePermissionAssembler
371
     */
372
    protected $pagePermissionAssembler;
373
374
    /**
375
     * 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.
376
     *
377
     * @var array
378
     */
379
    protected $excludedTablesAndFields = [];
380
381
    /**
382
     * Data submitted from the form view, used to control behaviours,
383
     * e.g. this is used to activate/deactivate fields and thus store NULL values
384
     *
385
     * @var array
386
     */
387
    protected $control = [];
388
389
    /**
390
     * Set with incoming data array
391
     *
392
     * @var array<int|string, array<int|string, array>>
393
     */
394
    public $datamap = [];
395
396
    /**
397
     * Set with incoming cmd array
398
     *
399
     * @var array<string, array<int|string, array>>
400
     */
401
    public $cmdmap = [];
402
403
    /**
404
     * List of changed old record ids to new records ids
405
     *
406
     * @var array
407
     */
408
    protected $mmHistoryRecords = [];
409
410
    /**
411
     * List of changed old record ids to new records ids
412
     *
413
     * @var array
414
     */
415
    protected $historyRecords = [];
416
417
    // Internal static:
418
419
    /**
420
     * The interval between sorting numbers used with tables with a 'sorting' field defined.
421
     *
422
     * Min 1, should be power of 2
423
     *
424
     * @var int
425
     * @internal should only be used from within TYPO3 Core
426
     */
427
    public $sortIntervals = 256;
428
429
    // Internal caching arrays
430
    /**
431
     * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
432
     *
433
     * @var array
434
     */
435
    protected $recInsertAccessCache = [];
436
437
    /**
438
     * Caching array for check of whether records are in a webmount
439
     *
440
     * @var array
441
     */
442
    protected $isRecordInWebMount_Cache = [];
443
444
    /**
445
     * Caching array for page ids in webmounts
446
     *
447
     * @var array
448
     */
449
    protected $isInWebMount_Cache = [];
450
451
    /**
452
     * Used for caching page records in pageInfo()
453
     *
454
     * @var array<int, array<string, array>>
455
     */
456
    protected $pageCache = [];
457
458
    // Other arrays:
459
    /**
460
     * For accumulation of MM relations that must be written after new records are created.
461
     *
462
     * @var array
463
     * @internal
464
     */
465
    public $dbAnalysisStore = [];
466
467
    /**
468
     * Used for tracking references that might need correction after operations
469
     *
470
     * @var array<string, array<int, array>>
471
     * @internal
472
     */
473
    public $registerDBList = [];
474
475
    /**
476
     * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
477
     *
478
     * @var array
479
     * @internal
480
     */
481
    public $registerDBPids = [];
482
483
    /**
484
     * Used by the copy action to track the ids of new pages so subpages are correctly inserted!
485
     * THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE!
486
     * Read from copyMappingArray_merged instead which is accumulating this information.
487
     *
488
     * NOTE: This is used by some outside scripts (e.g. hooks), as the results in $copyMappingArray_merged
489
     * are only available after an action has been completed.
490
     *
491
     * @var array<string, array>
492
     * @internal
493
     */
494
    public $copyMappingArray = [];
495
496
    /**
497
     * Array used for remapping uids and values at the end of process_datamap
498
     *
499
     * @var array
500
     * @internal
501
     */
502
    public $remapStack = [];
503
504
    /**
505
     * Array used for remapping uids and values at the end of process_datamap
506
     * (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
507
     *
508
     * @var array
509
     * @internal
510
     */
511
    public $remapStackRecords = [];
512
513
    /**
514
     * Array used for checking whether new children need to be remapped
515
     *
516
     * @var array
517
     */
518
    protected $remapStackChildIds = [];
519
520
    /**
521
     * Array used for executing addition actions after remapping happened (set processRemapStack())
522
     *
523
     * @var array
524
     */
525
    protected $remapStackActions = [];
526
527
    /**
528
     * Registry object to gather reference index update requests and perform updates after
529
     * main processing has been done. The first call to start() instantiates this object.
530
     * Recursive sub instances receive this instance via __construct().
531
     * The final update() call is done at the end of process_cmdmap() or process_datamap()
532
     * in the outer most instance.
533
     *
534
     * @var ReferenceIndexUpdater
535
     */
536
    protected $referenceIndexUpdater;
537
538
    /**
539
     * Tells, that this DataHandler instance was called from \TYPO3\CMS\Impext\ImportExport.
540
     * This variable is set by \TYPO3\CMS\Impext\ImportExport
541
     *
542
     * @var bool
543
     * @internal only used within TYPO3 Core
544
     */
545
    public $callFromImpExp = false;
546
547
    // Various
548
549
    /**
550
     * Set to "currentRecord" during checking of values.
551
     *
552
     * @var array
553
     * @internal
554
     */
555
    public $checkValue_currentRecord = [];
556
557
    /**
558
     * Disable delete clause
559
     *
560
     * @var bool
561
     */
562
    protected $disableDeleteClause = false;
563
564
    /**
565
     * @var array
566
     */
567
    protected $checkModifyAccessListHookObjects;
568
569
    /**
570
     * @var array
571
     */
572
    protected $version_remapMMForVersionSwap_reg;
573
574
    /**
575
     * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
576
     * This object instantiates itself on versioning and localization ...
577
     *
578
     * @var \TYPO3\CMS\Core\DataHandling\DataHandler
579
     */
580
    protected $outerMostInstance;
581
582
    /**
583
     * Internal cache for collecting records that should trigger cache clearing
584
     *
585
     * @var array
586
     */
587
    protected static $recordsToClearCacheFor = [];
588
589
    /**
590
     * Internal cache for pids of records which were deleted. It's not possible
591
     * to retrieve the parent folder/page at a later stage
592
     *
593
     * @var array
594
     */
595
    protected static $recordPidsForDeletedRecords = [];
596
597
    /**
598
     * Runtime Cache to store and retrieve data computed for a single request
599
     *
600
     * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
601
     */
602
    protected $runtimeCache;
603
604
    /**
605
     * Prefix for the cache entries of nested element calls since the runtimeCache has a global scope.
606
     *
607
     * @var string
608
     */
609
    protected $cachePrefixNestedElementCalls = 'core-datahandler-nestedElementCalls-';
610
611
    /**
612
     * Sets up the data handler cache and some additional options, the main logic is done in the start() method.
613
     *
614
     * @param ReferenceIndexUpdater|null $referenceIndexUpdater Hand over from outer most instance to sub instances
615
     */
616
    public function __construct(ReferenceIndexUpdater $referenceIndexUpdater = null)
617
    {
618
        $this->checkStoredRecords = (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecords'];
619
        $this->checkStoredRecords_loose = (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecordsLoose'];
620
        $this->runtimeCache = $this->getRuntimeCache();
621
        $this->pagePermissionAssembler = GeneralUtility::makeInstance(PagePermissionAssembler::class, $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions']);
622
        if ($referenceIndexUpdater === null) {
623
            // Create ReferenceIndexUpdater object. This should only happen on outer most instance,
624
            // sub instances should receive the reference index updater from a parent.
625
            $referenceIndexUpdater = GeneralUtility::makeInstance(ReferenceIndexUpdater::class);
626
        }
627
        $this->referenceIndexUpdater = $referenceIndexUpdater;
628
    }
629
630
    /**
631
     * @param array $control
632
     * @internal
633
     */
634
    public function setControl(array $control)
635
    {
636
        $this->control = $control;
637
    }
638
639
    /**
640
     * Initializing.
641
     * For details, see 'TYPO3 Core API' document.
642
     * This function does not start the processing of data, but merely initializes the object
643
     *
644
     * @param array $data Data to be modified or inserted in the database
645
     * @param array $cmd Commands to copy, move, delete, localize, versionize records.
646
     * @param BackendUserAuthentication|null $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
647
     */
648
    public function start($data, $cmd, $altUserObject = null)
649
    {
650
        // Initializing BE_USER
651
        $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
652
        $this->userid = $this->BE_USER->user['uid'] ?? 0;
653
        $this->username = $this->BE_USER->user['username'] ?? '';
654
        $this->admin = $this->BE_USER->user['admin'] ?? false;
655
656
        // set correlation id for each new set of data or commands
657
        $this->correlationId = CorrelationId::forScope(
658
            md5(StringUtility::getUniqueId(self::class))
659
        );
660
661
        // Get default values from user TSconfig
662
        $tcaDefaultOverride = $this->BE_USER->getTSConfig()['TCAdefaults.'] ?? null;
663
        if (is_array($tcaDefaultOverride)) {
664
            $this->setDefaultsFromUserTS($tcaDefaultOverride);
665
        }
666
667
        // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
668
        if (!$this->admin) {
669
            $this->excludedTablesAndFields = array_flip($this->getExcludeListArray());
670
        }
671
        // Setting the data and cmd arrays
672
        if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
673
            reset($data);
674
            $this->datamap = $data;
675
        }
676
        if (is_array($cmd)) {
0 ignored issues
show
introduced by
The condition is_array($cmd) is always true.
Loading history...
677
            reset($cmd);
678
            $this->cmdmap = $cmd;
679
        }
680
    }
681
682
    /**
683
     * Function that can mirror input values in datamap-array to other uid numbers.
684
     * 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]
685
     *
686
     * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
687
     * @internal
688
     */
689
    public function setMirror($mirror)
690
    {
691
        if (!is_array($mirror)) {
0 ignored issues
show
introduced by
The condition is_array($mirror) is always true.
Loading history...
692
            return;
693
        }
694
695
        foreach ($mirror as $table => $uid_array) {
696
            if (!isset($this->datamap[$table])) {
697
                continue;
698
            }
699
700
            foreach ($uid_array as $id => $uidList) {
701
                if (!isset($this->datamap[$table][$id])) {
702
                    continue;
703
                }
704
705
                $theIdsInArray = GeneralUtility::trimExplode(',', $uidList, true);
706
                foreach ($theIdsInArray as $copyToUid) {
707
                    $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
708
                }
709
            }
710
        }
711
    }
712
713
    /**
714
     * Initializes default values coming from User TSconfig
715
     *
716
     * @param array $userTS User TSconfig array
717
     * @internal should only be used from within DataHandler
718
     */
719
    public function setDefaultsFromUserTS($userTS)
720
    {
721
        if (!is_array($userTS)) {
0 ignored issues
show
introduced by
The condition is_array($userTS) is always true.
Loading history...
722
            return;
723
        }
724
725
        foreach ($userTS as $k => $v) {
726
            $k = mb_substr($k, 0, -1);
727
            if (!$k || !is_array($v) || !isset($GLOBALS['TCA'][$k])) {
728
                continue;
729
            }
730
731
            if (is_array($this->defaultValues[$k] ?? false)) {
732
                $this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
733
            } else {
734
                $this->defaultValues[$k] = $v;
735
            }
736
        }
737
    }
738
739
    /**
740
     * When a new record is created, all values that haven't been set but are set via PageTSconfig / UserTSconfig
741
     * get applied here.
742
     *
743
     * This is only executed for new records. The most important part is that the pageTS of the actual resolved $pid
744
     * is taken, and a new field array with empty defaults is set again.
745
     *
746
     * @param string $table
747
     * @param int $pageId
748
     * @param array $prepopulatedFieldArray
749
     * @return array
750
     */
751
    protected function applyDefaultsForFieldArray(string $table, int $pageId, array $prepopulatedFieldArray): array
752
    {
753
        // First set TCAdefaults respecting the given PageID
754
        $tcaDefaults = BackendUtility::getPagesTSconfig($pageId)['TCAdefaults.'] ?? null;
755
        // Re-apply $this->defaultValues settings
756
        $this->setDefaultsFromUserTS($tcaDefaults);
757
        $cleanFieldArray = $this->newFieldArray($table);
758
        if (isset($prepopulatedFieldArray['pid'])) {
759
            $cleanFieldArray['pid'] = $prepopulatedFieldArray['pid'];
760
        }
761
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? null;
762
        if ($sortColumn !== null && isset($prepopulatedFieldArray[$sortColumn])) {
763
            $cleanFieldArray[$sortColumn] = $prepopulatedFieldArray[$sortColumn];
764
        }
765
        return $cleanFieldArray;
766
    }
767
768
    /*********************************************
769
     *
770
     * HOOKS
771
     *
772
     *********************************************/
773
    /**
774
     * Hook: processDatamap_afterDatabaseOperations
775
     * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
776
     *
777
     * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
778
     * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
779
     *
780
     * @param array $hookObjectsArr (reference) Array with hook objects
781
     * @param string $status (reference) Status of the current operation, 'new' or 'update
782
     * @param string $table (reference) The table currently processing data for
783
     * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
784
     * @param array $fieldArray (reference) The field array of a record
785
     * @internal should only be used from within DataHandler
786
     */
787
    public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray)
788
    {
789
        // Process hook directly:
790
        if (!isset($this->remapStackRecords[$table][$id])) {
791
            foreach ($hookObjectsArr as $hookObj) {
792
                if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
793
                    $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
794
                }
795
            }
796
        } else {
797
            $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = [
798
                'status' => $status,
799
                'fieldArray' => $fieldArray,
800
                'hookObjectsArr' => $hookObjectsArr
801
            ];
802
        }
803
    }
804
805
    /**
806
     * Gets the 'checkModifyAccessList' hook objects.
807
     * The first call initializes the accordant objects.
808
     *
809
     * @return array The 'checkModifyAccessList' hook objects (if any)
810
     * @throws \UnexpectedValueException
811
     */
812
    protected function getCheckModifyAccessListHookObjects()
813
    {
814
        if (!isset($this->checkModifyAccessListHookObjects)) {
815
            $this->checkModifyAccessListHookObjects = [];
816
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] ?? [] as $className) {
817
                $hookObject = GeneralUtility::makeInstance($className);
818
                if (!$hookObject instanceof DataHandlerCheckModifyAccessListHookInterface) {
819
                    throw new \UnexpectedValueException($className . ' must implement interface ' . DataHandlerCheckModifyAccessListHookInterface::class, 1251892472);
820
                }
821
                $this->checkModifyAccessListHookObjects[] = $hookObject;
822
            }
823
        }
824
        return $this->checkModifyAccessListHookObjects;
825
    }
826
827
    /*********************************************
828
     *
829
     * PROCESSING DATA
830
     *
831
     *********************************************/
832
    /**
833
     * Processing the data-array
834
     * Call this function to process the data-array set by start()
835
     *
836
     * @return bool|void
837
     */
838
    public function process_datamap()
839
    {
840
        $this->controlActiveElements();
841
842
        // Keep versionized(!) relations here locally:
843
        $registerDBList = [];
844
        $this->registerElementsToBeDeleted();
845
        $this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
846
        // Editing frozen:
847
        if ($this->BE_USER->workspace !== 0 && ($this->BE_USER->workspaceRec['freeze'] ?? false)) {
848
            $this->newlog('All editing in this workspace has been frozen!', SystemLogErrorClassification::USER_ERROR);
849
            return false;
850
        }
851
        // First prepare user defined objects (if any) for hooks which extend this function:
852
        $hookObjectsArr = [];
853
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] ?? [] as $className) {
854
            $hookObject = GeneralUtility::makeInstance($className);
855
            if (method_exists($hookObject, 'processDatamap_beforeStart')) {
856
                $hookObject->processDatamap_beforeStart($this);
857
            }
858
            $hookObjectsArr[] = $hookObject;
859
        }
860
        // Pre-process data-map and synchronize localization states
861
        $this->datamap = GeneralUtility::makeInstance(SlugEnricher::class)->enrichDataMap($this->datamap);
862
        $this->datamap = DataMapProcessor::instance($this->datamap, $this->BE_USER, $this->referenceIndexUpdater)->process();
863
        // 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.
864
        $orderOfTables = [];
865
        // Set pages first.
866
        if (isset($this->datamap['pages'])) {
867
            $orderOfTables[] = 'pages';
868
        }
869
        $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
870
        // Process the tables...
871
        foreach ($orderOfTables as $table) {
872
            // Check if
873
            //	   - table is set in $GLOBALS['TCA'],
874
            //	   - table is NOT readOnly
875
            //	   - the table is set with content in the data-array (if not, there's nothing to process...)
876
            //	   - permissions for tableaccess OK
877
            $modifyAccessList = $this->checkModifyAccessList($table);
878
            if (!$modifyAccessList) {
879
                $this->log($table, 0, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
880
            }
881
            if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->datamap[$table]) || !$modifyAccessList) {
882
                continue;
883
            }
884
885
            if ($this->reverseOrder) {
886
                $this->datamap[$table] = array_reverse($this->datamap[$table], true);
887
            }
888
            // For each record from the table, do:
889
            // $id is the record uid, may be a string if new records...
890
            // $incomingFieldArray is the array of fields
891
            foreach ($this->datamap[$table] as $id => $incomingFieldArray) {
892
                if (!is_array($incomingFieldArray)) {
893
                    continue;
894
                }
895
                $theRealPid = null;
896
897
                // Hook: processDatamap_preProcessFieldArray
898
                foreach ($hookObjectsArr as $hookObj) {
899
                    if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
900
                        $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
901
                    }
902
                }
903
                // ******************************
904
                // Checking access to the record
905
                // ******************************
906
                $createNewVersion = false;
907
                $recordAccess = false;
908
                $old_pid_value = '';
909
                // Is it a new record? (Then Id is a string)
910
                if (!MathUtility::canBeInterpretedAsInteger($id)) {
911
                    // Get a fieldArray with tca default values
912
                    $fieldArray = $this->newFieldArray($table);
913
                    // A pid must be set for new records.
914
                    if (isset($incomingFieldArray['pid'])) {
915
                        $pid_value = $incomingFieldArray['pid'];
916
                        // Checking and finding numerical pid, it may be a string-reference to another value
917
                        $canProceed = true;
918
                        // If a NEW... id
919
                        if (strpos($pid_value, 'NEW') !== false) {
920
                            if ($pid_value[0] === '-') {
921
                                $negFlag = -1;
922
                                $pid_value = substr($pid_value, 1);
923
                            } else {
924
                                $negFlag = 1;
925
                            }
926
                            // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
927
                            if (isset($this->substNEWwithIDs[$pid_value])) {
928
                                if ($negFlag === 1) {
929
                                    $old_pid_value = $this->substNEWwithIDs[$pid_value];
930
                                }
931
                                $pid_value = (int)($negFlag * $this->substNEWwithIDs[$pid_value]);
932
                            } else {
933
                                $canProceed = false;
934
                            }
935
                        }
936
                        $pid_value = (int)$pid_value;
937
                        if ($canProceed) {
938
                            $fieldArray = $this->resolveSortingAndPidForNewRecord($table, $pid_value, $fieldArray);
939
                        }
940
                    }
941
                    $theRealPid = $fieldArray['pid'];
942
                    // Checks if records can be inserted on this $pid.
943
                    // If this is a page translation, the check needs to be done for the l10n_parent record
944
                    $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? null;
945
                    $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? null;
946
                    if ($table === 'pages'
947
                        && $languageField && isset($incomingFieldArray[$languageField]) && $incomingFieldArray[$languageField] > 0
948
                        && $transOrigPointerField && isset($incomingFieldArray[$transOrigPointerField]) && $incomingFieldArray[$transOrigPointerField] > 0
949
                    ) {
950
                        $recordAccess = $this->checkRecordInsertAccess($table, $incomingFieldArray[$transOrigPointerField]);
951
                    } else {
952
                        $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
953
                    }
954
                    if ($recordAccess) {
955
                        $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
956
                        $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, true);
957
                        if (!$recordAccess) {
958
                            $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', SystemLogErrorClassification::USER_ERROR);
959
                        } elseif (!$this->bypassWorkspaceRestrictions && !$this->BE_USER->workspaceAllowsLiveEditingInTable($table)) {
960
                            // If LIVE records cannot be created due to workspace restrictions, prepare creation of placeholder-record
961
                            // So, if no live records were allowed in the current workspace, we have to create a new version of this record
962
                            if (BackendUtility::isTableWorkspaceEnabled($table)) {
963
                                $createNewVersion = true;
964
                            } else {
965
                                $recordAccess = false;
966
                                $this->newlog('Record could not be created in this workspace', SystemLogErrorClassification::USER_ERROR);
967
                            }
968
                        }
969
                    }
970
                    // Yes new record, change $record_status to 'insert'
971
                    $status = 'new';
972
                } else {
973
                    // Nope... $id is a number
974
                    $id = (int)$id;
975
                    $fieldArray = [];
976
                    $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
977
                    if (!$recordAccess) {
978
                        if ($this->enableLogging) {
979
                            $propArr = $this->getRecordProperties($table, $id);
980
                            $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']);
981
                        }
982
                        continue;
983
                    }
984
                    // Next check of the record permissions (internals)
985
                    $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
986
                    if (!$recordAccess) {
987
                        $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', SystemLogErrorClassification::USER_ERROR);
988
                    } else {
989
                        // Here we fetch the PID of the record that we point to...
990
                        $tempdata = $this->recordInfo($table, $id, 'pid' . (BackendUtility::isTableWorkspaceEnabled($table) ? ',t3ver_oid,t3ver_wsid,t3ver_stage' : ''));
991
                        $theRealPid = $tempdata['pid'] ?? null;
992
                        // Use the new id of the versionized record we're trying to write to:
993
                        // (This record is a child record of a parent and has already been versionized.)
994
                        if (!empty($this->autoVersionIdMap[$table][$id])) {
995
                            // For the reason that creating a new version of this record, automatically
996
                            // created related child records (e.g. "IRRE"), update the accordant field:
997
                            $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
998
                            // Use the new id of the copied/versionized record:
999
                            $id = $this->autoVersionIdMap[$table][$id];
1000
                            $recordAccess = true;
1001
                        } elseif (!$this->bypassWorkspaceRestrictions && ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $tempdata))) {
1002
                            $recordAccess = false;
1003
                            // Versioning is required and it must be offline version!
1004
                            // Check if there already is a workspace version
1005
                            $workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid,t3ver_oid');
1006
                            if ($workspaceVersion) {
1007
                                $id = $workspaceVersion['uid'];
1008
                                $recordAccess = true;
1009
                            } elseif ($this->BE_USER->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1010
                                // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1011
                                $this->pagetreeNeedsRefresh = true;
1012
1013
                                /** @var DataHandler $tce */
1014
                                $tce = GeneralUtility::makeInstance(__CLASS__, $this->referenceIndexUpdater);
1015
                                $tce->enableLogging = $this->enableLogging;
1016
                                // Setting up command for creating a new version of the record:
1017
                                $cmd = [];
1018
                                $cmd[$table][$id]['version'] = [
1019
                                    'action' => 'new',
1020
                                    // Default is to create a version of the individual records
1021
                                    'label' => 'Auto-created for WS #' . $this->BE_USER->workspace
1022
                                ];
1023
                                $tce->start([], $cmd, $this->BE_USER);
1024
                                $tce->process_cmdmap();
1025
                                $this->errorLog = array_merge($this->errorLog, $tce->errorLog);
1026
                                // If copying was successful, share the new uids (also of related children):
1027
                                if (!empty($tce->copyMappingArray[$table][$id])) {
1028
                                    foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
1029
                                        foreach ($origIdArray as $origId => $newId) {
1030
                                            $this->autoVersionIdMap[$origTable][$origId] = $newId;
1031
                                        }
1032
                                    }
1033
                                    // Update registerDBList, that holds the copied relations to child records:
1034
                                    $registerDBList = array_merge($registerDBList, $tce->registerDBList);
1035
                                    // For the reason that creating a new version of this record, automatically
1036
                                    // created related child records (e.g. "IRRE"), update the accordant field:
1037
                                    $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1038
                                    // Use the new id of the copied/versionized record:
1039
                                    $id = $this->autoVersionIdMap[$table][$id];
1040
                                    $recordAccess = true;
1041
                                } else {
1042
                                    $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version failed!', SystemLogErrorClassification::USER_ERROR);
1043
                                }
1044
                            } else {
1045
                                $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version not allowed in workspace!', SystemLogErrorClassification::USER_ERROR);
1046
                            }
1047
                        }
1048
                    }
1049
                    // The default is 'update'
1050
                    $status = 'update';
1051
                }
1052
                // If access was granted above, proceed to create or update record:
1053
                if (!$recordAccess) {
1054
                    continue;
1055
                }
1056
1057
                // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1058
                [$tscPID] = BackendUtility::getTSCpid($table, $id, $old_pid_value ?: ($fieldArray['pid'] ?? 0));
1059
                if ($status === 'new') {
1060
                    // Apply TCAdefaults from pageTS
1061
                    $fieldArray = $this->applyDefaultsForFieldArray($table, (int)$tscPID, $fieldArray);
1062
                    // Apply page permissions as well
1063
                    if ($table === 'pages') {
1064
                        $fieldArray = $this->pagePermissionAssembler->applyDefaults(
1065
                            $fieldArray,
1066
                            (int)$tscPID,
1067
                            (int)$this->userid,
1068
                            (int)$this->BE_USER->firstMainGroup
1069
                        );
1070
                    }
1071
                }
1072
                // Processing of all fields in incomingFieldArray and setting them in $fieldArray
1073
                $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1074
                // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations to field!
1075
                // Forcing some values unto field array:
1076
                // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
1077
                $fieldArray = $this->overrideFieldArray($table, $fieldArray);
1078
                // Setting system fields
1079
                if ($status === 'new') {
1080
                    if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1081
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1082
                    }
1083
                    if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1084
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
1085
                    }
1086
                } elseif ($this->checkSimilar) {
1087
                    // Removing fields which are equal to the current value:
1088
                    $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
1089
                }
1090
                if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && !empty($fieldArray)) {
1091
                    $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1092
                }
1093
                // Set stage to "Editing" to make sure we restart the workflow
1094
                if (BackendUtility::isTableWorkspaceEnabled($table)) {
1095
                    $fieldArray['t3ver_stage'] = 0;
1096
                }
1097
                // Hook: processDatamap_postProcessFieldArray
1098
                foreach ($hookObjectsArr as $hookObj) {
1099
                    if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
1100
                        $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
1101
                    }
1102
                }
1103
                // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1104
                // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already
1105
                if (is_array($fieldArray)) {
1106
                    if ($status === 'new') {
1107
                        if ($table === 'pages') {
1108
                            // for new pages always a refresh is needed
1109
                            $this->pagetreeNeedsRefresh = true;
1110
                        }
1111
1112
                        // This creates a version of the record, instead of adding it to the live workspace
1113
                        if ($createNewVersion) {
1114
                            // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1115
                            $this->pagetreeNeedsRefresh = true;
1116
                            $fieldArray['pid'] = $theRealPid;
1117
                            $fieldArray['t3ver_oid'] = 0;
1118
                            // Setting state for version (so it can know it is currently a new version...)
1119
                            $fieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER);
1120
                            $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1121
                            $this->insertDB($table, $id, $fieldArray, true, (int)($incomingFieldArray['uid'] ?? 0));
1122
                            // Hold auto-versionized ids of placeholders
1123
                            $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $this->substNEWwithIDs[$id];
1124
                        } else {
1125
                            $this->insertDB($table, $id, $fieldArray, false, (int)($incomingFieldArray['uid'] ?? 0));
1126
                        }
1127
                    } else {
1128
                        if ($table === 'pages') {
1129
                            // only a certain number of fields needs to be checked for updates
1130
                            // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
1131
                            $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages, array_keys($fieldArray));
1132
                            if (!empty($fieldsToCheck)) {
1133
                                $this->pagetreeNeedsRefresh = true;
1134
                            }
1135
                        }
1136
                        $this->updateDB($table, $id, $fieldArray);
1137
                    }
1138
                }
1139
                // Hook: processDatamap_afterDatabaseOperations
1140
                // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
1141
                // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
1142
                $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
1143
            }
1144
        }
1145
        // Process the stack of relations to remap/correct
1146
        $this->processRemapStack();
1147
        $this->dbAnalysisStoreExec();
1148
        // Hook: processDatamap_afterAllOperations
1149
        // Note: When this hook gets called, all operations on the submitted data have been finished.
1150
        foreach ($hookObjectsArr as $hookObj) {
1151
            if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
1152
                $hookObj->processDatamap_afterAllOperations($this);
1153
            }
1154
        }
1155
1156
        if ($this->isOuterMostInstance()) {
1157
            $this->referenceIndexUpdater->update();
1158
            $this->processClearCacheQueue();
1159
            $this->resetElementsToBeDeleted();
1160
        }
1161
    }
1162
1163
    /**
1164
     * @param string $table
1165
     * @param string $value
1166
     * @param string $dbType
1167
     * @return string
1168
     */
1169
    protected function normalizeTimeFormat(string $table, string $value, string $dbType): string
1170
    {
1171
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
1172
        $platform = $connection->getDatabasePlatform();
1173
        if ($platform instanceof SQLServerPlatform) {
1174
            $defaultLength = QueryHelper::getDateTimeFormats()[$dbType]['empty'];
1175
            $value = substr(
1176
                $value,
1177
                0,
1178
                strlen($defaultLength)
1179
            );
1180
        }
1181
        return $value;
1182
    }
1183
1184
    /**
1185
     * Sets the "sorting" DB field and the "pid" field of an incoming record that should be added (NEW1234)
1186
     * depending on the record that should be added or where it should be added.
1187
     *
1188
     * This method is called from process_datamap()
1189
     *
1190
     * @param string $table the table name of the record to insert
1191
     * @param int $pid the real PID (numeric) where the record should be
1192
     * @param array $fieldArray field+value pairs to add
1193
     * @return array the modified field array
1194
     */
1195
    protected function resolveSortingAndPidForNewRecord(string $table, int $pid, array $fieldArray): array
1196
    {
1197
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
1198
        // Points to a page on which to insert the element, possibly in the top of the page
1199
        if ($pid >= 0) {
1200
            // Ensure that the "pid" is not a translated page ID, but the default page ID
1201
            $pid = $this->getDefaultLanguagePageId($pid);
1202
            // The numerical pid is inserted in the data array
1203
            $fieldArray['pid'] = $pid;
1204
            // If this table is sorted we better find the top sorting number
1205
            if ($sortColumn) {
1206
                $fieldArray[$sortColumn] = $this->getSortNumber($table, 0, $pid);
1207
            }
1208
        } elseif ($sortColumn) {
1209
            // Points to another record before itself
1210
            // If this table is sorted we better find the top sorting number
1211
            // Because $pid is < 0, getSortNumber() returns an array
1212
            $sortingInfo = $this->getSortNumber($table, 0, $pid);
1213
            $fieldArray['pid'] = $sortingInfo['pid'];
1214
            $fieldArray[$sortColumn] = $sortingInfo['sortNumber'];
1215
        } else {
1216
            // Here we fetch the PID of the record that we point to
1217
            $record = $this->recordInfo($table, abs($pid), 'pid');
0 ignored issues
show
Bug introduced by
It seems like abs($pid) can also be of type double; however, parameter $id of TYPO3\CMS\Core\DataHandl...taHandler::recordInfo() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1217
            $record = $this->recordInfo($table, /** @scrutinizer ignore-type */ abs($pid), 'pid');
Loading history...
1218
            // Ensure that the "pid" is not a translated page ID, but the default page ID
1219
            $fieldArray['pid'] = $this->getDefaultLanguagePageId($record['pid']);
1220
        }
1221
        return $fieldArray;
1222
    }
1223
1224
    /**
1225
     * Filling in the field array
1226
     * $this->excludedTablesAndFields is used to filter fields if needed.
1227
     *
1228
     * @param string $table Table name
1229
     * @param int|string $id Record ID
1230
     * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1231
     * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
1232
     * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1233
     * @param string $status Is 'new' or 'update'
1234
     * @param int $tscPID TSconfig PID
1235
     * @return array Field Array
1236
     * @internal should only be used from within DataHandler
1237
     */
1238
    public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
1239
    {
1240
        // Initialize:
1241
        $originalLanguageRecord = null;
1242
        $originalLanguage_diffStorage = null;
1243
        $diffStorageFlag = false;
1244
        // Setting 'currentRecord' and 'checkValueRecord':
1245
        if (strpos((string)$id, 'NEW') !== false) {
1246
            // Must have the 'current' array - not the values after processing below...
1247
            $checkValueRecord = $fieldArray;
1248
            // IF $incomingFieldArray is an array, overlay it.
1249
            // The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
1250
            if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
0 ignored issues
show
introduced by
The condition is_array($checkValueRecord) is always true.
Loading history...
1251
                ArrayUtility::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
1252
            }
1253
            $currentRecord = $checkValueRecord;
1254
        } else {
1255
            $id = (int)$id;
1256
            // We must use the current values as basis for this!
1257
            $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
1258
        }
1259
1260
        // Get original language record if available:
1261
        if (is_array($currentRecord)
1262
            && ($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'] ?? false)
1263
            && !empty($GLOBALS['TCA'][$table]['ctrl']['languageField'])
1264
            && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
1265
            && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
1266
            && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0
1267
        ) {
1268
            $originalLanguageRecord = $this->recordInfo($table, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1269
            BackendUtility::workspaceOL($table, $originalLanguageRecord);
1270
            $originalLanguage_diffStorage = json_decode(
1271
                (string)($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] ?? ''),
1272
                true
1273
            );
1274
        }
1275
1276
        $this->checkValue_currentRecord = $checkValueRecord;
1277
        // In the following all incoming value-fields are tested:
1278
        // - Are the user allowed to change the field?
1279
        // - Is the field uid/pid (which are already set)
1280
        // - perms-fields for pages-table, then do special things...
1281
        // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1282
        // If everything is OK, the field is entered into $fieldArray[]
1283
        foreach ($incomingFieldArray as $field => $fieldValue) {
1284
            if (isset($this->excludedTablesAndFields[$table . '-' . $field]) || (bool)($this->data_disableFields[$table][$id][$field] ?? false)) {
1285
                continue;
1286
            }
1287
1288
            // The field must be editable.
1289
            // Checking if a value for language can be changed:
1290
            if (($GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? false)
1291
                && (string)$GLOBALS['TCA'][$table]['ctrl']['languageField'] === (string)$field
1292
                && !$this->BE_USER->checkLanguageAccess($fieldValue)
1293
            ) {
1294
                continue;
1295
            }
1296
1297
            switch ($field) {
1298
                case 'uid':
1299
                case 'pid':
1300
                    // Nothing happens, already set
1301
                    break;
1302
                case 'perms_userid':
1303
                case 'perms_groupid':
1304
                case 'perms_user':
1305
                case 'perms_group':
1306
                case 'perms_everybody':
1307
                    // Permissions can be edited by the owner or the administrator
1308
                    if ($table === 'pages' && ($this->admin || $status === 'new' || $this->pageInfo((int)$id, 'perms_userid') == $this->userid)) {
1309
                        $value = (int)$fieldValue;
1310
                        switch ($field) {
1311
                            case 'perms_userid':
1312
                            case 'perms_groupid':
1313
                                $fieldArray[$field] = $value;
1314
                                break;
1315
                            default:
1316
                                if ($value >= 0 && $value < (2 ** 5)) {
1317
                                    $fieldArray[$field] = $value;
1318
                                }
1319
                        }
1320
                    }
1321
                    break;
1322
                case 't3ver_oid':
1323
                case 't3ver_wsid':
1324
                case 't3ver_state':
1325
                case 't3ver_stage':
1326
                    break;
1327
                case 'l10n_state':
1328
                    $fieldArray[$field] = $fieldValue;
1329
                    break;
1330
                default:
1331
                    if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1332
                        // Evaluating the value
1333
                        $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID, $incomingFieldArray);
1334
                        if (array_key_exists('value', $res)) {
1335
                            $fieldArray[$field] = $res['value'];
1336
                        }
1337
                        // Add the value of the original record to the diff-storage content:
1338
                        if ($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'] ?? false) {
1339
                            $originalLanguage_diffStorage[$field] = (string)($originalLanguageRecord[$field] ?? '');
1340
                            $diffStorageFlag = true;
1341
                        }
1342
                    } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['origUid']) && $GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1343
                        // Allow value for original UID to pass by...
1344
                        $fieldArray[$field] = $fieldValue;
1345
                    }
1346
            }
1347
        }
1348
1349
        // Dealing with a page translation, setting "sorting", "pid", "perms_*" to the same values as the original record
1350
        if ($table === 'pages' && is_array($originalLanguageRecord)) {
1351
            $fieldArray['sorting'] = $originalLanguageRecord['sorting'];
1352
            $fieldArray['perms_userid'] = $originalLanguageRecord['perms_userid'];
1353
            $fieldArray['perms_groupid'] = $originalLanguageRecord['perms_groupid'];
1354
            $fieldArray['perms_user'] = $originalLanguageRecord['perms_user'];
1355
            $fieldArray['perms_group'] = $originalLanguageRecord['perms_group'];
1356
            $fieldArray['perms_everybody'] = $originalLanguageRecord['perms_everybody'];
1357
        }
1358
1359
        // Add diff-storage information:
1360
        if ($diffStorageFlag
1361
            && !array_key_exists($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'], $fieldArray)
1362
        ) {
1363
            // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
1364
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = json_encode($originalLanguage_diffStorage);
1365
        }
1366
        // Return fieldArray
1367
        return $fieldArray;
1368
    }
1369
1370
    /*********************************************
1371
     *
1372
     * Evaluation of input values
1373
     *
1374
     ********************************************/
1375
    /**
1376
     * Evaluates a value according to $table/$field settings.
1377
     * This function is for real database fields - NOT FlexForm "pseudo" fields.
1378
     * NOTICE: Calling this function expects this: 1) That the data is saved!
1379
     *
1380
     * @param string $table Table name
1381
     * @param string $field Field name
1382
     * @param string $value Value to be evaluated. Notice, this is the INPUT value from the form. The original value (from any existing record) must be manually looked up inside the function if needed - or taken from $currentRecord array.
1383
     * @param int|string $id The record-uid, mainly - but not exclusively - used for logging
1384
     * @param string $status 'update' or 'new' flag
1385
     * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1386
     * @param int $tscPID TSconfig PID
1387
     * @param array $incomingFieldArray the fields being explicitly set by the outside (unlike $fieldArray)
1388
     * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1389
     * @internal should only be used from within DataHandler
1390
     */
1391
    public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID, $incomingFieldArray = [])
1392
    {
1393
        $curValueRec = null;
1394
        // Result array
1395
        $res = [];
1396
1397
        // Processing special case of field pages.doktype
1398
        if ($table === 'pages' && $field === 'doktype') {
1399
            // If the user may not use this specific doktype, we issue a warning
1400
            if (!($this->admin || GeneralUtility::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
1401
                if ($this->enableLogging) {
1402
                    $propArr = $this->getRecordProperties($table, $id);
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type string; however, parameter $id of TYPO3\CMS\Core\DataHandl...::getRecordProperties() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1402
                    $propArr = $this->getRecordProperties($table, /** @scrutinizer ignore-type */ $id);
Loading history...
1403
                    $this->log($table, (int)$id, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'You cannot change the \'doktype\' of page \'%s\' to the desired value.', 1, [$propArr['header']], $propArr['event_pid']);
1404
                }
1405
                return $res;
1406
            }
1407
            if ($status === 'update') {
1408
                // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1409
                $onlyAllowedTables = $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1410
                if ($onlyAllowedTables) {
1411
                    // use the real page id (default language)
1412
                    $recordId = $this->getDefaultLanguagePageId((int)$id);
1413
                    $theWrongTables = $this->doesPageHaveUnallowedTables($recordId, (int)$value);
1414
                    if ($theWrongTables) {
1415
                        if ($this->enableLogging) {
1416
                            $propArr = $this->getRecordProperties($table, $id);
1417
                            $this->log($table, (int)$id, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, '\'doktype\' of page \'%s\' could not be changed because the page contains records from disallowed tables; %s', 2, [$propArr['header'], $theWrongTables], $propArr['event_pid']);
1418
                        }
1419
                        return $res;
1420
                    }
1421
                }
1422
            }
1423
        }
1424
1425
        $curValue = null;
1426
        if ((int)$id !== 0) {
1427
            // Get current value:
1428
            $curValueRec = $this->recordInfo($table, (int)$id, $field);
1429
            // isset() won't work here, since values can be NULL
1430
            if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1431
                $curValue = $curValueRec[$field];
1432
            }
1433
        }
1434
1435
        if ($table === 'be_users'
1436
            && ($field === 'admin' || $field === 'password')
1437
            && $status === 'update'
1438
        ) {
1439
            // Do not allow a non system maintainer admin to change admin flag and password of system maintainers
1440
            $systemMaintainers = array_map('intval', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? []);
1441
            // False if current user is not in system maintainer list or if switch to user mode is active
1442
            $isCurrentUserSystemMaintainer = $this->BE_USER->isSystemMaintainer();
1443
            $isTargetUserInSystemMaintainerList = in_array((int)$id, $systemMaintainers, true);
1444
            if ($field === 'admin') {
1445
                $isFieldChanged = (int)$curValueRec[$field] !== (int)$value;
1446
            } else {
1447
                $isFieldChanged = $curValueRec[$field] !== $value;
1448
            }
1449
            if (!$isCurrentUserSystemMaintainer && $isTargetUserInSystemMaintainerList && $isFieldChanged) {
1450
                $value = $curValueRec[$field];
1451
                $message = GeneralUtility::makeInstance(
1452
                    FlashMessage::class,
1453
                    $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.adminCanNotChangeSystemMaintainer'),
1454
                    '',
1455
                    FlashMessage::ERROR,
1456
                    true
1457
                );
1458
                $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1459
                $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
1460
            }
1461
        }
1462
1463
        // Getting config for the field
1464
        $tcaFieldConf = $this->resolveFieldConfigurationAndRespectColumnsOverrides($table, $field);
1465
1466
        // Create $recFID only for those types that need it
1467
        if ($tcaFieldConf['type'] === 'flex') {
1468
            $recFID = $table . ':' . $id . ':' . $field;
1469
        } else {
1470
            $recFID = '';
1471
        }
1472
1473
        // Perform processing:
1474
        $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, [], $tscPID, ['incomingFieldArray' => $incomingFieldArray]);
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type string; however, parameter $id of TYPO3\CMS\Core\DataHandl...andler::checkValue_SW() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1474
        $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, /** @scrutinizer ignore-type */ $id, $curValue, $status, $realPid, $recFID, $field, [], $tscPID, ['incomingFieldArray' => $incomingFieldArray]);
Loading history...
1475
        return $res;
1476
    }
1477
1478
    /**
1479
     * Use columns overrides for evaluation.
1480
     *
1481
     * Fetch the TCA ["config"] part for a specific field, including the columnsOverrides value.
1482
     * Used for checkValue purposes currently (as it takes the checkValue_currentRecord value).
1483
     *
1484
     * @param string $table
1485
     * @param string $field
1486
     * @return array
1487
     */
1488
    protected function resolveFieldConfigurationAndRespectColumnsOverrides(string $table, string $field): array
1489
    {
1490
        $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1491
        $recordType = BackendUtility::getTCAtypeValue($table, $this->checkValue_currentRecord);
1492
        $columnsOverridesConfigOfField = $GLOBALS['TCA'][$table]['types'][$recordType]['columnsOverrides'][$field]['config'] ?? null;
1493
        if ($columnsOverridesConfigOfField) {
1494
            ArrayUtility::mergeRecursiveWithOverrule($tcaFieldConf, $columnsOverridesConfigOfField);
1495
        }
1496
        return $tcaFieldConf;
1497
    }
1498
1499
    /**
1500
     * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1501
     * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1502
     * And hey, there's a good thing about the method arguments: 13 is prime :-P
1503
     *
1504
     * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1505
     * @param string $value The value to set.
1506
     * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1507
     * @param string $table Table name
1508
     * @param int $id UID of record
1509
     * @param mixed $curValue Current value of the field
1510
     * @param string $status 'update' or 'new' flag
1511
     * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1512
     * @param string $recFID Field identifier [table:uid:field] for flexforms
1513
     * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1514
     * @param array $uploadedFiles
1515
     * @param int $tscPID TSconfig PID
1516
     * @param array|null $additionalData Additional data to be forwarded to sub-processors
1517
     * @return array Returns the evaluated $value as key "value" in this array.
1518
     * @internal should only be used from within DataHandler
1519
     */
1520
    public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = null)
1521
    {
1522
        // Convert to NULL value if defined in TCA
1523
        if ($value === null && !empty($tcaFieldConf['eval']) && GeneralUtility::inList($tcaFieldConf['eval'], 'null')) {
0 ignored issues
show
introduced by
The condition $value === null is always false.
Loading history...
1524
            $res = ['value' => null];
1525
            return $res;
1526
        }
1527
1528
        switch ($tcaFieldConf['type']) {
1529
            case 'text':
1530
                $res = $this->checkValueForText($value, $tcaFieldConf, $table, $realPid, $field);
1531
                break;
1532
            case 'passthrough':
1533
            case 'imageManipulation':
1534
            case 'user':
1535
                $res['value'] = $value;
1536
                break;
1537
            case 'input':
1538
                $res = $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1539
                break;
1540
            case 'slug':
1541
                $res = $this->checkValueForSlug((string)$value, $tcaFieldConf, $table, $id, (int)$realPid, $field, $additionalData['incomingFieldArray'] ?? []);
1542
                break;
1543
            case 'language':
1544
                $res = $this->checkValueForLanguage((int)$value, $table, $field);
1545
                break;
1546
            case 'check':
1547
                $res = $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1548
                break;
1549
            case 'radio':
1550
                $res = $this->checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1551
                break;
1552
            case 'group':
1553
            case 'select':
1554
                $res = $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $status, $field);
1555
                break;
1556
            case 'inline':
1557
                $res = $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData) ?: [];
1558
                break;
1559
            case 'flex':
1560
                // FlexForms are only allowed for real fields.
1561
                if ($field) {
1562
                    $res = $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
1563
                }
1564
                break;
1565
            default:
1566
                // Do nothing
1567
        }
1568
        $res = $this->checkValueForInternalReferences($res, $value, $tcaFieldConf, $table, $id, $field);
1569
        return $res;
1570
    }
1571
1572
    /**
1573
     * Checks values that are used for internal references. If the provided $value
1574
     * is a NEW-identifier, the direct processing is stopped. Instead, the value is
1575
     * forwarded to the remap-stack to be post-processed and resolved into a proper
1576
     * UID after all data has been resolved.
1577
     *
1578
     * This method considers TCA types that cannot handle and resolve these internal
1579
     * values directly, like 'passthrough', 'none' or 'user'. Values are only modified
1580
     * here if the $field is used as 'transOrigPointerField' or 'translationSource'.
1581
     *
1582
     * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1583
     * @param string $value The value to set.
1584
     * @param array $tcaFieldConf Field configuration from TCA
1585
     * @param string $table Table name
1586
     * @param int|string $id UID of record
1587
     * @param string $field The field name
1588
     * @return array The result array. The processed value (if any!) is set in the "value" key.
1589
     */
1590
    protected function checkValueForInternalReferences(array $res, $value, $tcaFieldConf, $table, $id, $field)
1591
    {
1592
        $relevantFieldNames = [
1593
            $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? null,
1594
            $GLOBALS['TCA'][$table]['ctrl']['translationSource'] ?? null,
1595
        ];
1596
1597
        if (
1598
            // in case field is empty
1599
            empty($field)
1600
            // in case the field is not relevant
1601
            || !in_array($field, $relevantFieldNames)
1602
            // in case the 'value' index has been unset already
1603
            || !array_key_exists('value', $res)
1604
            // in case it's not a NEW-identifier
1605
            || strpos($value, 'NEW') === false
1606
        ) {
1607
            return $res;
1608
        }
1609
1610
        $valueArray = [$value];
1611
        $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
1612
        $this->addNewValuesToRemapStackChildIds($valueArray);
1613
        $this->remapStack[] = [
1614
            'args' => [$valueArray, $tcaFieldConf, $id, $table, $field],
1615
            'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 3],
1616
            'field' => $field
1617
        ];
1618
        unset($res['value']);
1619
1620
        return $res;
1621
    }
1622
1623
    /**
1624
     * Evaluate "text" type values.
1625
     *
1626
     * @param string $value The value to set.
1627
     * @param array $tcaFieldConf Field configuration from TCA
1628
     * @param string $table Table name
1629
     * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1630
     * @param string $field Field name
1631
     * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1632
     */
1633
    protected function checkValueForText($value, $tcaFieldConf, $table, $realPid, $field)
1634
    {
1635
        if (isset($tcaFieldConf['eval']) && $tcaFieldConf['eval'] !== '') {
1636
            $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1637
            $evalCodesArray = $this->runtimeCache->get($cacheId);
1638
            if (!is_array($evalCodesArray)) {
1639
                $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1640
                $this->runtimeCache->set($cacheId, $evalCodesArray);
1641
            }
1642
            $valueArray = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in'] ?? '');
1643
        } else {
1644
            $valueArray = ['value' => $value];
1645
        }
1646
1647
        // Handle richtext transformations
1648
        if ($this->dontProcessTransformations) {
1649
            return $valueArray;
1650
        }
1651
        // Keep null as value
1652
        if ($value === null) {
0 ignored issues
show
introduced by
The condition $value === null is always false.
Loading history...
1653
            return $valueArray;
1654
        }
1655
        if (isset($tcaFieldConf['enableRichtext']) && (bool)$tcaFieldConf['enableRichtext'] === true) {
1656
            $recordType = BackendUtility::getTCAtypeValue($table, $this->checkValue_currentRecord);
1657
            $richtextConfigurationProvider = GeneralUtility::makeInstance(Richtext::class);
1658
            $richtextConfiguration = $richtextConfigurationProvider->getConfiguration($table, $field, $realPid, $recordType, $tcaFieldConf);
1659
            $rteParser = GeneralUtility::makeInstance(RteHtmlParser::class);
1660
            $valueArray['value'] = $rteParser->transformTextForPersistence((string)$value, $richtextConfiguration['proc.'] ?? []);
1661
        }
1662
1663
        return $valueArray;
1664
    }
1665
1666
    /**
1667
     * Evaluate "input" type values.
1668
     *
1669
     * @param string $value The value to set.
1670
     * @param array $tcaFieldConf Field configuration from TCA
1671
     * @param string $table Table name
1672
     * @param int $id UID of record
1673
     * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1674
     * @param string $field Field name
1675
     * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1676
     */
1677
    protected function checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field)
1678
    {
1679
        // Handle native date/time fields
1680
        $isDateOrDateTimeField = false;
1681
        $format = '';
1682
        $emptyValue = '';
1683
        $dateTimeTypes = QueryHelper::getDateTimeTypes();
1684
        // normal integer "date" fields (timestamps) are handled in checkValue_input_Eval
1685
        if (isset($tcaFieldConf['dbType']) && in_array($tcaFieldConf['dbType'], $dateTimeTypes, true)) {
1686
            if (empty($value)) {
1687
                $value = null;
1688
            } else {
1689
                $isDateOrDateTimeField = true;
1690
                $dateTimeFormats = QueryHelper::getDateTimeFormats();
1691
                $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1692
1693
                // Convert the date/time into a timestamp for the sake of the checks
1694
                $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1695
                // We expect the ISO 8601 $value to contain a UTC timezone specifier.
1696
                // We explicitly fallback to UTC if no timezone specifier is given (e.g. for copy operations).
1697
                $dateTime = new \DateTime($value, new \DateTimeZone('UTC'));
1698
                // The timestamp (UTC) returned by getTimestamp() will be converted to
1699
                // a local time string by gmdate() later.
1700
                $value = $value === $emptyValue ? null : $dateTime->getTimestamp();
1701
            }
1702
        }
1703
        // Secures the string-length to be less than max.
1704
        if (isset($tcaFieldConf['max']) && (int)$tcaFieldConf['max'] > 0) {
1705
            $value = mb_substr((string)$value, 0, (int)$tcaFieldConf['max'], 'utf-8');
1706
        }
1707
1708
        if (empty($tcaFieldConf['eval'])) {
1709
            $res = ['value' => $value];
1710
        } else {
1711
            // Process evaluation settings:
1712
            $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1713
            $evalCodesArray = $this->runtimeCache->get($cacheId);
1714
            if (!is_array($evalCodesArray)) {
1715
                $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1716
                $this->runtimeCache->set($cacheId, $evalCodesArray);
1717
            }
1718
1719
            $res = $this->checkValue_input_Eval((string)$value, $evalCodesArray, $tcaFieldConf['is_in'] ?? '', $table);
1720
            if (isset($tcaFieldConf['dbType']) && isset($res['value']) && !$res['value']) {
1721
                // set the value to null if we have an empty value for a native field
1722
                $res['value'] = null;
1723
            }
1724
1725
            // Process UNIQUE settings:
1726
            // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning
1727
            if ($field && !empty($res['value'])) {
1728
                if (in_array('uniqueInPid', $evalCodesArray, true)) {
1729
                    $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1730
                }
1731
                if ($res['value'] && in_array('unique', $evalCodesArray, true)) {
1732
                    $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1733
                }
1734
            }
1735
        }
1736
1737
        // Checking range of value:
1738
        // @todo: The "checkbox" option was removed for type=input, this check could be probably relaxed?
1739
        if (
1740
            isset($tcaFieldConf['range']) && $tcaFieldConf['range']
1741
            && (!isset($tcaFieldConf['checkbox']) || $res['value'] != $tcaFieldConf['checkbox'])
1742
            && (!isset($tcaFieldConf['default']) || (int)$res['value'] !== (int)$tcaFieldConf['default'])
1743
        ) {
1744
            if (isset($tcaFieldConf['range']['upper']) && (int)$res['value'] > (int)$tcaFieldConf['range']['upper']) {
1745
                $res['value'] = (int)$tcaFieldConf['range']['upper'];
1746
            }
1747
            if (isset($tcaFieldConf['range']['lower']) && (int)$res['value'] < (int)$tcaFieldConf['range']['lower']) {
1748
                $res['value'] = (int)$tcaFieldConf['range']['lower'];
1749
            }
1750
        }
1751
1752
        // Handle native date/time fields
1753
        if ($isDateOrDateTimeField) {
1754
            // Convert the timestamp back to a date/time
1755
            $res['value'] = $res['value'] ? gmdate($format, $res['value']) : $emptyValue;
1756
        }
1757
        return $res;
1758
    }
1759
1760
    /**
1761
     * Evaluate "slug" type values.
1762
     *
1763
     * @param string $value The value to set.
1764
     * @param array $tcaFieldConf Field configuration from TCA
1765
     * @param string $table Table name
1766
     * @param int $id UID of record
1767
     * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1768
     * @param string $field Field name
1769
     * @param array $incomingFieldArray the fields being explicitly set by the outside (unlike $fieldArray) for the record
1770
     * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1771
     * @see SlugEnricher
1772
     * @see SlugHelper
1773
     */
1774
    protected function checkValueForSlug(string $value, array $tcaFieldConf, string $table, $id, int $realPid, string $field, array $incomingFieldArray = []): array
1775
    {
1776
        $workspaceId = $this->BE_USER->workspace;
1777
        $helper = GeneralUtility::makeInstance(SlugHelper::class, $table, $field, $tcaFieldConf, $workspaceId);
1778
        $fullRecord = array_replace_recursive($this->checkValue_currentRecord, $incomingFieldArray ?? []);
1779
        // Generate a value if there is none, otherwise ensure that all characters are cleaned up
1780
        if ($value === '') {
1781
            $value = $helper->generate($fullRecord, $realPid);
1782
        } else {
1783
            $value = $helper->sanitize($value);
1784
        }
1785
1786
        // Return directly in case no evaluations are defined
1787
        if (empty($tcaFieldConf['eval'])) {
1788
            return ['value' => $value];
1789
        }
1790
1791
        $state = RecordStateFactory::forName($table)
1792
            ->fromArray($fullRecord, $realPid, $id);
1793
        $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1794
        if (in_array('unique', $evalCodesArray, true)) {
1795
            $value = $helper->buildSlugForUniqueInTable($value, $state);
1796
        }
1797
        if (in_array('uniqueInSite', $evalCodesArray, true)) {
1798
            $value = $helper->buildSlugForUniqueInSite($value, $state);
1799
        }
1800
        if (in_array('uniqueInPid', $evalCodesArray, true)) {
1801
            $value = $helper->buildSlugForUniqueInPid($value, $state);
1802
        }
1803
1804
        return ['value' => $value];
1805
    }
1806
1807
    /**
1808
     * Evaluate "language" type value.
1809
     *
1810
     * Checks whether the user is allowed to add such a value as language
1811
     *
1812
     * @param int $value The value to set.
1813
     * @param string $table Table name
1814
     * @param string $field Field name
1815
     * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1816
     */
1817
    protected function checkValueForLanguage(int $value, string $table, string $field): array
1818
    {
1819
        // If given table is localizable and the given field is the defined
1820
        // languageField, check if the selected language is allowed for the user.
1821
        // Note: Usually this method should never be reached, in case the language value is
1822
        // not valid, since recordEditAccessInternals checks for proper permission beforehand.
1823
        if (BackendUtility::isTableLocalizable($table)
1824
            && ($GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? '') === $field
1825
            && !$this->BE_USER->checkLanguageAccess($value)
1826
        ) {
1827
            return [];
1828
        }
1829
1830
        // @todo Should we also check if the language is allowed for the current site - if record has site context?
1831
1832
        return ['value' => $value];
1833
    }
1834
1835
    /**
1836
     * Evaluates 'check' type values.
1837
     *
1838
     * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1839
     * @param string $value The value to set.
1840
     * @param array $tcaFieldConf Field configuration from TCA
1841
     * @param string $table Table name
1842
     * @param int $id UID of record
1843
     * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1844
     * @param string $field Field name
1845
     * @return array Modified $res array
1846
     */
1847
    protected function checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field)
1848
    {
1849
        $items = $tcaFieldConf['items'] ?? null;
1850
        if (!empty($tcaFieldConf['itemsProcFunc'])) {
1851
            /** @var ItemProcessingService $processingService */
1852
            $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
1853
            $items = $processingService->getProcessingItems(
1854
                $table,
1855
                $realPid,
1856
                $field,
1857
                $this->checkValue_currentRecord,
1858
                $tcaFieldConf,
1859
                $tcaFieldConf['items']
1860
            );
1861
        }
1862
1863
        $itemC = 0;
1864
        if ($items !== null) {
1865
            $itemC = count($items);
1866
        }
1867
        if (!$itemC) {
1868
            $itemC = 1;
1869
        }
1870
        $maxV = (2 ** $itemC) - 1;
1871
        if ($value < 0) {
1872
            // @todo: throw LogicException here? Negative values for checkbox items do not make sense and indicate a coding error.
1873
            $value = 0;
1874
        }
1875
        if ($value > $maxV) {
1876
            // @todo: This case is pretty ugly: If there is an itemsProcFunc registered, and if it returns a dynamic,
1877
            // @todo: changing list of items, then it may happen that a value is transformed and vanished checkboxes
1878
            // @todo: are permanently removed from the value.
1879
            // @todo: Suggestion: Throw an exception instead? Maybe a specific, catchable exception that generates a
1880
            // @todo: error message to the user - dynamic item sets via itemProcFunc on check would be a bad idea anyway.
1881
            $value = $value & $maxV;
1882
        }
1883
        if ($field && $value > 0 && !empty($tcaFieldConf['eval'])) {
1884
            $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1885
            $otherRecordsWithSameValue = [];
1886
            $maxCheckedRecords = 0;
1887
            if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, true)) {
1888
                $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1889
                $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1890
            }
1891
            if (in_array('maximumRecordsChecked', $evalCodesArray, true)) {
1892
                $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1893
                $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1894
            }
1895
1896
            // there are more than enough records with value "1" in the DB
1897
            // if so, set this value to "0" again
1898
            if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1899
                $value = 0;
1900
                $this->log($table, $id, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'Could not activate checkbox for field "%s". A total of %s record(s) can have this checkbox activated. Uncheck other records first in order to activate the checkbox of this record.', -1, [$this->getLanguageService()->sL(BackendUtility::getItemLabel($table, $field)), $maxCheckedRecords]);
1901
            }
1902
        }
1903
        $res['value'] = $value;
1904
        return $res;
1905
    }
1906
1907
    /**
1908
     * Evaluates 'radio' type values.
1909
     *
1910
     * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1911
     * @param string $value The value to set.
1912
     * @param array $tcaFieldConf Field configuration from TCA
1913
     * @param string $table The table of the record
1914
     * @param int $id The id of the record
1915
     * @param int $pid The pid of the record
1916
     * @param string $field The field to check
1917
     * @return array Modified $res array
1918
     */
1919
    protected function checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $pid, $field)
1920
    {
1921
        if (is_array($tcaFieldConf['items'])) {
1922
            foreach ($tcaFieldConf['items'] as $set) {
1923
                if ((string)$set[1] === (string)$value) {
1924
                    $res['value'] = $value;
1925
                    break;
1926
                }
1927
            }
1928
        }
1929
1930
        // if no value was found and an itemsProcFunc is defined, check that for the value
1931
        if (!empty($tcaFieldConf['itemsProcFunc']) && empty($res['value'])) {
1932
            $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
1933
            $processedItems = $processingService->getProcessingItems(
1934
                $table,
1935
                $pid,
1936
                $field,
1937
                $this->checkValue_currentRecord,
1938
                $tcaFieldConf,
1939
                $tcaFieldConf['items']
1940
            );
1941
1942
            foreach ($processedItems as $set) {
1943
                if ((string)$set[1] === (string)$value) {
1944
                    $res['value'] = $value;
1945
                    break;
1946
                }
1947
            }
1948
        }
1949
1950
        return $res;
1951
    }
1952
1953
    /**
1954
     * Evaluates 'group' or 'select' type values.
1955
     *
1956
     * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1957
     * @param string|array $value The value to set.
1958
     * @param array $tcaFieldConf Field configuration from TCA
1959
     * @param string $table Table name
1960
     * @param int $id UID of record
1961
     * @param string $status 'update' or 'new' flag
1962
     * @param string $field Field name
1963
     * @return array Modified $res array
1964
     */
1965
    protected function checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $status, $field)
1966
    {
1967
        // Detecting if value sent is an array and if so, implode it around a comma:
1968
        if (is_array($value)) {
1969
            $value = implode(',', $value);
1970
        }
1971
        // This converts all occurrences of '&#123;' to the byte 123 in the string - this is needed in very rare cases where file names with special characters (e.g. ???, umlaut) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not Mozilla and Opera.
1972
        // Anyway, this should NOT disturb anything else:
1973
        $value = $this->convNumEntityToByteValue($value);
1974
        // When values are sent as group or select they come as comma-separated values which are exploded by this function:
1975
        $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1976
        // If multiple is not set, remove duplicates:
1977
        if (!($tcaFieldConf['multiple'] ?? false)) {
1978
            $valueArray = array_unique($valueArray);
1979
        }
1980
        // If an exclusive key is found, discard all others:
1981
        if ($tcaFieldConf['type'] === 'select' && ($tcaFieldConf['exclusiveKeys'] ?? false)) {
1982
            $exclusiveKeys = GeneralUtility::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
1983
            foreach ($valueArray as $index => $key) {
1984
                if (in_array($key, $exclusiveKeys, true)) {
1985
                    $valueArray = [$index => $key];
1986
                    break;
1987
                }
1988
            }
1989
        }
1990
        // This could be a good spot for parsing the array through a validation-function which checks if the values are correct (except that database references are not in their final form - but that is the point, isn't it?)
1991
        // NOTE!!! Must check max-items of files before the later check because that check would just leave out file names if there are too many!!
1992
        $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
1993
        // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1994
        if ($tcaFieldConf['type'] === 'select' && ($tcaFieldConf['authMode'] ?? false)) {
1995
            $preCount = count($valueArray);
1996
            foreach ($valueArray as $index => $key) {
1997
                if (!$this->BE_USER->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
1998
                    unset($valueArray[$index]);
1999
                }
2000
            }
2001
            // During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
2002
            if ($preCount && empty($valueArray)) {
2003
                return [];
2004
            }
2005
        }
2006
        // For select types which has a foreign table attached:
2007
        $unsetResult = false;
2008
        if (($tcaFieldConf['type'] === 'group' && $tcaFieldConf['internal_type'] === 'db')
2009
            || ($tcaFieldConf['type'] === 'select' && ($tcaFieldConf['foreign_table'] ?? false))
2010
        ) {
2011
            // check, if there is a NEW... id in the value, that should be substituted later
2012
            if (strpos($value, 'NEW') !== false) {
2013
                $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
2014
                $this->addNewValuesToRemapStackChildIds($valueArray);
2015
                $this->remapStack[] = [
2016
                    'func' => 'checkValue_group_select_processDBdata',
2017
                    'args' => [$valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field],
2018
                    'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5],
2019
                    'field' => $field
2020
                ];
2021
                $unsetResult = true;
2022
            } else {
2023
                $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field);
2024
            }
2025
        }
2026
        if (!$unsetResult) {
2027
            $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2028
            $res['value'] = $this->castReferenceValue(implode(',', $newVal), $tcaFieldConf);
2029
        } else {
2030
            unset($res['value']);
2031
        }
2032
        return $res;
2033
    }
2034
2035
    /**
2036
     * Applies the filter methods from a column's TCA configuration to a value array.
2037
     *
2038
     * @param array $tcaFieldConfiguration
2039
     * @param array $values
2040
     * @return array|mixed
2041
     * @throws \RuntimeException
2042
     */
2043
    protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values)
2044
    {
2045
        if (empty($tcaFieldConfiguration['filter']) || !is_array($tcaFieldConfiguration['filter'])) {
2046
            return $values;
2047
        }
2048
        foreach ($tcaFieldConfiguration['filter'] as $filter) {
2049
            if (empty($filter['userFunc'])) {
2050
                continue;
2051
            }
2052
            $parameters = $filter['parameters'] ?: [];
2053
            $parameters['values'] = $values;
2054
            $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
2055
            $values = GeneralUtility::callUserFunction($filter['userFunc'], $parameters, $this);
2056
            if (!is_array($values)) {
2057
                throw new \RuntimeException('Failed calling filter userFunc.', 1336051942);
2058
            }
2059
        }
2060
        return $values;
2061
    }
2062
2063
    /**
2064
     * Evaluates 'flex' type values.
2065
     *
2066
     * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2067
     * @param string|array $value The value to set.
2068
     * @param array $tcaFieldConf Field configuration from TCA
2069
     * @param string $table Table name
2070
     * @param int $id UID of record
2071
     * @param mixed $curValue Current value of the field
2072
     * @param string $status 'update' or 'new' flag
2073
     * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
2074
     * @param string $recFID Field identifier [table:uid:field] for flexforms
2075
     * @param int $tscPID TSconfig PID
2076
     * @param array $uploadedFiles Uploaded files for the field
2077
     * @param string $field Field name
2078
     * @return array Modified $res array
2079
     */
2080
    protected function checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field)
2081
    {
2082
        if (is_array($value)) {
2083
            // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2084
            // Problem: when copying a page, flexform XML comes along in the array for the new record - but since $this->checkValue_currentRecord
2085
            // does not have a uid or pid for that sake, the FlexFormTools->getDataStructureIdentifier() function returns no good DS. For new
2086
            // records we do know the expected PID so therefore we send that with this special parameter. Only active when larger than zero.
2087
            $row = $this->checkValue_currentRecord;
2088
            if ($status === 'new') {
2089
                $row['pid'] = $realPid;
2090
            }
2091
2092
            $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
2093
2094
            // Get data structure. The methods may throw various exceptions, with some of them being
2095
            // ok in certain scenarios, for instance on new record rows. Those are ok to "eat" here
2096
            // and substitute with a dummy DS.
2097
            $dataStructureArray = ['sheets' => ['sDEF' => []]];
2098
            try {
2099
                $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
2100
                    ['config' => $tcaFieldConf],
2101
                    $table,
2102
                    $field,
2103
                    $row
2104
                );
2105
2106
                $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
2107
            } catch (InvalidParentRowException|InvalidParentRowLoopException|InvalidParentRowRootException|InvalidPointerFieldValueException|InvalidIdentifierException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2108
            }
2109
2110
            // Get current value array:
2111
            $currentValueArray = (string)$curValue !== '' ? GeneralUtility::xml2array($curValue) : [];
2112
            if (!is_array($currentValueArray)) {
2113
                $currentValueArray = [];
2114
            }
2115
            // Remove all old meta for languages...
2116
            // Evaluation of input values:
2117
            $value['data'] = $this->checkValue_flex_procInData($value['data'] ?? [], $currentValueArray['data'] ?? [], $uploadedFiles['data'] ?? [], $dataStructureArray, [$table, $id, $curValue, $status, $realPid, $recFID, $tscPID]);
2118
            // Create XML from input value:
2119
            $xmlValue = $this->checkValue_flexArray2Xml($value, true);
2120
2121
            // Here we convert the currently submitted values BACK to an array, then merge the two and then BACK to XML again. This is needed to ensure the charsets are the same
2122
            // (provided that the current value was already stored IN the charset that the new value is converted to).
2123
            $arrValue = GeneralUtility::xml2array($xmlValue);
2124
2125
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] ?? [] as $className) {
2126
                $hookObject = GeneralUtility::makeInstance($className);
2127
                if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2128
                    $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2129
                }
2130
            }
2131
2132
            ArrayUtility::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2133
            $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, true);
2134
2135
            // Action commands (sorting order and removals of elements) for flexform sections,
2136
            // see FormEngine for the use of this GP parameter
2137
            $actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
2138
            if (is_array($actionCMDs[$table][$id][$field]['data'] ?? null)) {
2139
                $arrValue = GeneralUtility::xml2array($xmlValue);
2140
                $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2141
                $xmlValue = $this->checkValue_flexArray2Xml($arrValue, true);
2142
            }
2143
            // Create the value XML:
2144
            $res['value'] = '';
2145
            $res['value'] .= $xmlValue;
2146
        } else {
2147
            // Passthrough...:
2148
            $res['value'] = $value;
2149
        }
2150
2151
        return $res;
2152
    }
2153
2154
    /**
2155
     * Converts an array to FlexForm XML
2156
     *
2157
     * @param array $array Array with FlexForm data
2158
     * @param bool $addPrologue If set, the XML prologue is returned as well.
2159
     * @return string Input array converted to XML
2160
     * @internal should only be used from within DataHandler
2161
     */
2162
    public function checkValue_flexArray2Xml($array, $addPrologue = false)
2163
    {
2164
        /** @var FlexFormTools $flexObj */
2165
        $flexObj = GeneralUtility::makeInstance(FlexFormTools::class);
2166
        return $flexObj->flexArray2Xml($array, $addPrologue);
2167
    }
2168
2169
    /**
2170
     * Actions for flex form element (move, delete)
2171
     * allows to remove and move flexform sections
2172
     *
2173
     * @param array $valueArray by reference
2174
     * @param array $actionCMDs
2175
     */
2176
    protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs)
2177
    {
2178
        if (!is_array($valueArray) || !is_array($actionCMDs)) {
0 ignored issues
show
introduced by
The condition is_array($valueArray) is always true.
Loading history...
introduced by
The condition is_array($actionCMDs) is always true.
Loading history...
2179
            return;
2180
        }
2181
2182
        foreach ($actionCMDs as $key => $value) {
2183
            if ($key === '_ACTION') {
2184
                // First, check if there are "commands":
2185
                if (empty(array_filter($actionCMDs[$key]))) {
2186
                    continue;
2187
                }
2188
2189
                asort($actionCMDs[$key]);
2190
                $newValueArray = [];
2191
                foreach ($actionCMDs[$key] as $idx => $order) {
2192
                    // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost
2193
                    // files unless we act on this delete operation by traversing and deleting files that were referred to.
2194
                    if ($order !== 'DELETE') {
2195
                        $newValueArray[$idx] = $valueArray[$idx];
2196
                    }
2197
                    unset($valueArray[$idx]);
2198
                }
2199
                $valueArray += $newValueArray;
2200
            } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2201
                $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2202
            }
2203
        }
2204
    }
2205
2206
    /**
2207
     * Evaluates 'inline' type values.
2208
     * (partly copied from the select_group function on this issue)
2209
     *
2210
     * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2211
     * @param string $value The value to set.
2212
     * @param array $tcaFieldConf Field configuration from TCA
2213
     * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2214
     * @param string $field Field name
2215
     * @param array $additionalData Additional data to be forwarded to sub-processors
2216
     * @internal should only be used from within DataHandler
2217
     */
2218
    public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = null)
2219
    {
2220
        [$table, $id, , $status] = $PP;
2221
        $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
2222
    }
2223
2224
    /**
2225
     * Evaluates 'inline' type values.
2226
     * (partly copied from the select_group function on this issue)
2227
     *
2228
     * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2229
     * @param string $value The value to set.
2230
     * @param array $tcaFieldConf Field configuration from TCA
2231
     * @param string $table Table name
2232
     * @param int $id UID of record
2233
     * @param string $status 'update' or 'new' flag
2234
     * @param string $field Field name
2235
     * @param array $additionalData Additional data to be forwarded to sub-processors
2236
     * @return array|false Modified $res array
2237
     * @internal should only be used from within DataHandler
2238
     */
2239
    public function checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, array $additionalData = null)
2240
    {
2241
        if (!$tcaFieldConf['foreign_table']) {
2242
            // Fatal error, inline fields should always have a foreign_table defined
2243
            return false;
2244
        }
2245
        // When values are sent they come as comma-separated values which are exploded by this function:
2246
        $valueArray = GeneralUtility::trimExplode(',', $value);
2247
        // Remove duplicates: (should not be needed)
2248
        $valueArray = array_unique($valueArray);
2249
        // Example for received data:
2250
        // $value = 45,NEW4555fdf59d154,12,123
2251
        // We need to decide whether we use the stack or can save the relation directly.
2252
        if (!empty($value) && (strpos($value, 'NEW') !== false || !MathUtility::canBeInterpretedAsInteger($id))) {
2253
            $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
2254
            $this->addNewValuesToRemapStackChildIds($valueArray);
2255
            $this->remapStack[] = [
2256
                'func' => 'checkValue_inline_processDBdata',
2257
                'args' => [$valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData],
2258
                'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4],
2259
                'additionalData' => $additionalData,
2260
                'field' => $field,
2261
            ];
2262
            unset($res['value']);
2263
        } elseif ($value || MathUtility::canBeInterpretedAsInteger($id)) {
2264
            $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field);
2265
        }
2266
        return $res;
2267
    }
2268
2269
    /**
2270
     * Checks if a fields has more items than defined via TCA in maxitems.
2271
     * If there are more items than allowed, the item list is truncated to the defined number.
2272
     *
2273
     * @param array $tcaFieldConf Field configuration from TCA
2274
     * @param array $valueArray Current value array of items
2275
     * @return array The truncated value array of items
2276
     * @internal should only be used from within DataHandler
2277
     */
2278
    public function checkValue_checkMax($tcaFieldConf, $valueArray)
2279
    {
2280
        // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function
2281
        // calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check
2282
        // before? Probably because we could not evaluate the validity of record uids etc... Hmm...
2283
        // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first,
2284
        // if the field is actual used regarding the CType.
2285
        $maxitems = isset($tcaFieldConf['maxitems']) ? (int)$tcaFieldConf['maxitems'] : 99999;
2286
        return array_slice($valueArray, 0, $maxitems);
2287
    }
2288
2289
    /*********************************************
2290
     *
2291
     * Helper functions for evaluation functions.
2292
     *
2293
     ********************************************/
2294
    /**
2295
     * Gets a unique value for $table/$id/$field based on $value
2296
     *
2297
     * @param string $table Table name
2298
     * @param string $field Field name for which $value must be unique
2299
     * @param string $value Value string.
2300
     * @param int $id UID to filter out in the lookup (the record itself...)
2301
     * @param int $newPid If set, the value will be unique for this PID
2302
     * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2303
     * @todo: consider workspaces, especially when publishing a unique value which has a unique value already in live
2304
     * @internal should only be used from within DataHandler
2305
     */
2306
    public function getUnique($table, $field, $value, $id, $newPid = 0)
2307
    {
2308
        if (!is_array($GLOBALS['TCA'][$table]) || !is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2309
            // Field is not configured in TCA
2310
            return $value;
2311
        }
2312
2313
        if ((string)$GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode'] === 'exclude') {
2314
            $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
2315
            $l10nParent = (int)$this->checkValue_currentRecord[$transOrigPointerField];
2316
            if ($l10nParent > 0) {
2317
                // Current record is a translation and l10n_mode "exclude" just copies the value from source language
2318
                return $value;
2319
            }
2320
        }
2321
2322
        $newValue = $originalValue = $value;
2323
        $statement = $this->getUniqueCountStatement($newValue, $table, $field, (int)$id, (int)$newPid);
2324
        // For as long as records with the test-value existing, try again (with incremented numbers appended)
2325
        if ($statement->fetchColumn()) {
2326
            for ($counter = 0; $counter <= 100; $counter++) {
2327
                $newValue = $value . $counter;
2328
                $statement->bindValue(1, $newValue);
2329
                $statement->execute();
2330
                if (!$statement->fetchColumn()) {
2331
                    break;
2332
                }
2333
            }
2334
        }
2335
2336
        if ($originalValue !== $newValue) {
2337
            $this->log($table, $id, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::WARNING, 'The value of the field "%s" has been changed from "%s" to "%s" as it is required to be unique.', 1, [$field, $originalValue, $newValue], $newPid);
2338
        }
2339
2340
        return $newValue;
2341
    }
2342
2343
    /**
2344
     * Gets the count of records for a unique field
2345
     *
2346
     * @param string $value The string value which should be unique
2347
     * @param string $table Table name
2348
     * @param string $field Field name for which $value must be unique
2349
     * @param int $uid UID to filter out in the lookup (the record itself...)
2350
     * @param int $pid If set, the value will be unique for this PID
2351
     * @return \Doctrine\DBAL\Driver\Statement Return the prepared statement to check uniqueness
2352
     */
2353
    protected function getUniqueCountStatement(
2354
        string $value,
2355
        string $table,
2356
        string $field,
2357
        int $uid,
2358
        int $pid
2359
    ): Statement {
2360
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
2361
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
2362
        $queryBuilder
2363
            ->count('uid')
2364
            ->from($table)
2365
            ->where(
2366
                $queryBuilder->expr()->eq($field, $queryBuilder->createPositionalParameter($value, \PDO::PARAM_STR)),
2367
                $queryBuilder->expr()->neq('uid', $queryBuilder->createPositionalParameter($uid, \PDO::PARAM_INT))
2368
            );
2369
        // ignore translations of current record if field is configured with l10n_mode = "exclude"
2370
        if (($GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode'] ?? '') === 'exclude'
2371
            && ($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? '') !== ''
2372
            && ($GLOBALS['TCA'][$table]['columns'][$field]['languageField'] ?? '') !== '') {
2373
            $queryBuilder
2374
                ->andWhere(
2375
                    $queryBuilder->expr()->orX(
2376
                    // records without l10n_parent must be taken into account (in any language)
2377
                        $queryBuilder->expr()->eq(
2378
                            $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
2379
                            $queryBuilder->createPositionalParameter(0, \PDO::PARAM_INT)
2380
                        ),
2381
                        // translations of other records must be taken into account
2382
                        $queryBuilder->expr()->neq(
2383
                            $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
2384
                            $queryBuilder->createPositionalParameter($uid, \PDO::PARAM_INT)
2385
                        )
2386
                    )
2387
                );
2388
        }
2389
        if ($pid !== 0) {
2390
            $queryBuilder->andWhere(
2391
                $queryBuilder->expr()->eq('pid', $queryBuilder->createPositionalParameter($pid, \PDO::PARAM_INT))
2392
            );
2393
        } else {
2394
            // pid>=0 for versioning
2395
            $queryBuilder->andWhere(
2396
                $queryBuilder->expr()->gte('pid', $queryBuilder->createPositionalParameter(0, \PDO::PARAM_INT))
2397
            );
2398
        }
2399
        return $queryBuilder->execute();
2400
    }
2401
2402
    /**
2403
     * gets all records that have the same value in a field
2404
     * excluding the given uid
2405
     *
2406
     * @param string $tableName Table name
2407
     * @param int $uid UID to filter out in the lookup (the record itself...)
2408
     * @param string $fieldName Field name for which $value must be unique
2409
     * @param string $value Value string.
2410
     * @param int $pageId If set, the value will be unique for this PID
2411
     * @return array
2412
     * @internal should only be used from within DataHandler
2413
     */
2414
    public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0)
2415
    {
2416
        $result = [];
2417
        if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2418
            return $result;
2419
        }
2420
2421
        $uid = (int)$uid;
2422
        $pageId = (int)$pageId;
2423
2424
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
2425
        $queryBuilder->getRestrictions()
2426
            ->removeAll()
2427
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
2428
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->BE_USER->workspace));
2429
2430
        $queryBuilder->select('*')
2431
            ->from($tableName)
2432
            ->where(
2433
                $queryBuilder->expr()->eq(
2434
                    $fieldName,
2435
                    $queryBuilder->createNamedParameter($value, \PDO::PARAM_STR)
2436
                ),
2437
                $queryBuilder->expr()->neq(
2438
                    'uid',
2439
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
2440
                )
2441
            );
2442
2443
        if ($pageId) {
2444
            $queryBuilder->andWhere(
2445
                $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT))
2446
            );
2447
        }
2448
2449
        $result = $queryBuilder->execute()->fetchAll();
2450
2451
        return $result;
2452
    }
2453
2454
    /**
2455
     * @param string $value The field value to be evaluated
2456
     * @param array $evalArray Array of evaluations to traverse.
2457
     * @param string $is_in The "is_in" value of the field configuration from TCA
2458
     * @return array
2459
     * @internal should only be used from within DataHandler
2460
     */
2461
    public function checkValue_text_Eval($value, $evalArray, $is_in)
2462
    {
2463
        $res = [];
2464
        $set = true;
2465
        foreach ($evalArray as $func) {
2466
            switch ($func) {
2467
                case 'trim':
2468
                    $value = trim($value);
2469
                    break;
2470
                case 'required':
2471
                    if (!$value) {
2472
                        $set = false;
2473
                    }
2474
                    break;
2475
                default:
2476
                    if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2477
                        if (class_exists($func)) {
2478
                            $evalObj = GeneralUtility::makeInstance($func);
2479
                            if (method_exists($evalObj, 'evaluateFieldValue')) {
2480
                                $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2481
                            }
2482
                        }
2483
                    }
2484
            }
2485
        }
2486
        if ($set) {
2487
            $res['value'] = $value;
2488
        }
2489
        return $res;
2490
    }
2491
2492
    /**
2493
     * Evaluation of 'input'-type values based on 'eval' list
2494
     *
2495
     * @param string $value Value to evaluate
2496
     * @param array $evalArray Array of evaluations to traverse.
2497
     * @param string $is_in Is-in string for 'is_in' evaluation
2498
     * @param string $table Table name the eval is evaluated on
2499
     * @return array Modified $value in key 'value' or empty array
2500
     * @internal should only be used from within DataHandler
2501
     */
2502
    public function checkValue_input_Eval($value, $evalArray, $is_in, string $table = ''): array
2503
    {
2504
        $res = [];
2505
        $set = true;
2506
        foreach ($evalArray as $func) {
2507
            switch ($func) {
2508
                case 'int':
2509
                case 'year':
2510
                    $value = (int)$value;
2511
                    break;
2512
                case 'time':
2513
                case 'timesec':
2514
                    // If $value is a pure integer we have the number of seconds, we can store that directly
2515
                    if ($value !== '' && !MathUtility::canBeInterpretedAsInteger($value)) {
2516
                        // $value is an ISO 8601 date
2517
                        $value = (new \DateTime($value))->getTimestamp();
2518
                    }
2519
                    break;
2520
                case 'date':
2521
                case 'datetime':
2522
                    // If $value is a pure integer we have the number of seconds, we can store that directly
2523
                    if ($value !== null && $value !== '' && !MathUtility::canBeInterpretedAsInteger($value)) {
2524
                        // The value we receive from JS is an ISO 8601 date, which is always in UTC. (the JS code works like that, on purpose!)
2525
                        // For instance "1999-11-11T11:11:11Z"
2526
                        // Since the user actually specifies the time in the server's local time, we need to mangle this
2527
                        // to reflect the server TZ. So we make this 1999-11-11T11:11:11+0200 (assuming Europe/Vienna here)
2528
                        // In the database we store the date in UTC (1999-11-11T09:11:11Z), hence we take the timestamp of this converted value.
2529
                        // For achieving this we work with timestamps only (which are UTC) and simply adjust it for the
2530
                        // TZ difference.
2531
                        try {
2532
                            // Make the date from JS a timestamp
2533
                            $value = (new \DateTime($value))->getTimestamp();
2534
                        } catch (\Exception $e) {
2535
                            // set the default timezone value to achieve the value of 0 as a result
2536
                            $value = (int)date('Z', 0);
2537
                        }
2538
2539
                        // @todo this hacky part is problematic when it comes to times around DST switch! Add test to prove that this is broken.
2540
                        $value -= date('Z', $value);
2541
                    }
2542
                    break;
2543
                case 'double2':
2544
                    $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2545
                    $negative = $value[0] === '-';
2546
                    $value = strtr($value, [',' => '.', '-' => '']);
2547
                    if (strpos($value, '.') === false) {
2548
                        $value .= '.0';
2549
                    }
2550
                    $valueArray = explode('.', $value);
2551
                    $dec = array_pop($valueArray);
2552
                    $value = implode('', $valueArray) . '.' . $dec;
2553
                    if ($negative) {
2554
                        $value *= -1;
2555
                    }
2556
                    $value = number_format($value, 2, '.', '');
0 ignored issues
show
Bug introduced by
$value of type string is incompatible with the type double expected by parameter $num of number_format(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2556
                    $value = number_format(/** @scrutinizer ignore-type */ $value, 2, '.', '');
Loading history...
2557
                    break;
2558
                case 'md5':
2559
                    if (strlen($value) !== 32) {
2560
                        $set = false;
2561
                    }
2562
                    break;
2563
                case 'trim':
2564
                    $value = trim($value);
2565
                    break;
2566
                case 'upper':
2567
                    $value = mb_strtoupper($value, 'utf-8');
2568
                    break;
2569
                case 'lower':
2570
                    $value = mb_strtolower($value, 'utf-8');
2571
                    break;
2572
                case 'required':
2573
                    if (!isset($value) || $value === '') {
2574
                        $set = false;
2575
                    }
2576
                    break;
2577
                case 'is_in':
2578
                    $c = mb_strlen($value);
2579
                    if ($c) {
2580
                        $newVal = '';
2581
                        for ($a = 0; $a < $c; $a++) {
2582
                            $char = mb_substr($value, $a, 1);
2583
                            if (mb_strpos($is_in, $char) !== false) {
2584
                                $newVal .= $char;
2585
                            }
2586
                        }
2587
                        $value = $newVal;
2588
                    }
2589
                    break;
2590
                case 'nospace':
2591
                    $value = str_replace(' ', '', $value);
2592
                    break;
2593
                case 'alpha':
2594
                    $value = preg_replace('/[^a-zA-Z]/', '', $value);
2595
                    break;
2596
                case 'num':
2597
                    $value = preg_replace('/[^0-9]/', '', $value);
2598
                    break;
2599
                case 'alphanum':
2600
                    $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2601
                    break;
2602
                case 'alphanum_x':
2603
                    $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2604
                    break;
2605
                case 'domainname':
2606
                    if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2607
                        $value = (string)HttpUtility::idn_to_ascii($value);
2608
                    }
2609
                    break;
2610
                case 'email':
2611
                    if ((string)$value !== '') {
2612
                        $this->checkValue_input_ValidateEmail($value, $set);
2613
                    }
2614
                    break;
2615
                case 'saltedPassword':
2616
                    // An incoming value is either the salted password if the user did not change existing password
2617
                    // when submitting the form, or a plaintext new password that needs to be turned into a salted password now.
2618
                    // The strategy is to see if a salt instance can be created from the incoming value. If so,
2619
                    // no new password was submitted and we keep the value. If no salting instance can be created,
2620
                    // incoming value must be a new plain text value that needs to be hashed.
2621
                    $hashFactory = GeneralUtility::makeInstance(PasswordHashFactory::class);
2622
                    $mode = $table === 'fe_users' ? 'FE' : 'BE';
2623
                    try {
2624
                        $hashFactory->get($value, $mode);
2625
                    } catch (InvalidPasswordHashException $e) {
2626
                        // We got no salted password instance, incoming value must be a new plaintext password
2627
                        // Get an instance of the current configured salted password strategy and hash the value
2628
                        $newHashInstance = $hashFactory->getDefaultHashInstance($mode);
2629
                        $value = $newHashInstance->getHashedPassword($value);
2630
                    }
2631
                    break;
2632
                default:
2633
                    if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2634
                        if (class_exists($func)) {
2635
                            $evalObj = GeneralUtility::makeInstance($func);
2636
                            if (method_exists($evalObj, 'evaluateFieldValue')) {
2637
                                $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2638
                            }
2639
                        }
2640
                    }
2641
            }
2642
        }
2643
        if ($set) {
2644
            $res['value'] = $value;
2645
        }
2646
        return $res;
2647
    }
2648
2649
    /**
2650
     * If $value is not a valid e-mail address,
2651
     * $set will be set to false and a flash error
2652
     * message will be added
2653
     *
2654
     * @param string $value Value to evaluate
2655
     * @param bool $set TRUE if an update should be done
2656
     * @throws \InvalidArgumentException
2657
     * @throws \TYPO3\CMS\Core\Exception
2658
     */
2659
    protected function checkValue_input_ValidateEmail($value, &$set)
2660
    {
2661
        if (GeneralUtility::validEmail($value)) {
2662
            return;
2663
        }
2664
2665
        $set = false;
2666
        /** @var FlashMessage $message */
2667
        $message = GeneralUtility::makeInstance(
2668
            FlashMessage::class,
2669
            sprintf($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.invalidEmail'), $value),
2670
            '', // header is optional
2671
            FlashMessage::ERROR,
2672
            true // whether message should be stored in session
2673
        );
2674
        /** @var FlashMessageService $flashMessageService */
2675
        $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
2676
        $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
2677
    }
2678
2679
    /**
2680
     * Returns data for group/db and select fields
2681
     *
2682
     * @param array $valueArray Current value array
2683
     * @param array $tcaFieldConf TCA field config
2684
     * @param int $id Record id, used for look-up of MM relations (local_uid)
2685
     * @param string $status Status string ('update' or 'new')
2686
     * @param string $type The type, either 'select', 'group' or 'inline'
2687
     * @param string $currentTable Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2688
     * @param string $currentField field name, needs to be set for writing to sys_history
2689
     * @return array Modified value array
2690
     * @internal should only be used from within DataHandler
2691
     */
2692
    public function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField)
2693
    {
2694
        $tables = $type === 'group' ? $tcaFieldConf['allowed'] : $tcaFieldConf['foreign_table'];
2695
        $prep = $type === 'group' ? ($tcaFieldConf['prepend_tname'] ?? '') : '';
2696
        $newRelations = implode(',', $valueArray);
2697
        /** @var RelationHandler $dbAnalysis */
2698
        $dbAnalysis = $this->createRelationHandlerInstance();
2699
        $dbAnalysis->registerNonTableValues = !empty($tcaFieldConf['allowNonIdValues']);
2700
        $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2701
        if ($tcaFieldConf['MM'] ?? false) {
2702
            // convert submitted items to use version ids instead of live ids
2703
            // (only required for MM relations in a workspace context)
2704
            $dbAnalysis->convertItemArray();
2705
            if ($status === 'update') {
2706
                /** @var RelationHandler $oldRelations_dbAnalysis */
2707
                $oldRelations_dbAnalysis = $this->createRelationHandlerInstance();
2708
                $oldRelations_dbAnalysis->registerNonTableValues = !empty($tcaFieldConf['allowNonIdValues']);
2709
                // Db analysis with $id will initialize with the existing relations
2710
                $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2711
                $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2712
                $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, $prep);
0 ignored issues
show
Bug introduced by
It seems like $prep can also be of type string; however, parameter $prependTableName of TYPO3\CMS\Core\Database\RelationHandler::writeMM() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2712
                $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, /** @scrutinizer ignore-type */ $prep);
Loading history...
2713
                if ($oldRelations != $newRelations) {
2714
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2715
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2716
                } else {
2717
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2718
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2719
                }
2720
            } else {
2721
                $this->dbAnalysisStore[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable];
2722
            }
2723
            $valueArray = $dbAnalysis->countItems();
2724
        } else {
2725
            $valueArray = $dbAnalysis->getValueArray($prep);
0 ignored issues
show
Bug introduced by
It seems like $prep can also be of type string; however, parameter $prependTableName of TYPO3\CMS\Core\Database\...andler::getValueArray() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2725
            $valueArray = $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prep);
Loading history...
2726
        }
2727
        // Here we should see if 1) the records exist anymore, 2) which are new and check if the BE_USER has read-access to the new ones.
2728
        return $valueArray;
2729
    }
2730
2731
    /**
2732
     * Explodes the $value, which is a list of files/uids (group select)
2733
     *
2734
     * @param string $value Input string, comma separated values. For each part it will also be detected if a '|' is found and the first part will then be used if that is the case. Further the value will be rawurldecoded.
2735
     * @return array The value array.
2736
     * @internal should only be used from within DataHandler
2737
     */
2738
    public function checkValue_group_select_explodeSelectGroupValue($value)
2739
    {
2740
        $valueArray = GeneralUtility::trimExplode(',', $value, true);
2741
        foreach ($valueArray as &$newVal) {
2742
            $temp = explode('|', $newVal, 2);
2743
            $newVal = str_replace(['|', ','], '', rawurldecode($temp[0]));
2744
        }
2745
        unset($newVal);
2746
        return $valueArray;
2747
    }
2748
2749
    /**
2750
     * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2751
     * See checkValue_flex_procInData_travDS() for more details.
2752
     * WARNING: Currently, it traverses based on the actual _data_ array and NOT the _structure_. This means that values for non-valid fields, lKey/vKey/sKeys will be accepted! For traversal of data with a call back function you should rather use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools
2753
     *
2754
     * @param array $dataPart The 'data' part of the INPUT flexform data
2755
     * @param array $dataPart_current The 'data' part of the CURRENT flexform data
2756
     * @param array $uploadedFiles The uploaded files for the 'data' part of the INPUT flexform data
2757
     * @param array $dataStructure Data structure for the form (might be sheets or not). Only values in the data array which has a configuration in the data structure will be processed.
2758
     * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions
2759
     * @param string $callBackFunc Optional call back function, see checkValue_flex_procInData_travDS()  DEPRECATED, use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools instead for traversal!
2760
     * @param array $workspaceOptions
2761
     * @return array The modified 'data' part.
2762
     * @see checkValue_flex_procInData_travDS()
2763
     * @internal should only be used from within DataHandler
2764
     */
2765
    public function checkValue_flex_procInData($dataPart, $dataPart_current, $uploadedFiles, $dataStructure, $pParams, $callBackFunc = '', array $workspaceOptions = [])
2766
    {
2767
        if (is_array($dataPart)) {
0 ignored issues
show
introduced by
The condition is_array($dataPart) is always true.
Loading history...
2768
            foreach ($dataPart as $sKey => $sheetDef) {
2769
                if (isset($dataStructure['sheets'][$sKey]) && is_array($dataStructure['sheets'][$sKey]) && is_array($sheetDef)) {
2770
                    foreach ($sheetDef as $lKey => $lData) {
2771
                        $this->checkValue_flex_procInData_travDS(
2772
                            $dataPart[$sKey][$lKey],
2773
                            $dataPart_current[$sKey][$lKey] ?? null,
2774
                            $uploadedFiles[$sKey][$lKey] ?? null,
2775
                            $dataStructure['sheets'][$sKey]['ROOT']['el'] ?? null,
2776
                            $pParams,
2777
                            $callBackFunc,
2778
                            $sKey . '/' . $lKey . '/',
2779
                            $workspaceOptions
2780
                        );
2781
                    }
2782
                }
2783
            }
2784
        }
2785
        return $dataPart;
2786
    }
2787
2788
    /**
2789
     * Processing of the sheet/language data array
2790
     * When it finds a field with a value the processing is done by ->checkValue_SW() by default but if a call back function name is given that method in this class will be called for the processing instead.
2791
     *
2792
     * @param array $dataValues New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2793
     * @param array $dataValues_current Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2794
     * @param array $uploadedFiles Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2795
     * @param array $DSelements Data structure which fits the data array
2796
     * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions / call back function
2797
     * @param string $callBackFunc Call back function, default is checkValue_SW(). If $this->callBackObj is set to an object, the callback function in that object is called instead.
2798
     * @param string $structurePath
2799
     * @param array $workspaceOptions
2800
     * @see checkValue_flex_procInData()
2801
     * @internal should only be used from within DataHandler
2802
     */
2803
    public function checkValue_flex_procInData_travDS(&$dataValues, $dataValues_current, $uploadedFiles, $DSelements, $pParams, $callBackFunc, $structurePath, array $workspaceOptions = [])
2804
    {
2805
        if (!is_array($DSelements)) {
0 ignored issues
show
introduced by
The condition is_array($DSelements) is always true.
Loading history...
2806
            return;
2807
        }
2808
2809
        // For each DS element:
2810
        foreach ($DSelements as $key => $dsConf) {
2811
            // Array/Section:
2812
            if (isset($DSelements[$key]['type']) && $DSelements[$key]['type'] === 'array') {
2813
                if (!is_array($dataValues[$key]['el'])) {
2814
                    continue;
2815
                }
2816
2817
                if ($DSelements[$key]['section']) {
2818
                    foreach ($dataValues[$key]['el'] as $ik => $el) {
2819
                        if (!is_array($el)) {
2820
                            continue;
2821
                        }
2822
2823
                        if (!is_array($dataValues_current[$key]['el'])) {
2824
                            $dataValues_current[$key]['el'] = [];
2825
                        }
2826
                        $theKey = key($el);
2827
                        if (!is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2828
                            continue;
2829
                        }
2830
2831
                        $this->checkValue_flex_procInData_travDS($dataValues[$key]['el'][$ik][$theKey]['el'], is_array($dataValues_current[$key]['el'][$ik]) ? $dataValues_current[$key]['el'][$ik][$theKey]['el'] : [], $uploadedFiles[$key]['el'][$ik][$theKey]['el'], $DSelements[$key]['el'][$theKey]['el'], $pParams, $callBackFunc, $structurePath . $key . '/el/' . $ik . '/' . $theKey . '/el/', $workspaceOptions);
2832
                    }
2833
                } else {
2834
                    if (!isset($dataValues[$key]['el'])) {
2835
                        $dataValues[$key]['el'] = [];
2836
                    }
2837
                    $this->checkValue_flex_procInData_travDS($dataValues[$key]['el'], $dataValues_current[$key]['el'], $uploadedFiles[$key]['el'], $DSelements[$key]['el'], $pParams, $callBackFunc, $structurePath . $key . '/el/', $workspaceOptions);
2838
                }
2839
            } else {
2840
                // When having no specific sheets, it's "TCEforms.config", when having a sheet, it's just "config"
2841
                $fieldConfiguration = $dsConf['TCEforms']['config'] ?? $dsConf['config'] ?? null;
2842
                // init with value from config for passthrough fields
2843
                if (!empty($fieldConfiguration['type']) && $fieldConfiguration['type'] === 'passthrough') {
2844
                    if (!empty($dataValues_current[$key]['vDEF'])) {
2845
                        // If there is existing value, keep it
2846
                        $dataValues[$key]['vDEF'] = $dataValues_current[$key]['vDEF'];
2847
                    } elseif (
2848
                        !empty($fieldConfiguration['default'])
2849
                        && isset($pParams[1])
2850
                        && !MathUtility::canBeInterpretedAsInteger($pParams[1])
2851
                    ) {
2852
                        // If is new record and a default is specified for field, use it.
2853
                        $dataValues[$key]['vDEF'] = $fieldConfiguration['default'];
2854
                    }
2855
                }
2856
                if (!is_array($fieldConfiguration) || !isset($dataValues[$key]) || !is_array($dataValues[$key])) {
2857
                    continue;
2858
                }
2859
2860
                foreach ($dataValues[$key] as $vKey => $data) {
2861
                    if ($callBackFunc) {
2862
                        if (is_object($this->callBackObj)) {
2863
                            $res = $this->callBackObj->{$callBackFunc}($pParams, $fieldConfiguration, $dataValues[$key][$vKey], $dataValues_current[$key][$vKey], $uploadedFiles[$key][$vKey], $structurePath . $key . '/' . $vKey . '/', $workspaceOptions);
2864
                        } else {
2865
                            $res = $this->{$callBackFunc}(
2866
                                $pParams,
2867
                                $fieldConfiguration,
2868
                                $dataValues[$key][$vKey] ?? null,
2869
                                $dataValues_current[$key][$vKey] ?? null,
2870
                                $uploadedFiles[$key][$vKey] ?? null,
2871
                                $structurePath . $key . '/' . $vKey . '/',
2872
                                $workspaceOptions
2873
                            );
2874
                        }
2875
                    } else {
2876
                        // Default
2877
                        [$CVtable, $CVid, $CVcurValue, $CVstatus, $CVrealPid, $CVrecFID, $CVtscPID] = $pParams;
2878
2879
                        $additionalData = [
2880
                            'flexFormId' => $CVrecFID,
2881
                            'flexFormPath' => trim(rtrim($structurePath, '/') . '/' . $key . '/' . $vKey, '/'),
2882
                        ];
2883
2884
                        $res = $this->checkValue_SW(
2885
                            [],
2886
                            $dataValues[$key][$vKey] ?? null,
2887
                            $fieldConfiguration,
2888
                            $CVtable,
2889
                            $CVid,
2890
                            $dataValues_current[$key][$vKey] ?? null,
2891
                            $CVstatus,
2892
                            $CVrealPid,
2893
                            $CVrecFID,
2894
                            '',
2895
                            $uploadedFiles[$key][$vKey] ?? null,
2896
                            $CVtscPID,
2897
                            $additionalData
2898
                        );
2899
                    }
2900
                    // Adding the value:
2901
                    if (isset($res['value'])) {
2902
                        $dataValues[$key][$vKey] = $res['value'];
2903
                    }
2904
                    // Finally, check if new and old values are different (or no .vDEFbase value is found) and if so, we record the vDEF value for diff'ing.
2905
                    // We do this after $dataValues has been updated since I expect that $dataValues_current holds evaluated values from database (so this must be the right value to compare with).
2906
                    if (mb_substr($vKey, -9) !== '.vDEFbase') {
2907
                        if (($GLOBALS['TYPO3_CONF_VARS']['BE']['flexFormXMLincludeDiffBase'] ?? false)
2908
                            && $vKey !== 'vDEF'
2909
                            && ((string)$dataValues[$key][$vKey] !== (string)$dataValues_current[$key][$vKey] || !isset($dataValues_current[$key][$vKey . '.vDEFbase']))
2910
                        ) {
2911
                            // Now, check if a vDEF value is submitted in the input data, if so we expect this has been processed prior to this operation (normally the case since those fields are higher in the form) and we can use that:
2912
                            if (isset($dataValues[$key]['vDEF'])) {
2913
                                $diffValue = $dataValues[$key]['vDEF'];
2914
                            } else {
2915
                                // If not found (for translators with no access to the default language) we use the one from the current-value data set:
2916
                                $diffValue = $dataValues_current[$key]['vDEF'];
2917
                            }
2918
                            // Setting the reference value for vDEF for this translation. This will be used for translation tools to make a diff between the vDEF and vDEFbase to see if an update would be fitting.
2919
                            $dataValues[$key][$vKey . '.vDEFbase'] = $diffValue;
2920
                        }
2921
                    }
2922
                }
2923
            }
2924
        }
2925
    }
2926
2927
    /**
2928
     * Returns data for inline fields.
2929
     *
2930
     * @param array $valueArray Current value array
2931
     * @param array $tcaFieldConf TCA field config
2932
     * @param int $id Record id
2933
     * @param string $status Status string ('update' or 'new')
2934
     * @param string $table Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2935
     * @param string $field The current field the values are modified for
2936
     * @return string Modified values
2937
     */
2938
    protected function checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field)
2939
    {
2940
        $foreignTable = $tcaFieldConf['foreign_table'];
2941
        $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
2942
        // Fetch the related child records using \TYPO3\CMS\Core\Database\RelationHandler
2943
        /** @var RelationHandler $dbAnalysis */
2944
        $dbAnalysis = $this->createRelationHandlerInstance();
2945
        $dbAnalysis->start(implode(',', $valueArray), $foreignTable, '', 0, $table, $tcaFieldConf);
2946
        // IRRE with a pointer field (database normalization):
2947
        if ($tcaFieldConf['foreign_field'] ?? false) {
2948
            // if the record was imported, sorting was also imported, so skip this
2949
            $skipSorting = (bool)$this->callFromImpExp;
2950
            // update record in intermediate table (sorting & pointer uid to parent record)
2951
            $dbAnalysis->writeForeignField($tcaFieldConf, $id, 0, $skipSorting);
2952
            $newValue = $dbAnalysis->countItems(false);
2953
        } elseif ($this->getInlineFieldType($tcaFieldConf) === 'mm') {
2954
            // In order to fully support all the MM stuff, directly call checkValue_group_select_processDBdata instead of repeating the needed code here
2955
            $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
2956
            $newValue = $valueArray[0];
2957
        } else {
2958
            $valueArray = $dbAnalysis->getValueArray();
2959
            // Checking that the number of items is correct:
2960
            $valueArray = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2961
            $newValue = $this->castReferenceValue(implode(',', $valueArray), $tcaFieldConf);
2962
        }
2963
        return $newValue;
2964
    }
2965
2966
    /*********************************************
2967
     *
2968
     * PROCESSING COMMANDS
2969
     *
2970
     ********************************************/
2971
    /**
2972
     * Processing the cmd-array
2973
     * See "TYPO3 Core API" for a description of the options.
2974
     *
2975
     * @return void|bool
2976
     */
2977
    public function process_cmdmap()
2978
    {
2979
        // Editing frozen:
2980
        if ($this->BE_USER->workspace !== 0 && ($this->BE_USER->workspaceRec['freeze'] ?? false)) {
2981
            $this->newlog('All editing in this workspace has been frozen!', SystemLogErrorClassification::USER_ERROR);
2982
            return false;
2983
        }
2984
        // Hook initialization:
2985
        $hookObjectsArr = [];
2986
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
2987
            $hookObj = GeneralUtility::makeInstance($className);
2988
            if (method_exists($hookObj, 'processCmdmap_beforeStart')) {
2989
                $hookObj->processCmdmap_beforeStart($this);
2990
            }
2991
            $hookObjectsArr[] = $hookObj;
2992
        }
2993
        $pasteDatamap = [];
2994
        // Traverse command map:
2995
        foreach ($this->cmdmap as $table => $_) {
2996
            // Check if the table may be modified!
2997
            $modifyAccessList = $this->checkModifyAccessList($table);
2998
            if (!$modifyAccessList) {
2999
                $this->log($table, 0, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
3000
            }
3001
            // Check basic permissions and circumstances:
3002
            if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->cmdmap[$table]) || !$modifyAccessList) {
3003
                continue;
3004
            }
3005
3006
            // Traverse the command map:
3007
            foreach ($this->cmdmap[$table] as $id => $incomingCmdArray) {
3008
                if (!is_array($incomingCmdArray)) {
3009
                    continue;
3010
                }
3011
3012
                if ($table === 'pages') {
3013
                    // for commands on pages do a pagetree-refresh
3014
                    $this->pagetreeNeedsRefresh = true;
3015
                }
3016
3017
                foreach ($incomingCmdArray as $command => $value) {
3018
                    $pasteUpdate = false;
3019
                    if (is_array($value) && isset($value['action']) && $value['action'] === 'paste') {
3020
                        // Extended paste command: $command is set to "move" or "copy"
3021
                        // $value['update'] holds field/value pairs which should be updated after copy/move operation
3022
                        // $value['target'] holds original $value (target of move/copy)
3023
                        $pasteUpdate = $value['update'];
3024
                        $value = $value['target'];
3025
                    }
3026
                    foreach ($hookObjectsArr as $hookObj) {
3027
                        if (method_exists($hookObj, 'processCmdmap_preProcess')) {
3028
                            $hookObj->processCmdmap_preProcess($command, $table, $id, $value, $this, $pasteUpdate);
3029
                        }
3030
                    }
3031
                    // Init copyMapping array:
3032
                    // Must clear this array before call from here to those functions:
3033
                    // Contains mapping information between new and old id numbers.
3034
                    $this->copyMappingArray = [];
3035
                    // process the command
3036
                    $commandIsProcessed = false;
3037
                    foreach ($hookObjectsArr as $hookObj) {
3038
                        if (method_exists($hookObj, 'processCmdmap')) {
3039
                            $hookObj->processCmdmap($command, $table, $id, $value, $commandIsProcessed, $this, $pasteUpdate);
3040
                        }
3041
                    }
3042
                    // Only execute default commands if a hook hasn't been processed the command already
3043
                    if (!$commandIsProcessed) {
3044
                        $procId = $id;
3045
                        $backupUseTransOrigPointerField = $this->useTransOrigPointerField;
3046
                        // Branch, based on command
3047
                        switch ($command) {
3048
                            case 'move':
3049
                                $this->moveRecord($table, (int)$id, $value);
3050
                                break;
3051
                            case 'copy':
3052
                                $target = $value['target'] ?? $value;
3053
                                $ignoreLocalization = (bool)($value['ignoreLocalization'] ?? false);
3054
                                if ($table === 'pages') {
3055
                                    $this->copyPages((int)$id, $target);
3056
                                } else {
3057
                                    $this->copyRecord($table, (int)$id, $target, true, [], '', 0, $ignoreLocalization);
3058
                                }
3059
                                $procId = $this->copyMappingArray[$table][$id];
3060
                                break;
3061
                            case 'localize':
3062
                                $this->useTransOrigPointerField = true;
3063
                                $this->localize($table, (int)$id, $value);
3064
                                break;
3065
                            case 'copyToLanguage':
3066
                                $this->useTransOrigPointerField = false;
3067
                                $this->localize($table, (int)$id, $value);
3068
                                break;
3069
                            case 'inlineLocalizeSynchronize':
3070
                                $this->inlineLocalizeSynchronize($table, (int)$id, $value);
3071
                                break;
3072
                            case 'delete':
3073
                                $this->deleteAction($table, (int)$id);
3074
                                break;
3075
                            case 'undelete':
3076
                                $this->undeleteRecord((string)$table, (int)$id);
3077
                                break;
3078
                        }
3079
                        $this->useTransOrigPointerField = $backupUseTransOrigPointerField;
3080
                        if (is_array($pasteUpdate)) {
3081
                            $pasteDatamap[$table][$procId] = $pasteUpdate;
3082
                        }
3083
                    }
3084
                    foreach ($hookObjectsArr as $hookObj) {
3085
                        if (method_exists($hookObj, 'processCmdmap_postProcess')) {
3086
                            $hookObj->processCmdmap_postProcess($command, $table, $id, $value, $this, $pasteUpdate, $pasteDatamap);
3087
                        }
3088
                    }
3089
                    // Merging the copy-array info together for remapping purposes.
3090
                    ArrayUtility::mergeRecursiveWithOverrule($this->copyMappingArray_merged, $this->copyMappingArray);
3091
                }
3092
            }
3093
        }
3094
        /** @var DataHandler $copyTCE */
3095
        $copyTCE = $this->getLocalTCE();
3096
        $copyTCE->start($pasteDatamap, [], $this->BE_USER);
3097
        $copyTCE->process_datamap();
3098
        $this->errorLog = array_merge($this->errorLog, $copyTCE->errorLog);
3099
        unset($copyTCE);
3100
3101
        // Finally, before exit, check if there are ID references to remap.
3102
        // This might be the case if versioning or copying has taken place!
3103
        $this->remapListedDBRecords();
3104
        $this->processRemapStack();
3105
        foreach ($hookObjectsArr as $hookObj) {
3106
            if (method_exists($hookObj, 'processCmdmap_afterFinish')) {
3107
                $hookObj->processCmdmap_afterFinish($this);
3108
            }
3109
        }
3110
        if ($this->isOuterMostInstance()) {
3111
            $this->referenceIndexUpdater->update();
3112
            $this->processClearCacheQueue();
3113
            $this->resetNestedElementCalls();
3114
        }
3115
    }
3116
3117
    /*********************************************
3118
     *
3119
     * Cmd: Copying
3120
     *
3121
     ********************************************/
3122
    /**
3123
     * Copying a single record
3124
     *
3125
     * @param string $table Element table
3126
     * @param int $uid Element UID
3127
     * @param int $destPid >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
3128
     * @param bool $first Is a flag set, if the record copied is NOT a 'slave' to another record copied. That is, if this record was asked to be copied in the cmd-array
3129
     * @param array $overrideValues Associative array with field/value pairs to override directly. Notice; Fields must exist in the table record and NOT be among excluded fields!
3130
     * @param string $excludeFields Commalist of fields to exclude from the copy process (might get default values)
3131
     * @param int $language Language ID (from sys_language table)
3132
     * @param bool $ignoreLocalization If TRUE, any localization routine is skipped
3133
     * @return int|null ID of new record, if any
3134
     * @internal should only be used from within DataHandler
3135
     */
3136
    public function copyRecord($table, $uid, $destPid, $first = false, $overrideValues = [], $excludeFields = '', $language = 0, $ignoreLocalization = false)
3137
    {
3138
        $uid = ($origUid = (int)$uid);
3139
        // Only copy if the table is defined in $GLOBALS['TCA'], a uid is given and the record wasn't copied before:
3140
        if (empty($GLOBALS['TCA'][$table]) || $uid === 0) {
3141
            return null;
3142
        }
3143
        if ($this->isRecordCopied($table, $uid)) {
3144
            return null;
3145
        }
3146
3147
        // Fetch record with permission check
3148
        $row = $this->recordInfoWithPermissionCheck($table, $uid, Permission::PAGE_SHOW);
3149
3150
        // This checks if the record can be selected which is all that a copy action requires.
3151
        if ($row === false) {
3152
            $this->log($table, $uid, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to copy record "%s:%s" which does not exist or you do not have permission to read', -1, [$table, $uid]);
3153
            return null;
3154
        }
3155
3156
        // NOT using \TYPO3\CMS\Backend\Utility\BackendUtility::getTSCpid() because we need the real pid - not the ID of a page, if the input is a page...
3157
        $tscPID = (int)BackendUtility::getTSconfig_pidValue($table, $uid, $destPid);
3158
3159
        // Check if table is allowed on destination page
3160
        if (!$this->isTableAllowedForThisPage($tscPID, $table)) {
3161
            $this->log($table, $uid, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to insert record "%s:%s" on a page (%s) that can\'t store record type.', -1, [$table, $uid, $tscPID]);
3162
            return null;
3163
        }
3164
3165
        $fullLanguageCheckNeeded = $table !== 'pages';
3166
        // Used to check language and general editing rights
3167
        if (!$ignoreLocalization && ($language <= 0 || !$this->BE_USER->checkLanguageAccess($language)) && !$this->BE_USER->recordEditAccessInternals($table, $uid, false, false, $fullLanguageCheckNeeded)) {
3168
            $this->log($table, $uid, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to copy record "%s:%s" without having permissions to do so. [' . $this->BE_USER->errorMsg . '].', -1, [$table, $uid]);
3169
            return null;
3170
        }
3171
3172
        $data = [];
3173
        $nonFields = array_unique(GeneralUtility::trimExplode(',', 'uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_stage,' . $excludeFields, true));
3174
        BackendUtility::workspaceOL($table, $row, $this->BE_USER->workspace);
3175
        $row = BackendUtility::purgeComputedPropertiesFromRecord($row);
3176
3177
        // Initializing:
3178
        $theNewID = StringUtility::getUniqueId('NEW');
3179
        $enableField = isset($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']) ? $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'] : '';
3180
        $headerField = $GLOBALS['TCA'][$table]['ctrl']['label'];
3181
        // Getting "copy-after" fields if applicable:
3182
        $copyAfterFields = $destPid < 0 ? $this->fixCopyAfterDuplFields($table, $uid, abs($destPid), false) : [];
0 ignored issues
show
Bug introduced by
It seems like abs($destPid) can also be of type double; however, parameter $prevUid of TYPO3\CMS\Core\DataHandl...ixCopyAfterDuplFields() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3182
        $copyAfterFields = $destPid < 0 ? $this->fixCopyAfterDuplFields($table, $uid, /** @scrutinizer ignore-type */ abs($destPid), false) : [];
Loading history...
3183
        // Page TSconfig related:
3184
        $TSConfig = BackendUtility::getPagesTSconfig($tscPID)['TCEMAIN.'] ?? [];
3185
        $tE = $this->getTableEntries($table, $TSConfig);
3186
        // Traverse ALL fields of the selected record:
3187
        foreach ($row as $field => $value) {
3188
            if (!in_array($field, $nonFields, true)) {
3189
                // Get TCA configuration for the field:
3190
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'] ?? [];
3191
                // Preparation/Processing of the value:
3192
                // "pid" is hardcoded of course:
3193
                // isset() won't work here, since values can be NULL in each of the arrays
3194
                // except setDefaultOnCopyArray, since we exploded that from a string
3195
                if ($field === 'pid') {
3196
                    $value = $destPid;
3197
                } elseif (array_key_exists($field, $overrideValues)) {
3198
                    // Override value...
3199
                    $value = $overrideValues[$field];
3200
                } elseif (array_key_exists($field, $copyAfterFields)) {
3201
                    // Copy-after value if available:
3202
                    $value = $copyAfterFields[$field];
3203
                } else {
3204
                    // Hide at copy may override:
3205
                    if ($first && $field == $enableField
3206
                        && ($GLOBALS['TCA'][$table]['ctrl']['hideAtCopy'] ?? false)
3207
                        && !$this->neverHideAtCopy
3208
                        && !($tE['disableHideAtCopy'] ?? false)
3209
                    ) {
3210
                        $value = 1;
3211
                    }
3212
                    // Prepend label on copy:
3213
                    if ($first && $field == $headerField
3214
                        && ($GLOBALS['TCA'][$table]['ctrl']['prependAtCopy'] ?? false)
3215
                        && !($tE['disablePrependAtCopy'] ?? false)
3216
                    ) {
3217
                        $value = $this->getCopyHeader($table, $this->resolvePid($table, $destPid), $field, $this->clearPrefixFromValue($table, $value), 0);
3218
                    }
3219
                    // Processing based on the TCA config field type (files, references, flexforms...)
3220
                    $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $tscPID, $language);
3221
                }
3222
                // Add value to array.
3223
                $data[$table][$theNewID][$field] = $value;
3224
            }
3225
        }
3226
        // Overriding values:
3227
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock'] ?? false) {
3228
            $data[$table][$theNewID][$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
3229
        }
3230
        // Setting original UID:
3231
        if ($GLOBALS['TCA'][$table]['ctrl']['origUid'] ?? false) {
3232
            $data[$table][$theNewID][$GLOBALS['TCA'][$table]['ctrl']['origUid']] = $uid;
3233
        }
3234
        // Do the copy by simply submitting the array through DataHandler:
3235
        /** @var DataHandler $copyTCE */
3236
        $copyTCE = $this->getLocalTCE();
3237
        $copyTCE->start($data, [], $this->BE_USER);
3238
        $copyTCE->process_datamap();
3239
        // Getting the new UID:
3240
        $theNewSQLID = $copyTCE->substNEWwithIDs[$theNewID];
3241
        if ($theNewSQLID) {
3242
            $this->copyMappingArray[$table][$origUid] = $theNewSQLID;
3243
            // Keep automatically versionized record information:
3244
            if (isset($copyTCE->autoVersionIdMap[$table][$theNewSQLID])) {
3245
                $this->autoVersionIdMap[$table][$theNewSQLID] = $copyTCE->autoVersionIdMap[$table][$theNewSQLID];
3246
            }
3247
        }
3248
        $this->errorLog = array_merge($this->errorLog, $copyTCE->errorLog);
3249
        unset($copyTCE);
3250
        if (!$ignoreLocalization && $language == 0) {
3251
            //repointing the new translation records to the parent record we just created
3252
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $theNewSQLID;
3253
            if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
3254
                $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['translationSource']] = 0;
3255
            }
3256
            $this->copyL10nOverlayRecords($table, $uid, $destPid, $first, $overrideValues, $excludeFields);
3257
        }
3258
3259
        return $theNewSQLID;
3260
    }
3261
3262
    /**
3263
     * Copying pages
3264
     * Main function for copying pages.
3265
     *
3266
     * @param int $uid Page UID to copy
3267
     * @param int $destPid Destination PID: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
3268
     * @internal should only be used from within DataHandler
3269
     */
3270
    public function copyPages($uid, $destPid)
3271
    {
3272
        // Initialize:
3273
        $uid = (int)$uid;
3274
        $destPid = (int)$destPid;
3275
3276
        $copyTablesAlongWithPage = $this->getAllowedTablesToCopyWhenCopyingAPage();
3277
        // Begin to copy pages if we're allowed to:
3278
        if ($this->admin || in_array('pages', $copyTablesAlongWithPage, true)) {
3279
            // Copy this page we're on. And set first-flag (this will trigger that the record is hidden if that is configured)
3280
            // This method also copies the localizations of a page
3281
            $theNewRootID = $this->copySpecificPage($uid, $destPid, $copyTablesAlongWithPage, true);
3282
            // If we're going to copy recursively
3283
            if ($theNewRootID && $this->copyTree) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $theNewRootID of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
3284
                // Get ALL subpages to copy (read-permissions are respected!):
3285
                $CPtable = $this->int_pageTreeInfo([], $uid, (int)$this->copyTree, $theNewRootID);
3286
                // Now copying the subpages:
3287
                foreach ($CPtable as $thePageUid => $thePagePid) {
3288
                    $newPid = $this->copyMappingArray['pages'][$thePagePid];
3289
                    if (isset($newPid)) {
3290
                        $this->copySpecificPage($thePageUid, $newPid, $copyTablesAlongWithPage);
3291
                    } else {
3292
                        $this->log('pages', $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'Something went wrong during copying branch');
3293
                        break;
3294
                    }
3295
                }
3296
            }
3297
        } else {
3298
            $this->log('pages', $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to copy page without permission to this table');
3299
        }
3300
    }
3301
3302
    /**
3303
     * Compile a list of tables that should be copied along when a page is about to be copied.
3304
     *
3305
     * First, get the list that the user is allowed to modify (all if admin),
3306
     * and then check against a possible limitation within "DataHandler->copyWhichTables" if not set to "*"
3307
     * to limit the list further down
3308
     *
3309
     * @return array
3310
     */
3311
    protected function getAllowedTablesToCopyWhenCopyingAPage(): array
3312
    {
3313
        // Finding list of tables to copy.
3314
        // These are the tables, the user may modify
3315
        $copyTablesArray = $this->admin ? $this->compileAdminTables() : explode(',', $this->BE_USER->groupData['tables_modify']);
3316
        // If not all tables are allowed then make a list of allowed tables.
3317
        // That is the tables that figure in both allowed tables AND the copyTable-list
3318
        if (strpos($this->copyWhichTables, '*') === false) {
3319
            $definedTablesToCopy = GeneralUtility::trimExplode(',', $this->copyWhichTables, true);
3320
            // Pages are always allowed
3321
            $definedTablesToCopy[] = 'pages';
3322
            $definedTablesToCopy = array_flip($definedTablesToCopy);
3323
            foreach ($copyTablesArray as $k => $table) {
3324
                if (!$table || !isset($definedTablesToCopy[$table])) {
3325
                    unset($copyTablesArray[$k]);
3326
                }
3327
            }
3328
        }
3329
        $copyTablesArray = array_unique($copyTablesArray);
3330
        return $copyTablesArray;
3331
    }
3332
    /**
3333
     * Copying a single page ($uid) to $destPid and all tables in the array copyTablesArray.
3334
     *
3335
     * @param int $uid Page uid
3336
     * @param int $destPid Destination PID: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
3337
     * @param array $copyTablesArray Table on pages to copy along with the page.
3338
     * @param bool $first Is a flag set, if the record copied is NOT a 'slave' to another record copied. That is, if this record was asked to be copied in the cmd-array
3339
     * @return int|null The id of the new page, if applicable.
3340
     * @internal should only be used from within DataHandler
3341
     */
3342
    public function copySpecificPage($uid, $destPid, $copyTablesArray, $first = false)
3343
    {
3344
        // Copy the page itself:
3345
        $theNewRootID = $this->copyRecord('pages', $uid, $destPid, $first);
3346
        $currentWorkspaceId = (int)$this->BE_USER->workspace;
3347
        // If a new page was created upon the copy operation we will proceed with all the tables ON that page:
3348
        if ($theNewRootID) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $theNewRootID of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
3349
            foreach ($copyTablesArray as $table) {
3350
                // All records under the page is copied.
3351
                if ($table && is_array($GLOBALS['TCA'][$table]) && $table !== 'pages') {
3352
                    $fields = ['uid'];
3353
                    $languageField = null;
3354
                    $transOrigPointerField = null;
3355
                    $translationSourceField = null;
3356
                    if (BackendUtility::isTableLocalizable($table)) {
3357
                        $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
3358
                        $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
3359
                        $fields[] = $languageField;
3360
                        $fields[] = $transOrigPointerField;
3361
                        if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
3362
                            $translationSourceField = $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
3363
                            $fields[] = $translationSourceField;
3364
                        }
3365
                    }
3366
                    $isTableWorkspaceEnabled = BackendUtility::isTableWorkspaceEnabled($table);
3367
                    if ($isTableWorkspaceEnabled) {
3368
                        $fields[] = 't3ver_oid';
3369
                        $fields[] = 't3ver_state';
3370
                        $fields[] = 't3ver_wsid';
3371
                    }
3372
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3373
                    $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
3374
                    $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $currentWorkspaceId));
3375
                    $queryBuilder
3376
                        ->select(...$fields)
3377
                        ->from($table)
3378
                        ->where(
3379
                            $queryBuilder->expr()->eq(
3380
                                'pid',
3381
                                $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
3382
                            )
3383
                        );
3384
                    if (!empty($GLOBALS['TCA'][$table]['ctrl']['sortby'])) {
3385
                        $queryBuilder->orderBy($GLOBALS['TCA'][$table]['ctrl']['sortby'], 'DESC');
3386
                    }
3387
                    $queryBuilder->addOrderBy('uid');
3388
                    try {
3389
                        $result = $queryBuilder->execute();
3390
                        $rows = [];
3391
                        $movedLiveIds = [];
3392
                        $movedLiveRecords = [];
3393
                        while ($row = $result->fetch()) {
3394
                            if ($isTableWorkspaceEnabled && (int)$row['t3ver_state'] === VersionState::MOVE_POINTER) {
3395
                                $movedLiveIds[(int)$row['t3ver_oid']] = (int)$row['uid'];
3396
                            }
3397
                            $rows[(int)$row['uid']] = $row;
3398
                        }
3399
                        // Resolve placeholders of workspace versions
3400
                        if (!empty($rows) && $currentWorkspaceId > 0 && $isTableWorkspaceEnabled) {
3401
                            // If a record was moved within the page, the PlainDataResolver needs the moved record
3402
                            // but not the original live version, otherwise the moved record is not considered at all.
3403
                            // For this reason, we find the live ids, where there was also a moved record in the SQL
3404
                            // query above in $movedLiveIds and now we removed them before handing them over to PlainDataResolver.
3405
                            // see changeContentSortingAndCopyDraftPage test
3406
                            foreach ($movedLiveIds as $liveId => $movePlaceHolderId) {
3407
                                if (isset($rows[$liveId])) {
3408
                                    $movedLiveRecords[$movePlaceHolderId] = $rows[$liveId];
3409
                                    unset($rows[$liveId]);
3410
                                }
3411
                            }
3412
                            $rows = array_reverse(
3413
                                $this->resolveVersionedRecords(
3414
                                    $table,
3415
                                    implode(',', $fields),
3416
                                    $GLOBALS['TCA'][$table]['ctrl']['sortby'],
3417
                                    array_keys($rows)
3418
                                ),
3419
                                true
3420
                            );
3421
                            foreach ($movedLiveRecords as $movePlaceHolderId => $liveRecord) {
3422
                                $rows[$movePlaceHolderId] = $liveRecord;
3423
                            }
3424
                        }
3425
                        if (is_array($rows)) {
3426
                            $languageSourceMap = [];
3427
                            $overrideValues = $translationSourceField ? [$translationSourceField => 0] : [];
3428
                            $doRemap = false;
3429
                            foreach ($rows as $row) {
3430
                                // Skip localized records that will be processed in
3431
                                // copyL10nOverlayRecords() on copying the default language record
3432
                                $transOrigPointer = $row[$transOrigPointerField] ?? 0;
3433
                                if (!empty($languageField)
3434
                                    && $row[$languageField] > 0
3435
                                    && $transOrigPointer > 0
3436
                                    && (isset($rows[$transOrigPointer]) || isset($movedLiveIds[$transOrigPointer]))
3437
                                ) {
3438
                                    continue;
3439
                                }
3440
                                // Copying each of the underlying records...
3441
                                $newUid = $this->copyRecord($table, $row['uid'], $theNewRootID, false, $overrideValues);
3442
                                if ($translationSourceField) {
3443
                                    $languageSourceMap[$row['uid']] = $newUid;
3444
                                    if ($row[$languageField] > 0) {
3445
                                        $doRemap = true;
3446
                                    }
3447
                                }
3448
                            }
3449
                            if ($doRemap) {
3450
                                //remap is needed for records in non-default language records in the "free mode"
3451
                                $this->copy_remapTranslationSourceField($table, $rows, $languageSourceMap);
3452
                            }
3453
                        }
3454
                    } catch (DBALException $e) {
3455
                        $databaseErrorMessage = $e->getPrevious()->getMessage();
3456
                        $this->log($table, $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'An SQL error occurred: ' . $databaseErrorMessage);
3457
                    }
3458
                }
3459
            }
3460
            $this->processRemapStack();
3461
            return $theNewRootID;
3462
        }
3463
        return null;
3464
    }
3465
3466
    /**
3467
     * Copying records, but makes a "raw" copy of a record.
3468
     * Basically the only thing observed is field processing like the copying of files and correction of ids. All other fields are 1-1 copied.
3469
     * Technically the copy is made with THIS instance of the DataHandler class contrary to copyRecord() which creates a new instance and uses the processData() function.
3470
     * The copy is created by insertNewCopyVersion() which bypasses most of the regular input checking associated with processData() - maybe copyRecord() should even do this as well!?
3471
     * This function is used to create new versions of a record.
3472
     * NOTICE: DOES NOT CHECK PERMISSIONS to create! And since page permissions are just passed through and not changed to the user who executes the copy we cannot enforce permissions without getting an incomplete copy - unless we change permissions of course.
3473
     *
3474
     * @param string $table Element table
3475
     * @param int $uid Element UID
3476
     * @param int $pid Element PID (real PID, not checked)
3477
     * @param array $overrideArray Override array - must NOT contain any fields not in the table!
3478
     * @param array $workspaceOptions Options to be forwarded if actions happen on a workspace currently
3479
     * @return int Returns the new ID of the record (if applicable)
3480
     * @internal should only be used from within DataHandler
3481
     */
3482
    public function copyRecord_raw($table, $uid, $pid, $overrideArray = [], array $workspaceOptions = [])
3483
    {
3484
        $uid = (int)$uid;
3485
        // Stop any actions if the record is marked to be deleted:
3486
        // (this can occur if IRRE elements are versionized and child elements are removed)
3487
        if ($this->isElementToBeDeleted($table, $uid)) {
3488
            return null;
3489
        }
3490
        // Only copy if the table is defined in TCA, a uid is given and the record wasn't copied before:
3491
        if (!$GLOBALS['TCA'][$table] || !$uid || $this->isRecordCopied($table, $uid)) {
3492
            return null;
3493
        }
3494
3495
        // Fetch record with permission check
3496
        $row = $this->recordInfoWithPermissionCheck($table, $uid, Permission::PAGE_SHOW);
3497
3498
        // This checks if the record can be selected which is all that a copy action requires.
3499
        if ($row === false) {
3500
            $this->log(
3501
                $table,
3502
                $uid,
3503
                SystemLogDatabaseAction::DELETE,
3504
                0,
3505
                SystemLogErrorClassification::USER_ERROR,
3506
                'Attempt to rawcopy/versionize record which either does not exist or you don\'t have permission to read'
3507
            );
3508
            return null;
3509
        }
3510
3511
        // Set up fields which should not be processed. They are still written - just passed through no-questions-asked!
3512
        $nonFields = ['uid', 'pid', 't3ver_oid', 't3ver_wsid', 't3ver_state', 't3ver_stage', 'perms_userid', 'perms_groupid', 'perms_user', 'perms_group', 'perms_everybody'];
3513
3514
        // Merge in override array.
3515
        $row = array_merge($row, $overrideArray);
3516
        // Traverse ALL fields of the selected record:
3517
        foreach ($row as $field => $value) {
3518
            /** @var string $field */
3519
            if (!in_array($field, $nonFields, true)) {
3520
                // Get TCA configuration for the field:
3521
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'] ?? false;
3522
                if (is_array($conf)) {
3523
                    // Processing based on the TCA config field type (files, references, flexforms...)
3524
                    $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $pid, 0, $workspaceOptions);
3525
                }
3526
                // Add value to array.
3527
                $row[$field] = $value;
3528
            }
3529
        }
3530
        $row['pid'] = $pid;
3531
        // Setting original UID:
3532
        if ($GLOBALS['TCA'][$table]['ctrl']['origUid'] ?? '') {
3533
            $row[$GLOBALS['TCA'][$table]['ctrl']['origUid']] = $uid;
3534
        }
3535
        // Do the copy by internal function
3536
        $theNewSQLID = $this->insertNewCopyVersion($table, $row, $pid);
3537
3538
        // When a record is copied in workspace (eg. to create a delete placeholder record for a live record), records
3539
        // pointing to that record need a reference index update. This is for instance the case in FAL, if a sys_file_reference
3540
        // for a eg. tt_content record is marked as deleted. The tt_content record then needs a reference index update.
3541
        // This scenario seems to currently only show up if in workspaces, so the refindex update is restricted to this for now.
3542
        if (!empty($workspaceOptions)) {
3543
            $this->referenceIndexUpdater->registerUpdateForReferencesToItem($table, (int)$row['uid'], (int)$this->BE_USER->workspace);
3544
        }
3545
3546
        if ($theNewSQLID) {
3547
            $this->dbAnalysisStoreExec();
3548
            $this->dbAnalysisStore = [];
3549
            return $this->copyMappingArray[$table][$uid] = $theNewSQLID;
3550
        }
3551
        return null;
3552
    }
3553
3554
    /**
3555
     * Inserts a record in the database, passing TCA configuration values through checkValue() but otherwise does NOTHING and checks nothing regarding permissions.
3556
     * Passes the "version" parameter to insertDB() so the copy will look like a new version in the log - should probably be changed or modified a bit for more broad usage...
3557
     *
3558
     * @param string $table Table name
3559
     * @param array $fieldArray Field array to insert as a record
3560
     * @param int $realPid The value of PID field.
3561
     * @return int Returns the new ID of the record (if applicable)
3562
     * @internal should only be used from within DataHandler
3563
     */
3564
    public function insertNewCopyVersion($table, $fieldArray, $realPid)
3565
    {
3566
        $id = StringUtility::getUniqueId('NEW');
3567
        // $fieldArray is set as current record.
3568
        // The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
3569
        $this->checkValue_currentRecord = $fieldArray;
3570
        // Makes sure that transformations aren't processed on the copy.
3571
        $backupDontProcessTransformations = $this->dontProcessTransformations;
3572
        $this->dontProcessTransformations = true;
3573
        // Traverse record and input-process each value:
3574
        foreach ($fieldArray as $field => $fieldValue) {
3575
            if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
3576
                // Evaluating the value.
3577
                $res = $this->checkValue($table, $field, $fieldValue, $id, 'new', $realPid, 0, $fieldArray);
3578
                if (isset($res['value'])) {
3579
                    $fieldArray[$field] = $res['value'];
3580
                }
3581
            }
3582
        }
3583
        // System fields being set:
3584
        if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
3585
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
3586
        }
3587
        if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
3588
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
3589
        }
3590
        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
3591
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
3592
        }
3593
        // Finally, insert record:
3594
        $this->insertDB($table, $id, $fieldArray, true);
3595
        // Resets dontProcessTransformations to the previous state.
3596
        $this->dontProcessTransformations = $backupDontProcessTransformations;
3597
        // Return new id:
3598
        return $this->substNEWwithIDs[$id];
3599
    }
3600
3601
    /**
3602
     * Processing/Preparing content for copyRecord() function
3603
     *
3604
     * @param string $table Table name
3605
     * @param int $uid Record uid
3606
     * @param string $field Field name being processed
3607
     * @param string $value Input value to be processed.
3608
     * @param array $row Record array
3609
     * @param array $conf TCA field configuration
3610
     * @param int $realDestPid Real page id (pid) the record is copied to
3611
     * @param int $language Language ID (from sys_language table) used in the duplicated record
3612
     * @param array $workspaceOptions Options to be forwarded if actions happen on a workspace currently
3613
     * @return array|string
3614
     * @internal
3615
     * @see copyRecord()
3616
     */
3617
    public function copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $realDestPid, $language = 0, array $workspaceOptions = [])
3618
    {
3619
        $inlineSubType = $this->getInlineFieldType($conf);
3620
        // Get the localization mode for the current (parent) record (keep|select):
3621
        // Register if there are references to take care of or MM is used on an inline field (no change to value):
3622
        if ($this->isReferenceField($conf) || $inlineSubType === 'mm') {
3623
            $value = $this->copyRecord_processManyToMany($table, $uid, $field, $value, $conf, $language);
3624
        } elseif ($inlineSubType !== false) {
3625
            $value = $this->copyRecord_processInline($table, $uid, $field, $value, $row, $conf, $realDestPid, $language, $workspaceOptions);
3626
        }
3627
        // For "flex" fieldtypes we need to traverse the structure for two reasons: If there are file references they have to be prepended with absolute paths and if there are database reference they MIGHT need to be remapped (still done in remapListedDBRecords())
3628
        if (isset($conf['type']) && $conf['type'] === 'flex') {
3629
            // Get current value array:
3630
            $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
3631
            $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
3632
                ['config' => $conf],
3633
                $table,
3634
                $field,
3635
                $row
3636
            );
3637
            $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
3638
            $currentValueArray = GeneralUtility::xml2array($value);
3639
            // Traversing the XML structure, processing files:
3640
            if (is_array($currentValueArray)) {
3641
                $currentValueArray['data'] = $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $uid, $field, $realDestPid], 'copyRecord_flexFormCallBack', $workspaceOptions);
3642
                // Setting value as an array! -> which means the input will be processed according to the 'flex' type when the new copy is created.
3643
                $value = $currentValueArray;
3644
            }
3645
        }
3646
        return $value;
3647
    }
3648
3649
    /**
3650
     * Processes the children of an MM relation field (select, group, inline) when the parent record is copied.
3651
     *
3652
     * @param string $table
3653
     * @param int $uid
3654
     * @param string $field
3655
     * @param string $value
3656
     * @param array $conf
3657
     * @param int $language
3658
     * @return string
3659
     */
3660
    protected function copyRecord_processManyToMany($table, $uid, $field, $value, $conf, $language)
3661
    {
3662
        $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
3663
        $prependName = $conf['type'] === 'group' ? ($conf['prepend_tname'] ?? '') : '';
3664
        $mmTable = isset($conf['MM']) && $conf['MM'] ? $conf['MM'] : '';
3665
        $localizeForeignTable = isset($conf['foreign_table']) && BackendUtility::isTableLocalizable($conf['foreign_table']);
3666
        // Localize referenced records of select fields:
3667
        $localizingNonManyToManyFieldReferences = empty($mmTable) && $localizeForeignTable && isset($conf['localizeReferencesAtParentLocalization']) && $conf['localizeReferencesAtParentLocalization'];
3668
        /** @var RelationHandler $dbAnalysis */
3669
        $dbAnalysis = $this->createRelationHandlerInstance();
3670
        $dbAnalysis->start($value, $allowedTables, $mmTable, $uid, $table, $conf);
3671
        $purgeItems = false;
3672
        if ($language > 0 && $localizingNonManyToManyFieldReferences) {
3673
            foreach ($dbAnalysis->itemArray as $index => $item) {
3674
                // Since select fields can reference many records, check whether there's already a localization:
3675
                $recordLocalization = BackendUtility::getRecordLocalization($item['table'], $item['id'], $language);
3676
                if ($recordLocalization) {
3677
                    $dbAnalysis->itemArray[$index]['id'] = $recordLocalization[0]['uid'];
3678
                } elseif ($this->isNestedElementCallRegistered($item['table'], $item['id'], 'localize-' . (string)$language) === false) {
3679
                    $dbAnalysis->itemArray[$index]['id'] = $this->localize($item['table'], $item['id'], $language);
3680
                }
3681
            }
3682
            $purgeItems = true;
3683
        }
3684
3685
        if ($purgeItems || $mmTable) {
3686
            $dbAnalysis->purgeItemArray();
3687
            $value = implode(',', $dbAnalysis->getValueArray($prependName));
0 ignored issues
show
Bug introduced by
It seems like $prependName can also be of type string; however, parameter $prependTableName of TYPO3\CMS\Core\Database\...andler::getValueArray() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3687
            $value = implode(',', $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName));
Loading history...
3688
        }
3689
        // Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
3690
        if ($value) {
3691
            $this->registerDBList[$table][$uid][$field] = $value;
3692
        }
3693
3694
        return $value;
3695
    }
3696
3697
    /**
3698
     * Processes child records in an inline (IRRE) element when the parent record is copied.
3699
     *
3700
     * @param string $table
3701
     * @param int $uid
3702
     * @param string $field
3703
     * @param string $value
3704
     * @param array $row
3705
     * @param array $conf
3706
     * @param int $realDestPid
3707
     * @param int $language
3708
     * @param array $workspaceOptions
3709
     * @return string
3710
     */
3711
    protected function copyRecord_processInline(
3712
        $table,
3713
        $uid,
3714
        $field,
3715
        $value,
3716
        $row,
3717
        $conf,
3718
        $realDestPid,
3719
        $language,
3720
        array $workspaceOptions
3721
    ) {
3722
        // Fetch the related child records using \TYPO3\CMS\Core\Database\RelationHandler
3723
        /** @var RelationHandler $dbAnalysis */
3724
        $dbAnalysis = $this->createRelationHandlerInstance();
3725
        $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
3726
        // Walk through the items, copy them and remember the new id:
3727
        foreach ($dbAnalysis->itemArray as $k => $v) {
3728
            $newId = null;
3729
            // If language is set and differs from original record, this isn't a copy action but a localization of our parent/ancestor:
3730
            if ($language > 0 && BackendUtility::isTableLocalizable($table) && $language != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
3731
                // Children should be localized when the parent gets localized the first time, just do it:
3732
                $newId = $this->localize($v['table'], $v['id'], $language);
3733
            } else {
3734
                if (!MathUtility::canBeInterpretedAsInteger($realDestPid)) {
3735
                    $newId = $this->copyRecord($v['table'], $v['id'], -(int)($v['id']));
3736
                // If the destination page id is a NEW string, keep it on the same page
3737
                } elseif ($this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($v['table'])) {
3738
                    // A filled $workspaceOptions indicated that this call
3739
                    // has it's origin in previous versionizeRecord() processing
3740
                    if (!empty($workspaceOptions)) {
3741
                        // Versions use live default id, thus the "new"
3742
                        // id is the original live default child record
3743
                        $newId = $v['id'];
3744
                        $this->versionizeRecord(
3745
                            $v['table'],
3746
                            $v['id'],
3747
                            $workspaceOptions['label'] ?? 'Auto-created for WS #' . $this->BE_USER->workspace,
3748
                            $workspaceOptions['delete'] ?? false
3749
                        );
3750
                    // Otherwise just use plain copyRecord() to create placeholders etc.
3751
                    } else {
3752
                        // If a record has been copied already during this request,
3753
                        // prevent superfluous duplication and use the existing copy
3754
                        if (isset($this->copyMappingArray[$v['table']][$v['id']])) {
3755
                            $newId = $this->copyMappingArray[$v['table']][$v['id']];
3756
                        } else {
3757
                            $newId = $this->copyRecord($v['table'], $v['id'], $realDestPid);
3758
                        }
3759
                    }
3760
                } elseif ($this->BE_USER->workspace > 0 && !BackendUtility::isTableWorkspaceEnabled($v['table'])) {
3761
                    // We are in workspace context creating a new parent version and have a child table
3762
                    // that is not workspace aware. We don't do anything with this child.
3763
                    continue;
3764
                } else {
3765
                    // If a record has been copied already during this request,
3766
                    // prevent superfluous duplication and use the existing copy
3767
                    if (isset($this->copyMappingArray[$v['table']][$v['id']])) {
3768
                        $newId = $this->copyMappingArray[$v['table']][$v['id']];
3769
                    } else {
3770
                        $newId = $this->copyRecord_raw($v['table'], $v['id'], $realDestPid, [], $workspaceOptions);
3771
                    }
3772
                }
3773
            }
3774
            // If the current field is set on a page record, update the pid of related child records:
3775
            if ($table === 'pages') {
3776
                $this->registerDBPids[$v['table']][$v['id']] = $uid;
3777
            } elseif (isset($this->registerDBPids[$table][$uid])) {
3778
                $this->registerDBPids[$v['table']][$v['id']] = $this->registerDBPids[$table][$uid];
3779
            }
3780
            $dbAnalysis->itemArray[$k]['id'] = $newId;
3781
        }
3782
        // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
3783
        $value = implode(',', $dbAnalysis->getValueArray());
3784
        $this->registerDBList[$table][$uid][$field] = $value;
3785
3786
        return $value;
3787
    }
3788
3789
    /**
3790
     * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
3791
     *
3792
     * @param array $pParams Array of parameters in num-indexes: table, uid, field
3793
     * @param array $dsConf TCA field configuration (from Data Structure XML)
3794
     * @param string $dataValue The value of the flexForm field
3795
     * @param string $_1 Not used.
3796
     * @param string $_2 Not used.
3797
     * @param string $_3 Not used.
3798
     * @param array $workspaceOptions
3799
     * @return array Result array with key "value" containing the value of the processing.
3800
     * @see copyRecord()
3801
     * @see checkValue_flex_procInData_travDS()
3802
     * @internal should only be used from within DataHandler
3803
     */
3804
    public function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $_1, $_2, $_3, $workspaceOptions)
3805
    {
3806
        // Extract parameters:
3807
        [$table, $uid, $field, $realDestPid] = $pParams;
3808
        // If references are set for this field, set flag so they can be corrected later (in ->remapListedDBRecords())
3809
        if (($this->isReferenceField($dsConf) || $this->getInlineFieldType($dsConf) !== false) && (string)$dataValue !== '') {
3810
            $dataValue = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $dataValue, [], $dsConf, $realDestPid, 0, $workspaceOptions);
3811
            $this->registerDBList[$table][$uid][$field] = 'FlexForm_reference';
3812
        }
3813
        // Return
3814
        return ['value' => $dataValue];
3815
    }
3816
3817
    /**
3818
     * Find l10n-overlay records and perform the requested copy action for these records.
3819
     *
3820
     * @param string $table Record Table
3821
     * @param int $uid UID of the record in the default language
3822
     * @param int $destPid Position to copy to
3823
     * @param bool $first
3824
     * @param array $overrideValues
3825
     * @param string $excludeFields
3826
     * @internal should only be used from within DataHandler
3827
     */
3828
    public function copyL10nOverlayRecords($table, $uid, $destPid, $first = false, $overrideValues = [], $excludeFields = '')
3829
    {
3830
        // There's no need to perform this for tables that are not localizable
3831
        if (!BackendUtility::isTableLocalizable($table)) {
3832
            return;
3833
        }
3834
3835
        $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? null;
3836
        $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? null;
3837
3838
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3839
        $queryBuilder->getRestrictions()
3840
            ->removeAll()
3841
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
3842
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->BE_USER->workspace));
3843
3844
        $queryBuilder->select('*')
3845
            ->from($table)
3846
            ->where(
3847
                $queryBuilder->expr()->eq(
3848
                    $transOrigPointerField,
3849
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':pointer')
3850
                )
3851
            );
3852
3853
        // Never copy the actual placeholders around, as the newly copied records are
3854
        // always created as new record / new placeholder pairs
3855
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
3856
            $queryBuilder->andWhere(
3857
                $queryBuilder->expr()->neq(
3858
                    't3ver_state',
3859
                    VersionState::DELETE_PLACEHOLDER
3860
                )
3861
            );
3862
        }
3863
3864
        // If $destPid is < 0, get the pid of the record with uid equal to abs($destPid)
3865
        $tscPID = BackendUtility::getTSconfig_pidValue($table, $uid, $destPid) ?? 0;
3866
        // Get the localized records to be copied
3867
        $l10nRecords = $queryBuilder->execute()->fetchAll();
3868
        if (is_array($l10nRecords)) {
3869
            $localizedDestPids = [];
3870
            // If $destPid < 0, then it is the uid of the original language record we are inserting after
3871
            if ($destPid < 0) {
3872
                // Get the localized records of the record we are inserting after
3873
                $queryBuilder->setParameter('pointer', abs($destPid), \PDO::PARAM_INT);
3874
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
3875
                // Index the localized record uids by language
3876
                if (is_array($destL10nRecords)) {
3877
                    foreach ($destL10nRecords as $record) {
3878
                        $localizedDestPids[$record[$languageField]] = -$record['uid'];
3879
                    }
3880
                }
3881
            }
3882
            $languageSourceMap = [
3883
                $uid => $overrideValues[$transOrigPointerField]
3884
            ];
3885
            // Copy the localized records after the corresponding localizations of the destination record
3886
            foreach ($l10nRecords as $record) {
3887
                $localizedDestPid = (int)($localizedDestPids[$record[$languageField]] ?? 0);
3888
                if ($localizedDestPid < 0) {
3889
                    $newUid = $this->copyRecord($table, $record['uid'], $localizedDestPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
3890
                } else {
3891
                    $newUid = $this->copyRecord($table, $record['uid'], $destPid < 0 ? $tscPID : $destPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
3892
                }
3893
                $languageSourceMap[$record['uid']] = $newUid;
3894
            }
3895
            $this->copy_remapTranslationSourceField($table, $l10nRecords, $languageSourceMap);
3896
        }
3897
    }
3898
3899
    /**
3900
     * Remap languageSource field to uids of newly created records
3901
     *
3902
     * @param string $table Table name
3903
     * @param array $l10nRecords array of localized records from the page we're copying from (source records)
3904
     * @param array $languageSourceMap array mapping source records uids to newly copied uids
3905
     */
3906
    protected function copy_remapTranslationSourceField($table, $l10nRecords, $languageSourceMap)
3907
    {
3908
        if (empty($GLOBALS['TCA'][$table]['ctrl']['translationSource']) || empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])) {
3909
            return;
3910
        }
3911
        $translationSourceFieldName = $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
3912
        $translationParentFieldName = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
3913
3914
        //We can avoid running these update queries by sorting the $l10nRecords by languageSource dependency (in copyL10nOverlayRecords)
3915
        //and first copy records depending on default record (and map the field).
3916
        foreach ($l10nRecords as $record) {
3917
            $oldSourceUid = $record[$translationSourceFieldName];
3918
            if ($oldSourceUid <= 0 && $record[$translationParentFieldName] > 0) {
3919
                //BC fix - in connected mode 'translationSource' field should not be 0
3920
                $oldSourceUid = $record[$translationParentFieldName];
3921
            }
3922
            if ($oldSourceUid > 0) {
3923
                if (empty($languageSourceMap[$oldSourceUid])) {
3924
                    // we don't have mapping information available e.g when copyRecord returned null
3925
                    continue;
3926
                }
3927
                $newFieldValue = $languageSourceMap[$oldSourceUid];
3928
                $updateFields = [
3929
                    $translationSourceFieldName => $newFieldValue
3930
                ];
3931
                GeneralUtility::makeInstance(ConnectionPool::class)
3932
                    ->getConnectionForTable($table)
3933
                    ->update($table, $updateFields, ['uid' => (int)$languageSourceMap[$record['uid']]]);
3934
                if ($this->BE_USER->workspace > 0) {
3935
                    GeneralUtility::makeInstance(ConnectionPool::class)
3936
                        ->getConnectionForTable($table)
3937
                        ->update($table, $updateFields, ['t3ver_oid' => (int)$languageSourceMap[$record['uid']], 't3ver_wsid' => $this->BE_USER->workspace]);
3938
                }
3939
            }
3940
        }
3941
    }
3942
3943
    /*********************************************
3944
     *
3945
     * Cmd: Moving, Localizing
3946
     *
3947
     ********************************************/
3948
    /**
3949
     * Moving single records
3950
     *
3951
     * @param string $table Table name to move
3952
     * @param int $uid Record uid to move
3953
     * @param int $destPid Position to move to: $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
3954
     * @internal should only be used from within DataHandler
3955
     */
3956
    public function moveRecord($table, $uid, $destPid)
3957
    {
3958
        if (!$GLOBALS['TCA'][$table]) {
3959
            return;
3960
        }
3961
3962
        // In case the record to be moved turns out to be an offline version,
3963
        // we have to find the live version and work on that one.
3964
        if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $uid, 'uid')) {
3965
            $uid = $lookForLiveVersion['uid'];
3966
        }
3967
        // Initialize:
3968
        $destPid = (int)$destPid;
3969
        // Get this before we change the pid (for logging)
3970
        $propArr = $this->getRecordProperties($table, $uid);
3971
        $moveRec = $this->getRecordProperties($table, $uid, true);
3972
        // This is the actual pid of the moving to destination
3973
        $resolvedPid = $this->resolvePid($table, $destPid);
3974
        // Finding out, if the record may be moved from where it is. If the record is a non-page, then it depends on edit-permissions.
3975
        // If the record is a page, then there are two options: If the page is moved within itself,
3976
        // (same pid) it's edit-perms of the pid. If moved to another place then its both delete-perms of the pid and new-page perms on the destination.
3977
        if ($table !== 'pages' || $resolvedPid == $moveRec['pid']) {
3978
            // Edit rights for the record...
3979
            $mayMoveAccess = $this->checkRecordUpdateAccess($table, $uid);
3980
        } else {
3981
            $mayMoveAccess = $this->doesRecordExist($table, $uid, Permission::PAGE_DELETE);
3982
        }
3983
        // Finding out, if the record may be moved TO another place. Here we check insert-rights (non-pages = edit, pages = new),
3984
        // unless the pages are moved on the same pid, then edit-rights are checked
3985
        if ($table !== 'pages' || $resolvedPid != $moveRec['pid']) {
3986
            // Insert rights for the record...
3987
            $mayInsertAccess = $this->checkRecordInsertAccess($table, $resolvedPid, SystemLogDatabaseAction::MOVE);
3988
        } else {
3989
            $mayInsertAccess = $this->checkRecordUpdateAccess($table, $uid);
3990
        }
3991
        // Checking if there is anything else disallowing moving the record by checking if editing is allowed
3992
        $fullLanguageCheckNeeded = $table !== 'pages';
3993
        $mayEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, false, false, $fullLanguageCheckNeeded);
3994
        // If moving is allowed, begin the processing:
3995
        if (!$mayEditAccess) {
3996
            $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to move record "%s" (%s) without having permissions to do so. [' . $this->BE_USER->errorMsg . ']', 14, [$propArr['header'], $table . ':' . $uid], $propArr['event_pid']);
3997
            return;
3998
        }
3999
4000
        if (!$mayMoveAccess) {
4001
            $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to move record \'%s\' (%s) without having permissions to do so.', 14, [$propArr['header'], $table . ':' . $uid], $propArr['event_pid']);
4002
            return;
4003
        }
4004
4005
        if (!$mayInsertAccess) {
4006
            $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to move record \'%s\' (%s) without having permissions to insert.', 14, [$propArr['header'], $table . ':' . $uid], $propArr['event_pid']);
4007
            return;
4008
        }
4009
4010
        $recordWasMoved = false;
4011
        // Move the record via a hook, used e.g. for versioning
4012
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] ?? [] as $className) {
4013
            $hookObj = GeneralUtility::makeInstance($className);
4014
            if (method_exists($hookObj, 'moveRecord')) {
4015
                $hookObj->moveRecord($table, $uid, $destPid, $propArr, $moveRec, $resolvedPid, $recordWasMoved, $this);
4016
            }
4017
        }
4018
        // Move the record if a hook hasn't moved it yet
4019
        if (!$recordWasMoved) {
0 ignored issues
show
introduced by
The condition $recordWasMoved is always false.
Loading history...
4020
            $this->moveRecord_raw($table, $uid, $destPid);
4021
        }
4022
    }
4023
4024
    /**
4025
     * Moves a record without checking security of any sort.
4026
     * USE ONLY INTERNALLY
4027
     *
4028
     * @param string $table Table name to move
4029
     * @param int $uid Record uid to move
4030
     * @param int $destPid Position to move to: $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
4031
     * @see moveRecord()
4032
     * @internal should only be used from within DataHandler
4033
     */
4034
    public function moveRecord_raw($table, $uid, $destPid)
4035
    {
4036
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
4037
        $origDestPid = $destPid;
4038
        // This is the actual pid of the moving to destination
4039
        $resolvedPid = $this->resolvePid($table, $destPid);
4040
        // Checking if the pid is negative, but no sorting row is defined. In that case, find the correct pid.
4041
        // Basically this check make the error message 4-13 meaning less... But you can always remove this check if you
4042
        // prefer the error instead of a no-good action (which is to move the record to its own page...)
4043
        if (($destPid < 0 && !$sortColumn) || $destPid >= 0) {
4044
            $destPid = $resolvedPid;
4045
        }
4046
        // Get this before we change the pid (for logging)
4047
        $propArr = $this->getRecordProperties($table, $uid);
4048
        $moveRec = $this->getRecordProperties($table, $uid, true);
4049
        // Prepare user defined objects (if any) for hooks which extend this function:
4050
        $hookObjectsArr = [];
4051
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] ?? [] as $className) {
4052
            $hookObjectsArr[] = GeneralUtility::makeInstance($className);
4053
        }
4054
        // Timestamp field:
4055
        $updateFields = [];
4056
        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
4057
            $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
4058
        }
4059
4060
        // Check if this is a translation of a page, if so then it just needs to be kept "sorting" in sync
4061
        // Usually called from moveL10nOverlayRecords()
4062
        if ($table === 'pages') {
4063
            $defaultLanguagePageUid = $this->getDefaultLanguagePageId((int)$uid);
4064
            // In workspaces, the default language page may have been moved to a different pid than the
4065
            // default language page record of live workspace. In this case, localized pages need to be
4066
            // moved to the pid of the workspace move record.
4067
            $defaultLanguagePageWorkspaceOverlay = BackendUtility::getWorkspaceVersionOfRecord((int)$this->BE_USER->workspace, 'pages', $defaultLanguagePageUid, 'uid');
4068
            if (is_array($defaultLanguagePageWorkspaceOverlay)) {
4069
                $defaultLanguagePageUid = (int)$defaultLanguagePageWorkspaceOverlay['uid'];
4070
            }
4071
            if ($defaultLanguagePageUid !== (int)$uid) {
4072
                // If the default language page has been moved, localized pages need to be moved to
4073
                // that pid and sorting, too.
4074
                $originalTranslationRecord = $this->recordInfo($table, $defaultLanguagePageUid, 'pid,' . $sortColumn);
4075
                $updateFields[$sortColumn] = $originalTranslationRecord[$sortColumn];
4076
                $destPid = $originalTranslationRecord['pid'];
4077
            }
4078
        }
4079
4080
        // Insert as first element on page (where uid = $destPid)
4081
        if ($destPid >= 0) {
4082
            if ($table !== 'pages' || $this->destNotInsideSelf($destPid, $uid)) {
4083
                // Clear cache before moving
4084
                [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
4085
                $this->registerRecordIdForPageCacheClearing($table, $uid, $parentUid);
4086
                // Setting PID
4087
                $updateFields['pid'] = $destPid;
4088
                // Table is sorted by 'sortby'
4089
                if ($sortColumn && !isset($updateFields[$sortColumn])) {
4090
                    $sortNumber = $this->getSortNumber($table, $uid, $destPid);
4091
                    $updateFields[$sortColumn] = $sortNumber;
4092
                }
4093
                // Check for child records that have also to be moved
4094
                $this->moveRecord_procFields($table, $uid, $destPid);
4095
                // Create query for update:
4096
                GeneralUtility::makeInstance(ConnectionPool::class)
4097
                    ->getConnectionForTable($table)
4098
                    ->update($table, $updateFields, ['uid' => (int)$uid]);
4099
                // Check for the localizations of that element
4100
                $this->moveL10nOverlayRecords($table, $uid, $destPid, $destPid);
4101
                // Call post processing hooks:
4102
                foreach ($hookObjectsArr as $hookObj) {
4103
                    if (method_exists($hookObj, 'moveRecord_firstElementPostProcess')) {
4104
                        $hookObj->moveRecord_firstElementPostProcess($table, $uid, $destPid, $moveRec, $updateFields, $this);
4105
                    }
4106
                }
4107
4108
                $this->getRecordHistoryStore()->moveRecord($table, $uid, ['oldPageId' => $propArr['pid'], 'newPageId' => $destPid, 'oldData' => $propArr, 'newData' => $updateFields], $this->correlationId);
4109
                if ($this->enableLogging) {
4110
                    // Logging...
4111
                    $oldpagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4112
                    if ($destPid != $propArr['pid']) {
4113
                        // Logged to old page
4114
                        $newPropArr = $this->getRecordProperties($table, $uid);
4115
                        $newpagePropArr = $this->getRecordProperties('pages', $destPid);
4116
                        $this->log($table, $uid, SystemLogDatabaseAction::MOVE, $destPid, SystemLogErrorClassification::MESSAGE, 'Moved record \'%s\' (%s) to page \'%s\' (%s)', 2, [$propArr['header'], $table . ':' . $uid, $newpagePropArr['header'], $newPropArr['pid']], $propArr['pid']);
4117
                        // Logged to new page
4118
                        $this->log($table, $uid, SystemLogDatabaseAction::MOVE, $destPid, SystemLogErrorClassification::MESSAGE, 'Moved record \'%s\' (%s) from page \'%s\' (%s)', 3, [$propArr['header'], $table . ':' . $uid, $oldpagePropArr['header'], $propArr['pid']], $destPid);
4119
                    } else {
4120
                        // Logged to new page
4121
                        $this->log($table, $uid, SystemLogDatabaseAction::MOVE, $destPid, SystemLogErrorClassification::MESSAGE, 'Moved record \'%s\' (%s) on page \'%s\' (%s)', 4, [$propArr['header'], $table . ':' . $uid, $oldpagePropArr['header'], $propArr['pid']], $destPid);
4122
                    }
4123
                }
4124
                // Clear cache after moving
4125
                $this->registerRecordIdForPageCacheClearing($table, $uid);
4126
                $this->fixUniqueInPid($table, $uid);
4127
                $this->fixUniqueInSite($table, (int)$uid);
4128
                if ($table === 'pages') {
4129
                    $this->fixUniqueInSiteForSubpages((int)$uid);
4130
                }
4131
            } elseif ($this->enableLogging) {
4132
                $destPropArr = $this->getRecordProperties('pages', $destPid);
4133
                $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to move page \'%s\' (%s) to inside of its own rootline (at page \'%s\' (%s))', 10, [$propArr['header'], $uid, $destPropArr['header'], $destPid], $propArr['pid']);
4134
            }
4135
        } elseif ($sortColumn) {
4136
            // Put after another record
4137
            // Table is being sorted
4138
            // Save the position to which the original record is requested to be moved
4139
            $originalRecordDestinationPid = $destPid;
4140
            $sortInfo = $this->getSortNumber($table, $uid, $destPid);
4141
            // Setting the destPid to the new pid of the record.
4142
            $destPid = $sortInfo['pid'];
4143
            // If not an array, there was an error (which is already logged)
4144
            if (is_array($sortInfo)) {
4145
                if ($table !== 'pages' || $this->destNotInsideSelf($destPid, $uid)) {
4146
                    // clear cache before moving
4147
                    $this->registerRecordIdForPageCacheClearing($table, $uid);
4148
                    // We now update the pid and sortnumber (if not set for page translations)
4149
                    $updateFields['pid'] = $destPid;
4150
                    if (!isset($updateFields[$sortColumn])) {
4151
                        $updateFields[$sortColumn] = $sortInfo['sortNumber'];
4152
                    }
4153
                    // Check for child records that have also to be moved
4154
                    $this->moveRecord_procFields($table, $uid, $destPid);
4155
                    // Create query for update:
4156
                    GeneralUtility::makeInstance(ConnectionPool::class)
4157
                        ->getConnectionForTable($table)
4158
                        ->update($table, $updateFields, ['uid' => (int)$uid]);
4159
                    // Check for the localizations of that element
4160
                    $this->moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid);
4161
                    // Call post processing hooks:
4162
                    foreach ($hookObjectsArr as $hookObj) {
4163
                        if (method_exists($hookObj, 'moveRecord_afterAnotherElementPostProcess')) {
4164
                            $hookObj->moveRecord_afterAnotherElementPostProcess($table, $uid, $destPid, $origDestPid, $moveRec, $updateFields, $this);
4165
                        }
4166
                    }
4167
                    $this->getRecordHistoryStore()->moveRecord($table, $uid, ['oldPageId' => $propArr['pid'], 'newPageId' => $destPid, 'oldData' => $propArr, 'newData' => $updateFields], $this->correlationId);
4168
                    if ($this->enableLogging) {
4169
                        // Logging...
4170
                        $oldpagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4171
                        if ($destPid != $propArr['pid']) {
4172
                            // Logged to old page
4173
                            $newPropArr = $this->getRecordProperties($table, $uid);
4174
                            $newpagePropArr = $this->getRecordProperties('pages', $destPid);
4175
                            $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::MESSAGE, 'Moved record \'%s\' (%s) to page \'%s\' (%s)', 2, [$propArr['header'], $table . ':' . $uid, $newpagePropArr['header'], $newPropArr['pid']], $propArr['pid']);
4176
                            // Logged to old page
4177
                            $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::MESSAGE, 'Moved record \'%s\' (%s) from page \'%s\' (%s)', 3, [$propArr['header'], $table . ':' . $uid, $oldpagePropArr['header'], $propArr['pid']], $destPid);
4178
                        } else {
4179
                            // Logged to old page
4180
                            $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::MESSAGE, 'Moved record \'%s\' (%s) on page \'%s\' (%s)', 4, [$propArr['header'], $table . ':' . $uid, $oldpagePropArr['header'], $propArr['pid']], $destPid);
4181
                        }
4182
                    }
4183
                    // Clear cache after moving
4184
                    $this->registerRecordIdForPageCacheClearing($table, $uid);
4185
                    $this->fixUniqueInPid($table, $uid);
4186
                    $this->fixUniqueInSite($table, (int)$uid);
4187
                    if ($table === 'pages') {
4188
                        $this->fixUniqueInSiteForSubpages((int)$uid);
4189
                    }
4190
                } elseif ($this->enableLogging) {
4191
                    $destPropArr = $this->getRecordProperties('pages', $destPid);
4192
                    $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to move page \'%s\' (%s) to inside of its own rootline (at page \'%s\' (%s))', 10, [$propArr['header'], $uid, $destPropArr['header'], $destPid], $propArr['pid']);
4193
                }
4194
            } else {
4195
                $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to move record \'%s\' (%s) to after another record, although the table has no sorting row.', 13, [$propArr['header'], $table . ':' . $uid], $propArr['event_pid']);
4196
            }
4197
        }
4198
    }
4199
4200
    /**
4201
     * Walk through all fields of the moved record and look for children of e.g. the inline type.
4202
     * If child records are found, they are also move to the new $destPid.
4203
     *
4204
     * @param string $table Record Table
4205
     * @param int $uid Record UID
4206
     * @param int $destPid Position to move to
4207
     * @internal should only be used from within DataHandler
4208
     */
4209
    public function moveRecord_procFields($table, $uid, $destPid)
4210
    {
4211
        $row = BackendUtility::getRecordWSOL($table, $uid);
4212
        if (is_array($row) && (int)$destPid !== (int)$row['pid']) {
4213
            $conf = $GLOBALS['TCA'][$table]['columns'];
4214
            foreach ($row as $field => $value) {
4215
                $this->moveRecord_procBasedOnFieldType($table, $uid, $destPid, $value, $conf[$field]['config'] ?? []);
4216
            }
4217
        }
4218
    }
4219
4220
    /**
4221
     * Move child records depending on the field type of the parent record.
4222
     *
4223
     * @param string $table Record Table
4224
     * @param int $uid Record UID
4225
     * @param int $destPid Position to move to
4226
     * @param string $value Record field value
4227
     * @param array $conf TCA configuration of current field
4228
     * @internal should only be used from within DataHandler
4229
     */
4230
    public function moveRecord_procBasedOnFieldType($table, $uid, $destPid, $value, $conf)
4231
    {
4232
        $dbAnalysis = null;
4233
        if (!empty($conf['type']) && $conf['type'] === 'inline') {
4234
            $foreign_table = $conf['foreign_table'];
4235
            $moveChildrenWithParent = !isset($conf['behaviour']['disableMovingChildrenWithParent']) || !$conf['behaviour']['disableMovingChildrenWithParent'];
4236
            if ($foreign_table && $moveChildrenWithParent) {
4237
                $inlineType = $this->getInlineFieldType($conf);
4238
                if ($inlineType === 'list' || $inlineType === 'field') {
4239
                    if ($table === 'pages') {
4240
                        // If the inline elements are related to a page record,
4241
                        // make sure they reside at that page and not at its parent
4242
                        $destPid = $uid;
4243
                    }
4244
                    $dbAnalysis = $this->createRelationHandlerInstance();
4245
                    $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
4246
                }
4247
            }
4248
        }
4249
        // Move the records
4250
        if (isset($dbAnalysis)) {
4251
            // Moving records to a positive destination will insert each
4252
            // record at the beginning, thus the order is reversed here:
4253
            foreach (array_reverse($dbAnalysis->itemArray) as $v) {
4254
                $this->moveRecord($v['table'], $v['id'], $destPid);
4255
            }
4256
        }
4257
    }
4258
4259
    /**
4260
     * Find l10n-overlay records and perform the requested move action for these records.
4261
     *
4262
     * @param string $table Record Table
4263
     * @param int $uid Record UID
4264
     * @param int $destPid Position to move to
4265
     * @param string $originalRecordDestinationPid Position to move the original record to
4266
     * @internal should only be used from within DataHandler
4267
     */
4268
    public function moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid)
4269
    {
4270
        // There's no need to perform this for non-localizable tables
4271
        if (!BackendUtility::isTableLocalizable($table)) {
4272
            return;
4273
        }
4274
4275
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
4276
        $queryBuilder->getRestrictions()
4277
            ->removeAll()
4278
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
4279
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->BE_USER->workspace));
4280
4281
        $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
4282
        $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? null;
4283
        $l10nRecords = $queryBuilder->select('*')
4284
            ->from($table)
4285
            ->where(
4286
                $queryBuilder->expr()->eq(
4287
                    $transOrigPointerField,
4288
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':pointer')
4289
                )
4290
            )
4291
            ->execute()
4292
            ->fetchAll();
4293
4294
        if (is_array($l10nRecords)) {
4295
            $localizedDestPids = [];
4296
            // If $$originalRecordDestinationPid < 0, then it is the uid of the original language record we are inserting after
4297
            if ($originalRecordDestinationPid < 0) {
4298
                // Get the localized records of the record we are inserting after
4299
                $queryBuilder->setParameter('pointer', abs($originalRecordDestinationPid), \PDO::PARAM_INT);
0 ignored issues
show
Bug introduced by
$originalRecordDestinationPid of type string is incompatible with the type double|integer expected by parameter $num of abs(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4299
                $queryBuilder->setParameter('pointer', abs(/** @scrutinizer ignore-type */ $originalRecordDestinationPid), \PDO::PARAM_INT);
Loading history...
4300
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
4301
                // Index the localized record uids by language
4302
                if (is_array($destL10nRecords)) {
4303
                    foreach ($destL10nRecords as $record) {
4304
                        $localizedDestPids[$record[$languageField]] = -$record['uid'];
4305
                    }
4306
                }
4307
            }
4308
            // Move the localized records after the corresponding localizations of the destination record
4309
            foreach ($l10nRecords as $record) {
4310
                $localizedDestPid = (int)($localizedDestPids[$record[$languageField]] ?? 0);
4311
                if ($localizedDestPid < 0) {
4312
                    $this->moveRecord($table, $record['uid'], $localizedDestPid);
4313
                } else {
4314
                    $this->moveRecord($table, $record['uid'], $destPid);
4315
                }
4316
            }
4317
        }
4318
    }
4319
4320
    /**
4321
     * Localizes a record to another system language
4322
     *
4323
     * @param string $table Table name
4324
     * @param int $uid Record uid (to be localized)
4325
     * @param int $language Language ID (from sys_language table)
4326
     * @return int|bool The uid (int) of the new translated record or FALSE (bool) if something went wrong
4327
     * @internal should only be used from within DataHandler
4328
     */
4329
    public function localize($table, $uid, $language)
4330
    {
4331
        $newId = false;
4332
        $uid = (int)$uid;
4333
        if (!$GLOBALS['TCA'][$table] || !$uid || $this->isNestedElementCallRegistered($table, $uid, 'localize-' . (string)$language) !== false) {
4334
            return false;
4335
        }
4336
4337
        $this->registerNestedElementCall($table, $uid, 'localize-' . (string)$language);
4338
        if (!$GLOBALS['TCA'][$table]['ctrl']['languageField'] || !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
4339
            $this->newlog('Localization failed; "languageField" and "transOrigPointerField" must be defined for the table ' . $table, SystemLogErrorClassification::USER_ERROR);
4340
            return false;
4341
        }
4342
        $langRec = BackendUtility::getRecord('sys_language', (int)$language, 'uid,title');
4343
        if (!$langRec) {
4344
            $this->newlog('Sys language UID "' . $language . '" not found valid!', SystemLogErrorClassification::USER_ERROR);
4345
            return false;
4346
        }
4347
4348
        if (!$this->doesRecordExist($table, $uid, Permission::PAGE_SHOW)) {
4349
            $this->newlog('Attempt to localize record ' . $table . ':' . $uid . ' without permission.', SystemLogErrorClassification::USER_ERROR);
4350
            return false;
4351
        }
4352
4353
        // Getting workspace overlay if possible - this will localize versions in workspace if any
4354
        $row = BackendUtility::getRecordWSOL($table, $uid);
4355
        if (!is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
4356
            $this->newlog('Attempt to localize record ' . $table . ':' . $uid . ' that did not exist!', SystemLogErrorClassification::USER_ERROR);
4357
            return false;
4358
        }
4359
4360
        // Make sure that records which are translated from another language than the default language have a correct
4361
        // localization source set themselves, before translating them to another language.
4362
        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] !== 0
4363
            && $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
4364
            $localizationParentRecord = BackendUtility::getRecord(
4365
                $table,
4366
                $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]
4367
            );
4368
            if ((int)$localizationParentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] !== 0) {
4369
                $this->newlog('Localization failed; Source record ' . $table . ':' . $localizationParentRecord['uid'] . ' contained a reference to an original record that is not a default record (which is strange)!', SystemLogErrorClassification::USER_ERROR);
4370
                return false;
4371
            }
4372
        }
4373
4374
        // Default language records must never have a localization parent as they are the origin of any translation.
4375
        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] !== 0
4376
            && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
4377
            $this->newlog('Localization failed; Source record ' . $table . ':' . $row['uid'] . ' contained a reference to an original default record but is a default record itself (which is strange)!', SystemLogErrorClassification::USER_ERROR);
4378
            return false;
4379
        }
4380
4381
        $recordLocalizations = BackendUtility::getRecordLocalization($table, $uid, $language, 'AND pid=' . (int)$row['pid']);
4382
4383
        if (!empty($recordLocalizations)) {
4384
            $this->newlog(sprintf(
4385
                'Localization failed: there already are localizations (%s) for language %d of the "%s" record %d!',
4386
                implode(', ', array_column($recordLocalizations, 'uid')),
4387
                $language,
4388
                $table,
4389
                $uid
4390
            ), 1);
4391
            return false;
4392
        }
4393
4394
        // Initialize:
4395
        $overrideValues = [];
4396
        // Set override values:
4397
        $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $langRec['uid'];
4398
        // If the translated record is a default language record, set it's uid as localization parent of the new record.
4399
        // If translating from any other language, no override is needed; we just can copy the localization parent of
4400
        // the original record (which is pointing to the correspondent default language record) to the new record.
4401
        // In copy / free mode the TransOrigPointer field is always set to 0, as no connection to the localization parent is wanted in that case.
4402
        // For pages, there is no "copy/free mode".
4403
        if (($this->useTransOrigPointerField || $table === 'pages') && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
4404
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $uid;
4405
        } elseif (!$this->useTransOrigPointerField) {
4406
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = 0;
4407
        }
4408
        if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
4409
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['translationSource']] = $uid;
4410
        }
4411
        // Copy the type (if defined in both tables) from the original record so that translation has same type as original record
4412
        if (isset($GLOBALS['TCA'][$table]['ctrl']['type'])) {
4413
            // @todo: Possible bug here? type can be something like 'table:field', which is then null in $row, writing null to $overrideValues
4414
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['type']] = $row[$GLOBALS['TCA'][$table]['ctrl']['type']] ?? null;
4415
        }
4416
        // Set exclude Fields:
4417
        foreach ($GLOBALS['TCA'][$table]['columns'] as $fN => $fCfg) {
4418
            $translateToMsg = '';
4419
            // Check if we are just prefixing:
4420
            if (isset($fCfg['l10n_mode']) && $fCfg['l10n_mode'] === 'prefixLangTitle') {
4421
                if (($fCfg['config']['type'] === 'text' || $fCfg['config']['type'] === 'input') && (string)$row[$fN] !== '') {
4422
                    [$tscPID] = BackendUtility::getTSCpid($table, $uid, '');
4423
                    $TSConfig = BackendUtility::getPagesTSconfig($tscPID)['TCEMAIN.'] ?? [];
4424
                    $tE = $this->getTableEntries($table, $TSConfig);
4425
                    if (!empty($TSConfig['translateToMessage']) && !($tE['disablePrependAtCopy'] ?? false)) {
4426
                        $translateToMsg = $this->getLanguageService()->sL($TSConfig['translateToMessage']);
4427
                        $translateToMsg = @sprintf($translateToMsg, $langRec['title']);
4428
                    }
4429
4430
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processTranslateToClass'] ?? [] as $className) {
4431
                        $hookObj = GeneralUtility::makeInstance($className);
4432
                        if (method_exists($hookObj, 'processTranslateTo_copyAction')) {
4433
                            $hookObj->processTranslateTo_copyAction($row[$fN], $langRec, $this, $fN);
4434
                        }
4435
                    }
4436
                    if (!empty($translateToMsg)) {
4437
                        $overrideValues[$fN] = '[' . $translateToMsg . '] ' . $row[$fN];
4438
                    } else {
4439
                        $overrideValues[$fN] = $row[$fN];
4440
                    }
4441
                }
4442
            }
4443
        }
4444
4445
        if ($table !== 'pages') {
4446
            // Get the uid of record after which this localized record should be inserted
4447
            $previousUid = $this->getPreviousLocalizedRecordUid($table, $uid, $row['pid'], $language);
4448
            // Execute the copy:
4449
            $newId = $this->copyRecord($table, $uid, -$previousUid, true, $overrideValues, '', $language);
4450
        } else {
4451
            // Create new page which needs to contain the same pid as the original page
4452
            $overrideValues['pid'] = $row['pid'];
4453
            // Take over the hidden state of the original language state, this is done due to legacy reasons where-as
4454
            // pages_language_overlay was set to "hidden -> default=0" but pages hidden -> default 1"
4455
            if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'])) {
4456
                $hiddenFieldName = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
4457
                $overrideValues[$hiddenFieldName] = $row[$hiddenFieldName] ?? $GLOBALS['TCA'][$table]['columns'][$hiddenFieldName]['config']['default'];
4458
            }
4459
            $temporaryId = StringUtility::getUniqueId('NEW');
4460
            $copyTCE = $this->getLocalTCE();
4461
            $copyTCE->start([$table => [$temporaryId => $overrideValues]], [], $this->BE_USER);
4462
            $copyTCE->process_datamap();
4463
            // Getting the new UID as if it had been copied:
4464
            $theNewSQLID = $copyTCE->substNEWwithIDs[$temporaryId];
4465
            if ($theNewSQLID) {
4466
                $this->copyMappingArray[$table][$uid] = $theNewSQLID;
4467
                $newId = $theNewSQLID;
4468
            }
4469
        }
4470
4471
        return $newId;
4472
    }
4473
4474
    /**
4475
     * Performs localization or synchronization of child records.
4476
     * The $command argument expects an array, but supports a string for backward-compatibility.
4477
     *
4478
     * $command = array(
4479
     *   'field' => 'tx_myfieldname',
4480
     *   'language' => 2,
4481
     *   // either the key 'action' or 'ids' must be set
4482
     *   'action' => 'synchronize', // or 'localize'
4483
     *   'ids' => array(1, 2, 3, 4) // child element ids
4484
     * );
4485
     *
4486
     * @param string $table The table of the localized parent record
4487
     * @param int $id The uid of the localized parent record
4488
     * @param array|string $command Defines the command to be performed (see example above)
4489
     */
4490
    protected function inlineLocalizeSynchronize($table, $id, $command)
4491
    {
4492
        $parentRecord = BackendUtility::getRecordWSOL($table, $id);
4493
4494
        // Backward-compatibility handling
4495
        if (!is_array($command)) {
4496
            // <field>, (localize | synchronize | <uid>):
4497
            $parts = GeneralUtility::trimExplode(',', $command);
4498
            $command = [
4499
                'field' => $parts[0],
4500
                // The previous process expected $id to point to the localized record already
4501
                'language' => (int)$parentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']]
4502
            ];
4503
            if (!MathUtility::canBeInterpretedAsInteger($parts[1])) {
4504
                $command['action'] = $parts[1];
4505
            } else {
4506
                $command['ids'] = [$parts[1]];
4507
            }
4508
        }
4509
4510
        // In case the parent record is the default language record, fetch the localization
4511
        if (empty($parentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
4512
            // Fetch the live record
4513
            // @todo: this needs to be revisited, as getRecordLocalization() does a BackendWorkspaceRestriction
4514
            // based on $GLOBALS[BE_USER], which could differ from the $this->BE_USER->workspace value
4515
            $parentRecordLocalization = BackendUtility::getRecordLocalization($table, $id, $command['language'], 'AND t3ver_oid=0');
4516
            if (empty($parentRecordLocalization)) {
4517
                if ($this->enableLogging) {
4518
                    $this->log($table, $id, SystemLogGenericAction::UNDEFINED, 0, SystemLogErrorClassification::MESSAGE, 'Localization for parent record ' . $table . ':' . $id . '" cannot be fetched', -1, [], $this->eventPid($table, $id, $parentRecord['pid']));
4519
                }
4520
                return;
4521
            }
4522
            $parentRecord = $parentRecordLocalization[0];
4523
            $id = $parentRecord['uid'];
4524
            // Process overlay for current selected workspace
4525
            BackendUtility::workspaceOL($table, $parentRecord);
4526
        }
4527
4528
        $field = $command['field'];
4529
        $language = $command['language'];
4530
        $action = $command['action'];
4531
        $ids = $command['ids'];
4532
4533
        if (!$field || !($action === 'localize' || $action === 'synchronize') && empty($ids) || !isset($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
4534
            return;
4535
        }
4536
4537
        $config = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
4538
        $foreignTable = $config['foreign_table'];
4539
4540
        $transOrigPointer = (int)$parentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
4541
        $childTransOrigPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
4542
4543
        if (!$parentRecord || !is_array($parentRecord) || $language <= 0 || !$transOrigPointer) {
4544
            return;
4545
        }
4546
4547
        $inlineSubType = $this->getInlineFieldType($config);
4548
        if ($inlineSubType === false) {
4549
            return;
4550
        }
4551
4552
        $transOrigRecord = BackendUtility::getRecordWSOL($table, $transOrigPointer);
4553
4554
        $removeArray = [];
4555
        $mmTable = $inlineSubType === 'mm' && isset($config['MM']) && $config['MM'] ? $config['MM'] : '';
4556
        // Fetch children from original language parent:
4557
        /** @var RelationHandler $dbAnalysisOriginal */
4558
        $dbAnalysisOriginal = $this->createRelationHandlerInstance();
4559
        $dbAnalysisOriginal->start($transOrigRecord[$field], $foreignTable, $mmTable, $transOrigRecord['uid'], $table, $config);
4560
        $elementsOriginal = [];
4561
        foreach ($dbAnalysisOriginal->itemArray as $item) {
4562
            $elementsOriginal[$item['id']] = $item;
4563
        }
4564
        unset($dbAnalysisOriginal);
4565
        // Fetch children from current localized parent:
4566
        /** @var RelationHandler $dbAnalysisCurrent */
4567
        $dbAnalysisCurrent = $this->createRelationHandlerInstance();
4568
        $dbAnalysisCurrent->start($parentRecord[$field], $foreignTable, $mmTable, $id, $table, $config);
4569
        // Perform synchronization: Possibly removal of already localized records:
4570
        if ($action === 'synchronize') {
4571
            foreach ($dbAnalysisCurrent->itemArray as $index => $item) {
4572
                $childRecord = BackendUtility::getRecordWSOL($item['table'], $item['id']);
4573
                if (isset($childRecord[$childTransOrigPointerField]) && $childRecord[$childTransOrigPointerField] > 0) {
4574
                    $childTransOrigPointer = $childRecord[$childTransOrigPointerField];
4575
                    // If synchronization is requested, child record was translated once, but original record does not exist anymore, remove it:
4576
                    if (!isset($elementsOriginal[$childTransOrigPointer])) {
4577
                        unset($dbAnalysisCurrent->itemArray[$index]);
4578
                        $removeArray[$item['table']][$item['id']]['delete'] = 1;
4579
                    }
4580
                }
4581
            }
4582
        }
4583
        // Perform synchronization/localization: Possibly add unlocalized records for original language:
4584
        if ($action === 'localize' || $action === 'synchronize') {
4585
            foreach ($elementsOriginal as $originalId => $item) {
4586
                $item['id'] = $this->localize($item['table'], $item['id'], $language);
4587
                $item['id'] = $this->overlayAutoVersionId($item['table'], $item['id']);
4588
                $dbAnalysisCurrent->itemArray[] = $item;
4589
            }
4590
        } elseif (!empty($ids)) {
4591
            foreach ($ids as $childId) {
4592
                if (!MathUtility::canBeInterpretedAsInteger($childId) || !isset($elementsOriginal[$childId])) {
4593
                    continue;
4594
                }
4595
                $item = $elementsOriginal[$childId];
4596
                $item['id'] = $this->localize($item['table'], $item['id'], $language);
4597
                $item['id'] = $this->overlayAutoVersionId($item['table'], $item['id']);
4598
                $dbAnalysisCurrent->itemArray[] = $item;
4599
            }
4600
        }
4601
        // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
4602
        $value = implode(',', $dbAnalysisCurrent->getValueArray());
4603
        $this->registerDBList[$table][$id][$field] = $value;
4604
        // Remove child records (if synchronization requested it):
4605
        if (is_array($removeArray) && !empty($removeArray)) {
4606
            /** @var DataHandler $tce */
4607
            $tce = GeneralUtility::makeInstance(__CLASS__, $this->referenceIndexUpdater);
4608
            $tce->enableLogging = $this->enableLogging;
4609
            $tce->start([], $removeArray, $this->BE_USER);
4610
            $tce->process_cmdmap();
4611
            unset($tce);
4612
        }
4613
        $updateFields = [];
4614
        // Handle, reorder and store relations:
4615
        if ($inlineSubType === 'list') {
4616
            $updateFields = [$field => $value];
4617
        } elseif ($inlineSubType === 'field') {
4618
            $dbAnalysisCurrent->writeForeignField($config, $id);
4619
            $updateFields = [$field => $dbAnalysisCurrent->countItems(false)];
4620
        } elseif ($inlineSubType === 'mm') {
4621
            $dbAnalysisCurrent->writeMM($config['MM'], $id);
4622
            $updateFields = [$field => $dbAnalysisCurrent->countItems(false)];
4623
        }
4624
        // Update field referencing to child records of localized parent record:
4625
        if (!empty($updateFields)) {
4626
            $this->updateDB($table, $id, $updateFields);
4627
        }
4628
    }
4629
4630
    /*********************************************
4631
     *
4632
     * Cmd: delete
4633
     *
4634
     ********************************************/
4635
    /**
4636
     * Delete a single record
4637
     *
4638
     * @param string $table Table name
4639
     * @param int $id Record UID
4640
     * @internal should only be used from within DataHandler
4641
     */
4642
    public function deleteAction($table, $id)
4643
    {
4644
        $recordToDelete = BackendUtility::getRecord($table, $id);
4645
4646
        if (is_array($recordToDelete) && isset($recordToDelete['t3ver_wsid']) && (int)$recordToDelete['t3ver_wsid'] !== 0) {
4647
            // When dealing with a workspace record, use discard.
4648
            $this->discard($table, null, $recordToDelete);
4649
            return;
4650
        }
4651
4652
        // Record asked to be deleted was found:
4653
        if (is_array($recordToDelete)) {
4654
            $recordWasDeleted = false;
4655
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
4656
                $hookObj = GeneralUtility::makeInstance($className);
4657
                if (method_exists($hookObj, 'processCmdmap_deleteAction')) {
4658
                    $hookObj->processCmdmap_deleteAction($table, $id, $recordToDelete, $recordWasDeleted, $this);
4659
                }
4660
            }
4661
            // Delete the record if a hook hasn't deleted it yet
4662
            if (!$recordWasDeleted) {
0 ignored issues
show
introduced by
The condition $recordWasDeleted is always false.
Loading history...
4663
                $this->deleteEl($table, $id);
4664
            }
4665
        }
4666
    }
4667
4668
    /**
4669
     * Delete element from any table
4670
     *
4671
     * @param string $table Table name
4672
     * @param int $uid Record UID
4673
     * @param bool $noRecordCheck Flag: If $noRecordCheck is set, then the function does not check permission to delete record
4674
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4675
     * @param bool $deleteRecordsOnPage If false and if deleting pages, records on the page will not be deleted (edge case while swapping workspaces)
4676
     * @internal should only be used from within DataHandler
4677
     */
4678
    public function deleteEl($table, $uid, $noRecordCheck = false, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4679
    {
4680
        if ($table === 'pages') {
4681
            $this->deletePages($uid, $noRecordCheck, $forceHardDelete, $deleteRecordsOnPage);
4682
        } else {
4683
            $this->discardWorkspaceVersionsOfRecord($table, $uid);
4684
            $this->deleteRecord($table, $uid, $noRecordCheck, $forceHardDelete);
4685
        }
4686
    }
4687
4688
    /**
4689
     * Discard workspace overlays of a live record: When a live row
4690
     * is deleted, all existing workspace overlays are discarded.
4691
     *
4692
     * @param string $table Table name
4693
     * @param int $uid Record UID
4694
     * @internal should only be used from within DataHandler
4695
     */
4696
    protected function discardWorkspaceVersionsOfRecord($table, $uid): void
4697
    {
4698
        $versions = BackendUtility::selectVersionsOfRecord($table, $uid, '*', null);
4699
        if ($versions === null) {
4700
            // Null is returned by selectVersionsOfRecord() when table is not workspace aware.
4701
            return;
4702
        }
4703
        foreach ($versions as $record) {
4704
            if ($record['_CURRENT_VERSION'] ?? false) {
4705
                // The live record is included in the result from selectVersionsOfRecord()
4706
                // and marked as '_CURRENT_VERSION'. Skip this one.
4707
                continue;
4708
            }
4709
            // BE user must be put into this workspace temporarily so stuff like refindex updating
4710
            // is properly registered for this workspace when discarding records in there.
4711
            $currentUserWorkspace = $this->BE_USER->workspace;
4712
            $this->BE_USER->workspace = (int)$record['t3ver_wsid'];
4713
            $this->discard($table, null, $record);
4714
            // Switch user back to original workspace
4715
            $this->BE_USER->workspace = $currentUserWorkspace;
4716
        }
4717
    }
4718
4719
    /**
4720
     * Deleting a record
4721
     * This function may not be used to delete pages-records unless the underlying records are already deleted
4722
     * Deletes a record regardless of versioning state (live or offline, doesn't matter, the uid decides)
4723
     * If both $noRecordCheck and $forceHardDelete are set it could even delete a "deleted"-flagged record!
4724
     *
4725
     * @param string $table Table name
4726
     * @param int $uid Record UID
4727
     * @param bool $noRecordCheck Flag: If $noRecordCheck is set, then the function does not check permission to delete record
4728
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4729
     * @internal should only be used from within DataHandler
4730
     */
4731
    public function deleteRecord($table, $uid, $noRecordCheck = false, $forceHardDelete = false)
4732
    {
4733
        $currentUserWorkspace = (int)$this->BE_USER->workspace;
4734
        $uid = (int)$uid;
4735
        if (!$GLOBALS['TCA'][$table] || !$uid) {
4736
            $this->log($table, $uid, SystemLogDatabaseAction::DELETE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to delete record without delete-permissions. [' . $this->BE_USER->errorMsg . ']');
4737
            return;
4738
        }
4739
        // Skip processing already deleted records
4740
        if (!$forceHardDelete && $this->hasDeletedRecord($table, $uid)) {
4741
            return;
4742
        }
4743
4744
        // Checking if there is anything else disallowing deleting the record by checking if editing is allowed
4745
        $fullLanguageAccessCheck = true;
4746
        if ($table === 'pages') {
4747
            // If this is a page translation, the full language access check should not be done
4748
            $defaultLanguagePageId = $this->getDefaultLanguagePageId($uid);
4749
            if ($defaultLanguagePageId !== $uid) {
4750
                $fullLanguageAccessCheck = false;
4751
            }
4752
        }
4753
        $hasEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, false, $forceHardDelete, $fullLanguageAccessCheck);
4754
        if (!$hasEditAccess) {
4755
            $this->log($table, $uid, SystemLogDatabaseAction::DELETE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to delete record without delete-permissions');
4756
            return;
4757
        }
4758
        if ($table === 'pages') {
4759
            $perms = Permission::PAGE_DELETE;
4760
        } elseif ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap)) {
4761
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
4762
            $perms = Permission::PAGE_EDIT;
4763
        } else {
4764
            $perms = Permission::CONTENT_EDIT;
4765
        }
4766
        if (!$noRecordCheck && !$this->doesRecordExist($table, $uid, $perms)) {
4767
            return;
4768
        }
4769
4770
        $recordToDelete = [];
4771
        $recordWorkspaceId = 0;
4772
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
4773
            $recordToDelete = BackendUtility::getRecord($table, $uid);
4774
            $recordWorkspaceId = (int)$recordToDelete['t3ver_wsid'];
4775
        }
4776
4777
        // Clear cache before deleting the record, else the correct page cannot be identified by clear_cache
4778
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
4779
        $this->registerRecordIdForPageCacheClearing($table, $uid, $parentUid);
4780
        $deleteField = $GLOBALS['TCA'][$table]['ctrl']['delete'];
4781
        $databaseErrorMessage = '';
4782
        if ($recordWorkspaceId > 0) {
4783
            // If this is a workspace record, use discard
4784
            $this->BE_USER->workspace = $recordWorkspaceId;
4785
            $this->discard($table, null, $recordToDelete);
4786
            // Switch user back to original workspace
4787
            $this->BE_USER->workspace = $currentUserWorkspace;
4788
        } elseif ($deleteField && !$forceHardDelete) {
4789
            $updateFields = [
4790
                $deleteField => 1
4791
            ];
4792
            if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
4793
                $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
4794
            }
4795
            // before deleting this record, check for child records or references
4796
            $this->deleteRecord_procFields($table, $uid);
4797
            try {
4798
                // Delete all l10n records as well
4799
                $this->deletedRecords[$table][] = (int)$uid;
4800
                $this->deleteL10nOverlayRecords($table, $uid);
4801
                GeneralUtility::makeInstance(ConnectionPool::class)
4802
                    ->getConnectionForTable($table)
4803
                    ->update($table, $updateFields, ['uid' => (int)$uid]);
4804
            } catch (DBALException $e) {
4805
                $databaseErrorMessage = $e->getPrevious()->getMessage();
4806
            }
4807
        } else {
4808
            // Delete the hard way...:
4809
            try {
4810
                $this->hardDeleteSingleRecord($table, (int)$uid);
4811
                $this->deletedRecords[$table][] = (int)$uid;
4812
                $this->deleteL10nOverlayRecords($table, $uid);
4813
            } catch (DBALException $e) {
4814
                $databaseErrorMessage = $e->getPrevious()->getMessage();
4815
            }
4816
        }
4817
        if ($this->enableLogging) {
4818
            $state = SystemLogDatabaseAction::DELETE;
4819
            if ($databaseErrorMessage === '') {
4820
                if ($forceHardDelete) {
4821
                    $message = 'Record \'%s\' (%s) was deleted unrecoverable from page \'%s\' (%s)';
4822
                } else {
4823
                    $message = 'Record \'%s\' (%s) was deleted from page \'%s\' (%s)';
4824
                }
4825
                $propArr = $this->getRecordProperties($table, $uid);
4826
                $pagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4827
4828
                $this->log($table, $uid, $state, 0, SystemLogErrorClassification::MESSAGE, $message, 0, [
4829
                    $propArr['header'],
4830
                    $table . ':' . $uid,
4831
                    $pagePropArr['header'],
4832
                    $propArr['pid']
4833
                ], $propArr['event_pid']);
4834
            } else {
4835
                $this->log($table, $uid, $state, 0, SystemLogErrorClassification::TODAYS_SPECIAL, $databaseErrorMessage);
4836
            }
4837
        }
4838
4839
        // Add history entry
4840
        $this->getRecordHistoryStore()->deleteRecord($table, $uid, $this->correlationId);
4841
4842
        // Update reference index with table/uid on left side (recuid)
4843
        $this->updateRefIndex($table, $uid);
4844
        // Update reference index with table/uid on right side (ref_uid). Important if children of a relation are deleted.
4845
        $this->referenceIndexUpdater->registerUpdateForReferencesToItem($table, $uid, $currentUserWorkspace);
4846
    }
4847
4848
    /**
4849
     * Used to delete page because it will check for branch below pages and disallowed tables on the page as well.
4850
     *
4851
     * @param int $uid Page id
4852
     * @param bool $force If TRUE, pages are not checked for permission.
4853
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4854
     * @param bool $deleteRecordsOnPage If false, records on the page will not be deleted (edge case while swapping workspaces)
4855
     * @internal should only be used from within DataHandler
4856
     */
4857
    public function deletePages($uid, $force = false, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4858
    {
4859
        $uid = (int)$uid;
4860
        if ($uid === 0) {
4861
            if ($this->enableLogging) {
4862
                $this->log('pages', $uid, SystemLogGenericAction::UNDEFINED, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'Deleting all pages starting from the root-page is disabled.', -1, [], 0);
4863
            }
4864
            return;
4865
        }
4866
        // Getting list of pages to delete:
4867
        if ($force) {
4868
            // Returns the branch WITHOUT permission checks (0 secures that), so it cannot return -1
4869
            $pageIdsInBranch = $this->doesBranchExist('', $uid, 0, true);
4870
            $res = GeneralUtility::intExplode(',', $pageIdsInBranch . $uid, true);
4871
        } else {
4872
            $res = $this->canDeletePage($uid);
4873
        }
4874
        // Perform deletion if not error:
4875
        if (is_array($res)) {
4876
            foreach ($res as $deleteId) {
4877
                $this->deleteSpecificPage($deleteId, $forceHardDelete, $deleteRecordsOnPage);
4878
            }
4879
        } else {
4880
            /** @var FlashMessage $flashMessage */
4881
            $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $res, '', FlashMessage::ERROR, true);
4882
            /** @var FlashMessageService $flashMessageService */
4883
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
4884
            $flashMessageService->getMessageQueueByIdentifier()->addMessage($flashMessage);
4885
            $this->newlog($res, SystemLogErrorClassification::USER_ERROR);
4886
        }
4887
    }
4888
4889
    /**
4890
     * Delete a page (or set deleted field to 1) and all records on it.
4891
     *
4892
     * @param int $uid Page id
4893
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4894
     * @param bool $deleteRecordsOnPage If false, records on the page will not be deleted (edge case while swapping workspaces)
4895
     * @internal
4896
     * @see deletePages()
4897
     */
4898
    public function deleteSpecificPage($uid, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4899
    {
4900
        $uid = (int)$uid;
4901
        if (!$uid) {
4902
            // Early void return on invalid uid
4903
            return;
4904
        }
4905
        $forceHardDelete = (bool)$forceHardDelete;
4906
4907
        // Delete either a default language page or a translated page
4908
        $pageIdInDefaultLanguage = $this->getDefaultLanguagePageId($uid);
4909
        $isPageTranslation = false;
4910
        $pageLanguageId = 0;
4911
        if ($pageIdInDefaultLanguage !== $uid) {
4912
            // For translated pages, translated records in other tables (eg. tt_content) for the
4913
            // to-delete translated page have their pid field set to the uid of the default language record,
4914
            // NOT the uid of the translated page record.
4915
            // If a translated page is deleted, only translations of records in other tables of this language
4916
            // should be deleted. The code checks if the to-delete page is a translated page and
4917
            // adapts the query for other tables to use the uid of the default language page as pid together
4918
            // with the language id of the translated page.
4919
            $isPageTranslation = true;
4920
            $pageLanguageId = $this->pageInfo($uid, $GLOBALS['TCA']['pages']['ctrl']['languageField']);
4921
        }
4922
4923
        if ($deleteRecordsOnPage) {
4924
            $tableNames = $this->compileAdminTables();
4925
            foreach ($tableNames as $table) {
4926
                if ($table === 'pages' || ($isPageTranslation && !BackendUtility::isTableLocalizable($table))) {
4927
                    // Skip pages table. And skip table if not translatable, but a translated page is deleted
4928
                    continue;
4929
                }
4930
4931
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
4932
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
4933
                $queryBuilder
4934
                    ->select('uid')
4935
                    ->from($table)
4936
                    // order by uid is needed here to process possible live records first - overlays always
4937
                    // have a higher uid. Otherwise dbms like postgres may return rows in arbitrary order,
4938
                    // leading to hard to debug issues. This is especially relevant for the
4939
                    // discardWorkspaceVersionsOfRecord() call below.
4940
                    ->addOrderBy('uid');
4941
4942
                if ($isPageTranslation) {
4943
                    // Only delete records in the specified language
4944
                    $queryBuilder->where(
4945
                        $queryBuilder->expr()->eq(
4946
                            'pid',
4947
                            $queryBuilder->createNamedParameter($pageIdInDefaultLanguage, \PDO::PARAM_INT)
4948
                        ),
4949
                        $queryBuilder->expr()->eq(
4950
                            $GLOBALS['TCA'][$table]['ctrl']['languageField'],
4951
                            $queryBuilder->createNamedParameter($pageLanguageId, \PDO::PARAM_INT)
4952
                        )
4953
                    );
4954
                } else {
4955
                    // Delete all records on this page
4956
                    $queryBuilder->where(
4957
                        $queryBuilder->expr()->eq(
4958
                            'pid',
4959
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
4960
                        )
4961
                    );
4962
                }
4963
4964
                $currentUserWorkspace = (int)$this->BE_USER->workspace;
4965
                if ($currentUserWorkspace !== 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
4966
                    // If we are in a workspace, make sure only records of this workspace are deleted.
4967
                    $queryBuilder->andWhere(
4968
                        $queryBuilder->expr()->eq(
4969
                            't3ver_wsid',
4970
                            $queryBuilder->createNamedParameter($currentUserWorkspace, \PDO::PARAM_INT)
4971
                        )
4972
                    );
4973
                }
4974
4975
                $statement = $queryBuilder->execute();
4976
4977
                while ($row = $statement->fetch()) {
4978
                    // Delete any further workspace overlays of the record in question, then delete the record.
4979
                    $this->discardWorkspaceVersionsOfRecord($table, $row['uid']);
4980
                    $this->deleteRecord($table, $row['uid'], true, $forceHardDelete);
4981
                }
4982
            }
4983
        }
4984
4985
        // Delete any further workspace overlays of the record in question, then delete the record.
4986
        $this->discardWorkspaceVersionsOfRecord('pages', $uid);
4987
        $this->deleteRecord('pages', $uid, true, $forceHardDelete);
4988
    }
4989
4990
    /**
4991
     * Used to evaluate if a page can be deleted
4992
     *
4993
     * @param int $uid Page id
4994
     * @return int[]|string If array: List of page uids to traverse and delete (means OK), if string: error message.
4995
     * @internal should only be used from within DataHandler
4996
     */
4997
    public function canDeletePage($uid)
4998
    {
4999
        $uid = (int)$uid;
5000
        $isTranslatedPage = null;
5001
5002
        // If we may at all delete this page
5003
        // If this is a page translation, do the check against the perms_* of the default page
5004
        // Because it is currently only deleting the translation
5005
        $defaultLanguagePageId = $this->getDefaultLanguagePageId($uid);
5006
        if ($defaultLanguagePageId !== $uid) {
5007
            if ($this->doesRecordExist('pages', (int)$defaultLanguagePageId, Permission::PAGE_DELETE)) {
5008
                $isTranslatedPage = true;
5009
            } else {
5010
                return 'Attempt to delete page without permissions';
5011
            }
5012
        } elseif (!$this->doesRecordExist('pages', $uid, Permission::PAGE_DELETE)) {
5013
            return 'Attempt to delete page without permissions';
5014
        }
5015
5016
        $pageIdsInBranch = $this->doesBranchExist('', $uid, Permission::PAGE_DELETE, true);
5017
5018
        if ($pageIdsInBranch === -1) {
5019
            return 'Attempt to delete pages in branch without permissions';
5020
        }
5021
5022
        $pagesInBranch = GeneralUtility::intExplode(',', $pageIdsInBranch . $uid, true);
5023
5024
        if ($disallowedTables = $this->checkForRecordsFromDisallowedTables($pagesInBranch)) {
5025
            return 'Attempt to delete records from disallowed tables (' . implode(', ', $disallowedTables) . ')';
5026
        }
5027
5028
        foreach ($pagesInBranch as $pageInBranch) {
5029
            if (!$this->BE_USER->recordEditAccessInternals('pages', $pageInBranch, false, false, $isTranslatedPage ? false : true)) {
5030
                return 'Attempt to delete page which has prohibited localizations.';
5031
            }
5032
        }
5033
        return $pagesInBranch;
5034
    }
5035
5036
    /**
5037
     * Returns TRUE if record CANNOT be deleted, otherwise FALSE. Used to check before the versioning API allows a record to be marked for deletion.
5038
     *
5039
     * @param string $table Record Table
5040
     * @param int $id Record UID
5041
     * @return string Returns a string IF there is an error (error string explaining). FALSE means record can be deleted
5042
     * @internal should only be used from within DataHandler
5043
     */
5044
    public function cannotDeleteRecord($table, $id)
5045
    {
5046
        if ($table === 'pages') {
5047
            $res = $this->canDeletePage($id);
5048
            return is_array($res) ? false : $res;
0 ignored issues
show
Bug Best Practice introduced by
The expression return is_array($res) ? false : $res could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
5049
        }
5050
        if ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap)) {
5051
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
5052
            $perms = Permission::PAGE_EDIT;
5053
        } else {
5054
            $perms = Permission::CONTENT_EDIT;
5055
        }
5056
        return $this->doesRecordExist($table, $id, $perms) ? false : 'No permission to delete record';
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->doesRecord...ssion to delete record' could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
5057
    }
5058
5059
    /**
5060
     * Before a record is deleted, check if it has references such as inline type or MM references.
5061
     * If so, set these child records also to be deleted.
5062
     *
5063
     * @param string $table Record Table
5064
     * @param int $uid Record UID
5065
     * @see deleteRecord()
5066
     * @internal should only be used from within DataHandler
5067
     */
5068
    public function deleteRecord_procFields($table, $uid)
5069
    {
5070
        $conf = $GLOBALS['TCA'][$table]['columns'];
5071
        $row = BackendUtility::getRecord($table, $uid, '*', '', false);
5072
        if (empty($row)) {
5073
            return;
5074
        }
5075
        foreach ($row as $field => $value) {
5076
            $this->deleteRecord_procBasedOnFieldType($table, $uid, $value, $conf[$field]['config'] ?? []);
5077
        }
5078
    }
5079
5080
    /**
5081
     * Process fields of a record to be deleted and search for special handling, like
5082
     * inline type, MM records, etc.
5083
     *
5084
     * @param string $table Record Table
5085
     * @param int $uid Record UID
5086
     * @param string $value Record field value
5087
     * @param array $conf TCA configuration of current field
5088
     * @see deleteRecord()
5089
     * @internal should only be used from within DataHandler
5090
     */
5091
    public function deleteRecord_procBasedOnFieldType($table, $uid, $value, $conf): void
5092
    {
5093
        if (!isset($conf['type'])) {
5094
            return;
5095
        }
5096
        if ($conf['type'] === 'inline') {
5097
            $foreign_table = $conf['foreign_table'];
5098
            if ($foreign_table) {
5099
                $inlineType = $this->getInlineFieldType($conf);
5100
                if ($inlineType === 'list' || $inlineType === 'field') {
5101
                    /** @var RelationHandler $dbAnalysis */
5102
                    $dbAnalysis = $this->createRelationHandlerInstance();
5103
                    $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
5104
                    $dbAnalysis->undeleteRecord = true;
5105
5106
                    $enableCascadingDelete = true;
5107
                    // non type save comparison is intended!
5108
                    if (isset($conf['behaviour']['enableCascadingDelete']) && $conf['behaviour']['enableCascadingDelete'] == false) {
5109
                        $enableCascadingDelete = false;
5110
                    }
5111
5112
                    // Walk through the items and remove them
5113
                    foreach ($dbAnalysis->itemArray as $v) {
5114
                        if ($enableCascadingDelete) {
5115
                            $this->deleteAction($v['table'], $v['id']);
5116
                        }
5117
                    }
5118
                }
5119
            }
5120
        } elseif ($this->isReferenceField($conf)) {
5121
            $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5122
            $dbAnalysis = $this->createRelationHandlerInstance();
5123
            $dbAnalysis->start($value, $allowedTables, $conf['MM'] ?? '', $uid, $table, $conf);
5124
            foreach ($dbAnalysis->itemArray as $v) {
5125
                $this->updateRefIndex($v['table'], $v['id']);
5126
            }
5127
        }
5128
    }
5129
5130
    /**
5131
     * Find l10n-overlay records and perform the requested delete action for these records.
5132
     *
5133
     * @param string $table Record Table
5134
     * @param int $uid Record UID
5135
     * @internal should only be used from within DataHandler
5136
     */
5137
    public function deleteL10nOverlayRecords($table, $uid)
5138
    {
5139
        // Check whether table can be localized
5140
        if (!BackendUtility::isTableLocalizable($table)) {
5141
            return;
5142
        }
5143
5144
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5145
        $queryBuilder->getRestrictions()
5146
            ->removeAll()
5147
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
5148
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->BE_USER->workspace));
5149
5150
        $queryBuilder->select('*')
5151
            ->from($table)
5152
            ->where(
5153
                $queryBuilder->expr()->eq(
5154
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5155
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5156
                )
5157
            );
5158
5159
        $result = $queryBuilder->execute();
5160
        while ($record = $result->fetch()) {
5161
            // Ignore workspace delete placeholders. Those records have been marked for
5162
            // deletion before - deleting them again in a workspace would revert that state.
5163
            if ((int)$this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
5164
                BackendUtility::workspaceOL($table, $record, $this->BE_USER->workspace);
5165
                if (VersionState::cast($record['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)) {
5166
                    continue;
5167
                }
5168
            }
5169
            $this->deleteAction($table, (int)$record['t3ver_oid'] > 0 ? (int)$record['t3ver_oid'] : (int)$record['uid']);
5170
        }
5171
    }
5172
5173
    /*********************************************
5174
     *
5175
     * Cmd: undelete / restore
5176
     *
5177
     ********************************************/
5178
5179
    /**
5180
     * Restore live records by setting soft-delete flag to 0.
5181
     *
5182
     * Usually only used by ext:recycler.
5183
     * Connected relations (eg. inline) are restored, too.
5184
     * Additional existing localizations are not restored.
5185
     *
5186
     * @param string $table Record table name
5187
     * @param int $uid Record uid
5188
     */
5189
    protected function undeleteRecord(string $table, int $uid): void
5190
    {
5191
        $record = BackendUtility::getRecord($table, $uid, '*', '', false);
5192
        $deleteField = (string)($GLOBALS['TCA'][$table]['ctrl']['delete'] ?? '');
5193
        $timestampField = (string)($GLOBALS['TCA'][$table]['ctrl']['tstamp'] ?? '');
5194
5195
        if ($record === null
5196
            || $deleteField === ''
5197
            || !isset($record[$deleteField])
5198
            || (bool)$record[$deleteField] === false
5199
            || ($timestampField !== '' && !isset($record[$timestampField]))
5200
            || (int)$this->BE_USER->workspace > 0
5201
            || (BackendUtility::isTableWorkspaceEnabled($table) && (int)($record['t3ver_wsid'] ?? 0) > 0)
5202
        ) {
5203
            // Return early and silently, if:
5204
            // * Record not found
5205
            // * Table is not soft-delete aware
5206
            // * Record does not have deleted field - db analyzer not up-to-date?
5207
            // * Record is not deleted - may eventually happen via recursion with self referencing records?
5208
            // * Table is tstamp aware, but field does not exist - db analyzer not up-to-date?
5209
            // * User is in a workspace - does not make sense
5210
            // * Record is in a workspace - workspace records are not soft-delete aware
5211
            return;
5212
        }
5213
5214
        $recordPid = (int)($record['pid'] ?? 0);
5215
        if ($recordPid > 0) {
5216
            // Record is not on root level. Parent page record must exist and must not be deleted itself.
5217
            $page = BackendUtility::getRecord('pages', $recordPid, 'deleted', '', false);
5218
            if ($page === null || !isset($page['deleted']) || (bool)$page['deleted'] === true) {
5219
                $this->log(
5220
                    $table,
5221
                    $uid,
5222
                    SystemLogDatabaseAction::DELETE,
5223
                    0,
5224
                    SystemLogErrorClassification::USER_ERROR,
5225
                    sprintf('Record "%s:%s" can\'t be restored: The page:%s containing it does not exist or is soft-deleted.', $table, $uid, $recordPid),
5226
                    0,
5227
                    [],
5228
                    $recordPid
5229
                );
5230
                return;
5231
            }
5232
        }
5233
5234
        // @todo: When restoring a not-default language record, it should be verified the default language
5235
        // @todo: record is *not* set to deleted. Maybe even verify a possible l10n_source chain is not deleted?
5236
5237
        if (!$this->BE_USER->recordEditAccessInternals($table, $record, false, true)) {
5238
            // User misses access permissions to record
5239
            $this->log(
5240
                $table,
5241
                $uid,
5242
                SystemLogDatabaseAction::DELETE,
5243
                0,
5244
                SystemLogErrorClassification::USER_ERROR,
5245
                sprintf('Record "%s:%s" can\'t be restored: Insufficient user permissions.', $table, $uid),
5246
                0,
5247
                [],
5248
                $recordPid
5249
            );
5250
            return;
5251
        }
5252
5253
        // Restore referenced child records
5254
        $this->undeleteRecordRelations($table, $uid, $record);
5255
5256
        // Restore record
5257
        $updateFields[$deleteField] = 0;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$updateFields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $updateFields = array(); before regardless.
Loading history...
5258
        if ($timestampField !== '') {
5259
            $updateFields[$timestampField] = $GLOBALS['EXEC_TIME'];
5260
        }
5261
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table)
5262
            ->update(
5263
                $table,
5264
                $updateFields,
5265
                ['uid' => $uid]
5266
            );
5267
5268
        if ($this->enableLogging) {
5269
            $this->log(
5270
                $table,
5271
                $uid,
5272
                SystemLogDatabaseAction::INSERT,
5273
                0,
5274
                SystemLogErrorClassification::MESSAGE,
5275
                sprintf('Record "%s:%s" was restored on page:%s', $table, $uid, $recordPid),
5276
                0,
5277
                [],
5278
                $recordPid
5279
            );
5280
        }
5281
5282
        // Register cache clearing of page, or parent page if a page is restored.
5283
        $this->registerRecordIdForPageCacheClearing($table, $uid, $recordPid);
5284
        // Add history entry
5285
        $this->getRecordHistoryStore()->undeleteRecord($table, $uid, $this->correlationId);
5286
        // Update reference index with table/uid on left side (recuid)
5287
        $this->updateRefIndex($table, $uid);
5288
        // Update reference index with table/uid on right side (ref_uid). Important if children of a relation were restored.
5289
        $this->referenceIndexUpdater->registerUpdateForReferencesToItem($table, $uid, 0);
5290
    }
5291
5292
    /**
5293
     * Check if a to-restore record has inline references and restore them.
5294
     *
5295
     * @param string $table Record table name
5296
     * @param int $uid Record uid
5297
     * @param array $record Record row
5298
     * @todo: Add functional test undelete coverage to verify details, some details seem to be missing.
5299
     */
5300
    protected function undeleteRecordRelations(string $table, int $uid, array $record): void
5301
    {
5302
        foreach ($record as $fieldName => $value) {
5303
            $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$fieldName]['config'] ?? [];
5304
            $fieldType = (string)($fieldConfig['type'] ?? '');
5305
            if (empty($fieldConfig) || !is_array($fieldConfig) || $fieldType === '') {
5306
                continue;
5307
            }
5308
            $foreignTable = (string)($fieldConfig['foreign_table'] ?? '');
5309
            if ($fieldType === 'inline') {
5310
                // @todo: Inline MM not handled here, and what about group / select?
5311
                if ($foreignTable === ''
5312
                    || !in_array($this->getInlineFieldType($fieldConfig), ['list', 'field'], true)
5313
                ) {
5314
                    continue;
5315
                }
5316
                $relationHandler = $this->createRelationHandlerInstance();
5317
                $relationHandler->start($value, $foreignTable, '', $uid, $table, $fieldConfig);
5318
                $relationHandler->undeleteRecord = true;
5319
                foreach ($relationHandler->itemArray as $reference) {
5320
                    $this->undeleteRecord($reference['table'], (int)$reference['id']);
5321
                }
5322
            } elseif ($this->isReferenceField($fieldConfig)) {
5323
                $allowedTables = $fieldType === 'group' ? ($fieldConfig['allowed'] ?? '') : $foreignTable;
5324
                $relationHandler = $this->createRelationHandlerInstance();
5325
                $relationHandler->start($value, $allowedTables, $fieldConfig['MM'] ?? '', $uid, $table, $fieldConfig);
5326
                foreach ($relationHandler->itemArray as $reference) {
5327
                    // @todo: Unsure if this is ok / enough. Needs coverage.
5328
                    $this->updateRefIndex($reference['table'], $reference['id']);
5329
                }
5330
            }
5331
        }
5332
    }
5333
5334
    /*********************************************
5335
     *
5336
     * Cmd: Workspace discard & flush
5337
     *
5338
     ********************************************/
5339
5340
    /**
5341
     * Discard a versioned record from this workspace. This deletes records from the database - no soft delete.
5342
     * This main entry method is called recursive for sub pages, localizations, relations and records on a page.
5343
     * The method checks user access and gathers facts about this record to hand the deletion over to detail methods.
5344
     *
5345
     * The incoming $uid or $row can be anything: The workspace of current user is respected and only records
5346
     * of current user workspace are discarded. If giving a live record uid, the versioned overly will be fetched.
5347
     *
5348
     * @param string $table Database table name
5349
     * @param int|null $uid Uid of live or versioned record to be discarded, or null if $record is given
5350
     * @param array|null $record Record row that should be discarded. Used instead of $uid within recursion.
5351
     * @internal should only be used from within DataHandler
5352
     */
5353
    public function discard(string $table, ?int $uid, array $record = null): void
5354
    {
5355
        if ($uid === null && $record === null) {
5356
            throw new \RuntimeException('Either record $uid or $record row must be given', 1600373491);
5357
        }
5358
5359
        // Fetch record we are dealing with if not given
5360
        if ($record === null) {
5361
            $record = BackendUtility::getRecord($table, (int)$uid);
5362
        }
5363
        if (!is_array($record)) {
5364
            return;
5365
        }
5366
        $uid = (int)$record['uid'];
5367
5368
        // Call hook and return if hook took care of the element
5369
        $recordWasDiscarded = false;
5370
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
5371
            $hookObj = GeneralUtility::makeInstance($className);
5372
            if (method_exists($hookObj, 'processCmdmap_discardAction')) {
5373
                $hookObj->processCmdmap_discardAction($table, $uid, $record, $recordWasDiscarded);
5374
            }
5375
        }
5376
5377
        $userWorkspace = (int)$this->BE_USER->workspace;
5378
        if ($recordWasDiscarded
5379
            || $userWorkspace === 0
5380
            || !BackendUtility::isTableWorkspaceEnabled($table)
5381
            || $this->hasDeletedRecord($table, $uid)
5382
        ) {
5383
            return;
5384
        }
5385
5386
        // Gather versioned record
5387
        $versionRecord = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $versionRecord is dead and can be removed.
Loading history...
5388
        if ((int)$record['t3ver_wsid'] === 0) {
5389
            $record = BackendUtility::getWorkspaceVersionOfRecord($userWorkspace, $table, $uid);
5390
        }
5391
        if (!is_array($record)) {
5392
            return;
5393
        }
5394
        $versionRecord = $record;
5395
5396
        // User access checks
5397
        if ($userWorkspace !== (int)$versionRecord['t3ver_wsid']) {
5398
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: Different workspace', SystemLogErrorClassification::USER_ERROR);
5399
            return;
5400
        }
5401
        if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $versionRecord['uid'])) {
5402
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: ' . $errorCode, SystemLogErrorClassification::USER_ERROR);
5403
            return;
5404
        }
5405
        if (!$this->checkRecordUpdateAccess($table, $versionRecord['uid'])) {
5406
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: User has no edit access', SystemLogErrorClassification::USER_ERROR);
5407
            return;
5408
        }
5409
        $fullLanguageAccessCheck = !($table === 'pages' && (int)$versionRecord[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] !== 0);
5410
        if (!$this->BE_USER->recordEditAccessInternals($table, $versionRecord, false, true, $fullLanguageAccessCheck)) {
5411
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: User has no delete access', SystemLogErrorClassification::USER_ERROR);
5412
            return;
5413
        }
5414
5415
        // Perform discard operations
5416
        $versionState = VersionState::cast($versionRecord['t3ver_state']);
5417
        if ($table === 'pages' && $versionState->equals(VersionState::NEW_PLACEHOLDER)) {
5418
            // When discarding a new page, there can be new sub pages and new records.
5419
            // Those need to be discarded, otherwise they'd end up as records without parent page.
5420
            $this->discardSubPagesAndRecordsOnPage($versionRecord);
5421
        }
5422
5423
        $this->discardLocalizationOverlayRecords($table, $versionRecord);
5424
        $this->discardRecordRelations($table, $versionRecord);
5425
        $this->hardDeleteSingleRecord($table, (int)$versionRecord['uid']);
5426
        $this->deletedRecords[$table][] = (int)$versionRecord['uid'];
5427
        $this->registerReferenceIndexRowsForDrop($table, (int)$versionRecord['uid'], $userWorkspace);
5428
        $this->getRecordHistoryStore()->deleteRecord($table, (int)$versionRecord['uid'], $this->correlationId);
5429
        $this->log(
5430
            $table,
5431
            (int)$versionRecord['uid'],
5432
            SystemLogDatabaseAction::DELETE,
5433
            0,
5434
            SystemLogErrorClassification::MESSAGE,
5435
            'Record ' . $table . ':' . $versionRecord['uid'] . ' was deleted unrecoverable from page ' . $versionRecord['pid'],
5436
            0,
5437
            [],
5438
            (int)$versionRecord['pid']
5439
        );
5440
    }
5441
5442
    /**
5443
     * Also discard any sub pages and records of a new parent page if this page is discarded.
5444
     * Discarding only in specific localization, if needed.
5445
     *
5446
     * @param array $page Page record row
5447
     */
5448
    protected function discardSubPagesAndRecordsOnPage(array $page): void
5449
    {
5450
        $isLocalizedPage = false;
5451
        $sysLanguageId = (int)$page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
5452
        $versionState = VersionState::cast($page['t3ver_state']);
5453
        if ($sysLanguageId > 0) {
5454
            // New or moved localized page.
5455
            // Discard records on this page localization, but no sub pages.
5456
            // Records of a translated page have the pid set to the default language page uid. Found in l10n_parent.
5457
            // @todo: Discard other page translations that inherit from this?! (l10n_source field)
5458
            $isLocalizedPage = true;
5459
            $pid = (int)$page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
5460
        } elseif ($versionState->equals(VersionState::NEW_PLACEHOLDER)) {
5461
            // New default language page.
5462
            // Discard any sub pages and all other records of this page, including any page localizations.
5463
            // The t3ver_state=1 record is incoming here. Records on this page have their pid field set to the uid
5464
            // of this record. So, since t3ver_state=1 does not have an online counter-part, the actual UID is used here.
5465
            $pid = (int)$page['uid'];
5466
        } else {
5467
            // Moved default language page.
5468
            // Discard any sub pages and all other records of this page, including any page localizations.
5469
            $pid = (int)$page['t3ver_oid'];
5470
        }
5471
        $tables = $this->compileAdminTables();
5472
        foreach ($tables as $table) {
5473
            if (($isLocalizedPage && $table === 'pages')
5474
                || ($isLocalizedPage && !BackendUtility::isTableLocalizable($table))
5475
                || !BackendUtility::isTableWorkspaceEnabled($table)
5476
            ) {
5477
                continue;
5478
            }
5479
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5480
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5481
            $queryBuilder->select('*')
5482
                ->from($table)
5483
                ->where(
5484
                    $queryBuilder->expr()->eq(
5485
                        'pid',
5486
                        $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
5487
                    ),
5488
                    $queryBuilder->expr()->eq(
5489
                        't3ver_wsid',
5490
                        $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5491
                    )
5492
                );
5493
            if ($isLocalizedPage) {
5494
                // Add sys_language_uid = x restriction if discarding a localized page
5495
                $queryBuilder->andWhere(
5496
                    $queryBuilder->expr()->eq(
5497
                        $GLOBALS['TCA'][$table]['ctrl']['languageField'],
5498
                        $queryBuilder->createNamedParameter($sysLanguageId, \PDO::PARAM_INT)
5499
                    )
5500
                );
5501
            }
5502
            $statement = $queryBuilder->execute();
5503
            while ($row = $statement->fetch()) {
5504
                $this->discard($table, null, $row);
5505
            }
5506
        }
5507
    }
5508
5509
    /**
5510
     * Discard record relations like inline and MM of a record.
5511
     *
5512
     * @param string $table Table name of this record
5513
     * @param array $record The record row to handle
5514
     */
5515
    protected function discardRecordRelations(string $table, array $record): void
5516
    {
5517
        foreach ($record as $field => $value) {
5518
            $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'] ?? null;
5519
            if (!isset($fieldConfig['type'])) {
5520
                continue;
5521
            }
5522
            if ($fieldConfig['type'] === 'inline') {
5523
                $foreignTable = $fieldConfig['foreign_table'] ?? null;
5524
                if (!$foreignTable
5525
                     || (isset($fieldConfig['behaviour']['enableCascadingDelete'])
5526
                        && (bool)$fieldConfig['behaviour']['enableCascadingDelete'] === false)
5527
                ) {
5528
                    continue;
5529
                }
5530
                $inlineType = $this->getInlineFieldType($fieldConfig);
5531
                if ($inlineType === 'list' || $inlineType === 'field') {
5532
                    $dbAnalysis = $this->createRelationHandlerInstance();
5533
                    $dbAnalysis->start($value, $fieldConfig['foreign_table'], '', (int)$record['uid'], $table, $fieldConfig);
5534
                    $dbAnalysis->undeleteRecord = true;
5535
                    foreach ($dbAnalysis->itemArray as $relationRecord) {
5536
                        $this->discard($relationRecord['table'], (int)$relationRecord['id']);
5537
                    }
5538
                }
5539
            } elseif ($this->isReferenceField($fieldConfig) && !empty($fieldConfig['MM'])) {
5540
                $this->discardMmRelations($fieldConfig, $record);
5541
            }
5542
            // @todo not inline and not mm - probably not handled correctly and has no proper test coverage yet
5543
        }
5544
    }
5545
5546
    /**
5547
     * When a workspace record row is discarded that has mm relations, existing mm table rows need
5548
     * to be deleted. The method performs the delete operation depending on TCA field configuration.
5549
     *
5550
     * @param array $fieldConfig TCA configuration of this field
5551
     * @param array $record The full record of a left- or ride-side relation
5552
     */
5553
    protected function discardMmRelations(array $fieldConfig, array $record): void
5554
    {
5555
        $recordUid = (int)$record['uid'];
5556
        $mmTableName = $fieldConfig['MM'];
5557
        // left - non foreign - uid_local vs. right - foreign - uid_foreign decision
5558
        $relationUidFieldName = isset($fieldConfig['MM_opposite_field']) ? 'uid_foreign' : 'uid_local';
5559
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($mmTableName);
5560
        $queryBuilder->delete($mmTableName)->where(
5561
            // uid_local = given uid OR uid_foreign = given uid
5562
            $queryBuilder->expr()->eq($relationUidFieldName, $queryBuilder->createNamedParameter($recordUid, \PDO::PARAM_INT))
5563
        );
5564
        if (!empty($fieldConfig['MM_table_where']) && is_string($fieldConfig['MM_table_where'])) {
5565
            $queryBuilder->andWhere(
5566
                QueryHelper::stripLogicalOperatorPrefix(str_replace('###THIS_UID###', (string)$recordUid, $fieldConfig['MM_table_where']))
5567
            );
5568
        }
5569
        $mmMatchFields = $fieldConfig['MM_match_fields'] ?? [];
5570
        foreach ($mmMatchFields as $fieldName => $fieldValue) {
5571
            $queryBuilder->andWhere(
5572
                $queryBuilder->expr()->eq($fieldName, $queryBuilder->createNamedParameter($fieldValue, \PDO::PARAM_STR))
5573
            );
5574
        }
5575
        $queryBuilder->execute();
5576
    }
5577
5578
    /**
5579
     * Find localization overlays of a record and discard them.
5580
     *
5581
     * @param string $table Table of this record
5582
     * @param array $record Record row
5583
     */
5584
    protected function discardLocalizationOverlayRecords(string $table, array $record): void
5585
    {
5586
        if (!BackendUtility::isTableLocalizable($table)) {
5587
            return;
5588
        }
5589
        $uid = (int)$record['uid'];
5590
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5591
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5592
        $statement = $queryBuilder->select('*')
5593
            ->from($table)
5594
            ->where(
5595
                $queryBuilder->expr()->eq(
5596
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5597
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5598
                ),
5599
                $queryBuilder->expr()->eq(
5600
                    't3ver_wsid',
5601
                    $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5602
                )
5603
            )
5604
            ->execute();
5605
        while ($record = $statement->fetch()) {
5606
            $this->discard($table, null, $record);
5607
        }
5608
    }
5609
5610
    /*********************************************
5611
     *
5612
     * Cmd: Versioning
5613
     *
5614
     ********************************************/
5615
    /**
5616
     * Creates a new version of a record
5617
     * (Requires support in the table)
5618
     *
5619
     * @param string $table Table name
5620
     * @param int $id Record uid to versionize
5621
     * @param string $label Version label
5622
     * @param bool $delete If TRUE, the version is created to delete the record.
5623
     * @return int|null Returns the id of the new version (if any)
5624
     * @see copyRecord()
5625
     * @internal should only be used from within DataHandler
5626
     */
5627
    public function versionizeRecord($table, $id, $label, $delete = false)
5628
    {
5629
        $id = (int)$id;
5630
        // Stop any actions if the record is marked to be deleted:
5631
        // (this can occur if IRRE elements are versionized and child elements are removed)
5632
        if ($this->isElementToBeDeleted($table, $id)) {
5633
            return null;
5634
        }
5635
        if (!BackendUtility::isTableWorkspaceEnabled($table) || $id <= 0) {
5636
            $this->newlog('Versioning is not supported for this table "' . $table . '" / ' . $id, SystemLogErrorClassification::USER_ERROR);
5637
            return null;
5638
        }
5639
5640
        // Fetch record with permission check
5641
        $row = $this->recordInfoWithPermissionCheck($table, $id, Permission::PAGE_SHOW);
5642
5643
        // This checks if the record can be selected which is all that a copy action requires.
5644
        if ($row === false) {
5645
            $this->newlog(
5646
                'The record does not exist or you don\'t have correct permissions to make a new version (copy) of this record "' . $table . ':' . $id . '"',
5647
                SystemLogErrorClassification::USER_ERROR
5648
            );
5649
            return null;
5650
        }
5651
5652
        // Record must be online record, otherwise we would create a version of a version
5653
        if (($row['t3ver_oid'] ?? 0) > 0) {
5654
            $this->newlog('Record "' . $table . ':' . $id . '" you wanted to versionize was already a version in archive (record has an online ID)!', SystemLogErrorClassification::USER_ERROR);
5655
            return null;
5656
        }
5657
5658
        if ($delete && $this->cannotDeleteRecord($table, $id)) {
5659
            $this->newlog('Record cannot be deleted: ' . $this->cannotDeleteRecord($table, $id), SystemLogErrorClassification::USER_ERROR);
5660
            return null;
5661
        }
5662
5663
        // Set up the values to override when making a raw-copy:
5664
        $overrideArray = [
5665
            't3ver_oid' => $id,
5666
            't3ver_wsid' => $this->BE_USER->workspace,
5667
            't3ver_state' => (string)($delete ? new VersionState(VersionState::DELETE_PLACEHOLDER) : new VersionState(VersionState::DEFAULT_STATE)),
5668
            't3ver_stage' => 0,
5669
        ];
5670
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock'] ?? false) {
5671
            $overrideArray[$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
5672
        }
5673
        // Checking if the record already has a version in the current workspace of the backend user
5674
        $versionRecord = ['uid' => null];
5675
        if ($this->BE_USER->workspace !== 0) {
5676
            // Look for version already in workspace:
5677
            $versionRecord = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid');
5678
        }
5679
        // Create new version of the record and return the new uid
5680
        if (empty($versionRecord['uid'])) {
5681
            // Create raw-copy and return result:
5682
            // The information of the label to be used for the workspace record
5683
            // as well as the information whether the record shall be removed
5684
            // must be forwarded (creating delete placeholders on a workspace are
5685
            // done by copying the record and override several fields).
5686
            $workspaceOptions = [
5687
                'delete' => $delete,
5688
                'label' => $label,
5689
            ];
5690
            return $this->copyRecord_raw($table, $id, (int)$row['pid'], $overrideArray, $workspaceOptions);
5691
        }
5692
        // Reuse the existing record and return its uid
5693
        // (prior to TYPO3 CMS 6.2, an error was thrown here, which
5694
        // did not make much sense since the information is available)
5695
        return $versionRecord['uid'];
5696
    }
5697
5698
    /**
5699
     * Swaps MM-relations for current/swap record, see version_swap()
5700
     *
5701
     * @param string $table Table for the two input records
5702
     * @param int $id Current record (about to go offline)
5703
     * @param int $swapWith Swap record (about to go online)
5704
     * @see version_swap()
5705
     * @internal should only be used from within DataHandler
5706
     */
5707
    public function version_remapMMForVersionSwap($table, $id, $swapWith)
5708
    {
5709
        // Actually, selecting the records fully is only need if flexforms are found inside... This could be optimized ...
5710
        $currentRec = BackendUtility::getRecord($table, $id);
5711
        $swapRec = BackendUtility::getRecord($table, $swapWith);
5712
        $this->version_remapMMForVersionSwap_reg = [];
5713
        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5714
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fConf) {
5715
            $conf = $fConf['config'];
5716
            if ($this->isReferenceField($conf)) {
5717
                $allowedTables = $conf['type'] === 'group' ? ($conf['allowed'] ?? '') : $conf['foreign_table'];
5718
                $prependName = $conf['type'] === 'group' ? ($conf['prepend_tname'] ?? '') : '';
5719
                if ($conf['MM'] ?? false) {
5720
                    $dbAnalysis = $this->createRelationHandlerInstance();
5721
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $id, $table, $conf);
5722
                    if (!empty($dbAnalysis->getValueArray($prependName))) {
0 ignored issues
show
Bug introduced by
It seems like $prependName can also be of type string; however, parameter $prependTableName of TYPO3\CMS\Core\Database\...andler::getValueArray() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

5722
                    if (!empty($dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName))) {
Loading history...
5723
                        $this->version_remapMMForVersionSwap_reg[$id][$field] = [$dbAnalysis, $conf['MM'], $prependName];
5724
                    }
5725
                    $dbAnalysis = $this->createRelationHandlerInstance();
5726
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $swapWith, $table, $conf);
5727
                    if (!empty($dbAnalysis->getValueArray($prependName))) {
5728
                        $this->version_remapMMForVersionSwap_reg[$swapWith][$field] = [$dbAnalysis, $conf['MM'], $prependName];
5729
                    }
5730
                }
5731
            } elseif ($conf['type'] === 'flex') {
5732
                // Current record
5733
                $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5734
                    $fConf,
5735
                    $table,
5736
                    $field,
5737
                    $currentRec
5738
                );
5739
                $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5740
                $currentValueArray = GeneralUtility::xml2array($currentRec[$field]);
5741
                if (is_array($currentValueArray)) {
5742
                    $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $id, $field], 'version_remapMMForVersionSwap_flexFormCallBack');
5743
                }
5744
                // Swap record
5745
                $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5746
                    $fConf,
5747
                    $table,
5748
                    $field,
5749
                    $swapRec
5750
                );
5751
                $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5752
                $currentValueArray = GeneralUtility::xml2array($swapRec[$field]);
5753
                if (is_array($currentValueArray)) {
5754
                    $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $swapWith, $field], 'version_remapMMForVersionSwap_flexFormCallBack');
5755
                }
5756
            }
5757
        }
5758
        // Execute:
5759
        $this->version_remapMMForVersionSwap_execSwap($table, $id, $swapWith);
5760
    }
5761
5762
    /**
5763
     * Callback function for traversing the FlexForm structure in relation to ...
5764
     *
5765
     * @param array $pParams Array of parameters in num-indexes: table, uid, field
5766
     * @param array $dsConf TCA field configuration (from Data Structure XML)
5767
     * @param string $dataValue The value of the flexForm field
5768
     * @param string $dataValue_ext1 Not used.
5769
     * @param string $dataValue_ext2 Not used.
5770
     * @param string $path Path in flexforms
5771
     * @see version_remapMMForVersionSwap()
5772
     * @see checkValue_flex_procInData_travDS()
5773
     * @internal should only be used from within DataHandler
5774
     */
5775
    public function version_remapMMForVersionSwap_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
5776
    {
5777
        // Extract parameters:
5778
        [$table, $uid, $field] = $pParams;
5779
        if ($this->isReferenceField($dsConf)) {
5780
            $allowedTables = $dsConf['type'] === 'group' ? $dsConf['allowed'] : $dsConf['foreign_table'];
5781
            $prependName = $dsConf['type'] === 'group' ? $dsConf['prepend_tname'] : '';
5782
            if ($dsConf['MM']) {
5783
                /** @var RelationHandler $dbAnalysis */
5784
                $dbAnalysis = $this->createRelationHandlerInstance();
5785
                $dbAnalysis->start('', $allowedTables, $dsConf['MM'], $uid, $table, $dsConf);
5786
                $this->version_remapMMForVersionSwap_reg[$uid][$field . '/' . $path] = [$dbAnalysis, $dsConf['MM'], $prependName];
5787
            }
5788
        }
5789
    }
5790
5791
    /**
5792
     * Performing the remapping operations found necessary in version_remapMMForVersionSwap()
5793
     * It must be done in three steps with an intermediate "fake" uid. The UID can be something else than -$id (fx. 9999999+$id if you dare... :-)- as long as it is unique.
5794
     *
5795
     * @param string $table Table for the two input records
5796
     * @param int $id Current record (about to go offline)
5797
     * @param int $swapWith Swap record (about to go online)
5798
     * @see version_remapMMForVersionSwap()
5799
     * @internal should only be used from within DataHandler
5800
     */
5801
    public function version_remapMMForVersionSwap_execSwap($table, $id, $swapWith)
5802
    {
5803
        if (is_array($this->version_remapMMForVersionSwap_reg[$id] ?? false)) {
5804
            foreach ($this->version_remapMMForVersionSwap_reg[$id] as $field => $str) {
5805
                $str[0]->remapMM($str[1], $id, -$id, $str[2]);
5806
            }
5807
        }
5808
        if (is_array($this->version_remapMMForVersionSwap_reg[$swapWith] ?? false)) {
5809
            foreach ($this->version_remapMMForVersionSwap_reg[$swapWith] as $field => $str) {
5810
                $str[0]->remapMM($str[1], $swapWith, $id, $str[2]);
5811
            }
5812
        }
5813
        if (is_array($this->version_remapMMForVersionSwap_reg[$id] ?? false)) {
5814
            foreach ($this->version_remapMMForVersionSwap_reg[$id] as $field => $str) {
5815
                $str[0]->remapMM($str[1], -$id, $swapWith, $str[2]);
5816
            }
5817
        }
5818
    }
5819
5820
    /*********************************************
5821
     *
5822
     * Cmd: Helper functions
5823
     *
5824
     ********************************************/
5825
5826
    /**
5827
     * Returns an instance of DataHandler for handling local datamaps/cmdmaps
5828
     *
5829
     * @return DataHandler
5830
     */
5831
    protected function getLocalTCE()
5832
    {
5833
        $copyTCE = GeneralUtility::makeInstance(DataHandler::class, $this->referenceIndexUpdater);
5834
        $copyTCE->copyTree = $this->copyTree;
5835
        $copyTCE->enableLogging = $this->enableLogging;
5836
        // Transformations should NOT be carried out during copy
5837
        $copyTCE->dontProcessTransformations = true;
5838
        // make sure the isImporting flag is transferred, so all hooks know if
5839
        // the current process is an import process
5840
        $copyTCE->isImporting = $this->isImporting;
5841
        $copyTCE->bypassAccessCheckForRecords = $this->bypassAccessCheckForRecords;
5842
        $copyTCE->bypassWorkspaceRestrictions = $this->bypassWorkspaceRestrictions;
5843
        return $copyTCE;
5844
    }
5845
5846
    /**
5847
     * Processes the fields with references as registered during the copy process. This includes all FlexForm fields which had references.
5848
     * @internal should only be used from within DataHandler
5849
     */
5850
    public function remapListedDBRecords()
5851
    {
5852
        if (!empty($this->registerDBList)) {
5853
            $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5854
            foreach ($this->registerDBList as $table => $records) {
5855
                foreach ($records as $uid => $fields) {
5856
                    $newData = [];
5857
                    $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
5858
                    $theUidToUpdate_saveTo = BackendUtility::wsMapId($table, $theUidToUpdate);
5859
                    foreach ($fields as $fieldName => $value) {
5860
                        $conf = $GLOBALS['TCA'][$table]['columns'][$fieldName]['config'];
5861
                        switch ($conf['type']) {
5862
                            case 'group':
5863
                            case 'select':
5864
                                $vArray = $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
5865
                                if (is_array($vArray)) {
5866
                                    $newData[$fieldName] = implode(',', $vArray);
5867
                                }
5868
                                break;
5869
                            case 'flex':
5870
                                if ($value === 'FlexForm_reference') {
5871
                                    // This will fetch the new row for the element
5872
                                    $origRecordRow = $this->recordInfo($table, $theUidToUpdate, '*');
5873
                                    if (is_array($origRecordRow)) {
5874
                                        BackendUtility::workspaceOL($table, $origRecordRow);
5875
                                        // Get current data structure and value array:
5876
                                        $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5877
                                            ['config' => $conf],
5878
                                            $table,
5879
                                            $fieldName,
5880
                                            $origRecordRow
5881
                                        );
5882
                                        $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5883
                                        $currentValueArray = GeneralUtility::xml2array($origRecordRow[$fieldName]);
5884
                                        // Do recursive processing of the XML data:
5885
                                        $currentValueArray['data'] = $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $theUidToUpdate, $fieldName], 'remapListedDBRecords_flexFormCallBack');
5886
                                        // The return value should be compiled back into XML, ready to insert directly in the field (as we call updateDB() directly later):
5887
                                        if (is_array($currentValueArray['data'])) {
5888
                                            $newData[$fieldName] = $this->checkValue_flexArray2Xml($currentValueArray, true);
5889
                                        }
5890
                                    }
5891
                                }
5892
                                break;
5893
                            case 'inline':
5894
                                $this->remapListedDBRecords_procInline($conf, $value, $uid, $table);
5895
                                break;
5896
                            default:
5897
                                $this->logger->debug('Field type should not appear here: ' . $conf['type']);
5898
                        }
5899
                    }
5900
                    // If any fields were changed, those fields are updated!
5901
                    if (!empty($newData)) {
5902
                        $this->updateDB($table, $theUidToUpdate_saveTo, $newData);
5903
                    }
5904
                }
5905
            }
5906
        }
5907
    }
5908
5909
    /**
5910
     * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
5911
     *
5912
     * @param array $pParams Set of parameters in numeric array: table, uid, field
5913
     * @param array $dsConf TCA config for field (from Data Structure of course)
5914
     * @param string $dataValue Field value (from FlexForm XML)
5915
     * @param string $dataValue_ext1 Not used
5916
     * @param string $dataValue_ext2 Not used
5917
     * @return array Array where the "value" key carries the value.
5918
     * @see checkValue_flex_procInData_travDS()
5919
     * @see remapListedDBRecords()
5920
     * @internal should only be used from within DataHandler
5921
     */
5922
    public function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
5923
    {
5924
        // Extract parameters:
5925
        [$table, $uid, $field] = $pParams;
5926
        // If references are set for this field, set flag so they can be corrected later:
5927
        if ($this->isReferenceField($dsConf) && (string)$dataValue !== '') {
5928
            $vArray = $this->remapListedDBRecords_procDBRefs($dsConf, $dataValue, $uid, $table);
5929
            if (is_array($vArray)) {
5930
                $dataValue = implode(',', $vArray);
5931
            }
5932
        }
5933
        // Return
5934
        return ['value' => $dataValue];
5935
    }
5936
5937
    /**
5938
     * Performs remapping of old UID values to NEW uid values for a DB reference field.
5939
     *
5940
     * @param array $conf TCA field config
5941
     * @param string $value Field value
5942
     * @param int $MM_localUid UID of local record (for MM relations - might need to change if support for FlexForms should be done!)
5943
     * @param string $table Table name
5944
     * @return array|null Returns array of items ready to implode for field content.
5945
     * @see remapListedDBRecords()
5946
     * @internal should only be used from within DataHandler
5947
     */
5948
    public function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid, $table)
5949
    {
5950
        // Initialize variables
5951
        // Will be set TRUE if an upgrade should be done...
5952
        $set = false;
5953
        // Allowed tables for references.
5954
        $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5955
        // Table name to prepend the UID
5956
        $prependName = $conf['type'] === 'group' ? ($conf['prepend_tname'] ?? '') : '';
5957
        // Which tables that should possibly not be remapped
5958
        $dontRemapTables = GeneralUtility::trimExplode(',', $conf['dontRemapTablesOnCopy'] ?? '', true);
5959
        // Convert value to list of references:
5960
        $dbAnalysis = $this->createRelationHandlerInstance();
5961
        $dbAnalysis->registerNonTableValues = $conf['type'] === 'select' && ($conf['allowNonIdValues'] ?? false);
5962
        $dbAnalysis->start($value, $allowedTables, $conf['MM'] ?? '', $MM_localUid, $table, $conf);
5963
        // Traverse those references and map IDs:
5964
        foreach ($dbAnalysis->itemArray as $k => $v) {
5965
            $mapID = $this->copyMappingArray_merged[$v['table']][$v['id']] ?? 0;
5966
            if ($mapID && !in_array($v['table'], $dontRemapTables, true)) {
5967
                $dbAnalysis->itemArray[$k]['id'] = $mapID;
5968
                $set = true;
5969
            }
5970
        }
5971
        if (!empty($conf['MM'])) {
5972
            // Purge invalid items (live/version)
5973
            $dbAnalysis->purgeItemArray();
5974
            if ($dbAnalysis->isPurged()) {
5975
                $set = true;
5976
            }
5977
5978
            // If record has been versioned/copied in this process, handle invalid relations of the live record
5979
            $liveId = BackendUtility::getLiveVersionIdOfRecord($table, $MM_localUid);
5980
            $originalId = 0;
5981
            if (!empty($this->copyMappingArray_merged[$table])) {
5982
                $originalId = array_search($MM_localUid, $this->copyMappingArray_merged[$table]);
5983
            }
5984
            if (!empty($liveId) && !empty($originalId) && (int)$liveId === (int)$originalId) {
5985
                $liveRelations = $this->createRelationHandlerInstance();
5986
                $liveRelations->setWorkspaceId(0);
5987
                $liveRelations->start('', $allowedTables, $conf['MM'], $liveId, $table, $conf);
5988
                // Purge invalid relations in the live workspace ("0")
5989
                $liveRelations->purgeItemArray(0);
5990
                if ($liveRelations->isPurged()) {
5991
                    $liveRelations->writeMM($conf['MM'], $liveId, $prependName);
0 ignored issues
show
Bug introduced by
It seems like $prependName can also be of type string; however, parameter $prependTableName of TYPO3\CMS\Core\Database\RelationHandler::writeMM() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

5991
                    $liveRelations->writeMM($conf['MM'], $liveId, /** @scrutinizer ignore-type */ $prependName);
Loading history...
5992
                }
5993
            }
5994
        }
5995
        // If a change has been done, set the new value(s)
5996
        if ($set) {
5997
            if ($conf['MM'] ?? false) {
5998
                $dbAnalysis->writeMM($conf['MM'], $MM_localUid, $prependName);
5999
            } else {
6000
                return $dbAnalysis->getValueArray($prependName);
0 ignored issues
show
Bug introduced by
It seems like $prependName can also be of type string; however, parameter $prependTableName of TYPO3\CMS\Core\Database\...andler::getValueArray() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6000
                return $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName);
Loading history...
6001
            }
6002
        }
6003
        return null;
6004
    }
6005
6006
    /**
6007
     * Performs remapping of old UID values to NEW uid values for an inline field.
6008
     *
6009
     * @param array $conf TCA field config
6010
     * @param string $value Field value
6011
     * @param int $uid The uid of the ORIGINAL record
6012
     * @param string $table Table name
6013
     * @internal should only be used from within DataHandler
6014
     */
6015
    public function remapListedDBRecords_procInline($conf, $value, $uid, $table)
6016
    {
6017
        $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
6018
        if ($conf['foreign_table']) {
6019
            $inlineType = $this->getInlineFieldType($conf);
6020
            if ($inlineType === 'mm') {
6021
                $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
6022
            } elseif ($inlineType !== false) {
6023
                /** @var RelationHandler $dbAnalysis */
6024
                $dbAnalysis = $this->createRelationHandlerInstance();
6025
                $dbAnalysis->start($value, $conf['foreign_table'], '', 0, $table, $conf);
6026
6027
                $updatePidForRecords = [];
6028
                // Update values for specific versioned records
6029
                foreach ($dbAnalysis->itemArray as &$item) {
6030
                    $updatePidForRecords[$item['table']][] = $item['id'];
6031
                    $versionedId = $this->getAutoVersionId($item['table'], $item['id']);
6032
                    if ($versionedId !== null) {
6033
                        $updatePidForRecords[$item['table']][] = $versionedId;
6034
                        $item['id'] = $versionedId;
6035
                    }
6036
                }
6037
6038
                // Update child records if using pointer fields ('foreign_field'):
6039
                if ($inlineType === 'field') {
6040
                    $dbAnalysis->writeForeignField($conf, $uid, $theUidToUpdate);
6041
                }
6042
                $thePidToUpdate = null;
6043
                // If the current field is set on a page record, update the pid of related child records:
6044
                if ($table === 'pages') {
6045
                    $thePidToUpdate = $theUidToUpdate;
6046
                } elseif (isset($this->registerDBPids[$table][$uid])) {
6047
                    $thePidToUpdate = $this->registerDBPids[$table][$uid];
6048
                    $thePidToUpdate = $this->copyMappingArray_merged['pages'][$thePidToUpdate];
6049
                }
6050
6051
                // Update child records if change to pid is required
6052
                if ($thePidToUpdate && !empty($updatePidForRecords)) {
6053
                    // Ensure that only the default language page is used as PID
6054
                    $thePidToUpdate = $this->getDefaultLanguagePageId($thePidToUpdate);
6055
                    // @todo: this can probably go away
6056
                    // ensure, only live page ids are used as 'pid' values
6057
                    $liveId = BackendUtility::getLiveVersionIdOfRecord('pages', $theUidToUpdate);
6058
                    if ($liveId !== null) {
6059
                        $thePidToUpdate = $liveId;
6060
                    }
6061
                    $updateValues = ['pid' => $thePidToUpdate];
6062
                    foreach ($updatePidForRecords as $tableName => $uids) {
6063
                        if (empty($tableName) || empty($uids)) {
6064
                            continue;
6065
                        }
6066
                        $conn = GeneralUtility::makeInstance(ConnectionPool::class)
6067
                            ->getConnectionForTable($tableName);
6068
                        foreach ($uids as $updateUid) {
6069
                            $conn->update($tableName, $updateValues, ['uid' => $updateUid]);
6070
                        }
6071
                    }
6072
                }
6073
            }
6074
        }
6075
    }
6076
6077
    /**
6078
     * Processes the $this->remapStack at the end of copying, inserting, etc. actions.
6079
     * The remapStack takes care about the correct mapping of new and old uids in case of relational data.
6080
     * @internal should only be used from within DataHandler
6081
     */
6082
    public function processRemapStack()
6083
    {
6084
        // Processes the remap stack:
6085
        if (is_array($this->remapStack)) {
0 ignored issues
show
introduced by
The condition is_array($this->remapStack) is always true.
Loading history...
6086
            $remapFlexForms = [];
6087
            $hookPayload = [];
6088
6089
            $newValue = null;
6090
            foreach ($this->remapStack as $remapAction) {
6091
                // If no position index for the arguments was set, skip this remap action:
6092
                if (!is_array($remapAction['pos'])) {
6093
                    continue;
6094
                }
6095
                // Load values from the argument array in remapAction:
6096
                $field = $remapAction['field'];
6097
                $id = $remapAction['args'][$remapAction['pos']['id']];
6098
                $rawId = $id;
6099
                $table = $remapAction['args'][$remapAction['pos']['table']];
6100
                $valueArray = $remapAction['args'][$remapAction['pos']['valueArray']];
6101
                $tcaFieldConf = $remapAction['args'][$remapAction['pos']['tcaFieldConf']];
6102
                $additionalData = $remapAction['additionalData'] ?? [];
6103
                // The record is new and has one or more new ids (in case of versioning/workspaces):
6104
                if (strpos($id, 'NEW') !== false) {
6105
                    // Replace NEW...-ID with real uid:
6106
                    $id = $this->substNEWwithIDs[$id];
6107
                    // If the new parent record is on a non-live workspace or versionized, it has another new id:
6108
                    if (isset($this->autoVersionIdMap[$table][$id])) {
6109
                        $id = $this->autoVersionIdMap[$table][$id];
6110
                    }
6111
                    $remapAction['args'][$remapAction['pos']['id']] = $id;
6112
                }
6113
                // Replace relations to NEW...-IDs in field value (uids of child records):
6114
                if (is_array($valueArray)) {
6115
                    foreach ($valueArray as $key => $value) {
6116
                        if (strpos($value, 'NEW') !== false) {
6117
                            if (strpos($value, '_') === false) {
6118
                                $affectedTable = $tcaFieldConf['foreign_table'] ?? '';
6119
                                $prependTable = false;
6120
                            } else {
6121
                                $parts = explode('_', $value);
6122
                                $value = array_pop($parts);
6123
                                $affectedTable = implode('_', $parts);
6124
                                $prependTable = true;
6125
                            }
6126
                            $value = $this->substNEWwithIDs[$value];
6127
                            // The record is new, but was also auto-versionized and has another new id:
6128
                            if (isset($this->autoVersionIdMap[$affectedTable][$value])) {
6129
                                $value = $this->autoVersionIdMap[$affectedTable][$value];
6130
                            }
6131
                            if ($prependTable) {
6132
                                $value = $affectedTable . '_' . $value;
6133
                            }
6134
                            // Set a hint that this was a new child record:
6135
                            $this->newRelatedIDs[$affectedTable][] = $value;
6136
                            $valueArray[$key] = $value;
6137
                        }
6138
                    }
6139
                    $remapAction['args'][$remapAction['pos']['valueArray']] = $valueArray;
6140
                }
6141
                // Process the arguments with the defined function:
6142
                if (!empty($remapAction['func'])) {
6143
                    $newValue = call_user_func_array([$this, $remapAction['func']], $remapAction['args']);
6144
                }
6145
                // If array is returned, check for maxitems condition, if string is returned this was already done:
6146
                if (is_array($newValue)) {
6147
                    $newValue = implode(',', $this->checkValue_checkMax($tcaFieldConf, $newValue));
6148
                    // The reference casting is only required if
6149
                    // checkValue_group_select_processDBdata() returns an array
6150
                    $newValue = $this->castReferenceValue($newValue, $tcaFieldConf);
6151
                }
6152
                // Update in database (list of children (csv) or number of relations (foreign_field)):
6153
                if (!empty($field)) {
6154
                    $fieldArray = [$field => $newValue];
6155
                    if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
6156
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
6157
                    }
6158
                    $this->updateDB($table, $id, $fieldArray);
6159
                } elseif (!empty($additionalData['flexFormId']) && !empty($additionalData['flexFormPath'])) {
6160
                    // Collect data to update FlexForms
6161
                    $flexFormId = $additionalData['flexFormId'];
6162
                    $flexFormPath = $additionalData['flexFormPath'];
6163
6164
                    if (!isset($remapFlexForms[$flexFormId])) {
6165
                        $remapFlexForms[$flexFormId] = [];
6166
                    }
6167
6168
                    $remapFlexForms[$flexFormId][$flexFormPath] = $newValue;
6169
                }
6170
6171
                // Collect elements that shall trigger processDatamap_afterDatabaseOperations
6172
                if (isset($this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'])) {
6173
                    $hookArgs = $this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'];
6174
                    if (!isset($hookPayload[$table][$rawId])) {
6175
                        $hookPayload[$table][$rawId] = [
6176
                            'status' => $hookArgs['status'],
6177
                            'fieldArray' => $hookArgs['fieldArray'],
6178
                            'hookObjects' => $hookArgs['hookObjectsArr'],
6179
                        ];
6180
                    }
6181
                    $hookPayload[$table][$rawId]['fieldArray'][$field] = $newValue;
6182
                }
6183
            }
6184
6185
            if ($remapFlexForms) {
6186
                foreach ($remapFlexForms as $flexFormId => $modifications) {
6187
                    $this->updateFlexFormData((string)$flexFormId, $modifications);
6188
                }
6189
            }
6190
6191
            foreach ($hookPayload as $tableName => $rawIdPayload) {
6192
                foreach ($rawIdPayload as $rawId => $payload) {
6193
                    foreach ($payload['hookObjects'] as $hookObject) {
6194
                        if (!method_exists($hookObject, 'processDatamap_afterDatabaseOperations')) {
6195
                            continue;
6196
                        }
6197
                        $hookObject->processDatamap_afterDatabaseOperations(
6198
                            $payload['status'],
6199
                            $tableName,
6200
                            $rawId,
6201
                            $payload['fieldArray'],
6202
                            $this
6203
                        );
6204
                    }
6205
                }
6206
            }
6207
        }
6208
        // Processes the remap stack actions:
6209
        if ($this->remapStackActions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->remapStackActions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
6210
            foreach ($this->remapStackActions as $action) {
6211
                if (isset($action['callback'], $action['arguments'])) {
6212
                    call_user_func_array($action['callback'], $action['arguments']);
6213
                }
6214
            }
6215
        }
6216
        // Reset:
6217
        $this->remapStack = [];
6218
        $this->remapStackRecords = [];
6219
        $this->remapStackActions = [];
6220
    }
6221
6222
    /**
6223
     * Updates FlexForm data.
6224
     *
6225
     * @param string $flexFormId e.g. <table>:<uid>:<field>
6226
     * @param array $modifications Modifications with paths and values (e.g. 'sDEF/lDEV/field/vDEF' => 'TYPO3')
6227
     */
6228
    protected function updateFlexFormData($flexFormId, array $modifications)
6229
    {
6230
        [$table, $uid, $field] = explode(':', $flexFormId, 3);
6231
6232
        if (!MathUtility::canBeInterpretedAsInteger($uid) && !empty($this->substNEWwithIDs[$uid])) {
6233
            $uid = $this->substNEWwithIDs[$uid];
6234
        }
6235
6236
        $record = $this->recordInfo($table, $uid, '*');
6237
6238
        if (!$table || !$uid || !$field || !is_array($record)) {
6239
            return;
6240
        }
6241
6242
        BackendUtility::workspaceOL($table, $record);
6243
6244
        // Get current data structure and value array:
6245
        $valueStructure = GeneralUtility::xml2array($record[$field]);
6246
6247
        // Do recursive processing of the XML data:
6248
        foreach ($modifications as $path => $value) {
6249
            $valueStructure['data'] = ArrayUtility::setValueByPath(
6250
                $valueStructure['data'],
6251
                $path,
6252
                $value
6253
            );
6254
        }
6255
6256
        if (is_array($valueStructure['data'])) {
6257
            // The return value should be compiled back into XML
6258
            $values = [
6259
                $field => $this->checkValue_flexArray2Xml($valueStructure, true),
6260
            ];
6261
6262
            $this->updateDB($table, $uid, $values);
6263
        }
6264
    }
6265
6266
    /**
6267
     * Adds an instruction to the remap action stack (used with IRRE).
6268
     *
6269
     * @param string $table The affected table
6270
     * @param int|string $id The affected ID
6271
     * @param callable $callback The callback information (object and method)
6272
     * @param array $arguments The arguments to be used with the callback
6273
     * @internal should only be used from within DataHandler
6274
     */
6275
    public function addRemapAction($table, $id, callable $callback, array $arguments)
6276
    {
6277
        $this->remapStackActions[] = [
6278
            'affects' => [
6279
                'table' => $table,
6280
                'id' => $id
6281
            ],
6282
            'callback' => $callback,
6283
            'arguments' => $arguments
6284
        ];
6285
    }
6286
6287
    /**
6288
     * If a parent record was versionized on a workspace in $this->process_datamap,
6289
     * it might be possible, that child records (e.g. on using IRRE) were affected.
6290
     * This function finds these relations and updates their uids in the $incomingFieldArray.
6291
     * The $incomingFieldArray is updated by reference!
6292
     *
6293
     * @param string $table Table name of the parent record
6294
     * @param int $id Uid of the parent record
6295
     * @param array $incomingFieldArray Reference to the incomingFieldArray of process_datamap
6296
     * @param array $registerDBList Reference to the $registerDBList array that was created/updated by versionizing calls to DataHandler in process_datamap.
6297
     * @internal should only be used from within DataHandler
6298
     */
6299
    public function getVersionizedIncomingFieldArray($table, $id, &$incomingFieldArray, &$registerDBList): void
6300
    {
6301
        if (!isset($registerDBList[$table][$id]) || !is_array($registerDBList[$table][$id])) {
6302
            return;
6303
        }
6304
        foreach ($incomingFieldArray as $field => $value) {
6305
            $foreignTable = $GLOBALS['TCA'][$table]['columns'][$field]['config']['foreign_table'] ?? '';
6306
            if (($registerDBList[$table][$id][$field] ?? false)
6307
                && !empty($foreignTable)
6308
            ) {
6309
                $newValueArray = [];
6310
                $origValueArray = is_array($value) ? $value : explode(',', $value);
6311
                // Update the uids of the copied records, but also take care about new records:
6312
                foreach ($origValueArray as $childId) {
6313
                    $newValueArray[] = $this->autoVersionIdMap[$foreignTable][$childId] ?? $childId;
6314
                }
6315
                // Set the changed value to the $incomingFieldArray
6316
                $incomingFieldArray[$field] = implode(',', $newValueArray);
6317
            }
6318
        }
6319
        // Clean up the $registerDBList array:
6320
        unset($registerDBList[$table][$id]);
6321
        if (empty($registerDBList[$table])) {
6322
            unset($registerDBList[$table]);
6323
        }
6324
    }
6325
6326
    /**
6327
     * Simple helper method to hard delete one row from table ignoring delete TCA field
6328
     *
6329
     * @param string $table A row from this table should be deleted
6330
     * @param int $uid Uid of row to be deleted
6331
     */
6332
    protected function hardDeleteSingleRecord(string $table, int $uid): void
6333
    {
6334
        GeneralUtility::makeInstance(ConnectionPool::class)
6335
            ->getConnectionForTable($table)
6336
            ->delete($table, ['uid' => $uid], [\PDO::PARAM_INT]);
6337
    }
6338
6339
    /*****************************
6340
     *
6341
     * Access control / Checking functions
6342
     *
6343
     *****************************/
6344
    /**
6345
     * Checking group modify_table access list
6346
     *
6347
     * @param string $table Table name
6348
     * @return bool Returns TRUE if the user has general access to modify the $table
6349
     * @internal should only be used from within DataHandler
6350
     */
6351
    public function checkModifyAccessList($table)
6352
    {
6353
        $res = $this->admin || (!$this->tableAdminOnly($table) && isset($this->BE_USER->groupData['tables_modify']) && GeneralUtility::inList($this->BE_USER->groupData['tables_modify'], $table));
6354
        // Hook 'checkModifyAccessList': Post-processing of the state of access
6355
        foreach ($this->getCheckModifyAccessListHookObjects() as $hookObject) {
6356
            /** @var DataHandlerCheckModifyAccessListHookInterface $hookObject */
6357
            $hookObject->checkModifyAccessList($res, $table, $this);
6358
        }
6359
        return $res;
6360
    }
6361
6362
    /**
6363
     * Checking if a record with uid $id from $table is in the BE_USERS webmounts which is required for editing etc.
6364
     *
6365
     * @param string $table Table name
6366
     * @param int $id UID of record
6367
     * @return bool Returns TRUE if OK. Cached results.
6368
     * @internal should only be used from within DataHandler
6369
     */
6370
    public function isRecordInWebMount($table, $id)
6371
    {
6372
        if (!isset($this->isRecordInWebMount_Cache[$table . ':' . $id])) {
6373
            $recP = $this->getRecordProperties($table, $id);
6374
            $this->isRecordInWebMount_Cache[$table . ':' . $id] = $this->isInWebMount($recP['event_pid']);
6375
        }
6376
        return $this->isRecordInWebMount_Cache[$table . ':' . $id];
6377
    }
6378
6379
    /**
6380
     * Checks if the input page ID is in the BE_USER webmounts
6381
     *
6382
     * @param int $pid Page ID to check
6383
     * @return bool TRUE if OK. Cached results.
6384
     * @internal should only be used from within DataHandler
6385
     */
6386
    public function isInWebMount($pid)
6387
    {
6388
        if (!isset($this->isInWebMount_Cache[$pid])) {
6389
            $this->isInWebMount_Cache[$pid] = $this->BE_USER->isInWebMount($pid);
6390
        }
6391
        return $this->isInWebMount_Cache[$pid];
6392
    }
6393
6394
    /**
6395
     * Checks if user may update a record with uid=$id from $table
6396
     *
6397
     * @param string $table Record table
6398
     * @param int $id Record UID
6399
     * @param array|bool $data Record data
6400
     * @param array $hookObjectsArr Hook objects
6401
     * @return bool Returns TRUE if the user may update the record given by $table and $id
6402
     * @internal should only be used from within DataHandler
6403
     */
6404
    public function checkRecordUpdateAccess($table, $id, $data = false, $hookObjectsArr = null)
6405
    {
6406
        $res = null;
6407
        if (is_array($hookObjectsArr)) {
6408
            foreach ($hookObjectsArr as $hookObj) {
6409
                if (method_exists($hookObj, 'checkRecordUpdateAccess')) {
6410
                    $res = $hookObj->checkRecordUpdateAccess($table, $id, $data, $res, $this);
6411
                }
6412
            }
6413
            if (isset($res)) {
6414
                return (bool)$res;
6415
            }
6416
        }
6417
        $res = false;
6418
6419
        if ($GLOBALS['TCA'][$table] && (int)$id > 0) {
6420
            $cacheId = 'checkRecordUpdateAccess_' . $table . '_' . $id;
6421
6422
            // If information is cached, return it
6423
            $cachedValue = $this->runtimeCache->get($cacheId);
6424
            if (!empty($cachedValue)) {
6425
                return $cachedValue;
6426
            }
6427
6428
            if ($table === 'pages' || ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap))) {
6429
                // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
6430
                $perms = Permission::PAGE_EDIT;
6431
            } else {
6432
                $perms = Permission::CONTENT_EDIT;
6433
            }
6434
            if ($this->doesRecordExist($table, $id, $perms)) {
6435
                $res = 1;
6436
            }
6437
            // Cache the result
6438
            $this->runtimeCache->set($cacheId, $res);
6439
        }
6440
        return $res;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $res also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
6441
    }
6442
6443
    /**
6444
     * Checks if user may insert a record from $insertTable on $pid
6445
     *
6446
     * @param string $insertTable Tablename to check
6447
     * @param int $pid Integer PID
6448
     * @param int $action For logging: Action number.
6449
     * @return bool Returns TRUE if the user may insert a record from table $insertTable on page $pid
6450
     * @internal should only be used from within DataHandler
6451
     */
6452
    public function checkRecordInsertAccess($insertTable, $pid, $action = SystemLogDatabaseAction::INSERT)
6453
    {
6454
        $pid = (int)$pid;
6455
        if ($pid < 0) {
6456
            return false;
6457
        }
6458
        // If information is cached, return it
6459
        if (isset($this->recInsertAccessCache[$insertTable][$pid])) {
6460
            return $this->recInsertAccessCache[$insertTable][$pid];
6461
        }
6462
6463
        $res = false;
6464
        if ($insertTable === 'pages') {
6465
            $perms = Permission::PAGE_NEW;
6466
        } elseif (($insertTable === 'sys_file_reference') && array_key_exists('pages', $this->datamap)) {
6467
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
6468
            $perms = Permission::PAGE_EDIT;
6469
        } else {
6470
            $perms = Permission::CONTENT_EDIT;
6471
        }
6472
        $pageExists = (bool)$this->doesRecordExist('pages', $pid, $perms);
6473
        // If either admin and root-level or if page record exists and 1) if 'pages' you may create new ones 2) if page-content, new content items may be inserted on the $pid page
6474
        if ($pageExists || $pid === 0 && ($this->admin || BackendUtility::isRootLevelRestrictionIgnored($insertTable))) {
6475
            // Check permissions
6476
            if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
6477
                $res = true;
6478
                // Cache the result
6479
                $this->recInsertAccessCache[$insertTable][$pid] = $res;
6480
            } elseif ($this->enableLogging) {
6481
                $propArr = $this->getRecordProperties('pages', $pid);
6482
                $this->log($insertTable, $pid, $action, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to insert record on page \'%s\' (%s) where this table, %s, is not allowed', 11, [$propArr['header'], $pid, $insertTable], $propArr['event_pid']);
6483
            }
6484
        } elseif ($this->enableLogging) {
6485
            $propArr = $this->getRecordProperties('pages', $pid);
6486
            $this->log($insertTable, $pid, $action, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to insert a record on page \'%s\' (%s) from table \'%s\' without permissions. Or non-existing page.', 12, [$propArr['header'], $pid, $insertTable], $propArr['event_pid']);
6487
        }
6488
        return $res;
6489
    }
6490
6491
    /**
6492
     * Checks if a table is allowed on a certain page id according to allowed tables set for the page "doktype" and its [ctrl][rootLevel]-settings if any.
6493
     *
6494
     * @param int $page_uid Page id for which to check, including 0 (zero) if checking for page tree root.
6495
     * @param string $checkTable Table name to check
6496
     * @return bool TRUE if OK
6497
     * @internal should only be used from within DataHandler
6498
     */
6499
    public function isTableAllowedForThisPage($page_uid, $checkTable)
6500
    {
6501
        $page_uid = (int)$page_uid;
6502
        $rootLevelSetting = (int)($GLOBALS['TCA'][$checkTable]['ctrl']['rootLevel'] ?? 0);
6503
        // Check if rootLevel flag is set and we're trying to insert on rootLevel - and reversed - and that the table is not "pages" which are allowed anywhere.
6504
        if ($checkTable !== 'pages' && $rootLevelSetting !== -1 && ($rootLevelSetting xor !$page_uid)) {
6505
            return false;
6506
        }
6507
        $allowed = false;
6508
        // Check root-level
6509
        if (!$page_uid) {
6510
            if ($this->admin || BackendUtility::isRootLevelRestrictionIgnored($checkTable)) {
6511
                $allowed = true;
6512
            }
6513
        } else {
6514
            // Check non-root-level
6515
            $doktype = $this->pageInfo($page_uid, 'doktype');
6516
            $allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
6517
            $allowedArray = GeneralUtility::trimExplode(',', $allowedTableList, true);
6518
            // If all tables or the table is listed as an allowed type, return TRUE
6519
            if (strpos($allowedTableList, '*') !== false || in_array($checkTable, $allowedArray, true)) {
6520
                $allowed = true;
6521
            }
6522
        }
6523
        return $allowed;
6524
    }
6525
6526
    /**
6527
     * Checks if record can be selected based on given permission criteria
6528
     *
6529
     * @param string $table Record table name
6530
     * @param int $id Record UID
6531
     * @param int $perms Permission restrictions to observe: integer that will be bitwise AND'ed.
6532
     * @return bool Returns TRUE if the record given by $table, $id and $perms can be selected
6533
     *
6534
     * @throws \RuntimeException
6535
     * @internal should only be used from within DataHandler
6536
     */
6537
    public function doesRecordExist($table, $id, int $perms)
6538
    {
6539
        return $this->recordInfoWithPermissionCheck($table, $id, $perms, 'uid, pid') !== false;
6540
    }
6541
6542
    /**
6543
     * Looks up a page based on permissions.
6544
     *
6545
     * @param int $id Page id
6546
     * @param int $perms Permission integer
6547
     * @param array $columns Columns to select
6548
     * @return bool|array
6549
     * @internal
6550
     * @see doesRecordExist()
6551
     */
6552
    protected function doesRecordExist_pageLookUp($id, $perms, $columns = ['uid'])
6553
    {
6554
        $permission = new Permission($perms);
6555
        $cacheId = md5('doesRecordExist_pageLookUp_' . $id . '_' . $perms . '_' . implode(
6556
            '_',
6557
            $columns
6558
        ) . '_' . (string)$this->admin);
6559
6560
        // If result is cached, return it
6561
        $cachedResult = $this->runtimeCache->get($cacheId);
6562
        if (!empty($cachedResult)) {
6563
            return $cachedResult;
6564
        }
6565
6566
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6567
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6568
        $queryBuilder
6569
            ->select(...$columns)
6570
            ->from('pages')
6571
            ->where($queryBuilder->expr()->eq(
6572
                'uid',
6573
                $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
6574
            ));
6575
        if (!$permission->nothingIsGranted() && !$this->admin) {
6576
            $queryBuilder->andWhere($this->BE_USER->getPagePermsClause($perms));
6577
        }
6578
        if (!$this->admin && $GLOBALS['TCA']['pages']['ctrl']['editlock'] &&
6579
            ($permission->editPagePermissionIsGranted() || $permission->deletePagePermissionIsGranted() || $permission->editContentPermissionIsGranted())
6580
        ) {
6581
            $queryBuilder->andWhere($queryBuilder->expr()->eq(
6582
                $GLOBALS['TCA']['pages']['ctrl']['editlock'],
6583
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
6584
            ));
6585
        }
6586
6587
        $row = $queryBuilder->execute()->fetch();
6588
        $this->runtimeCache->set($cacheId, $row);
6589
6590
        return $row;
6591
    }
6592
6593
    /**
6594
     * Checks if a whole branch of pages exists
6595
     *
6596
     * Tests the branch under $pid like doesRecordExist(), but it doesn't test the page with $pid as uid - use doesRecordExist() for this purpose.
6597
     * If $recurse is set, the function will follow subpages. This MUST be set, if we need the id-list for deleting pages or else we get an incomplete list
6598
     *
6599
     * @param string $inList List of page uids, this is added to and returned in the end
6600
     * @param int $pid Page ID to select subpages from.
6601
     * @param int $perms Perms integer to check each page record for.
6602
     * @param bool $recurse Recursion flag: If set, it will go out through the branch.
6603
     * @return string|int List of page IDs in branch, if there are subpages, empty string if there are none or -1 if no permission
6604
     * @internal should only be used from within DataHandler
6605
     */
6606
    public function doesBranchExist($inList, $pid, $perms, $recurse)
6607
    {
6608
        $pid = (int)$pid;
6609
        $perms = (int)$perms;
6610
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6611
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6612
        $result = $queryBuilder
6613
            ->select('uid', 'perms_userid', 'perms_groupid', 'perms_user', 'perms_group', 'perms_everybody')
6614
            ->from('pages')
6615
            ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
6616
            ->orderBy('sorting')
6617
            ->execute();
6618
        while ($row = $result->fetch()) {
6619
            // IF admin, then it's OK
6620
            if ($this->admin || $this->BE_USER->doesUserHaveAccess($row, $perms)) {
6621
                $inList .= $row['uid'] . ',';
6622
                if ($recurse) {
6623
                    // Follow the subpages recursively...
6624
                    $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
6625
                    if ($inList === -1) {
6626
                        return -1;
6627
                    }
6628
                }
6629
            } else {
6630
                // No permissions
6631
                return -1;
6632
            }
6633
        }
6634
        return $inList;
6635
    }
6636
6637
    /**
6638
     * Checks if the $table is readOnly
6639
     *
6640
     * @param string $table Table name
6641
     * @return bool TRUE, if readonly
6642
     * @internal should only be used from within DataHandler
6643
     */
6644
    public function tableReadOnly($table)
6645
    {
6646
        // Returns TRUE if table is readonly
6647
        return (bool)($GLOBALS['TCA'][$table]['ctrl']['readOnly'] ?? false);
6648
    }
6649
6650
    /**
6651
     * Checks if the $table is only editable by admin-users
6652
     *
6653
     * @param string $table Table name
6654
     * @return bool TRUE, if readonly
6655
     * @internal should only be used from within DataHandler
6656
     */
6657
    public function tableAdminOnly($table)
6658
    {
6659
        // Returns TRUE if table is admin-only
6660
        return !empty($GLOBALS['TCA'][$table]['ctrl']['adminOnly']);
6661
    }
6662
6663
    /**
6664
     * Checks if page $id is a uid in the rootline of page id $destinationId
6665
     * Used when moving a page
6666
     *
6667
     * @param int $destinationId Destination Page ID to test
6668
     * @param int $id Page ID to test for presence inside Destination
6669
     * @return bool Returns FALSE if ID is inside destination (including equal to)
6670
     * @internal should only be used from within DataHandler
6671
     */
6672
    public function destNotInsideSelf($destinationId, $id)
6673
    {
6674
        $loopCheck = 100;
6675
        $destinationId = (int)$destinationId;
6676
        $id = (int)$id;
6677
        if ($destinationId === $id) {
6678
            return false;
6679
        }
6680
        while ($destinationId !== 0 && $loopCheck > 0) {
6681
            $loopCheck--;
6682
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6683
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6684
            $result = $queryBuilder
6685
                ->select('pid', 'uid', 't3ver_oid', 't3ver_wsid')
6686
                ->from('pages')
6687
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($destinationId, \PDO::PARAM_INT)))
6688
                ->execute();
6689
            if ($row = $result->fetch()) {
6690
                // Ensure that the moved location is used as the PID value
6691
                BackendUtility::workspaceOL('pages', $row, $this->BE_USER->workspace);
6692
                if ($row['pid'] == $id) {
6693
                    return false;
6694
                }
6695
                $destinationId = (int)$row['pid'];
6696
            } else {
6697
                return false;
6698
            }
6699
        }
6700
        return true;
6701
    }
6702
6703
    /**
6704
     * Generate an array of fields to be excluded from editing for the user. Based on "exclude"-field in TCA and a look up in non_exclude_fields
6705
     * Will also generate this list for admin-users so they must be check for before calling the function
6706
     *
6707
     * @return array Array of [table]-[field] pairs to exclude from editing.
6708
     * @internal should only be used from within DataHandler
6709
     */
6710
    public function getExcludeListArray()
6711
    {
6712
        $list = [];
6713
        if (isset($this->BE_USER->groupData['non_exclude_fields'])) {
6714
            $nonExcludeFieldsArray = array_flip(GeneralUtility::trimExplode(',', $this->BE_USER->groupData['non_exclude_fields']));
6715
            foreach ($GLOBALS['TCA'] as $table => $tableConfiguration) {
6716
                if (isset($tableConfiguration['columns'])) {
6717
                    foreach ($tableConfiguration['columns'] as $field => $config) {
6718
                        $isExcludeField = ($config['exclude'] ?? false);
6719
                        $isOnlyVisibleForAdmins = ($GLOBALS['TCA'][$table]['columns'][$field]['displayCond'] ?? '') === 'HIDE_FOR_NON_ADMINS';
6720
                        $editorHasPermissionForThisField = isset($nonExcludeFieldsArray[$table . ':' . $field]);
6721
                        if ($isOnlyVisibleForAdmins || ($isExcludeField && !$editorHasPermissionForThisField)) {
6722
                            $list[] = $table . '-' . $field;
6723
                        }
6724
                    }
6725
                }
6726
            }
6727
        }
6728
6729
        return $list;
6730
    }
6731
6732
    /**
6733
     * Checks if there are records on a page from tables that are not allowed
6734
     *
6735
     * @param int|string $page_uid Page ID
6736
     * @param int $doktype Page doktype
6737
     * @return bool|array Returns a list of the tables that are 'present' on the page but not allowed with the page_uid/doktype
6738
     * @internal should only be used from within DataHandler
6739
     */
6740
    public function doesPageHaveUnallowedTables($page_uid, $doktype)
6741
    {
6742
        $page_uid = (int)$page_uid;
6743
        if (!$page_uid) {
6744
            // Not a number. Probably a new page
6745
            return false;
6746
        }
6747
        $allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
6748
        // If all tables are allowed, return early
6749
        if (strpos($allowedTableList, '*') !== false) {
6750
            return false;
6751
        }
6752
        $allowedArray = GeneralUtility::trimExplode(',', $allowedTableList, true);
6753
        $tableList = [];
6754
        $allTableNames = $this->compileAdminTables();
6755
        foreach ($allTableNames as $table) {
6756
            // If the table is not in the allowed list, check if there are records...
6757
            if (in_array($table, $allowedArray, true)) {
6758
                continue;
6759
            }
6760
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6761
            $queryBuilder->getRestrictions()->removeAll();
6762
            $count = $queryBuilder
6763
                ->count('uid')
6764
                ->from($table)
6765
                ->where($queryBuilder->expr()->eq(
6766
                    'pid',
6767
                    $queryBuilder->createNamedParameter($page_uid, \PDO::PARAM_INT)
6768
                ))
6769
                ->execute()
6770
                ->fetchColumn(0);
6771
            if ($count) {
6772
                $tableList[] = $table;
6773
            }
6774
        }
6775
        return implode(',', $tableList);
0 ignored issues
show
Bug Best Practice introduced by
The expression return implode(',', $tableList) returns the type string which is incompatible with the documented return type array|boolean.
Loading history...
6776
    }
6777
6778
    /*****************************
6779
     *
6780
     * Information lookup
6781
     *
6782
     *****************************/
6783
    /**
6784
     * Returns the value of the $field from page $id
6785
     * NOTICE; the function caches the result for faster delivery next time. You can use this function repeatedly without performance loss since it doesn't look up the same record twice!
6786
     *
6787
     * @param int $id Page uid
6788
     * @param string $field Field name for which to return value
6789
     * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
6790
     * @internal should only be used from within DataHandler
6791
     */
6792
    public function pageInfo($id, $field)
6793
    {
6794
        if (!isset($this->pageCache[$id])) {
6795
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6796
            $queryBuilder->getRestrictions()->removeAll();
6797
            $row = $queryBuilder
6798
                ->select('*')
6799
                ->from('pages')
6800
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6801
                ->execute()
6802
                ->fetch();
6803
            if ($row) {
6804
                $this->pageCache[$id] = $row;
6805
            }
6806
        }
6807
        return $this->pageCache[$id][$field];
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->pageCache[$id][$field] returns the type array which is incompatible with the documented return type string.
Loading history...
6808
    }
6809
6810
    /**
6811
     * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
6812
     * NOTICE: No check for deleted or access!
6813
     *
6814
     * @param string $table Table name
6815
     * @param int $id UID of the record from $table
6816
     * @param string $fieldList Field list for the SELECT query, eg. "*" or "uid,pid,...
6817
     * @return array|null Returns the selected record on success, otherwise NULL.
6818
     * @internal should only be used from within DataHandler
6819
     */
6820
    public function recordInfo($table, $id, $fieldList)
6821
    {
6822
        // Skip, if searching for NEW records or there's no TCA table definition
6823
        if ((int)$id === 0 || !isset($GLOBALS['TCA'][$table])) {
6824
            return null;
6825
        }
6826
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6827
        $queryBuilder->getRestrictions()->removeAll();
6828
        $result = $queryBuilder
6829
            ->select(...GeneralUtility::trimExplode(',', $fieldList))
6830
            ->from($table)
6831
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6832
            ->execute()
6833
            ->fetch();
6834
        return $result ?: null;
6835
    }
6836
6837
    /**
6838
     * Checks if record exists with and without permission check and returns that row
6839
     *
6840
     * @param string $table Record table name
6841
     * @param int $id Record UID
6842
     * @param int $perms Permission restrictions to observe: An integer that will be bitwise AND'ed.
6843
     * @param string $fieldList - fields - default is '*'
6844
     * @throws \RuntimeException
6845
     * @return array<string,mixed>|false Row if exists and accessible, false otherwise
6846
     */
6847
    protected function recordInfoWithPermissionCheck(string $table, int $id, int $perms, string $fieldList = '*')
6848
    {
6849
        if ($this->bypassAccessCheckForRecords) {
6850
            $columns = GeneralUtility::trimExplode(',', $fieldList, true);
6851
6852
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6853
            $queryBuilder->getRestrictions()->removeAll();
6854
6855
            $record = $queryBuilder->select(...$columns)
6856
                ->from($table)
6857
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6858
                ->execute()
6859
                ->fetch();
6860
6861
            return $record ?: false;
6862
        }
6863
        if (!$perms) {
6864
            throw new \RuntimeException('Internal ERROR: no permissions to check for non-admin user', 1270853920);
6865
        }
6866
        // For all tables: Check if record exists:
6867
        $isWebMountRestrictionIgnored = BackendUtility::isWebMountRestrictionIgnored($table);
6868
        if (is_array($GLOBALS['TCA'][$table]) && $id > 0 && ($this->admin || $isWebMountRestrictionIgnored || $this->isRecordInWebMount($table, $id))) {
6869
            $columns = GeneralUtility::trimExplode(',', $fieldList, true);
6870
            if ($table !== 'pages') {
6871
                // Find record without checking page
6872
                // @todo: This should probably check for editlock
6873
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6874
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6875
                $output = $queryBuilder
6876
                    ->select(...$columns)
6877
                    ->from($table)
6878
                    ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6879
                    ->execute()
6880
                    ->fetch();
6881
                // If record found, check page as well:
6882
                if (is_array($output)) {
6883
                    // Looking up the page for record:
6884
                    $pageRec = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
6885
                    // Return TRUE if either a page was found OR if the PID is zero AND the user is ADMIN (in which case the record is at root-level):
6886
                    $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
6887
                    if (is_array($pageRec) || !$output['pid'] && ($this->admin || $isRootLevelRestrictionIgnored)) {
6888
                        return $output;
6889
                    }
6890
                }
6891
                return false;
6892
            }
6893
            return $this->doesRecordExist_pageLookUp($id, $perms, $columns);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->doesRecord...($id, $perms, $columns) also could return the type boolean which is incompatible with the documented return type array<string,mixed>|false.
Loading history...
6894
        }
6895
        return false;
6896
    }
6897
6898
    /**
6899
     * Returns an array with record properties, like header and pid
6900
     * No check for deleted or access is done!
6901
     * For versionized records, pid is resolved to its live versions pid.
6902
     * Used for logging
6903
     *
6904
     * @param string $table Table name
6905
     * @param int $id Uid of record
6906
     * @param bool $noWSOL If set, no workspace overlay is performed
6907
     * @return array Properties of record
6908
     * @internal should only be used from within DataHandler
6909
     */
6910
    public function getRecordProperties($table, $id, $noWSOL = false)
6911
    {
6912
        $row = $table === 'pages' && !$id ? ['title' => '[root-level]', 'uid' => 0, 'pid' => 0] : $this->recordInfo($table, $id, '*');
6913
        if (!$noWSOL) {
6914
            BackendUtility::workspaceOL($table, $row);
6915
        }
6916
        return $this->getRecordPropertiesFromRow($table, $row);
6917
    }
6918
6919
    /**
6920
     * Returns an array with record properties, like header and pid, based on the row
6921
     *
6922
     * @param string $table Table name
6923
     * @param array $row Input row
6924
     * @return array|null Output array
6925
     * @internal should only be used from within DataHandler
6926
     */
6927
    public function getRecordPropertiesFromRow($table, $row)
6928
    {
6929
        if ($GLOBALS['TCA'][$table]) {
6930
            $liveUid = ($row['t3ver_oid'] ?? null) ? ($row['t3ver_oid'] ?? null) : ($row['uid'] ?? null);
6931
            return [
6932
                'header' => BackendUtility::getRecordTitle($table, $row),
6933
                'pid' => $row['pid'] ?? null,
6934
                'event_pid' => $this->eventPid($table, (int)$liveUid, $row['pid'] ?? null),
6935
                't3ver_state' => BackendUtility::isTableWorkspaceEnabled($table) ? ($row['t3ver_state'] ?? '') : ''
6936
            ];
6937
        }
6938
        return null;
6939
    }
6940
6941
    /**
6942
     * @param string $table
6943
     * @param int $uid
6944
     * @param int $pid
6945
     * @return int
6946
     * @internal should only be used from within DataHandler
6947
     */
6948
    public function eventPid($table, $uid, $pid)
6949
    {
6950
        return $table === 'pages' ? $uid : $pid;
6951
    }
6952
6953
    /*********************************************
6954
     *
6955
     * Storing data to Database Layer
6956
     *
6957
     ********************************************/
6958
    /**
6959
     * Update database record
6960
     * Does not check permissions but expects them to be verified on beforehand
6961
     *
6962
     * @param string $table Record table name
6963
     * @param int $id Record uid
6964
     * @param array $fieldArray Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
6965
     * @internal should only be used from within DataHandler
6966
     */
6967
    public function updateDB($table, $id, $fieldArray)
6968
    {
6969
        if (is_array($fieldArray) && is_array($GLOBALS['TCA'][$table]) && (int)$id) {
6970
            // Do NOT update the UID field, ever!
6971
            unset($fieldArray['uid']);
6972
            if (!empty($fieldArray)) {
6973
                $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
6974
6975
                $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
6976
6977
                $types = [];
6978
                $platform = $connection->getDatabasePlatform();
6979
                if ($platform instanceof SQLServerPlatform) {
6980
                    // mssql needs to set proper PARAM_LOB and others to update fields
6981
                    $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
6982
                    foreach ($fieldArray as $columnName => $columnValue) {
6983
                        $types[$columnName] = $tableDetails->getColumn($columnName)->getType()->getBindingType();
6984
                    }
6985
                }
6986
6987
                // Execute the UPDATE query:
6988
                $updateErrorMessage = '';
6989
                try {
6990
                    $connection->update($table, $fieldArray, ['uid' => (int)$id], $types);
6991
                } catch (DBALException $e) {
6992
                    $updateErrorMessage = $e->getPrevious()->getMessage();
6993
                }
6994
                // If succeeds, do...:
6995
                if ($updateErrorMessage === '') {
6996
                    // Update reference index:
6997
                    $this->updateRefIndex($table, $id);
6998
                    // Set History data
6999
                    $historyEntryId = 0;
7000
                    if (isset($this->historyRecords[$table . ':' . $id])) {
7001
                        $historyEntryId = $this->getRecordHistoryStore()->modifyRecord($table, $id, $this->historyRecords[$table . ':' . $id], $this->correlationId);
7002
                    }
7003
                    if ($this->enableLogging) {
7004
                        if ($this->checkStoredRecords) {
7005
                            $newRow = $this->checkStoredRecord($table, $id, $fieldArray, SystemLogDatabaseAction::UPDATE) ?? [];
7006
                        } else {
7007
                            $newRow = $fieldArray;
7008
                            $newRow['uid'] = $id;
7009
                        }
7010
                        // Set log entry:
7011
                        $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
7012
                        $isOfflineVersion = (bool)($newRow['t3ver_oid'] ?? 0);
7013
                        $this->log($table, $id, SystemLogDatabaseAction::UPDATE, $propArr['pid'], SystemLogErrorClassification::MESSAGE, 'Record \'%s\' (%s) was updated.' . ($isOfflineVersion ? ' (Offline version).' : ' (Online).'), 10, [$propArr['header'], $table . ':' . $id, 'history' => $historyEntryId], $propArr['event_pid']);
7014
                    }
7015
                    // Clear cache for relevant pages:
7016
                    $this->registerRecordIdForPageCacheClearing($table, $id);
7017
                    // Unset the pageCache for the id if table was page.
7018
                    if ($table === 'pages') {
7019
                        unset($this->pageCache[$id]);
7020
                    }
7021
                } else {
7022
                    $this->log($table, $id, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$updateErrorMessage, $table . ':' . $id]);
7023
                }
7024
            }
7025
        }
7026
    }
7027
7028
    /**
7029
     * Insert into database
7030
     * Does not check permissions but expects them to be verified on beforehand
7031
     *
7032
     * @param string $table Record table name
7033
     * @param string $id "NEW...." uid string
7034
     * @param array $fieldArray Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done. "pid" must point to the destination of the record!
7035
     * @param bool $newVersion Set to TRUE if new version is created.
7036
     * @param int $suggestedUid Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
7037
     * @param bool $dontSetNewIdIndex If TRUE, the ->substNEWwithIDs array is not updated. Only useful in very rare circumstances!
7038
     * @return int|null Returns ID on success.
7039
     * @internal should only be used from within DataHandler
7040
     */
7041
    public function insertDB($table, $id, $fieldArray, $newVersion = false, $suggestedUid = 0, $dontSetNewIdIndex = false)
7042
    {
7043
        if (is_array($fieldArray) && is_array($GLOBALS['TCA'][$table]) && isset($fieldArray['pid'])) {
7044
            // Do NOT insert the UID field, ever!
7045
            unset($fieldArray['uid']);
7046
            if (!empty($fieldArray)) {
7047
                // Check for "suggestedUid".
7048
                // This feature is used by the import functionality to force a new record to have a certain UID value.
7049
                // This is only recommended for use when the destination server is a passive mirror of another server.
7050
                // As a security measure this feature is available only for Admin Users (for now)
7051
                $suggestedUid = (int)$suggestedUid;
7052
                if ($this->BE_USER->isAdmin() && $suggestedUid && $this->suggestedInsertUids[$table . ':' . $suggestedUid]) {
7053
                    // When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
7054
                    if ($this->suggestedInsertUids[$table . ':' . $suggestedUid] === 'DELETE') {
7055
                        $this->hardDeleteSingleRecord($table, (int)$suggestedUid);
7056
                    }
7057
                    $fieldArray['uid'] = $suggestedUid;
7058
                }
7059
                $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
7060
                $typeArray = [];
7061
                if (!empty($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'])
7062
                    && array_key_exists($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'], $fieldArray)
7063
                ) {
7064
                    $typeArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = Connection::PARAM_LOB;
7065
                }
7066
                $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
7067
                $insertErrorMessage = '';
7068
                try {
7069
                    // Execute the INSERT query:
7070
                    $connection->insert(
7071
                        $table,
7072
                        $fieldArray,
7073
                        $typeArray
7074
                    );
7075
                } catch (DBALException $e) {
7076
                    $insertErrorMessage = $e->getPrevious()->getMessage();
7077
                }
7078
                // If succees, do...:
7079
                if ($insertErrorMessage === '') {
7080
                    // Set mapping for NEW... -> real uid:
7081
                    // the NEW_id now holds the 'NEW....' -id
7082
                    $NEW_id = $id;
7083
                    $id = $this->postProcessDatabaseInsert($connection, $table, $suggestedUid);
7084
7085
                    if (!$dontSetNewIdIndex) {
7086
                        $this->substNEWwithIDs[$NEW_id] = $id;
7087
                        $this->substNEWwithIDs_table[$NEW_id] = $table;
7088
                    }
7089
                    $newRow = [];
7090
                    if ($this->enableLogging) {
7091
                        // Checking the record is properly saved if configured
7092
                        if ($this->checkStoredRecords) {
7093
                            $newRow = $this->checkStoredRecord($table, $id, $fieldArray, SystemLogDatabaseAction::INSERT) ?? [];
7094
                        } else {
7095
                            $newRow = $fieldArray;
7096
                            $newRow['uid'] = $id;
7097
                        }
7098
                    }
7099
                    // Update reference index:
7100
                    $this->updateRefIndex($table, $id);
7101
7102
                    // Store in history
7103
                    $this->getRecordHistoryStore()->addRecord($table, $id, $newRow, $this->correlationId);
7104
7105
                    if ($newVersion) {
7106
                        if ($this->enableLogging) {
7107
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
7108
                            $this->log($table, $id, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::MESSAGE, 'New version created of table \'%s\', uid \'%s\'. UID of new version is \'%s\'', 10, [$table, $fieldArray['t3ver_oid'], $id], $propArr['event_pid'], $NEW_id);
7109
                        }
7110
                    } else {
7111
                        if ($this->enableLogging) {
7112
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
7113
                            $page_propArr = $this->getRecordProperties('pages', $propArr['pid']);
7114
                            $this->log($table, $id, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::MESSAGE, 'Record \'%s\' (%s) was inserted on page \'%s\' (%s)', 10, [$propArr['header'], $table . ':' . $id, $page_propArr['header'], $newRow['pid']], $newRow['pid'], $NEW_id);
7115
                        }
7116
                        // Clear cache for relevant pages:
7117
                        $this->registerRecordIdForPageCacheClearing($table, $id);
7118
                    }
7119
                    return $id;
7120
                }
7121
                if ($this->enableLogging) {
7122
                    $this->log($table, 0, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$insertErrorMessage, $table . ':' . $id]);
7123
                }
7124
            }
7125
        }
7126
        return null;
7127
    }
7128
7129
    /**
7130
     * Checking stored record to see if the written values are properly updated.
7131
     *
7132
     * @param string $table Record table name
7133
     * @param int $id Record uid
7134
     * @param array $fieldArray Array of field=>value pairs to insert/update
7135
     * @param int $action Action, for logging only.
7136
     * @return array|null Selected row
7137
     * @see insertDB()
7138
     * @see updateDB()
7139
     * @internal should only be used from within DataHandler
7140
     */
7141
    public function checkStoredRecord($table, $id, $fieldArray, $action)
7142
    {
7143
        $id = (int)$id;
7144
        if (is_array($GLOBALS['TCA'][$table]) && $id) {
7145
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7146
            $queryBuilder->getRestrictions()->removeAll();
7147
7148
            $row = $queryBuilder
7149
                ->select('*')
7150
                ->from($table)
7151
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
7152
                ->execute()
7153
                ->fetch();
7154
7155
            if (!empty($row)) {
7156
                // Traverse array of values that was inserted into the database and compare with the actually stored value:
7157
                $errors = [];
7158
                foreach ($fieldArray as $key => $value) {
7159
                    if (!$this->checkStoredRecords_loose || $value || $row[$key]) {
7160
                        if (is_float($row[$key])) {
7161
                            // if the database returns the value as double, compare it as double
7162
                            if ((double)$value !== (double)$row[$key]) {
7163
                                $errors[] = $key;
7164
                            }
7165
                        } else {
7166
                            $dbType = $GLOBALS['TCA'][$table]['columns'][$key]['config']['dbType'] ?? false;
7167
                            if ($dbType === 'datetime' || $dbType === 'time') {
7168
                                $row[$key] = $this->normalizeTimeFormat($table, $row[$key], $dbType);
7169
                            }
7170
                            if ((string)$value !== (string)$row[$key]) {
7171
                                // The is_numeric check catches cases where we want to store a float/double value
7172
                                // and database returns the field as a string with the least required amount of
7173
                                // significant digits, i.e. "0.00" being saved and "0" being read back.
7174
                                if (is_numeric($value) && is_numeric($row[$key])) {
7175
                                    if ((double)$value === (double)$row[$key]) {
7176
                                        continue;
7177
                                    }
7178
                                }
7179
                                $errors[] = $key;
7180
                            }
7181
                        }
7182
                    }
7183
                }
7184
                // Set log message if there were fields with unmatching values:
7185
                if (!empty($errors)) {
7186
                    $message = sprintf(
7187
                        'These fields of record %d in table "%s" have not been saved correctly: %s! The values might have changed due to type casting of the database.',
7188
                        $id,
7189
                        $table,
7190
                        implode(', ', $errors)
7191
                    );
7192
                    $this->log($table, $id, $action, 0, SystemLogErrorClassification::USER_ERROR, $message);
7193
                }
7194
                // Return selected rows:
7195
                return $row;
7196
            }
7197
        }
7198
        return null;
7199
    }
7200
7201
    /**
7202
     * Setting sys_history record, based on content previously set in $this->historyRecords[$table . ':' . $id] (by compareFieldArrayWithCurrentAndUnset())
7203
     *
7204
     * This functionality is now moved into the RecordHistoryStore and can be used instead.
7205
     *
7206
     * @param string $table Table name
7207
     * @param int $id Record ID
7208
     * @internal should only be used from within DataHandler
7209
     */
7210
    public function setHistory($table, $id)
7211
    {
7212
        if (isset($this->historyRecords[$table . ':' . $id])) {
7213
            $this->getRecordHistoryStore()->modifyRecord(
7214
                $table,
7215
                $id,
7216
                $this->historyRecords[$table . ':' . $id],
7217
                $this->correlationId
7218
            );
7219
        }
7220
    }
7221
7222
    /**
7223
     * @return RecordHistoryStore
7224
     */
7225
    protected function getRecordHistoryStore(): RecordHistoryStore
7226
    {
7227
        return GeneralUtility::makeInstance(
7228
            RecordHistoryStore::class,
7229
            RecordHistoryStore::USER_BACKEND,
7230
            $this->BE_USER->user['uid'],
7231
            (int)$this->BE_USER->getOriginalUserIdWhenInSwitchUserMode(),
7232
            $GLOBALS['EXEC_TIME'],
7233
            $this->BE_USER->workspace
7234
        );
7235
    }
7236
7237
    /**
7238
     * Register a table/uid combination in current user workspace for reference updating.
7239
     * Should be called on almost any update to a record which could affect references inside the record.
7240
     *
7241
     * @param string $table Table name
7242
     * @param int $uid Record UID
7243
     * @param int $workspace Workspace the record lives in
7244
     * @internal should only be used from within DataHandler
7245
     */
7246
    public function updateRefIndex($table, $uid, int $workspace = null): void
7247
    {
7248
        if ($workspace === null) {
7249
            $workspace = (int)$this->BE_USER->workspace;
7250
        }
7251
        $this->referenceIndexUpdater->registerForUpdate((string)$table, (int)$uid, $workspace);
7252
    }
7253
7254
    /**
7255
     * Delete rows from sys_refindex a table / uid combination is involved in:
7256
     * Either on left side (tablename + recuid) OR right side (ref_table + ref_uid).
7257
     * Useful in scenarios like workspace-discard where parents or children are hard deleted: The
7258
     * expensive updateRefIndex() does not need to be called since we can just drop straight ahead.
7259
     *
7260
     * @param string $table Table name, used as tablename and ref_table
7261
     * @param int $uid Record uid, used as recuid and ref_uid
7262
     * @param int $workspace Workspace the record lives in
7263
     */
7264
    public function registerReferenceIndexRowsForDrop(string $table, int $uid, int $workspace): void
7265
    {
7266
        $this->referenceIndexUpdater->registerForDrop($table, $uid, $workspace);
7267
    }
7268
7269
    /*********************************************
7270
     *
7271
     * Misc functions
7272
     *
7273
     ********************************************/
7274
    /**
7275
     * Returning sorting number for tables with a "sortby" column
7276
     * Using when new records are created and existing records are moved around.
7277
     *
7278
     * The strategy is:
7279
     *  - if no record exists: set interval as sorting number
7280
     *  - if inserted before an element: put in the middle of the existing elements
7281
     *  - if inserted behind the last element: add interval to last sorting number
7282
     *  - if collision: move all subsequent records by 2 * interval, insert new record with collision + interval
7283
     *
7284
     * How to calculate the maximum possible inserts for the worst case of adding all records to the top,
7285
     * such that the sorting number stays within INT_MAX
7286
     *
7287
     * i = interval (currently 256)
7288
     * c = number of inserts until collision
7289
     * s = max sorting number to reach (INT_MAX - 32bit)
7290
     * n = number of records (~83 million)
7291
     *
7292
     * c = 2 * g
7293
     * g = log2(i) / 2 + 1
7294
     * n = g * s / i - g + 1
7295
     *
7296
     * The algorithm can be tuned by adjusting the interval value.
7297
     * Higher value means less collisions, but also less inserts are possible to stay within INT_MAX.
7298
     *
7299
     * @param string $table Table name
7300
     * @param int $uid Uid of record to find sorting number for. May be zero in case of new.
7301
     * @param int $pid Positioning PID, either >=0 (pointing to page in which case we find sorting number for first record in page) or <0 (pointing to record in which case to find next sorting number after this record)
7302
     * @return int|array|bool|null Returns integer if PID is >=0, otherwise an array with PID and sorting number. Possibly FALSE in case of error.
7303
     * @internal should only be used from within DataHandler
7304
     */
7305
    public function getSortNumber($table, $uid, $pid)
7306
    {
7307
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7308
        if (!$sortColumn) {
7309
            return null;
7310
        }
7311
7312
        $considerWorkspaces = BackendUtility::isTableWorkspaceEnabled($table);
7313
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
7314
        $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
7315
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7316
7317
        $queryBuilder
7318
            ->select($sortColumn, 'pid', 'uid')
7319
            ->from($table);
7320
        if ($considerWorkspaces) {
7321
            $queryBuilder->addSelect('t3ver_state');
7322
        }
7323
7324
        // find and return the sorting value for the first record on that pid
7325
        if ($pid >= 0) {
7326
            // Fetches the first record (lowest sorting) under this pid
7327
            $queryBuilder
7328
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)));
7329
7330
            if ($considerWorkspaces) {
7331
                $queryBuilder->andWhere(
7332
                    $queryBuilder->expr()->orX(
7333
                        $queryBuilder->expr()->eq('t3ver_oid', 0),
7334
                        $queryBuilder->expr()->eq('t3ver_state', VersionState::MOVE_POINTER)
7335
                    )
7336
                );
7337
            }
7338
            $row = $queryBuilder
7339
                ->orderBy($sortColumn, 'ASC')
7340
                ->addOrderBy('uid', 'ASC')
7341
                ->setMaxResults(1)
7342
                ->execute()
7343
                ->fetch();
7344
7345
            if (!empty($row)) {
7346
                // The top record was the record itself, so we return its current sorting value
7347
                if ($row['uid'] == $uid) {
7348
                    return $row[$sortColumn];
7349
                }
7350
                // If the record sorting value < 1 we must resort all the records under this pid
7351
                if ($row[$sortColumn] < 1) {
7352
                    $this->increaseSortingOfFollowingRecords($table, (int)$pid);
7353
                    // Lowest sorting value after full resorting is $sortIntervals
7354
                    return $this->sortIntervals;
7355
                }
7356
                // Sorting number between current top element and zero
7357
                return floor($row[$sortColumn] / 2);
7358
            }
7359
            // No records, so we choose the default value as sorting-number
7360
            return $this->sortIntervals;
7361
        }
7362
7363
        // Find and return first possible sorting value AFTER record with given uid ($pid)
7364
        // Fetches the record which is supposed to be the prev record
7365
        $row = $queryBuilder
7366
                ->where($queryBuilder->expr()->eq(
7367
                    'uid',
7368
                    $queryBuilder->createNamedParameter(abs($pid), \PDO::PARAM_INT)
7369
                ))
7370
                ->execute()
7371
                ->fetch();
7372
7373
        // There is a previous record
7374
        if (!empty($row)) {
7375
            // Look if the record UID happens to be a versioned record. If so, find its live version.
7376
            // If this is already a moved record in workspace, this is not needed
7377
            if ((int)$row['t3ver_state'] !== VersionState::MOVE_POINTER && $lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $row['uid'], $sortColumn . ',pid,uid')) {
7378
                $row = $lookForLiveVersion;
7379
            } elseif ($considerWorkspaces && $this->BE_USER->workspace > 0) {
7380
                // In case the previous record is moved in the workspace, we need to fetch the information from this specific record
7381
                $versionedRecord = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $row['uid'], $sortColumn . ',pid,uid,t3ver_state');
7382
                if (is_array($versionedRecord) && (int)$versionedRecord['t3ver_state'] === VersionState::MOVE_POINTER) {
7383
                    $row = $versionedRecord;
7384
                }
7385
            }
7386
            // If the record should be inserted after itself, keep the current sorting information:
7387
            if ((int)$row['uid'] === (int)$uid) {
7388
                $sortNumber = $row[$sortColumn];
7389
            } else {
7390
                $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
7391
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7392
7393
                $queryBuilder
7394
                        ->select($sortColumn, 'pid', 'uid')
7395
                        ->from($table)
7396
                        ->where(
7397
                            $queryBuilder->expr()->eq(
7398
                                'pid',
7399
                                $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
7400
                            ),
7401
                            $queryBuilder->expr()->gte(
7402
                                $sortColumn,
7403
                                $queryBuilder->createNamedParameter($row[$sortColumn], \PDO::PARAM_INT)
7404
                            )
7405
                        )
7406
                        ->orderBy($sortColumn, 'ASC')
7407
                        ->addOrderBy('uid', 'DESC')
7408
                        ->setMaxResults(2);
7409
7410
                if ($considerWorkspaces) {
7411
                    $queryBuilder->andWhere(
7412
                        $queryBuilder->expr()->orX(
7413
                            $queryBuilder->expr()->eq('t3ver_oid', 0),
7414
                            $queryBuilder->expr()->eq('t3ver_state', VersionState::MOVE_POINTER)
7415
                        )
7416
                    );
7417
                }
7418
7419
                $subResults = $queryBuilder
7420
                    ->execute()
7421
                    ->fetchAll();
7422
                // Fetches the next record in order to calculate the in-between sortNumber
7423
                // There was a record afterwards
7424
                if (count($subResults) === 2) {
7425
                    // There was a record afterwards, fetch that
7426
                    $subrow = array_pop($subResults);
7427
                    // The sortNumber is found in between these values
7428
                    $sortNumber = $row[$sortColumn] + floor(($subrow[$sortColumn] - $row[$sortColumn]) / 2);
7429
                    // The sortNumber happened NOT to be between the two surrounding numbers, so we'll have to resort the list
7430
                    if ($sortNumber <= $row[$sortColumn] || $sortNumber >= $subrow[$sortColumn]) {
7431
                        $this->increaseSortingOfFollowingRecords($table, (int)$row['pid'], (int)$row[$sortColumn]);
7432
                        $sortNumber = $row[$sortColumn] + $this->sortIntervals;
7433
                    }
7434
                } else {
7435
                    // If after the last record in the list, we just add the sortInterval to the last sortvalue
7436
                    $sortNumber = $row[$sortColumn] + $this->sortIntervals;
7437
                }
7438
            }
7439
            return ['pid' => $row['pid'], 'sortNumber' => $sortNumber];
7440
        }
7441
        if ($this->enableLogging) {
7442
            $propArr = $this->getRecordProperties($table, $uid);
7443
            // OK, don't insert $propArr['event_pid'] here...
7444
            $this->log($table, $uid, SystemLogDatabaseAction::MOVE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to move record \'%s\' (%s) to after a non-existing record (uid=%s)', 1, [$propArr['header'], $table . ':' . $uid, abs($pid)], $propArr['pid']);
7445
        }
7446
        // There MUST be a previous record or else this cannot work
7447
        return false;
7448
    }
7449
7450
    /**
7451
     * Increases sorting field value of all records with sorting higher than $sortingValue
7452
     *
7453
     * Used internally by getSortNumber() to "make space" in sorting values when inserting new record
7454
     *
7455
     * @param string $table Table name
7456
     * @param int $pid Page Uid in which to resort records
7457
     * @param int $sortingValue All sorting numbers larger than this number will be shifted
7458
     * @see getSortNumber()
7459
     */
7460
    protected function increaseSortingOfFollowingRecords(string $table, int $pid, int $sortingValue = null): void
7461
    {
7462
        $sortBy = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7463
        if ($sortBy) {
7464
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7465
7466
            $queryBuilder
7467
                ->update($table)
7468
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
7469
                ->set($sortBy, $queryBuilder->quoteIdentifier($sortBy) . ' + ' . $this->sortIntervals . ' + ' . $this->sortIntervals, false);
7470
            if ($sortingValue !== null) {
7471
                $queryBuilder->andWhere($queryBuilder->expr()->gt($sortBy, $sortingValue));
7472
            }
7473
            if (BackendUtility::isTableWorkspaceEnabled($table)) {
7474
                $queryBuilder
7475
                    ->andWhere(
7476
                        $queryBuilder->expr()->eq('t3ver_oid', 0)
7477
                    );
7478
            }
7479
7480
            $deleteColumn = $GLOBALS['TCA'][$table]['ctrl']['delete'] ?? '';
7481
            if ($deleteColumn) {
7482
                $queryBuilder->andWhere($queryBuilder->expr()->eq($deleteColumn, 0));
7483
            }
7484
7485
            $queryBuilder->execute();
7486
        }
7487
    }
7488
7489
    /**
7490
     * Returning uid of previous localized record, if any, for tables with a "sortby" column
7491
     * Used when new localized records are created so that localized records are sorted in the same order as the default language records
7492
     *
7493
     * For a given record (A) uid (record we're translating) it finds first default language record (from the same colpos)
7494
     * with sorting smaller than given record (B).
7495
     * Then it fetches a translated version of record B and returns it's uid.
7496
     *
7497
     * If there is no record B, or it has no translation in given language, the record A uid is returned.
7498
     * The localized record will be placed the after record which uid is returned.
7499
     *
7500
     * @param string $table Table name
7501
     * @param int $uid Uid of default language record
7502
     * @param int $pid Pid of default language record
7503
     * @param int $language Language of localization
7504
     * @return int uid of record after which the localized record should be inserted
7505
     */
7506
    protected function getPreviousLocalizedRecordUid($table, $uid, $pid, $language)
7507
    {
7508
        $previousLocalizedRecordUid = $uid;
7509
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7510
        if ($sortColumn) {
7511
            $select = [$sortColumn, 'pid', 'uid'];
7512
            // For content elements, we also need the colPos
7513
            if ($table === 'tt_content') {
7514
                $select[] = 'colPos';
7515
            }
7516
            // Get the sort value of the default language record
7517
            $row = BackendUtility::getRecord($table, $uid, implode(',', $select));
7518
            if (is_array($row)) {
7519
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7520
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7521
7522
                $queryBuilder
7523
                    ->select(...$select)
7524
                    ->from($table)
7525
                    ->where(
7526
                        $queryBuilder->expr()->eq(
7527
                            'pid',
7528
                            $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
7529
                        ),
7530
                        $queryBuilder->expr()->eq(
7531
                            $GLOBALS['TCA'][$table]['ctrl']['languageField'],
7532
                            $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
7533
                        ),
7534
                        $queryBuilder->expr()->lt(
7535
                            $sortColumn,
7536
                            $queryBuilder->createNamedParameter($row[$sortColumn], \PDO::PARAM_INT)
7537
                        )
7538
                    )
7539
                    ->orderBy($sortColumn, 'DESC')
7540
                    ->addOrderBy('uid', 'DESC')
7541
                    ->setMaxResults(1);
7542
                if ($table === 'tt_content') {
7543
                    $queryBuilder
7544
                        ->andWhere(
7545
                            $queryBuilder->expr()->eq(
7546
                                'colPos',
7547
                                $queryBuilder->createNamedParameter($row['colPos'], \PDO::PARAM_INT)
7548
                            )
7549
                        );
7550
                }
7551
                // If there is an element, find its localized record in specified localization language
7552
                if ($previousRow = $queryBuilder->execute()->fetch()) {
7553
                    $previousLocalizedRecord = BackendUtility::getRecordLocalization($table, $previousRow['uid'], $language);
7554
                    if (isset($previousLocalizedRecord[0]) && is_array($previousLocalizedRecord[0])) {
7555
                        $previousLocalizedRecordUid = $previousLocalizedRecord[0]['uid'];
7556
                    }
7557
                }
7558
            }
7559
        }
7560
        return $previousLocalizedRecordUid;
7561
    }
7562
7563
    /**
7564
     * Returns a fieldArray with default values. Values will be picked up from the TCA array looking at the config key "default" for each column. If values are set in ->defaultValues they will overrule though.
7565
     * Used for new records and during copy operations for defaults
7566
     *
7567
     * @param string $table Table name for which to set default values.
7568
     * @return array Array with default values.
7569
     * @internal should only be used from within DataHandler
7570
     */
7571
    public function newFieldArray($table)
7572
    {
7573
        $fieldArray = [];
7574
        if (is_array($GLOBALS['TCA'][$table]['columns'])) {
7575
            foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $content) {
7576
                if (isset($this->defaultValues[$table][$field])) {
7577
                    $fieldArray[$field] = $this->defaultValues[$table][$field];
7578
                } elseif (isset($content['config']['default'])) {
7579
                    $fieldArray[$field] = $content['config']['default'];
7580
                }
7581
            }
7582
        }
7583
        return $fieldArray;
7584
    }
7585
7586
    /**
7587
     * If a "languageField" is specified for $table this function will add a possible value to the incoming array if none is found in there already.
7588
     *
7589
     * @param string $table Table name
7590
     * @param array $incomingFieldArray Incoming array (passed by reference)
7591
     * @internal should only be used from within DataHandler
7592
     */
7593
    public function addDefaultPermittedLanguageIfNotSet($table, &$incomingFieldArray)
7594
    {
7595
        // Checking languages:
7596
        if ($GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? false) {
7597
            if (!isset($incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
7598
                // Language field must be found in input row - otherwise it does not make sense.
7599
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
7600
                    ->getQueryBuilderForTable('sys_language');
7601
                $queryBuilder->getRestrictions()
7602
                    ->removeAll()
7603
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7604
                $queryBuilder
7605
                    ->select('uid')
7606
                    ->from('sys_language')
7607
                    ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)));
7608
                $rows = array_merge([['uid' => 0]], $queryBuilder->execute()->fetchAll(), [['uid' => -1]]);
7609
                foreach ($rows as $r) {
7610
                    if ($this->BE_USER->checkLanguageAccess($r['uid'])) {
7611
                        $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $r['uid'];
7612
                        break;
7613
                    }
7614
                }
7615
            }
7616
        }
7617
    }
7618
7619
    /**
7620
     * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
7621
     *
7622
     * @param string $table Table name
7623
     * @param array $data Data array with fields from table. These will be overlaid with values in $this->overrideValues[$table]
7624
     * @return array Data array, processed.
7625
     * @internal should only be used from within DataHandler
7626
     */
7627
    public function overrideFieldArray($table, $data)
7628
    {
7629
        if (isset($this->overrideValues[$table]) && is_array($this->overrideValues[$table])) {
7630
            $data = array_merge($data, $this->overrideValues[$table]);
7631
        }
7632
        return $data;
7633
    }
7634
7635
    /**
7636
     * Compares the incoming field array with the current record and unsets all fields which are the same.
7637
     * Used for existing records being updated
7638
     *
7639
     * @param string $table Record table name
7640
     * @param int $id Record uid
7641
     * @param array $fieldArray Array of field=>value pairs intended to be inserted into the database. All keys with values matching exactly the current value will be unset!
7642
     * @return array Returns $fieldArray. If the returned array is empty, then the record should not be updated!
7643
     * @internal should only be used from within DataHandler
7644
     */
7645
    public function compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray)
7646
    {
7647
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
7648
        $queryBuilder = $connection->createQueryBuilder();
7649
        $queryBuilder->getRestrictions()->removeAll();
7650
        $currentRecord = $queryBuilder->select('*')
7651
            ->from($table)
7652
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
7653
            ->execute()
7654
            ->fetch();
7655
        // If the current record exists (which it should...), begin comparison:
7656
        if (is_array($currentRecord)) {
7657
            $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
7658
            $columnRecordTypes = [];
7659
            foreach ($currentRecord as $columnName => $_) {
7660
                $columnRecordTypes[$columnName] = '';
7661
                $type = $tableDetails->getColumn($columnName)->getType();
7662
                if ($type instanceof IntegerType) {
7663
                    $columnRecordTypes[$columnName] = 'int';
7664
                }
7665
            }
7666
            // Unset the fields which are similar:
7667
            foreach ($fieldArray as $col => $val) {
7668
                $fieldConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'] ?? [];
7669
                $isNullField = (!empty($fieldConfiguration['eval']) && GeneralUtility::inList($fieldConfiguration['eval'], 'null'));
7670
7671
                // Unset fields if stored and submitted values are equal - except the current field holds MM relations.
7672
                // In general this avoids to store superfluous data which also will be visualized in the editing history.
7673
                if (empty($fieldConfiguration['MM']) && $this->isSubmittedValueEqualToStoredValue($val, $currentRecord[$col], $columnRecordTypes[$col], $isNullField)) {
7674
                    unset($fieldArray[$col]);
7675
                } else {
7676
                    if (!isset($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col])) {
7677
                        $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $currentRecord[$col];
7678
                    } elseif ($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col]) {
7679
                        $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col];
7680
                    }
7681
                    if (!isset($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col])) {
7682
                        $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $fieldArray[$col];
7683
                    } elseif ($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col]) {
7684
                        $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col];
7685
                    }
7686
                }
7687
            }
7688
        } else {
7689
            // If the current record does not exist this is an error anyways and we just return an empty array here.
7690
            $fieldArray = [];
7691
        }
7692
        return $fieldArray;
7693
    }
7694
7695
    /**
7696
     * Determines whether submitted values and stored values are equal.
7697
     * This prevents from adding superfluous field changes which would be shown in the record history as well.
7698
     * For NULL fields (see accordant TCA definition 'eval' = 'null'), a special handling is required since
7699
     * (!strcmp(NULL, '')) would be a false-positive.
7700
     *
7701
     * @param mixed $submittedValue Value that has submitted (e.g. from a backend form)
7702
     * @param mixed $storedValue Value that is currently stored in the database
7703
     * @param string $storedType SQL type of the stored value column (see mysql_field_type(), e.g 'int', 'string',  ...)
7704
     * @param bool $allowNull Whether NULL values are allowed by accordant TCA definition ('eval' = 'null')
7705
     * @return bool Whether both values are considered to be equal
7706
     */
7707
    protected function isSubmittedValueEqualToStoredValue($submittedValue, $storedValue, $storedType, $allowNull = false)
7708
    {
7709
        // No NULL values are allowed, this is the regular behaviour.
7710
        // Thus, check whether strings are the same or whether integer values are empty ("0" or "").
7711
        if (!$allowNull) {
7712
            $result = (string)$submittedValue === (string)$storedValue || $storedType === 'int' && (int)$storedValue === (int)$submittedValue;
7713
        // Null values are allowed, but currently there's a real (not NULL) value.
7714
        // Thus, ensure no NULL value was submitted and fallback to the regular behaviour.
7715
        } elseif ($storedValue !== null) {
7716
            $result = (
7717
                $submittedValue !== null
7718
                && $this->isSubmittedValueEqualToStoredValue($submittedValue, $storedValue, $storedType, false)
7719
            );
7720
        // Null values are allowed, and currently there's a NULL value.
7721
        // Thus, check whether a NULL value was submitted.
7722
        } else {
7723
            $result = ($submittedValue === null);
7724
        }
7725
7726
        return $result;
7727
    }
7728
7729
    /**
7730
     * Converts a HTML entity (like &#123;) to the character '123'
7731
     *
7732
     * @param string $input Input string
7733
     * @return string Output string
7734
     * @internal should only be used from within DataHandler
7735
     */
7736
    public function convNumEntityToByteValue($input)
7737
    {
7738
        $token = md5(microtime());
7739
        $parts = explode($token, (string)preg_replace('/(&#([0-9]+);)/', $token . '\\2' . $token, $input));
7740
        foreach ($parts as $k => $v) {
7741
            if ($k % 2) {
7742
                $v = (int)$v;
7743
                // Just to make sure that control bytes are not converted.
7744
                if ($v > 32) {
7745
                    $parts[$k] = chr($v);
7746
                }
7747
            }
7748
        }
7749
        return implode('', $parts);
7750
    }
7751
7752
    /**
7753
     * Disables the delete clause for fetching records.
7754
     * In general only undeleted records will be used. If the delete
7755
     * clause is disabled, also deleted records are taken into account.
7756
     */
7757
    public function disableDeleteClause()
7758
    {
7759
        $this->disableDeleteClause = true;
7760
    }
7761
7762
    /**
7763
     * Returns delete-clause for the $table
7764
     *
7765
     * @param string $table Table name
7766
     * @return string Delete clause
7767
     * @internal should only be used from within DataHandler
7768
     */
7769
    public function deleteClause($table)
7770
    {
7771
        // Returns the proper delete-clause if any for a table from TCA
7772
        if (!$this->disableDeleteClause && $GLOBALS['TCA'][$table]['ctrl']['delete']) {
7773
            return ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
7774
        }
7775
        return '';
7776
    }
7777
7778
    /**
7779
     * Add delete restriction if not disabled
7780
     *
7781
     * @param QueryRestrictionContainerInterface $restrictions
7782
     */
7783
    protected function addDeleteRestriction(QueryRestrictionContainerInterface $restrictions)
7784
    {
7785
        if (!$this->disableDeleteClause) {
7786
            $restrictions->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7787
        }
7788
    }
7789
7790
    /**
7791
     * Gets UID of parent record. If record is deleted it will be looked up in
7792
     * an array built before the record was deleted
7793
     *
7794
     * @param string $table Table where record lives/lived
7795
     * @param int $uid Record UID
7796
     * @return int[] Parent UIDs
7797
     */
7798
    protected function getOriginalParentOfRecord($table, $uid)
7799
    {
7800
        if (isset(self::$recordPidsForDeletedRecords[$table][$uid])) {
7801
            return self::$recordPidsForDeletedRecords[$table][$uid];
7802
        }
7803
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
7804
        return [$parentUid];
7805
    }
7806
7807
    /**
7808
     * Extract entries from TSconfig for a specific table. This will merge specific and default configuration together.
7809
     *
7810
     * @param string $table Table name
7811
     * @param array $TSconfig TSconfig for page
7812
     * @return array TSconfig merged
7813
     * @internal should only be used from within DataHandler
7814
     */
7815
    public function getTableEntries($table, $TSconfig)
7816
    {
7817
        $tA = is_array($TSconfig['table.'][$table . '.'] ?? false) ? $TSconfig['table.'][$table . '.'] : [];
7818
        $dA = is_array($TSconfig['default.'] ?? false) ? $TSconfig['default.'] : [];
7819
        ArrayUtility::mergeRecursiveWithOverrule($dA, $tA);
7820
        return $dA;
7821
    }
7822
7823
    /**
7824
     * Returns the pid of a record from $table with $uid
7825
     *
7826
     * @param string $table Table name
7827
     * @param int $uid Record uid
7828
     * @return int|false PID value (unless the record did not exist in which case FALSE is returned)
7829
     * @internal should only be used from within DataHandler
7830
     */
7831
    public function getPID($table, $uid)
7832
    {
7833
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7834
        $queryBuilder->getRestrictions()
7835
            ->removeAll();
7836
        $queryBuilder->select('pid')
7837
            ->from($table)
7838
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)));
7839
        if ($row = $queryBuilder->execute()->fetch()) {
7840
            return $row['pid'];
7841
        }
7842
        return false;
7843
    }
7844
7845
    /**
7846
     * Executing dbAnalysisStore
7847
     * This will save MM relations for new records but is executed after records are created because we need to know the ID of them
7848
     * @internal should only be used from within DataHandler
7849
     */
7850
    public function dbAnalysisStoreExec()
7851
    {
7852
        foreach ($this->dbAnalysisStore as $action) {
7853
            $id = BackendUtility::wsMapId($action[4], MathUtility::canBeInterpretedAsInteger($action[2]) ? $action[2] : $this->substNEWwithIDs[$action[2]]);
7854
            if ($id) {
7855
                $action[0]->writeMM($action[1], $id, $action[3]);
7856
            }
7857
        }
7858
    }
7859
7860
    /**
7861
     * Returns array, $CPtable, of pages under the $pid going down to $counter levels.
7862
     * Selecting ONLY pages which the user has read-access to!
7863
     *
7864
     * @param array $CPtable Accumulation of page uid=>pid pairs in branch of $pid
7865
     * @param int $pid Page ID for which to find subpages
7866
     * @param int $counter Number of levels to go down.
7867
     * @param int $rootID ID of root point for new copied branch: The idea seems to be that a copy is not made of the already new page!
7868
     * @return array Return array.
7869
     * @internal should only be used from within DataHandler
7870
     */
7871
    public function int_pageTreeInfo($CPtable, $pid, $counter, $rootID)
7872
    {
7873
        if ($counter) {
7874
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
7875
            $restrictions = $queryBuilder->getRestrictions()->removeAll();
7876
            $this->addDeleteRestriction($restrictions);
7877
            $queryBuilder
7878
                ->select('uid')
7879
                ->from('pages')
7880
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
7881
                ->orderBy('sorting', 'DESC');
7882
            if (!$this->admin) {
7883
                $queryBuilder->andWhere($this->BE_USER->getPagePermsClause(Permission::PAGE_SHOW));
7884
            }
7885
            if ((int)$this->BE_USER->workspace === 0) {
7886
                $queryBuilder->andWhere(
7887
                    $queryBuilder->expr()->eq('t3ver_wsid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
7888
                );
7889
            } else {
7890
                $queryBuilder->andWhere($queryBuilder->expr()->in(
7891
                    't3ver_wsid',
7892
                    $queryBuilder->createNamedParameter([0, $this->BE_USER->workspace], Connection::PARAM_INT_ARRAY)
7893
                ));
7894
            }
7895
            $result = $queryBuilder->execute();
7896
7897
            $pages = [];
7898
            while ($row = $result->fetch()) {
7899
                $pages[$row['uid']] = $row;
7900
            }
7901
7902
            // Resolve placeholders of workspace versions
7903
            if (!empty($pages) && (int)$this->BE_USER->workspace !== 0) {
7904
                $pages = array_reverse(
7905
                    $this->resolveVersionedRecords(
7906
                        'pages',
7907
                        'uid',
7908
                        'sorting',
7909
                        array_keys($pages)
7910
                    ),
7911
                    true
7912
                );
7913
            }
7914
7915
            foreach ($pages as $page) {
7916
                if ($page['uid'] != $rootID) {
7917
                    $CPtable[$page['uid']] = $pid;
7918
                    // If the uid is NOT the rootID of the copyaction and if we are supposed to walk further down
7919
                    if ($counter - 1) {
7920
                        $CPtable = $this->int_pageTreeInfo($CPtable, $page['uid'], $counter - 1, $rootID);
7921
                    }
7922
                }
7923
            }
7924
        }
7925
        return $CPtable;
7926
    }
7927
7928
    /**
7929
     * List of all tables (those administrators has access to = array_keys of $GLOBALS['TCA'])
7930
     *
7931
     * @return array Array of all TCA table names
7932
     * @internal should only be used from within DataHandler
7933
     */
7934
    public function compileAdminTables()
7935
    {
7936
        return array_keys($GLOBALS['TCA']);
7937
    }
7938
7939
    /**
7940
     * Checks if any uniqueInPid eval input fields are in the record and if so, they are re-written to be correct.
7941
     *
7942
     * @param string $table Table name
7943
     * @param int $uid Record UID
7944
     * @internal should only be used from within DataHandler
7945
     */
7946
    public function fixUniqueInPid($table, $uid)
7947
    {
7948
        if (empty($GLOBALS['TCA'][$table])) {
7949
            return;
7950
        }
7951
7952
        $curData = $this->recordInfo($table, $uid, '*');
7953
        $newData = [];
7954
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
7955
            if ($conf['config']['type'] === 'input' && (string)$curData[$field] !== '') {
7956
                $evalCodesArray = GeneralUtility::trimExplode(',', $conf['config']['eval'] ?? '', true);
7957
                if (in_array('uniqueInPid', $evalCodesArray, true)) {
7958
                    $newV = $this->getUnique($table, $field, $curData[$field], $uid, $curData['pid']);
7959
                    if ((string)$newV !== (string)$curData[$field]) {
7960
                        $newData[$field] = $newV;
7961
                    }
7962
                }
7963
            }
7964
        }
7965
        // IF there are changed fields, then update the database
7966
        if (!empty($newData)) {
7967
            $this->updateDB($table, $uid, $newData);
7968
        }
7969
    }
7970
7971
    /**
7972
     * Checks if any uniqueInSite eval fields are in the record and if so, they are re-written to be correct.
7973
     *
7974
     * @param string $table Table name
7975
     * @param int $uid Record UID
7976
     * @return bool whether the record had to be fixed or not
7977
     */
7978
    protected function fixUniqueInSite(string $table, int $uid): bool
7979
    {
7980
        $curData = $this->recordInfo($table, $uid, '*');
7981
        $workspaceId = $this->BE_USER->workspace;
7982
        $newData = [];
7983
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
7984
            if ($conf['config']['type'] === 'slug' && (string)$curData[$field] !== '') {
7985
                $evalCodesArray = GeneralUtility::trimExplode(',', $conf['config']['eval'], true);
7986
                if (in_array('uniqueInSite', $evalCodesArray, true)) {
7987
                    $helper = GeneralUtility::makeInstance(SlugHelper::class, $table, $field, $conf['config'], $workspaceId);
7988
                    $state = RecordStateFactory::forName($table)->fromArray($curData);
0 ignored issues
show
Bug introduced by
It seems like $curData can also be of type null; however, parameter $data of TYPO3\CMS\Core\DataHandl...ateFactory::fromArray() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

7988
                    $state = RecordStateFactory::forName($table)->fromArray(/** @scrutinizer ignore-type */ $curData);
Loading history...
7989
                    $newValue = $helper->buildSlugForUniqueInSite($curData[$field], $state);
7990
                    if ((string)$newValue !== (string)$curData[$field]) {
7991
                        $newData[$field] = $newValue;
7992
                    }
7993
                }
7994
            }
7995
        }
7996
        // IF there are changed fields, then update the database
7997
        if (!empty($newData)) {
7998
            $this->updateDB($table, $uid, $newData);
7999
            return true;
8000
        }
8001
        return false;
8002
    }
8003
8004
    /**
8005
     * Check if there are subpages that need an adoption as well
8006
     * @param int $pageId
8007
     */
8008
    protected function fixUniqueInSiteForSubpages(int $pageId)
8009
    {
8010
        // Get ALL subpages to update - read-permissions are respected
8011
        $subPages = $this->int_pageTreeInfo([], $pageId, 99, $pageId);
8012
        // Now fix uniqueInSite for subpages
8013
        foreach ($subPages as $thePageUid => $thePagePid) {
8014
            $recordWasModified = $this->fixUniqueInSite('pages', $thePageUid);
8015
            if ($recordWasModified) {
8016
                // @todo: Add logging and history - but how? we don't know the data that was in the system before
8017
            }
8018
        }
8019
    }
8020
8021
    /**
8022
     * When er record is copied you can specify fields from the previous record which should be copied into the new one
8023
     * This function is also called with new elements. But then $update must be set to zero and $newData containing the data array. In that case data in the incoming array is NOT overridden. (250202)
8024
     *
8025
     * @param string $table Table name
8026
     * @param int $uid Record UID
8027
     * @param int $prevUid UID of previous record
8028
     * @param bool $update If set, updates the record
8029
     * @param array $newData Input array. If fields are already specified AND $update is not set, values are not set in output array.
8030
     * @return array Output array (For when the copying operation needs to get the information instead of updating the info)
8031
     * @internal should only be used from within DataHandler
8032
     */
8033
    public function fixCopyAfterDuplFields($table, $uid, $prevUid, $update, $newData = [])
8034
    {
8035
        if ($GLOBALS['TCA'][$table]['ctrl']['copyAfterDuplFields'] ?? false) {
8036
            $prevData = $this->recordInfo($table, $prevUid, '*');
8037
            $theFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['copyAfterDuplFields'], true);
8038
            foreach ($theFields as $field) {
8039
                if ($GLOBALS['TCA'][$table]['columns'][$field] && ($update || !isset($newData[$field]))) {
8040
                    $newData[$field] = $prevData[$field];
8041
                }
8042
            }
8043
            if ($update && !empty($newData)) {
8044
                $this->updateDB($table, $uid, $newData);
8045
            }
8046
        }
8047
        return $newData;
8048
    }
8049
8050
    /**
8051
     * Casts a reference value. In case MM relations or foreign_field
8052
     * references are used. All other configurations, as well as
8053
     * foreign_table(!) could be stored as comma-separated-values
8054
     * as well. Since the system is not able to determine the default
8055
     * value automatically then, the TCA default value is used if
8056
     * it has been defined.
8057
     *
8058
     * @param int|string $value The value to be casted (e.g. '', '0', '1,2,3')
8059
     * @param array $configuration The TCA configuration of the accordant field
8060
     * @return int|string
8061
     */
8062
    protected function castReferenceValue($value, array $configuration)
8063
    {
8064
        if ((string)$value !== '') {
8065
            return $value;
8066
        }
8067
8068
        if (!empty($configuration['MM']) || !empty($configuration['foreign_field'])) {
8069
            return 0;
8070
        }
8071
8072
        if (array_key_exists('default', $configuration)) {
8073
            return $configuration['default'];
8074
        }
8075
8076
        return $value;
8077
    }
8078
8079
    /**
8080
     * Returns TRUE if the TCA/columns field type is a DB reference field
8081
     *
8082
     * @param array $conf Config array for TCA/columns field
8083
     * @return bool TRUE if DB reference field (group/db or select with foreign-table)
8084
     * @internal should only be used from within DataHandler
8085
     */
8086
    public function isReferenceField($conf)
8087
    {
8088
        return isset($conf['type'], $conf['internal_type']) && $conf['type'] === 'group' && $conf['internal_type'] === 'db'
8089
            || isset($conf['type'], $conf['foreign_table']) && $conf['type'] === 'select' && $conf['foreign_table'];
8090
    }
8091
8092
    /**
8093
     * Returns the subtype as a string of an inline field.
8094
     * If it's not an inline field at all, it returns FALSE.
8095
     *
8096
     * @param array $conf Config array for TCA/columns field
8097
     * @return string|bool string Inline subtype (field|mm|list), boolean: FALSE
8098
     * @internal should only be used from within DataHandler
8099
     */
8100
    public function getInlineFieldType($conf)
8101
    {
8102
        if (empty($conf['type']) || $conf['type'] !== 'inline' || empty($conf['foreign_table'])) {
8103
            return false;
8104
        }
8105
        if ($conf['foreign_field'] ?? false) {
8106
            // The reference to the parent is stored in a pointer field in the child record
8107
            return 'field';
8108
        }
8109
        if ($conf['MM'] ?? false) {
8110
            // Regular MM intermediate table is used to store data
8111
            return 'mm';
8112
        }
8113
        // An item list (separated by comma) is stored (like select type is doing)
8114
        return 'list';
8115
    }
8116
8117
    /**
8118
     * Get modified header for a copied record
8119
     *
8120
     * @param string $table Table name
8121
     * @param int $pid PID value in which other records to test might be
8122
     * @param string $field Field name to get header value for.
8123
     * @param string $value Current field value
8124
     * @param int $count Counter (number of recursions)
8125
     * @param string $prevTitle Previous title we checked for (in previous recursion)
8126
     * @return string The field value, possibly appended with a "copy label
8127
     * @internal should only be used from within DataHandler
8128
     */
8129
    public function getCopyHeader($table, $pid, $field, $value, $count, $prevTitle = '')
8130
    {
8131
        // Set title value to check for:
8132
        $checkTitle = $value;
8133
        if ($count > 0) {
8134
            $checkTitle = $value . rtrim(' ' . sprintf($this->prependLabel($table), $count));
8135
        }
8136
        // Do check:
8137
        if ($prevTitle != $checkTitle || $count < 100) {
8138
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
8139
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
8140
            $rowCount = $queryBuilder
8141
                ->count('uid')
8142
                ->from($table)
8143
                ->where(
8144
                    $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)),
8145
                    $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($checkTitle, \PDO::PARAM_STR))
8146
                )
8147
                ->execute()
8148
                ->fetchColumn(0);
8149
            if ($rowCount) {
8150
                return $this->getCopyHeader($table, $pid, $field, $value, $count + 1, $checkTitle);
8151
            }
8152
        }
8153
        // Default is to just return the current input title if no other was returned before:
8154
        return $checkTitle;
8155
    }
8156
8157
    /**
8158
     * Return "copy" label for a table. Although the name is "prepend" it actually APPENDs the label (after ...)
8159
     *
8160
     * @param string $table Table name
8161
     * @return string Label to append, containing "%s" for the number
8162
     * @see getCopyHeader()
8163
     * @internal should only be used from within DataHandler
8164
     */
8165
    public function prependLabel($table)
8166
    {
8167
        return $this->getLanguageService()->sL($GLOBALS['TCA'][$table]['ctrl']['prependAtCopy']);
8168
    }
8169
8170
    /**
8171
     * Get the final pid based on $table and $pid ($destPid type... pos/neg)
8172
     *
8173
     * @param string $table Table name
8174
     * @param int $pid "Destination pid" : If the value is >= 0 it's just returned directly (through (int)though) but if the value is <0 then the method looks up the record with the uid equal to abs($pid) (positive number) and returns the PID of that record! The idea is that negative numbers point to the record AFTER WHICH the position is supposed to be!
8175
     * @return int
8176
     * @internal should only be used from within DataHandler
8177
     */
8178
    public function resolvePid($table, $pid)
8179
    {
8180
        $pid = (int)$pid;
8181
        if ($pid < 0) {
8182
            $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
8183
            $query->getRestrictions()
8184
                ->removeAll();
8185
            $row = $query
8186
                ->select('pid')
8187
                ->from($table)
8188
                ->where($query->expr()->eq('uid', $query->createNamedParameter(abs($pid), \PDO::PARAM_INT)))
8189
                ->execute()
8190
                ->fetch();
8191
            $pid = (int)$row['pid'];
8192
        }
8193
        return $pid;
8194
    }
8195
8196
    /**
8197
     * Removes the prependAtCopy prefix on values
8198
     *
8199
     * @param string $table Table name
8200
     * @param string $value The value to fix
8201
     * @return string Clean name
8202
     * @internal should only be used from within DataHandler
8203
     */
8204
    public function clearPrefixFromValue($table, $value)
8205
    {
8206
        $regex = '/\s' . sprintf(preg_quote($this->prependLabel($table)), '[0-9]*') . '$/';
8207
        return @preg_replace($regex, '', $value);
8208
    }
8209
8210
    /**
8211
     * Check if there are records from tables on the pages to be deleted which the current user is not allowed to
8212
     *
8213
     * @param int[] $pageIds IDs of pages which should be checked
8214
     * @return string[]|null Return null, if permission granted, otherwise an array with the tables that are not allowed to be deleted
8215
     * @see canDeletePage()
8216
     */
8217
    protected function checkForRecordsFromDisallowedTables(array $pageIds): ?array
8218
    {
8219
        if ($this->admin) {
8220
            return null;
8221
        }
8222
8223
        $disallowedTables = [];
8224
        if (!empty($pageIds)) {
8225
            $tableNames = $this->compileAdminTables();
8226
            foreach ($tableNames as $table) {
8227
                $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
8228
                $query->getRestrictions()
8229
                    ->removeAll()
8230
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8231
                $count = $query->count('uid')
8232
                    ->from($table)
8233
                    ->where($query->expr()->in(
8234
                        'pid',
8235
                        $query->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
8236
                    ))
8237
                    ->execute()
8238
                    ->fetchColumn(0);
8239
                if ($count && ($this->tableReadOnly($table) || !$this->checkModifyAccessList($table))) {
8240
                    $disallowedTables[] = $table;
8241
                }
8242
            }
8243
        }
8244
        return !empty($disallowedTables) ? $disallowedTables : null;
8245
    }
8246
8247
    /**
8248
     * Determine if a record was copied or if a record is the result of a copy action.
8249
     *
8250
     * @param string $table The tablename of the record
8251
     * @param int $uid The uid of the record
8252
     * @return bool Returns TRUE if the record is copied or is the result of a copy action
8253
     * @internal should only be used from within DataHandler
8254
     */
8255
    public function isRecordCopied($table, $uid)
8256
    {
8257
        // If the record was copied:
8258
        if (isset($this->copyMappingArray[$table][$uid])) {
8259
            return true;
8260
        }
8261
        if (isset($this->copyMappingArray[$table]) && in_array($uid, array_values($this->copyMappingArray[$table]))) {
8262
            return true;
8263
        }
8264
        return false;
8265
    }
8266
8267
    /******************************
8268
     *
8269
     * Clearing cache
8270
     *
8271
     ******************************/
8272
8273
    /**
8274
     * Clearing the cache based on a page being updated
8275
     * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
8276
     * Else just clear the cache for the parent page of the record.
8277
     *
8278
     * @param string $table Table name of record that was just updated.
8279
     * @param int $uid UID of updated / inserted record
8280
     * @param int $pid REAL PID of page of a deleted/moved record to get TSconfig in ClearCache.
8281
     * @internal This method is not meant to be called directly but only from the core itself or from hooks
8282
     */
8283
    public function registerRecordIdForPageCacheClearing($table, $uid, $pid = null)
8284
    {
8285
        if (!is_array(static::$recordsToClearCacheFor[$table] ?? false)) {
8286
            static::$recordsToClearCacheFor[$table] = [];
8287
        }
8288
        static::$recordsToClearCacheFor[$table][] = (int)$uid;
8289
        if ($pid !== null) {
8290
            if (!isset(static::$recordPidsForDeletedRecords[$table]) || !is_array(static::$recordPidsForDeletedRecords[$table])) {
8291
                static::$recordPidsForDeletedRecords[$table] = [];
8292
            }
8293
            static::$recordPidsForDeletedRecords[$table][$uid][] = (int)$pid;
8294
        }
8295
    }
8296
8297
    /**
8298
     * Do the actual clear cache
8299
     */
8300
    protected function processClearCacheQueue()
8301
    {
8302
        $tagsToClear = [];
8303
        $clearCacheCommands = [];
8304
8305
        foreach (static::$recordsToClearCacheFor as $table => $uids) {
8306
            foreach (array_unique($uids) as $uid) {
8307
                if (!isset($GLOBALS['TCA'][$table]) || $uid <= 0) {
8308
                    return;
8309
                }
8310
                // For move commands we may get more then 1 parent.
8311
                $pageUids = $this->getOriginalParentOfRecord($table, $uid);
8312
                foreach ($pageUids as $originalParent) {
8313
                    [$tagsToClearFromPrepare, $clearCacheCommandsFromPrepare]
8314
                        = $this->prepareCacheFlush($table, $uid, $originalParent);
8315
                    $tagsToClear = array_merge($tagsToClear, $tagsToClearFromPrepare);
8316
                    $clearCacheCommands = array_merge($clearCacheCommands, $clearCacheCommandsFromPrepare);
8317
                }
8318
            }
8319
        }
8320
8321
        /** @var CacheManager $cacheManager */
8322
        $cacheManager = $this->getCacheManager();
8323
        $cacheManager->flushCachesInGroupByTags('pages', array_keys($tagsToClear));
8324
8325
        // Filter duplicate cache commands from cacheQueue
8326
        $clearCacheCommands = array_unique($clearCacheCommands);
8327
        // Execute collected clear cache commands from page TSConfig
8328
        foreach ($clearCacheCommands as $command) {
8329
            $this->clear_cacheCmd($command);
8330
        }
8331
8332
        // Reset the cache clearing array
8333
        static::$recordsToClearCacheFor = [];
8334
8335
        // Reset the original pid array
8336
        static::$recordPidsForDeletedRecords = [];
8337
    }
8338
8339
    /**
8340
     * Prepare the cache clearing
8341
     *
8342
     * @param string $table Table name of record that needs to be cleared
8343
     * @param int $uid UID of record for which the cache needs to be cleared
8344
     * @param int $pid Original pid of the page of the record which the cache needs to be cleared
8345
     * @return array Array with tagsToClear and clearCacheCommands
8346
     * @internal This function is internal only it may be changed/removed also in minor version numbers.
8347
     */
8348
    protected function prepareCacheFlush($table, $uid, $pid)
8349
    {
8350
        $tagsToClear = [];
8351
        $clearCacheCommands = [];
8352
        $pageUid = 0;
8353
        // Get Page TSconfig relevant:
8354
        $TSConfig = BackendUtility::getPagesTSconfig($pid)['TCEMAIN.'] ?? [];
8355
        if (empty($TSConfig['clearCache_disable']) && $this->BE_USER->workspace === 0) {
8356
            $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
8357
            // If table is "pages":
8358
            $pageIdsThatNeedCacheFlush = [];
8359
            if ($table === 'pages') {
8360
                // Find out if the record is a get the original page
8361
                $pageUid = $this->getDefaultLanguagePageId($uid);
8362
8363
                // Builds list of pages on the SAME level as this page (siblings)
8364
                $queryBuilder = $connectionPool->getQueryBuilderForTable('pages');
8365
                $queryBuilder->getRestrictions()
8366
                    ->removeAll()
8367
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8368
                $siblings = $queryBuilder
8369
                    ->select('A.pid AS pid', 'B.uid AS uid')
8370
                    ->from('pages', 'A')
8371
                    ->from('pages', 'B')
8372
                    ->where(
8373
                        $queryBuilder->expr()->eq('A.uid', $queryBuilder->createNamedParameter($pageUid, \PDO::PARAM_INT)),
8374
                        $queryBuilder->expr()->eq('B.pid', $queryBuilder->quoteIdentifier('A.pid')),
8375
                        $queryBuilder->expr()->gte('A.pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
8376
                    )
8377
                    ->execute();
8378
8379
                $parentPageId = 0;
8380
                while ($row_tmp = $siblings->fetch()) {
8381
                    $pageIdsThatNeedCacheFlush[] = (int)$row_tmp['uid'];
8382
                    $parentPageId = (int)$row_tmp['pid'];
8383
                    // Add children as well:
8384
                    if ($TSConfig['clearCache_pageSiblingChildren'] ?? false) {
8385
                        $siblingChildrenQuery = $connectionPool->getQueryBuilderForTable('pages');
8386
                        $siblingChildrenQuery->getRestrictions()
8387
                            ->removeAll()
8388
                            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8389
                        $siblingChildren = $siblingChildrenQuery
8390
                            ->select('uid')
8391
                            ->from('pages')
8392
                            ->where($siblingChildrenQuery->expr()->eq(
8393
                                'pid',
8394
                                $siblingChildrenQuery->createNamedParameter($row_tmp['uid'], \PDO::PARAM_INT)
8395
                            ))
8396
                            ->execute();
8397
                        while ($row_tmp2 = $siblingChildren->fetch()) {
8398
                            $pageIdsThatNeedCacheFlush[] = (int)$row_tmp2['uid'];
8399
                        }
8400
                    }
8401
                }
8402
                // Finally, add the parent page as well when clearing a specific page
8403
                if ($parentPageId > 0) {
8404
                    $pageIdsThatNeedCacheFlush[] = $parentPageId;
8405
                }
8406
                // Add grand-parent as well if configured
8407
                if ($TSConfig['clearCache_pageGrandParent'] ?? false) {
8408
                    $parentQuery = $connectionPool->getQueryBuilderForTable('pages');
8409
                    $parentQuery->getRestrictions()
8410
                        ->removeAll()
8411
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8412
                    $row_tmp = $parentQuery
8413
                        ->select('pid')
8414
                        ->from('pages')
8415
                        ->where($parentQuery->expr()->eq(
8416
                            'uid',
8417
                            $parentQuery->createNamedParameter($parentPageId, \PDO::PARAM_INT)
8418
                        ))
8419
                        ->execute()
8420
                        ->fetch();
8421
                    if (!empty($row_tmp)) {
8422
                        $pageIdsThatNeedCacheFlush[] = (int)$row_tmp['pid'];
8423
                    }
8424
                }
8425
            } else {
8426
                // For other tables than "pages", delete cache for the records "parent page".
8427
                $pageIdsThatNeedCacheFlush[] = $pageUid = (int)$this->getPID($table, $uid);
8428
                // Add the parent page as well
8429
                if ($TSConfig['clearCache_pageGrandParent'] ?? false) {
8430
                    $parentQuery = $connectionPool->getQueryBuilderForTable('pages');
8431
                    $parentQuery->getRestrictions()
8432
                        ->removeAll()
8433
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8434
                    $parentPageRecord = $parentQuery
8435
                        ->select('pid')
8436
                        ->from('pages')
8437
                        ->where($parentQuery->expr()->eq(
8438
                            'uid',
8439
                            $parentQuery->createNamedParameter($pageUid, \PDO::PARAM_INT)
8440
                        ))
8441
                        ->execute()
8442
                        ->fetch();
8443
                    if (!empty($parentPageRecord)) {
8444
                        $pageIdsThatNeedCacheFlush[] = (int)$parentPageRecord['pid'];
8445
                    }
8446
                }
8447
            }
8448
            // Call pre-processing function for clearing of cache for page ids:
8449
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] ?? [] as $funcName) {
8450
                $_params = ['pageIdArray' => &$pageIdsThatNeedCacheFlush, 'table' => $table, 'uid' => $uid, 'functionID' => 'clear_cache()'];
8451
                // Returns the array of ids to clear, FALSE if nothing should be cleared! Never an empty array!
8452
                GeneralUtility::callUserFunction($funcName, $_params, $this);
8453
            }
8454
            // Delete cache for selected pages:
8455
            foreach ($pageIdsThatNeedCacheFlush as $pageId) {
8456
                $tagsToClear['pageId_' . $pageId] = true;
8457
            }
8458
            // Queue delete cache for current table and record
8459
            $tagsToClear[$table] = true;
8460
            $tagsToClear[$table . '_' . $uid] = true;
8461
        }
8462
        // Clear cache for pages entered in TSconfig:
8463
        if (!empty($TSConfig['clearCacheCmd'])) {
8464
            $commands = GeneralUtility::trimExplode(',', $TSConfig['clearCacheCmd'], true);
8465
            $clearCacheCommands = array_unique($commands);
8466
        }
8467
        // Call post processing function for clear-cache:
8468
        $_params = ['table' => $table, 'uid' => $uid, 'uid_page' => $pageUid, 'TSConfig' => $TSConfig, 'tags' => $tagsToClear];
8469
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] ?? [] as $_funcRef) {
8470
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
8471
        }
8472
        return [
8473
            $tagsToClear,
8474
            $clearCacheCommands
8475
        ];
8476
    }
8477
8478
    /**
8479
     * Clears the cache based on the command $cacheCmd.
8480
     *
8481
     * $cacheCmd='pages'
8482
     * Clears cache for all pages and page-based caches inside the cache manager.
8483
     * Requires admin-flag to be set for BE_USER.
8484
     *
8485
     * $cacheCmd='all'
8486
     * Clears all cache_tables. This is necessary if templates are updated.
8487
     * Requires admin-flag to be set for BE_USER.
8488
     *
8489
     * The following cache_* are intentionally not cleared by 'all'
8490
     *
8491
     * - imagesizes:	Clearing this table would cause a lot of unneeded
8492
     * Imagemagick calls because the size information has
8493
     * to be fetched again after clearing.
8494
     * - all caches inside the cache manager that are inside the group "system"
8495
     * - they are only needed to build up the core system and templates.
8496
     *   If the group of system caches needs to be deleted explicitly, use
8497
     *   flushCachesInGroup('system') of CacheManager directly.
8498
     *
8499
     * $cacheCmd=[integer]
8500
     * Clears cache for the page pointed to by $cacheCmd (an integer).
8501
     *
8502
     * $cacheCmd='cacheTag:[string]'
8503
     * Flush page and pagesection cache by given tag
8504
     *
8505
     * $cacheCmd='cacheId:[string]'
8506
     * Removes cache identifier from page and page section cache
8507
     *
8508
     * Can call a list of post processing functions as defined in
8509
     * $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc']
8510
     * (numeric array with values being the function references, called by
8511
     * GeneralUtility::callUserFunction()).
8512
     *
8513
     *
8514
     * @param string $cacheCmd The cache command, see above description
8515
     */
8516
    public function clear_cacheCmd($cacheCmd)
8517
    {
8518
        if (is_object($this->BE_USER)) {
8519
            $this->BE_USER->writeLog(SystemLogType::CACHE, SystemLogCacheAction::CLEAR, SystemLogErrorClassification::MESSAGE, 0, 'User %s has cleared the cache (cacheCmd=%s)', [$this->BE_USER->user['username'], $cacheCmd]);
8520
        }
8521
        $userTsConfig = $this->BE_USER->getTSConfig();
8522
        switch (strtolower($cacheCmd)) {
8523
            case 'pages':
8524
                if ($this->admin || ($userTsConfig['options.']['clearCache.']['pages'] ?? false)) {
8525
                    $this->getCacheManager()->flushCachesInGroup('pages');
8526
                }
8527
                break;
8528
            case 'all':
8529
                // allow to clear all caches if the TS config option is enabled or the option is not explicitly
8530
                // disabled for admins (which could clear all caches by default). The latter option is useful
8531
                // for big production sites where it should be possible to restrict the cache clearing for some admins.
8532
                if (($userTsConfig['options.']['clearCache.']['all'] ?? false)
8533
                    || ($this->admin && (bool)($userTsConfig['options.']['clearCache.']['all'] ?? true))
8534
                ) {
8535
                    $this->getCacheManager()->flushCaches();
8536
                    GeneralUtility::makeInstance(ConnectionPool::class)
8537
                        ->getConnectionForTable('cache_treelist')
8538
                        ->truncate('cache_treelist');
8539
8540
                    // Delete Opcode Cache
8541
                    GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive();
8542
                }
8543
                break;
8544
        }
8545
8546
        $tagsToFlush = [];
8547
        // Clear cache for a page ID!
8548
        if (MathUtility::canBeInterpretedAsInteger($cacheCmd)) {
8549
            $list_cache = [$cacheCmd];
8550
            // Call pre-processing function for clearing of cache for page ids:
8551
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] ?? [] as $funcName) {
8552
                $_params = ['pageIdArray' => &$list_cache, 'cacheCmd' => $cacheCmd, 'functionID' => 'clear_cacheCmd()'];
8553
                // Returns the array of ids to clear, FALSE if nothing should be cleared! Never an empty array!
8554
                GeneralUtility::callUserFunction($funcName, $_params, $this);
8555
            }
8556
            // Delete cache for selected pages:
8557
            if (is_array($list_cache)) {
0 ignored issues
show
introduced by
The condition is_array($list_cache) is always true.
Loading history...
8558
                foreach ($list_cache as $pageId) {
8559
                    $tagsToFlush[] = 'pageId_' . (int)$pageId;
8560
                }
8561
            }
8562
        }
8563
        // flush cache by tag
8564
        if (GeneralUtility::isFirstPartOfStr(strtolower($cacheCmd), 'cachetag:')) {
8565
            $cacheTag = substr($cacheCmd, 9);
8566
            $tagsToFlush[] = $cacheTag;
8567
        }
8568
        // process caching framework operations
8569
        if (!empty($tagsToFlush)) {
8570
            $this->getCacheManager()->flushCachesInGroupByTags('pages', $tagsToFlush);
0 ignored issues
show
Bug introduced by
The method getCacheManager() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

8570
            $this->/** @scrutinizer ignore-call */ 
8571
                   getCacheManager()->flushCachesInGroupByTags('pages', $tagsToFlush);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
8571
        }
8572
8573
        // Call post processing function for clear-cache:
8574
        $_params = ['cacheCmd' => strtolower($cacheCmd), 'tags' => $tagsToFlush];
8575
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] ?? [] as $_funcRef) {
8576
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
8577
        }
8578
    }
8579
8580
    /*****************************
8581
     *
8582
     * Logging
8583
     *
8584
     *****************************/
8585
    /**
8586
     * Logging actions from DataHandler
8587
     *
8588
     * @param string $table Table name the log entry is concerned with. Blank if NA
8589
     * @param int $recuid Record UID. Zero if NA
8590
     * @param int $action Action number: 0=No category, 1=new record, 2=update record, 3= delete record, 4= move record, 5= Check/evaluate
8591
     * @param int|string $recpid Normally 0 (zero). If set, it indicates that this log-entry is used to notify the backend of a record which is moved to another location
8592
     * @param int $error The severity: 0 = message, 1 = error, 2 = System Error, 3 = security notice (admin), 4 warning
8593
     * @param string $details Default error message in english
8594
     * @param int $details_nr This number is unique for every combination of $type and $action. This is the error-message number, which can later be used to translate error messages. 0 if not categorized, -1 if temporary
8595
     * @param array $data Array with special information that may go into $details by '%s' marks / sprintf() when the log is shown
8596
     * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
8597
     * @param string $NEWid NEW id for new records
8598
     * @return int Log entry UID (0 if no log entry was written or logging is disabled)
8599
     * @see \TYPO3\CMS\Core\SysLog\Action\Database for all available values of argument $action
8600
     * @see \TYPO3\CMS\Core\SysLog\Error for all available values of argument $error
8601
     * @internal should only be used from within TYPO3 Core
8602
     */
8603
    public function log($table, $recuid, $action, $recpid, $error, $details, $details_nr = -1, $data = [], $event_pid = -1, $NEWid = '')
8604
    {
8605
        if (!$this->enableLogging) {
8606
            return 0;
8607
        }
8608
        // Type value for DataHandler
8609
        if (!$this->storeLogMessages) {
8610
            $details = '';
8611
        }
8612
        if ($error > 0) {
8613
            $detailMessage = $details;
8614
            if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
8615
                $detailMessage = vsprintf($details, $data);
8616
            }
8617
            $this->errorLog[] = '[' . SystemLogType::DB . '.' . $action . '.' . $details_nr . ']: ' . $detailMessage;
8618
        }
8619
        return $this->BE_USER->writelog(SystemLogType::DB, $action, $error, $details_nr, $details, $data, $table, $recuid, $recpid, $event_pid, $NEWid);
8620
    }
8621
8622
    /**
8623
     * Simple logging function meant to be used when logging messages is not yet fixed.
8624
     *
8625
     * @param string $message Message string
8626
     * @param int $error Error code, see log()
8627
     * @return int Log entry UID
8628
     * @see log()
8629
     * @internal should only be used from within TYPO3 Core
8630
     */
8631
    public function newlog($message, $error = SystemLogErrorClassification::MESSAGE)
8632
    {
8633
        return $this->log('', 0, SystemLogGenericAction::UNDEFINED, 0, $error, $message, -1);
8634
    }
8635
8636
    /**
8637
     * Print log error messages from the operations of this script instance
8638
     * @internal should only be used from within TYPO3 Core
8639
     */
8640
    public function printLogErrorMessages()
8641
    {
8642
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_log');
8643
        $queryBuilder->getRestrictions()->removeAll();
8644
        $result = $queryBuilder
8645
            ->select('*')
8646
            ->from('sys_log')
8647
            ->where(
8648
                $queryBuilder->expr()->eq('type', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT)),
8649
                $queryBuilder->expr()->lt('action', $queryBuilder->createNamedParameter(256, \PDO::PARAM_INT)),
8650
                $queryBuilder->expr()->eq(
8651
                    'userid',
8652
                    $queryBuilder->createNamedParameter($this->BE_USER->user['uid'], \PDO::PARAM_INT)
8653
                ),
8654
                $queryBuilder->expr()->eq(
8655
                    'tstamp',
8656
                    $queryBuilder->createNamedParameter($GLOBALS['EXEC_TIME'], \PDO::PARAM_INT)
8657
                ),
8658
                $queryBuilder->expr()->neq('error', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
8659
            )
8660
            ->execute();
8661
8662
        while ($row = $result->fetch()) {
8663
            $log_data = unserialize($row['log_data']);
8664
            $msg = $row['error'] . ': ' . sprintf($row['details'], $log_data[0], $log_data[1], $log_data[2], $log_data[3], $log_data[4]);
8665
            /** @var FlashMessage $flashMessage */
8666
            $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $msg, '', $row['error'] === 4 ? FlashMessage::WARNING : FlashMessage::ERROR, true);
8667
            /** @var FlashMessageService $flashMessageService */
8668
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
8669
            $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
8670
            $defaultFlashMessageQueue->enqueue($flashMessage);
8671
        }
8672
    }
8673
8674
    /*****************************
8675
     *
8676
     * Internal (do not use outside Core!)
8677
     *
8678
     *****************************/
8679
8680
    /**
8681
     * Find out if the record is a localization. If so, get the uid of the default language page.
8682
     * Always returns the uid of the workspace live record: No explicit workspace overlay is applied.
8683
     *
8684
     * @param int $pageId Page UID, can be the default page record, or a page translation record ID
8685
     * @return int UID of the default page record in live workspace
8686
     */
8687
    protected function getDefaultLanguagePageId(int $pageId): int
8688
    {
8689
        $localizationParentFieldName = $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'];
8690
        $row = $this->recordInfo('pages', $pageId, $localizationParentFieldName);
8691
        $localizationParent = (int)($row[$localizationParentFieldName] ?? 0);
8692
        if ($localizationParent > 0) {
8693
            return $localizationParent;
8694
        }
8695
        return $pageId;
8696
    }
8697
8698
    /**
8699
     * Preprocesses field array based on field type. Some fields must be adjusted
8700
     * before going to database. This is done on the copy of the field array because
8701
     * original values are used in remap action later.
8702
     *
8703
     * @param string $table	Table name
8704
     * @param array $fieldArray	Field array to check
8705
     * @return array Updated field array
8706
     * @internal should only be used from within TYPO3 Core
8707
     */
8708
    public function insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray)
8709
    {
8710
        $result = $fieldArray;
8711
        foreach ($fieldArray as $field => $value) {
8712
            if (!MathUtility::canBeInterpretedAsInteger($value)
8713
                && isset($GLOBALS['TCA'][$table]['columns'][$field]['config']['type'])
8714
                && $GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'inline'
8715
                && ($GLOBALS['TCA'][$table]['columns'][$field]['config']['foreign_field'] ?? false)
8716
            ) {
8717
                $result[$field] = count(GeneralUtility::trimExplode(',', $value, true));
8718
            }
8719
        }
8720
        return $result;
8721
    }
8722
8723
    /**
8724
     * Determines whether a particular record has been deleted
8725
     * using DataHandler::deleteRecord() in this instance.
8726
     *
8727
     * @param string $tableName
8728
     * @param int $uid
8729
     * @return bool
8730
     * @internal should only be used from within TYPO3 Core
8731
     */
8732
    public function hasDeletedRecord($tableName, $uid)
8733
    {
8734
        return
8735
            !empty($this->deletedRecords[$tableName])
8736
            && in_array($uid, $this->deletedRecords[$tableName])
8737
        ;
8738
    }
8739
8740
    /**
8741
     * Gets the automatically versionized id of a record.
8742
     *
8743
     * @param string $table Name of the table
8744
     * @param int $id Uid of the record
8745
     * @return int|null
8746
     * @internal should only be used from within TYPO3 Core
8747
     */
8748
    public function getAutoVersionId($table, $id): ?int
8749
    {
8750
        $result = null;
8751
        if (isset($this->autoVersionIdMap[$table][$id])) {
8752
            $result = (int)trim($this->autoVersionIdMap[$table][$id]);
8753
        }
8754
        return $result;
8755
    }
8756
8757
    /**
8758
     * Overlays the automatically versionized id of a record.
8759
     *
8760
     * @param string $table Name of the table
8761
     * @param int $id Uid of the record
8762
     * @return int
8763
     */
8764
    protected function overlayAutoVersionId($table, $id)
8765
    {
8766
        $autoVersionId = $this->getAutoVersionId($table, $id);
8767
        if ($autoVersionId !== null) {
8768
            $id = $autoVersionId;
8769
        }
8770
        return $id;
8771
    }
8772
8773
    /**
8774
     * Adds new values to the remapStackChildIds array.
8775
     *
8776
     * @param array $idValues uid values
8777
     */
8778
    protected function addNewValuesToRemapStackChildIds(array $idValues)
8779
    {
8780
        foreach ($idValues as $idValue) {
8781
            if (strpos($idValue, 'NEW') === 0) {
8782
                $this->remapStackChildIds[$idValue] = true;
8783
            }
8784
        }
8785
    }
8786
8787
    /**
8788
     * Resolves versioned records for the current workspace scope.
8789
     * Delete placeholders are substituted and removed.
8790
     *
8791
     * @param string $tableName Name of the table to be processed
8792
     * @param string $fieldNames List of the field names to be fetched
8793
     * @param string $sortingField Name of the sorting field to be used
8794
     * @param array $liveIds Flat array of (live) record ids
8795
     * @return array
8796
     */
8797
    protected function resolveVersionedRecords($tableName, $fieldNames, $sortingField, array $liveIds)
8798
    {
8799
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)
8800
            ->getConnectionForTable($tableName);
8801
        $sortingStatement = !empty($sortingField)
8802
            ? [$connection->quoteIdentifier($sortingField)]
8803
            : null;
8804
        /** @var PlainDataResolver $resolver */
8805
        $resolver = GeneralUtility::makeInstance(
8806
            PlainDataResolver::class,
8807
            $tableName,
8808
            $liveIds,
8809
            $sortingStatement
8810
        );
8811
8812
        $resolver->setWorkspaceId($this->BE_USER->workspace);
8813
        $resolver->setKeepDeletePlaceholder(false);
8814
        $resolver->setKeepMovePlaceholder(false);
8815
        $resolver->setKeepLiveIds(true);
8816
        $recordIds = $resolver->get();
8817
8818
        $records = [];
8819
        foreach ($recordIds as $recordId) {
8820
            $records[$recordId] = BackendUtility::getRecord($tableName, $recordId, $fieldNames);
8821
        }
8822
8823
        return $records;
8824
    }
8825
8826
    /**
8827
     * Gets the outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler
8828
     * Since \TYPO3\CMS\Core\DataHandling\DataHandler can create nested objects of itself,
8829
     * this method helps to determine the first (= outer most) one.
8830
     *
8831
     * @return DataHandler
8832
     */
8833
    protected function getOuterMostInstance()
8834
    {
8835
        if (!isset($this->outerMostInstance)) {
8836
            $stack = array_reverse(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS));
8837
            foreach ($stack as $stackItem) {
8838
                if (isset($stackItem['object']) && $stackItem['object'] instanceof self) {
8839
                    $this->outerMostInstance = $stackItem['object'];
8840
                    break;
8841
                }
8842
            }
8843
        }
8844
        return $this->outerMostInstance;
8845
    }
8846
8847
    /**
8848
     * Determines whether the this object is the outer most instance of itself
8849
     * Since DataHandler can create nested objects of itself,
8850
     * this method helps to determine the first (= outer most) one.
8851
     *
8852
     * @return bool
8853
     */
8854
    public function isOuterMostInstance()
8855
    {
8856
        return $this->getOuterMostInstance() === $this;
8857
    }
8858
8859
    /**
8860
     * Gets an instance of the runtime cache.
8861
     *
8862
     * @return FrontendInterface
8863
     */
8864
    protected function getRuntimeCache()
8865
    {
8866
        return $this->getCacheManager()->getCache('runtime');
8867
    }
8868
8869
    /**
8870
     * Determines nested element calls.
8871
     *
8872
     * @param string $table Name of the table
8873
     * @param int $id Uid of the record
8874
     * @param string $identifier Name of the action to be checked
8875
     * @return bool
8876
     */
8877
    protected function isNestedElementCallRegistered($table, $id, $identifier)
8878
    {
8879
        $nestedElementCalls = (array)$this->runtimeCache->get($this->cachePrefixNestedElementCalls);
8880
        return isset($nestedElementCalls[$identifier][$table][$id]);
8881
    }
8882
8883
    /**
8884
     * Registers nested elements calls.
8885
     * This is used to track nested calls (e.g. for following m:n relations).
8886
     *
8887
     * @param string $table Name of the table
8888
     * @param int $id Uid of the record
8889
     * @param string $identifier Name of the action to be tracked
8890
     */
8891
    protected function registerNestedElementCall($table, $id, $identifier)
8892
    {
8893
        $nestedElementCalls = (array)$this->runtimeCache->get($this->cachePrefixNestedElementCalls);
8894
        $nestedElementCalls[$identifier][$table][$id] = true;
8895
        $this->runtimeCache->set($this->cachePrefixNestedElementCalls, $nestedElementCalls);
8896
    }
8897
8898
    /**
8899
     * Resets the nested element calls.
8900
     */
8901
    protected function resetNestedElementCalls()
8902
    {
8903
        $this->runtimeCache->remove($this->cachePrefixNestedElementCalls);
8904
    }
8905
8906
    /**
8907
     * Determines whether an element was registered to be deleted in the registry.
8908
     *
8909
     * @param string $table Name of the table
8910
     * @param int $id Uid of the record
8911
     * @return bool
8912
     * @see registerElementsToBeDeleted
8913
     * @see resetElementsToBeDeleted
8914
     * @see copyRecord_raw
8915
     * @see versionizeRecord
8916
     */
8917
    protected function isElementToBeDeleted($table, $id)
8918
    {
8919
        $elementsToBeDeleted = (array)$this->runtimeCache->get('core-datahandler-elementsToBeDeleted');
8920
        return isset($elementsToBeDeleted[$table][$id]);
8921
    }
8922
8923
    /**
8924
     * Registers elements to be deleted in the registry.
8925
     *
8926
     * @see process_datamap
8927
     */
8928
    protected function registerElementsToBeDeleted()
8929
    {
8930
        $elementsToBeDeleted = (array)$this->runtimeCache->get('core-datahandler-elementsToBeDeleted');
8931
        $this->runtimeCache->set('core-datahandler-elementsToBeDeleted', array_merge($elementsToBeDeleted, $this->getCommandMapElements('delete')));
8932
    }
8933
8934
    /**
8935
     * Resets the elements to be deleted in the registry.
8936
     *
8937
     * @see process_datamap
8938
     */
8939
    protected function resetElementsToBeDeleted()
8940
    {
8941
        $this->runtimeCache->remove('core-datahandler-elementsToBeDeleted');
8942
    }
8943
8944
    /**
8945
     * Unsets elements (e.g. of the data map) that shall be deleted.
8946
     * This avoids to modify records that will be deleted later on.
8947
     *
8948
     * @param array $elements Elements to be modified
8949
     * @return array
8950
     */
8951
    protected function unsetElementsToBeDeleted(array $elements)
8952
    {
8953
        $elements = ArrayUtility::arrayDiffAssocRecursive($elements, $this->getCommandMapElements('delete'));
8954
        foreach ($elements as $key => $value) {
8955
            if (empty($value)) {
8956
                unset($elements[$key]);
8957
            }
8958
        }
8959
        return $elements;
8960
    }
8961
8962
    /**
8963
     * Gets elements of the command map that match a particular command.
8964
     *
8965
     * @param string $needle The command to be matched
8966
     * @return array
8967
     */
8968
    protected function getCommandMapElements($needle)
8969
    {
8970
        $elements = [];
8971
        foreach ($this->cmdmap as $tableName => $idArray) {
8972
            foreach ($idArray as $id => $commandArray) {
8973
                foreach ($commandArray as $command => $value) {
8974
                    if ($value && $command == $needle) {
8975
                        $elements[$tableName][$id] = true;
8976
                    }
8977
                }
8978
            }
8979
        }
8980
        return $elements;
8981
    }
8982
8983
    /**
8984
     * Controls active elements and sets NULL values if not active.
8985
     * Datamap is modified accordant to submitted control values.
8986
     */
8987
    protected function controlActiveElements()
8988
    {
8989
        if (!empty($this->control['active'])) {
8990
            $this->setNullValues(
8991
                $this->control['active'],
8992
                $this->datamap
8993
            );
8994
        }
8995
    }
8996
8997
    /**
8998
     * Sets NULL values in haystack array.
8999
     * The general behaviour in the user interface is to enable/activate fields.
9000
     * Thus, this method uses NULL as value to be stored if a field is not active.
9001
     *
9002
     * @param array $active hierarchical array with active elements
9003
     * @param array $haystack hierarchical array with haystack to be modified
9004
     */
9005
    protected function setNullValues(array $active, array &$haystack)
9006
    {
9007
        foreach ($active as $key => $value) {
9008
            // Nested data is processes recursively
9009
            if (is_array($value)) {
9010
                $this->setNullValues(
9011
                    $value,
9012
                    $haystack[$key]
9013
                );
9014
            } elseif ($value == 0) {
9015
                // Field has not been activated in the user interface,
9016
                // thus a NULL value shall be stored in the database
9017
                $haystack[$key] = null;
9018
            }
9019
        }
9020
    }
9021
9022
    /**
9023
     * @param CorrelationId $correlationId
9024
     */
9025
    public function setCorrelationId(CorrelationId $correlationId): void
9026
    {
9027
        $this->correlationId = $correlationId;
9028
    }
9029
9030
    /**
9031
     * @return CorrelationId|null
9032
     */
9033
    public function getCorrelationId(): ?CorrelationId
9034
    {
9035
        return $this->correlationId;
9036
    }
9037
9038
    /**
9039
     * Entry point to post process a database insert. Currently bails early unless a UID has been forced
9040
     * and the database platform is not MySQL.
9041
     *
9042
     * @param \TYPO3\CMS\Core\Database\Connection $connection
9043
     * @param string $tableName
9044
     * @param int $suggestedUid
9045
     * @return int
9046
     */
9047
    protected function postProcessDatabaseInsert(Connection $connection, string $tableName, int $suggestedUid): int
9048
    {
9049
        if ($suggestedUid !== 0 && $connection->getDatabasePlatform() instanceof PostgreSqlPlatform) {
9050
            $this->postProcessPostgresqlInsert($connection, $tableName);
9051
            // The last inserted id on postgresql is actually the last value generated by the sequence.
9052
            // On a forced UID insert this might not be the actual value or the sequence might not even
9053
            // have generated a value yet.
9054
            // Return the actual ID we forced on insert as a surrogate.
9055
            return $suggestedUid;
9056
        }
9057
        if ($connection->getDatabasePlatform() instanceof SQLServerPlatform) {
9058
            return $this->postProcessSqlServerInsert($connection, $tableName);
9059
        }
9060
        $id = $connection->lastInsertId($tableName);
9061
        return (int)$id;
9062
    }
9063
9064
    /**
9065
     * Get the last insert ID from sql server
9066
     *
9067
     * - first checks whether doctrine might be able to fetch the ID from the
9068
     * sequence table
9069
     * - if that does not succeed it manually selects the current IDENTITY value
9070
     * from a table
9071
     * - returns 0 if both fail
9072
     *
9073
     * @param \TYPO3\CMS\Core\Database\Connection $connection
9074
     * @param string $tableName
9075
     * @return int
9076
     * @throws \Doctrine\DBAL\Exception
9077
     */
9078
    protected function postProcessSqlServerInsert(Connection $connection, string $tableName): int
9079
    {
9080
        $id = $connection->lastInsertId($tableName);
9081
        if (!((int)$id > 0)) {
9082
            $table = $connection->quoteIdentifier($tableName);
9083
            $result = $connection->executeQuery('SELECT IDENT_CURRENT(\'' . $table . '\') AS id')->fetch();
9084
            if (isset($result['id']) && $result['id'] > 0) {
9085
                $id = $result['id'];
9086
            }
9087
        }
9088
        return (int)$id;
9089
    }
9090
9091
    /**
9092
     * PostgreSQL works with sequences for auto increment columns. A sequence is not updated when a value is
9093
     * written to such a column. To avoid clashes when the sequence returns an existing ID this helper will
9094
     * update the sequence to the current max value of the column.
9095
     *
9096
     * @param \TYPO3\CMS\Core\Database\Connection $connection
9097
     * @param string $tableName
9098
     */
9099
    protected function postProcessPostgresqlInsert(Connection $connection, string $tableName)
9100
    {
9101
        $queryBuilder = $connection->createQueryBuilder();
9102
        $queryBuilder->getRestrictions()->removeAll();
9103
        $row = $queryBuilder->select('PGT.schemaname', 'S.relname', 'C.attname', 'T.relname AS tablename')
9104
            ->from('pg_class', 'S')
9105
            ->from('pg_depend', 'D')
9106
            ->from('pg_class', 'T')
9107
            ->from('pg_attribute', 'C')
9108
            ->from('pg_tables', 'PGT')
9109
            ->where(
9110
                $queryBuilder->expr()->eq('S.relkind', $queryBuilder->quote('S')),
9111
                $queryBuilder->expr()->eq('S.oid', $queryBuilder->quoteIdentifier('D.objid')),
9112
                $queryBuilder->expr()->eq('D.refobjid', $queryBuilder->quoteIdentifier('T.oid')),
9113
                $queryBuilder->expr()->eq('D.refobjid', $queryBuilder->quoteIdentifier('C.attrelid')),
9114
                $queryBuilder->expr()->eq('D.refobjsubid', $queryBuilder->quoteIdentifier('C.attnum')),
9115
                $queryBuilder->expr()->eq('T.relname', $queryBuilder->quoteIdentifier('PGT.tablename')),
9116
                $queryBuilder->expr()->eq('PGT.tablename', $queryBuilder->quote($tableName))
9117
            )
9118
            ->setMaxResults(1)
9119
            ->execute()
9120
            ->fetch();
9121
9122
        if ($row !== false) {
9123
            $connection->exec(
9124
                sprintf(
9125
                    'SELECT SETVAL(%s, COALESCE(MAX(%s), 0)+1, FALSE) FROM %s',
9126
                    $connection->quote($row['schemaname'] . '.' . $row['relname']),
9127
                    $connection->quoteIdentifier($row['attname']),
9128
                    $connection->quoteIdentifier($row['schemaname'] . '.' . $row['tablename'])
9129
                )
9130
            );
9131
        }
9132
    }
9133
9134
    /**
9135
     * Return the cache entry identifier for field evals
9136
     *
9137
     * @param string $additionalIdentifier
9138
     * @return string
9139
     */
9140
    protected function getFieldEvalCacheIdentifier($additionalIdentifier)
9141
    {
9142
        return 'core-datahandler-eval-' . md5($additionalIdentifier);
9143
    }
9144
9145
    /**
9146
     * @return RelationHandler
9147
     */
9148
    protected function createRelationHandlerInstance()
9149
    {
9150
        $isWorkspacesLoaded = ExtensionManagementUtility::isLoaded('workspaces');
9151
        $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
9152
        $relationHandler->setWorkspaceId($this->BE_USER->workspace);
9153
        $relationHandler->setUseLiveReferenceIds($isWorkspacesLoaded);
9154
        $relationHandler->setUseLiveParentIds($isWorkspacesLoaded);
9155
        $relationHandler->setReferenceIndexUpdater($this->referenceIndexUpdater);
9156
        return $relationHandler;
9157
    }
9158
9159
    /**
9160
     * Create and returns an instance of the CacheManager
9161
     *
9162
     * @return CacheManager
9163
     */
9164
    protected function getCacheManager()
9165
    {
9166
        return GeneralUtility::makeInstance(CacheManager::class);
9167
    }
9168
9169
    /**
9170
     * Gets the resourceFactory
9171
     *
9172
     * @return ResourceFactory
9173
     */
9174
    protected function getResourceFactory()
9175
    {
9176
        return GeneralUtility::makeInstance(ResourceFactory::class);
9177
    }
9178
9179
    /**
9180
     * @return LanguageService
9181
     */
9182
    protected function getLanguageService()
9183
    {
9184
        return $GLOBALS['LANG'];
9185
    }
9186
9187
    /**
9188
     * @internal should only be used from within TYPO3 Core
9189
     * @return array
9190
     */
9191
    public function getHistoryRecords(): array
9192
    {
9193
        return $this->historyRecords;
9194
    }
9195
}
9196