Passed
Push — master ( 1e85f0...74899e )
by
unknown
14:10
created

DataHandler::isRecordCopied()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 3
nop 2
dl 0
loc 10
rs 10
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\DBALException;
19
use Doctrine\DBAL\Driver\Statement;
20
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
21
use Doctrine\DBAL\Platforms\SQLServerPlatform;
22
use Doctrine\DBAL\Types\IntegerType;
23
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
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
393
     */
394
    public $datamap = [];
395
396
    /**
397
     * Set with incoming cmd array
398
     *
399
     * @var 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
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
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
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])) {
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']) {
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], 1);
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
                    if ($table === 'pages' && $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0 && $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0) {
945
                        $recordAccess = $this->checkRecordInsertAccess($table, $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
946
                    } else {
947
                        $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
948
                    }
949
                    if ($recordAccess) {
950
                        $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
951
                        $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, true);
952
                        if (!$recordAccess) {
953
                            $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', SystemLogErrorClassification::USER_ERROR);
954
                        } elseif (!$this->bypassWorkspaceRestrictions && !$this->BE_USER->workspaceAllowsLiveEditingInTable($table)) {
955
                            // If LIVE records cannot be created due to workspace restrictions, prepare creation of placeholder-record
956
                            // So, if no live records were allowed in the current workspace, we have to create a new version of this record
957
                            if (BackendUtility::isTableWorkspaceEnabled($table)) {
958
                                $createNewVersion = true;
959
                            } else {
960
                                $recordAccess = false;
961
                                $this->newlog('Record could not be created in this workspace', SystemLogErrorClassification::USER_ERROR);
962
                            }
963
                        }
964
                    }
965
                    // Yes new record, change $record_status to 'insert'
966
                    $status = 'new';
967
                } else {
968
                    // Nope... $id is a number
969
                    $fieldArray = [];
970
                    $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
971
                    if (!$recordAccess) {
972
                        if ($this->enableLogging) {
973
                            $propArr = $this->getRecordProperties($table, $id);
974
                            $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']);
975
                        }
976
                        continue;
977
                    }
978
                    // Next check of the record permissions (internals)
979
                    $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
980
                    if (!$recordAccess) {
981
                        $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', SystemLogErrorClassification::USER_ERROR);
982
                    } else {
983
                        // Here we fetch the PID of the record that we point to...
984
                        $tempdata = $this->recordInfo($table, $id, 'pid' . (BackendUtility::isTableWorkspaceEnabled($table) ? ',t3ver_oid,t3ver_wsid,t3ver_stage' : ''));
985
                        $theRealPid = $tempdata['pid'] ?? null;
986
                        // Use the new id of the versionized record we're trying to write to:
987
                        // (This record is a child record of a parent and has already been versionized.)
988
                        if (!empty($this->autoVersionIdMap[$table][$id])) {
989
                            // For the reason that creating a new version of this record, automatically
990
                            // created related child records (e.g. "IRRE"), update the accordant field:
991
                            $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
992
                            // Use the new id of the copied/versionized record:
993
                            $id = $this->autoVersionIdMap[$table][$id];
994
                            $recordAccess = true;
995
                        } elseif (!$this->bypassWorkspaceRestrictions && ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $tempdata))) {
996
                            $recordAccess = false;
997
                            // Versioning is required and it must be offline version!
998
                            // Check if there already is a workspace version
999
                            $workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid,t3ver_oid');
1000
                            if ($workspaceVersion) {
1001
                                $id = $workspaceVersion['uid'];
1002
                                $recordAccess = true;
1003
                            } elseif ($this->BE_USER->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1004
                                // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1005
                                $this->pagetreeNeedsRefresh = true;
1006
1007
                                /** @var DataHandler $tce */
1008
                                $tce = GeneralUtility::makeInstance(__CLASS__, $this->referenceIndexUpdater);
1009
                                $tce->enableLogging = $this->enableLogging;
1010
                                // Setting up command for creating a new version of the record:
1011
                                $cmd = [];
1012
                                $cmd[$table][$id]['version'] = [
1013
                                    'action' => 'new',
1014
                                    // Default is to create a version of the individual records
1015
                                    'label' => 'Auto-created for WS #' . $this->BE_USER->workspace
1016
                                ];
1017
                                $tce->start([], $cmd, $this->BE_USER);
1018
                                $tce->process_cmdmap();
1019
                                $this->errorLog = array_merge($this->errorLog, $tce->errorLog);
1020
                                // If copying was successful, share the new uids (also of related children):
1021
                                if (!empty($tce->copyMappingArray[$table][$id])) {
1022
                                    foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
1023
                                        foreach ($origIdArray as $origId => $newId) {
1024
                                            $this->autoVersionIdMap[$origTable][$origId] = $newId;
1025
                                        }
1026
                                    }
1027
                                    // Update registerDBList, that holds the copied relations to child records:
1028
                                    $registerDBList = array_merge($registerDBList, $tce->registerDBList);
1029
                                    // For the reason that creating a new version of this record, automatically
1030
                                    // created related child records (e.g. "IRRE"), update the accordant field:
1031
                                    $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1032
                                    // Use the new id of the copied/versionized record:
1033
                                    $id = $this->autoVersionIdMap[$table][$id];
1034
                                    $recordAccess = true;
1035
                                } else {
1036
                                    $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);
1037
                                }
1038
                            } else {
1039
                                $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);
1040
                            }
1041
                        }
1042
                    }
1043
                    // The default is 'update'
1044
                    $status = 'update';
1045
                }
1046
                // If access was granted above, proceed to create or update record:
1047
                if (!$recordAccess) {
1048
                    continue;
1049
                }
1050
1051
                // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1052
                [$tscPID] = BackendUtility::getTSCpid($table, $id, $old_pid_value ?: $fieldArray['pid']);
1053
                if ($status === 'new') {
1054
                    // Apply TCAdefaults from pageTS
1055
                    $fieldArray = $this->applyDefaultsForFieldArray($table, (int)$tscPID, $fieldArray);
1056
                    // Apply page permissions as well
1057
                    if ($table === 'pages') {
1058
                        $fieldArray = $this->pagePermissionAssembler->applyDefaults(
1059
                            $fieldArray,
1060
                            (int)$tscPID,
1061
                            (int)$this->userid,
1062
                            (int)$this->BE_USER->firstMainGroup
1063
                        );
1064
                    }
1065
                }
1066
                // Processing of all fields in incomingFieldArray and setting them in $fieldArray
1067
                $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1068
                // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations to field!
1069
                // Forcing some values unto field array:
1070
                // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
1071
                $fieldArray = $this->overrideFieldArray($table, $fieldArray);
1072
                // Setting system fields
1073
                if ($status === 'new') {
1074
                    if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1075
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1076
                    }
1077
                    if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1078
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
1079
                    }
1080
                } elseif ($this->checkSimilar) {
1081
                    // Removing fields which are equal to the current value:
1082
                    $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
1083
                }
1084
                if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && !empty($fieldArray)) {
1085
                    $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1086
                }
1087
                // Set stage to "Editing" to make sure we restart the workflow
1088
                if (BackendUtility::isTableWorkspaceEnabled($table)) {
1089
                    $fieldArray['t3ver_stage'] = 0;
1090
                }
1091
                // Hook: processDatamap_postProcessFieldArray
1092
                foreach ($hookObjectsArr as $hookObj) {
1093
                    if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
1094
                        $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
1095
                    }
1096
                }
1097
                // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1098
                // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already
1099
                if (is_array($fieldArray)) {
1100
                    if ($status === 'new') {
1101
                        if ($table === 'pages') {
1102
                            // for new pages always a refresh is needed
1103
                            $this->pagetreeNeedsRefresh = true;
1104
                        }
1105
1106
                        // This creates a version of the record, instead of adding it to the live workspace
1107
                        if ($createNewVersion) {
1108
                            // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1109
                            $this->pagetreeNeedsRefresh = true;
1110
                            $fieldArray['pid'] = $theRealPid;
1111
                            $fieldArray['t3ver_oid'] = 0;
1112
                            // Setting state for version (so it can know it is currently a new version...)
1113
                            $fieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER);
1114
                            $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1115
                            $this->insertDB($table, $id, $fieldArray, true, (int)($incomingFieldArray['uid'] ?? 0));
1116
                            // Hold auto-versionized ids of placeholders
1117
                            $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $this->substNEWwithIDs[$id];
1118
                        } else {
1119
                            $this->insertDB($table, $id, $fieldArray, false, (int)($incomingFieldArray['uid'] ?? 0));
1120
                        }
1121
                    } else {
1122
                        if ($table === 'pages') {
1123
                            // only a certain number of fields needs to be checked for updates
1124
                            // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
1125
                            $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages, array_keys($fieldArray));
1126
                            if (!empty($fieldsToCheck)) {
1127
                                $this->pagetreeNeedsRefresh = true;
1128
                            }
1129
                        }
1130
                        $this->updateDB($table, $id, $fieldArray);
1131
                    }
1132
                }
1133
                // Hook: processDatamap_afterDatabaseOperations
1134
                // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
1135
                // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
1136
                $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
1137
            }
1138
        }
1139
        // Process the stack of relations to remap/correct
1140
        $this->processRemapStack();
1141
        $this->dbAnalysisStoreExec();
1142
        // Hook: processDatamap_afterAllOperations
1143
        // Note: When this hook gets called, all operations on the submitted data have been finished.
1144
        foreach ($hookObjectsArr as $hookObj) {
1145
            if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
1146
                $hookObj->processDatamap_afterAllOperations($this);
1147
            }
1148
        }
1149
1150
        if ($this->isOuterMostInstance()) {
1151
            $this->referenceIndexUpdater->update();
1152
            $this->processClearCacheQueue();
1153
            $this->resetElementsToBeDeleted();
1154
        }
1155
    }
1156
1157
    /**
1158
     * @param string $table
1159
     * @param string $value
1160
     * @param string $dbType
1161
     * @return string
1162
     */
1163
    protected function normalizeTimeFormat(string $table, string $value, string $dbType): string
1164
    {
1165
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
1166
        $platform = $connection->getDatabasePlatform();
1167
        if ($platform instanceof SQLServerPlatform) {
1168
            $defaultLength = QueryHelper::getDateTimeFormats()[$dbType]['empty'];
1169
            $value = substr(
1170
                $value,
1171
                0,
1172
                strlen($defaultLength)
1173
            );
1174
        }
1175
        return $value;
1176
    }
1177
1178
    /**
1179
     * Sets the "sorting" DB field and the "pid" field of an incoming record that should be added (NEW1234)
1180
     * depending on the record that should be added or where it should be added.
1181
     *
1182
     * This method is called from process_datamap()
1183
     *
1184
     * @param string $table the table name of the record to insert
1185
     * @param int $pid the real PID (numeric) where the record should be
1186
     * @param array $fieldArray field+value pairs to add
1187
     * @return array the modified field array
1188
     */
1189
    protected function resolveSortingAndPidForNewRecord(string $table, int $pid, array $fieldArray): array
1190
    {
1191
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
1192
        // Points to a page on which to insert the element, possibly in the top of the page
1193
        if ($pid >= 0) {
1194
            // Ensure that the "pid" is not a translated page ID, but the default page ID
1195
            $pid = $this->getDefaultLanguagePageId($pid);
1196
            // The numerical pid is inserted in the data array
1197
            $fieldArray['pid'] = $pid;
1198
            // If this table is sorted we better find the top sorting number
1199
            if ($sortColumn) {
1200
                $fieldArray[$sortColumn] = $this->getSortNumber($table, 0, $pid);
1201
            }
1202
        } elseif ($sortColumn) {
1203
            // Points to another record before itself
1204
            // If this table is sorted we better find the top sorting number
1205
            // Because $pid is < 0, getSortNumber() returns an array
1206
            $sortingInfo = $this->getSortNumber($table, 0, $pid);
1207
            $fieldArray['pid'] = $sortingInfo['pid'];
1208
            $fieldArray[$sortColumn] = $sortingInfo['sortNumber'];
1209
        } else {
1210
            // Here we fetch the PID of the record that we point to
1211
            $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

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

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

1393
                    $propArr = $this->getRecordProperties($table, /** @scrutinizer ignore-type */ $id);
Loading history...
1394
                    $this->log($table, $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']);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $recuid of TYPO3\CMS\Core\DataHandling\DataHandler::log(). ( Ignorable by Annotation )

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

1394
                    $this->log($table, /** @scrutinizer ignore-type */ $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']);
Loading history...
1395
                }
1396
                return $res;
1397
            }
1398
            if ($status === 'update') {
1399
                // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1400
                $onlyAllowedTables = $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1401
                if ($onlyAllowedTables) {
1402
                    // use the real page id (default language)
1403
                    $recordId = $this->getDefaultLanguagePageId($id);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $pageId of TYPO3\CMS\Core\DataHandl...DefaultLanguagePageId(). ( Ignorable by Annotation )

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

1403
                    $recordId = $this->getDefaultLanguagePageId(/** @scrutinizer ignore-type */ $id);
Loading history...
1404
                    $theWrongTables = $this->doesPageHaveUnallowedTables($recordId, $value);
0 ignored issues
show
Bug introduced by
$value of type string is incompatible with the type integer expected by parameter $doktype of TYPO3\CMS\Core\DataHandl...geHaveUnallowedTables(). ( Ignorable by Annotation )

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

1404
                    $theWrongTables = $this->doesPageHaveUnallowedTables($recordId, /** @scrutinizer ignore-type */ $value);
Loading history...
1405
                    if ($theWrongTables) {
1406
                        if ($this->enableLogging) {
1407
                            $propArr = $this->getRecordProperties($table, $id);
1408
                            $this->log($table, $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']);
1409
                        }
1410
                        return $res;
1411
                    }
1412
                }
1413
            }
1414
        }
1415
1416
        $curValue = null;
1417
        if ((int)$id !== 0) {
1418
            // Get current value:
1419
            $curValueRec = $this->recordInfo($table, $id, $field);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $id of TYPO3\CMS\Core\DataHandl...taHandler::recordInfo(). ( Ignorable by Annotation )

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

1419
            $curValueRec = $this->recordInfo($table, /** @scrutinizer ignore-type */ $id, $field);
Loading history...
1420
            // isset() won't work here, since values can be NULL
1421
            if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1422
                $curValue = $curValueRec[$field];
1423
            }
1424
        }
1425
1426
        if ($table === 'be_users'
1427
            && ($field === 'admin' || $field === 'password')
1428
            && $status === 'update'
1429
        ) {
1430
            // Do not allow a non system maintainer admin to change admin flag and password of system maintainers
1431
            $systemMaintainers = array_map('intval', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? []);
1432
            // False if current user is not in system maintainer list or if switch to user mode is active
1433
            $isCurrentUserSystemMaintainer = $this->BE_USER->isSystemMaintainer();
1434
            $isTargetUserInSystemMaintainerList = in_array((int)$id, $systemMaintainers, true);
1435
            if ($field === 'admin') {
1436
                $isFieldChanged = (int)$curValueRec[$field] !== (int)$value;
1437
            } else {
1438
                $isFieldChanged = $curValueRec[$field] !== $value;
1439
            }
1440
            if (!$isCurrentUserSystemMaintainer && $isTargetUserInSystemMaintainerList && $isFieldChanged) {
1441
                $value = $curValueRec[$field];
1442
                $message = GeneralUtility::makeInstance(
1443
                    FlashMessage::class,
1444
                    $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.adminCanNotChangeSystemMaintainer'),
1445
                    '',
1446
                    FlashMessage::ERROR,
1447
                    true
1448
                );
1449
                $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1450
                $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
1451
            }
1452
        }
1453
1454
        // Getting config for the field
1455
        $tcaFieldConf = $this->resolveFieldConfigurationAndRespectColumnsOverrides($table, $field);
1456
1457
        // Create $recFID only for those types that need it
1458
        if ($tcaFieldConf['type'] === 'flex') {
1459
            $recFID = $table . ':' . $id . ':' . $field;
1460
        } else {
1461
            $recFID = null;
1462
        }
1463
1464
        // Perform processing:
1465
        $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, [], $tscPID, ['incomingFieldArray' => $incomingFieldArray]);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $id of TYPO3\CMS\Core\DataHandl...andler::checkValue_SW(). ( Ignorable by Annotation )

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

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

2517
                    $value = number_format(/** @scrutinizer ignore-type */ $value, 2, '.', '');
Loading history...
2518
                    break;
2519
                case 'md5':
2520
                    if (strlen($value) !== 32) {
2521
                        $set = false;
2522
                    }
2523
                    break;
2524
                case 'trim':
2525
                    $value = trim($value);
2526
                    break;
2527
                case 'upper':
2528
                    $value = mb_strtoupper($value, 'utf-8');
2529
                    break;
2530
                case 'lower':
2531
                    $value = mb_strtolower($value, 'utf-8');
2532
                    break;
2533
                case 'required':
2534
                    if (!isset($value) || $value === '') {
2535
                        $set = false;
2536
                    }
2537
                    break;
2538
                case 'is_in':
2539
                    $c = mb_strlen($value);
2540
                    if ($c) {
2541
                        $newVal = '';
2542
                        for ($a = 0; $a < $c; $a++) {
2543
                            $char = mb_substr($value, $a, 1);
2544
                            if (mb_strpos($is_in, $char) !== false) {
2545
                                $newVal .= $char;
2546
                            }
2547
                        }
2548
                        $value = $newVal;
2549
                    }
2550
                    break;
2551
                case 'nospace':
2552
                    $value = str_replace(' ', '', $value);
2553
                    break;
2554
                case 'alpha':
2555
                    $value = preg_replace('/[^a-zA-Z]/', '', $value);
2556
                    break;
2557
                case 'num':
2558
                    $value = preg_replace('/[^0-9]/', '', $value);
2559
                    break;
2560
                case 'alphanum':
2561
                    $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2562
                    break;
2563
                case 'alphanum_x':
2564
                    $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2565
                    break;
2566
                case 'domainname':
2567
                    if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2568
                        $value = (string)HttpUtility::idn_to_ascii($value);
2569
                    }
2570
                    break;
2571
                case 'email':
2572
                    if ((string)$value !== '') {
2573
                        $this->checkValue_input_ValidateEmail($value, $set);
2574
                    }
2575
                    break;
2576
                case 'saltedPassword':
2577
                    // An incoming value is either the salted password if the user did not change existing password
2578
                    // when submitting the form, or a plaintext new password that needs to be turned into a salted password now.
2579
                    // The strategy is to see if a salt instance can be created from the incoming value. If so,
2580
                    // no new password was submitted and we keep the value. If no salting instance can be created,
2581
                    // incoming value must be a new plain text value that needs to be hashed.
2582
                    $hashFactory = GeneralUtility::makeInstance(PasswordHashFactory::class);
2583
                    $mode = $table === 'fe_users' ? 'FE' : 'BE';
2584
                    try {
2585
                        $hashFactory->get($value, $mode);
2586
                    } catch (InvalidPasswordHashException $e) {
2587
                        // We got no salted password instance, incoming value must be a new plaintext password
2588
                        // Get an instance of the current configured salted password strategy and hash the value
2589
                        $newHashInstance = $hashFactory->getDefaultHashInstance($mode);
2590
                        $value = $newHashInstance->getHashedPassword($value);
2591
                    }
2592
                    break;
2593
                default:
2594
                    if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2595
                        if (class_exists($func)) {
2596
                            $evalObj = GeneralUtility::makeInstance($func);
2597
                            if (method_exists($evalObj, 'evaluateFieldValue')) {
2598
                                $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2599
                            }
2600
                        }
2601
                    }
2602
            }
2603
        }
2604
        if ($set) {
2605
            $res['value'] = $value;
2606
        }
2607
        return $res;
2608
    }
2609
2610
    /**
2611
     * If $value is not a valid e-mail address,
2612
     * $set will be set to false and a flash error
2613
     * message will be added
2614
     *
2615
     * @param string $value Value to evaluate
2616
     * @param bool $set TRUE if an update should be done
2617
     * @throws \InvalidArgumentException
2618
     * @throws \TYPO3\CMS\Core\Exception
2619
     */
2620
    protected function checkValue_input_ValidateEmail($value, &$set)
2621
    {
2622
        if (GeneralUtility::validEmail($value)) {
2623
            return;
2624
        }
2625
2626
        $set = false;
2627
        /** @var FlashMessage $message */
2628
        $message = GeneralUtility::makeInstance(
2629
            FlashMessage::class,
2630
            sprintf($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.invalidEmail'), $value),
2631
            '', // header is optional
2632
            FlashMessage::ERROR,
2633
            true // whether message should be stored in session
2634
        );
2635
        /** @var FlashMessageService $flashMessageService */
2636
        $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
2637
        $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
2638
    }
2639
2640
    /**
2641
     * Returns data for group/db and select fields
2642
     *
2643
     * @param array $valueArray Current value array
2644
     * @param array $tcaFieldConf TCA field config
2645
     * @param int $id Record id, used for look-up of MM relations (local_uid)
2646
     * @param string $status Status string ('update' or 'new')
2647
     * @param string $type The type, either 'select', 'group' or 'inline'
2648
     * @param string $currentTable Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2649
     * @param string $currentField field name, needs to be set for writing to sys_history
2650
     * @return array Modified value array
2651
     * @internal should only be used from within DataHandler
2652
     */
2653
    public function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField)
2654
    {
2655
        if ($type === 'group') {
2656
            $tables = $tcaFieldConf['allowed'];
2657
        } elseif (!empty($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages') {
2658
            $tables = 'sys_language';
2659
        } else {
2660
            $tables = $tcaFieldConf['foreign_table'];
2661
        }
2662
        $prep = $type === 'group' ? $tcaFieldConf['prepend_tname'] : '';
2663
        $newRelations = implode(',', $valueArray);
2664
        /** @var RelationHandler $dbAnalysis */
2665
        $dbAnalysis = $this->createRelationHandlerInstance();
2666
        $dbAnalysis->registerNonTableValues = !empty($tcaFieldConf['allowNonIdValues']);
2667
        $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2668
        if ($tcaFieldConf['MM']) {
2669
            // convert submitted items to use version ids instead of live ids
2670
            // (only required for MM relations in a workspace context)
2671
            $dbAnalysis->convertItemArray();
2672
            if ($status === 'update') {
2673
                /** @var RelationHandler $oldRelations_dbAnalysis */
2674
                $oldRelations_dbAnalysis = $this->createRelationHandlerInstance();
2675
                $oldRelations_dbAnalysis->registerNonTableValues = !empty($tcaFieldConf['allowNonIdValues']);
2676
                // Db analysis with $id will initialize with the existing relations
2677
                $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2678
                $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2679
                $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

2679
                $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, /** @scrutinizer ignore-type */ $prep);
Loading history...
2680
                if ($oldRelations != $newRelations) {
2681
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2682
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2683
                } else {
2684
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2685
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2686
                }
2687
            } else {
2688
                $this->dbAnalysisStore[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable];
2689
            }
2690
            $valueArray = $dbAnalysis->countItems();
2691
        } else {
2692
            $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

2692
            $valueArray = $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prep);
Loading history...
2693
        }
2694
        // 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.
2695
        return $valueArray;
2696
    }
2697
2698
    /**
2699
     * Explodes the $value, which is a list of files/uids (group select)
2700
     *
2701
     * @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.
2702
     * @return array The value array.
2703
     * @internal should only be used from within DataHandler
2704
     */
2705
    public function checkValue_group_select_explodeSelectGroupValue($value)
2706
    {
2707
        $valueArray = GeneralUtility::trimExplode(',', $value, true);
2708
        foreach ($valueArray as &$newVal) {
2709
            $temp = explode('|', $newVal, 2);
2710
            $newVal = str_replace(['|', ','], '', rawurldecode($temp[0]));
2711
        }
2712
        unset($newVal);
2713
        return $valueArray;
2714
    }
2715
2716
    /**
2717
     * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2718
     * See checkValue_flex_procInData_travDS() for more details.
2719
     * 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
2720
     *
2721
     * @param array $dataPart The 'data' part of the INPUT flexform data
2722
     * @param array $dataPart_current The 'data' part of the CURRENT flexform data
2723
     * @param array $uploadedFiles The uploaded files for the 'data' part of the INPUT flexform data
2724
     * @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.
2725
     * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions
2726
     * @param string $callBackFunc Optional call back function, see checkValue_flex_procInData_travDS()  DEPRECATED, use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools instead for traversal!
2727
     * @param array $workspaceOptions
2728
     * @return array The modified 'data' part.
2729
     * @see checkValue_flex_procInData_travDS()
2730
     * @internal should only be used from within DataHandler
2731
     */
2732
    public function checkValue_flex_procInData($dataPart, $dataPart_current, $uploadedFiles, $dataStructure, $pParams, $callBackFunc = '', array $workspaceOptions = [])
2733
    {
2734
        if (is_array($dataPart)) {
0 ignored issues
show
introduced by
The condition is_array($dataPart) is always true.
Loading history...
2735
            foreach ($dataPart as $sKey => $sheetDef) {
2736
                if (isset($dataStructure['sheets'][$sKey]) && is_array($dataStructure['sheets'][$sKey]) && is_array($sheetDef)) {
2737
                    foreach ($sheetDef as $lKey => $lData) {
2738
                        $this->checkValue_flex_procInData_travDS(
2739
                            $dataPart[$sKey][$lKey],
2740
                            $dataPart_current[$sKey][$lKey],
2741
                            $uploadedFiles[$sKey][$lKey],
2742
                            $dataStructure['sheets'][$sKey]['ROOT']['el'],
2743
                            $pParams,
2744
                            $callBackFunc,
2745
                            $sKey . '/' . $lKey . '/',
2746
                            $workspaceOptions
2747
                        );
2748
                    }
2749
                }
2750
            }
2751
        }
2752
        return $dataPart;
2753
    }
2754
2755
    /**
2756
     * Processing of the sheet/language data array
2757
     * 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.
2758
     *
2759
     * @param array $dataValues New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2760
     * @param array $dataValues_current Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2761
     * @param array $uploadedFiles Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2762
     * @param array $DSelements Data structure which fits the data array
2763
     * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions / call back function
2764
     * @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.
2765
     * @param string $structurePath
2766
     * @param array $workspaceOptions
2767
     * @see checkValue_flex_procInData()
2768
     * @internal should only be used from within DataHandler
2769
     */
2770
    public function checkValue_flex_procInData_travDS(&$dataValues, $dataValues_current, $uploadedFiles, $DSelements, $pParams, $callBackFunc, $structurePath, array $workspaceOptions = [])
2771
    {
2772
        if (!is_array($DSelements)) {
0 ignored issues
show
introduced by
The condition is_array($DSelements) is always true.
Loading history...
2773
            return;
2774
        }
2775
2776
        // For each DS element:
2777
        foreach ($DSelements as $key => $dsConf) {
2778
            // Array/Section:
2779
            if ($DSelements[$key]['type'] === 'array') {
2780
                if (!is_array($dataValues[$key]['el'])) {
2781
                    continue;
2782
                }
2783
2784
                if ($DSelements[$key]['section']) {
2785
                    foreach ($dataValues[$key]['el'] as $ik => $el) {
2786
                        if (!is_array($el)) {
2787
                            continue;
2788
                        }
2789
2790
                        if (!is_array($dataValues_current[$key]['el'])) {
2791
                            $dataValues_current[$key]['el'] = [];
2792
                        }
2793
                        $theKey = key($el);
2794
                        if (!is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2795
                            continue;
2796
                        }
2797
2798
                        $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);
2799
                    }
2800
                } else {
2801
                    if (!isset($dataValues[$key]['el'])) {
2802
                        $dataValues[$key]['el'] = [];
2803
                    }
2804
                    $this->checkValue_flex_procInData_travDS($dataValues[$key]['el'], $dataValues_current[$key]['el'], $uploadedFiles[$key]['el'], $DSelements[$key]['el'], $pParams, $callBackFunc, $structurePath . $key . '/el/', $workspaceOptions);
2805
                }
2806
            } else {
2807
                // When having no specific sheets, it's "TCEforms.config", when having a sheet, it's just "config"
2808
                $fieldConfiguration = $dsConf['TCEforms']['config'] ?? $dsConf['config'] ?? null;
2809
                // init with value from config for passthrough fields
2810
                if (!empty($fieldConfiguration['type']) && $fieldConfiguration['type'] === 'passthrough') {
2811
                    if (!empty($dataValues_current[$key]['vDEF'])) {
2812
                        // If there is existing value, keep it
2813
                        $dataValues[$key]['vDEF'] = $dataValues_current[$key]['vDEF'];
2814
                    } elseif (
2815
                        !empty($fieldConfiguration['default'])
2816
                        && isset($pParams[1])
2817
                        && !MathUtility::canBeInterpretedAsInteger($pParams[1])
2818
                    ) {
2819
                        // If is new record and a default is specified for field, use it.
2820
                        $dataValues[$key]['vDEF'] = $fieldConfiguration['default'];
2821
                    }
2822
                }
2823
                if (!is_array($fieldConfiguration) || !is_array($dataValues[$key])) {
2824
                    continue;
2825
                }
2826
2827
                foreach ($dataValues[$key] as $vKey => $data) {
2828
                    if ($callBackFunc) {
2829
                        if (is_object($this->callBackObj)) {
2830
                            $res = $this->callBackObj->{$callBackFunc}($pParams, $fieldConfiguration, $dataValues[$key][$vKey], $dataValues_current[$key][$vKey], $uploadedFiles[$key][$vKey], $structurePath . $key . '/' . $vKey . '/', $workspaceOptions);
2831
                        } else {
2832
                            $res = $this->{$callBackFunc}($pParams, $fieldConfiguration, $dataValues[$key][$vKey], $dataValues_current[$key][$vKey], $uploadedFiles[$key][$vKey], $structurePath . $key . '/' . $vKey . '/', $workspaceOptions);
2833
                        }
2834
                    } else {
2835
                        // Default
2836
                        [$CVtable, $CVid, $CVcurValue, $CVstatus, $CVrealPid, $CVrecFID, $CVtscPID] = $pParams;
2837
2838
                        $additionalData = [
2839
                            'flexFormId' => $CVrecFID,
2840
                            'flexFormPath' => trim(rtrim($structurePath, '/') . '/' . $key . '/' . $vKey, '/'),
2841
                        ];
2842
2843
                        $res = $this->checkValue_SW([], $dataValues[$key][$vKey], $fieldConfiguration, $CVtable, $CVid, $dataValues_current[$key][$vKey], $CVstatus, $CVrealPid, $CVrecFID, '', $uploadedFiles[$key][$vKey], $CVtscPID, $additionalData);
2844
                    }
2845
                    // Adding the value:
2846
                    if (isset($res['value'])) {
2847
                        $dataValues[$key][$vKey] = $res['value'];
2848
                    }
2849
                    // 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.
2850
                    // 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).
2851
                    if (mb_substr($vKey, -9) !== '.vDEFbase') {
2852
                        if ($GLOBALS['TYPO3_CONF_VARS']['BE']['flexFormXMLincludeDiffBase'] && $vKey !== 'vDEF' && ((string)$dataValues[$key][$vKey] !== (string)$dataValues_current[$key][$vKey] || !isset($dataValues_current[$key][$vKey . '.vDEFbase']))) {
2853
                            // 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:
2854
                            if (isset($dataValues[$key]['vDEF'])) {
2855
                                $diffValue = $dataValues[$key]['vDEF'];
2856
                            } else {
2857
                                // If not found (for translators with no access to the default language) we use the one from the current-value data set:
2858
                                $diffValue = $dataValues_current[$key]['vDEF'];
2859
                            }
2860
                            // 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.
2861
                            $dataValues[$key][$vKey . '.vDEFbase'] = $diffValue;
2862
                        }
2863
                    }
2864
                }
2865
            }
2866
        }
2867
    }
2868
2869
    /**
2870
     * Returns data for inline fields.
2871
     *
2872
     * @param array $valueArray Current value array
2873
     * @param array $tcaFieldConf TCA field config
2874
     * @param int $id Record id
2875
     * @param string $status Status string ('update' or 'new')
2876
     * @param string $table Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2877
     * @param string $field The current field the values are modified for
2878
     * @param array $additionalData Additional data to be forwarded to sub-processors
2879
     * @return string Modified values
2880
     */
2881
    protected function checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, array $additionalData = null)
2882
    {
2883
        $foreignTable = $tcaFieldConf['foreign_table'];
2884
        $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
2885
        // Fetch the related child records using \TYPO3\CMS\Core\Database\RelationHandler
2886
        /** @var RelationHandler $dbAnalysis */
2887
        $dbAnalysis = $this->createRelationHandlerInstance();
2888
        $dbAnalysis->start(implode(',', $valueArray), $foreignTable, '', 0, $table, $tcaFieldConf);
2889
        // IRRE with a pointer field (database normalization):
2890
        if ($tcaFieldConf['foreign_field']) {
2891
            // if the record was imported, sorting was also imported, so skip this
2892
            $skipSorting = (bool)$this->callFromImpExp;
2893
            // update record in intermediate table (sorting & pointer uid to parent record)
2894
            $dbAnalysis->writeForeignField($tcaFieldConf, $id, 0, $skipSorting);
2895
            $newValue = $dbAnalysis->countItems(false);
2896
        } elseif ($this->getInlineFieldType($tcaFieldConf) === 'mm') {
2897
            // In order to fully support all the MM stuff, directly call checkValue_group_select_processDBdata instead of repeating the needed code here
2898
            $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
2899
            $newValue = $valueArray[0];
2900
        } else {
2901
            $valueArray = $dbAnalysis->getValueArray();
2902
            // Checking that the number of items is correct:
2903
            $valueArray = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2904
            $newValue = $this->castReferenceValue(implode(',', $valueArray), $tcaFieldConf);
2905
        }
2906
        return $newValue;
2907
    }
2908
2909
    /*********************************************
2910
     *
2911
     * PROCESSING COMMANDS
2912
     *
2913
     ********************************************/
2914
    /**
2915
     * Processing the cmd-array
2916
     * See "TYPO3 Core API" for a description of the options.
2917
     *
2918
     * @return void|bool
2919
     */
2920
    public function process_cmdmap()
2921
    {
2922
        // Editing frozen:
2923
        if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
2924
            $this->newlog('All editing in this workspace has been frozen!', SystemLogErrorClassification::USER_ERROR);
2925
            return false;
2926
        }
2927
        // Hook initialization:
2928
        $hookObjectsArr = [];
2929
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
2930
            $hookObj = GeneralUtility::makeInstance($className);
2931
            if (method_exists($hookObj, 'processCmdmap_beforeStart')) {
2932
                $hookObj->processCmdmap_beforeStart($this);
2933
            }
2934
            $hookObjectsArr[] = $hookObj;
2935
        }
2936
        $pasteDatamap = [];
2937
        // Traverse command map:
2938
        foreach ($this->cmdmap as $table => $_) {
2939
            // Check if the table may be modified!
2940
            $modifyAccessList = $this->checkModifyAccessList($table);
2941
            if (!$modifyAccessList) {
2942
                $this->log($table, 0, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
2943
            }
2944
            // Check basic permissions and circumstances:
2945
            if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->cmdmap[$table]) || !$modifyAccessList) {
2946
                continue;
2947
            }
2948
2949
            // Traverse the command map:
2950
            foreach ($this->cmdmap[$table] as $id => $incomingCmdArray) {
2951
                if (!is_array($incomingCmdArray)) {
2952
                    continue;
2953
                }
2954
2955
                if ($table === 'pages') {
2956
                    // for commands on pages do a pagetree-refresh
2957
                    $this->pagetreeNeedsRefresh = true;
2958
                }
2959
2960
                foreach ($incomingCmdArray as $command => $value) {
2961
                    $pasteUpdate = false;
2962
                    if (is_array($value) && isset($value['action']) && $value['action'] === 'paste') {
2963
                        // Extended paste command: $command is set to "move" or "copy"
2964
                        // $value['update'] holds field/value pairs which should be updated after copy/move operation
2965
                        // $value['target'] holds original $value (target of move/copy)
2966
                        $pasteUpdate = $value['update'];
2967
                        $value = $value['target'];
2968
                    }
2969
                    foreach ($hookObjectsArr as $hookObj) {
2970
                        if (method_exists($hookObj, 'processCmdmap_preProcess')) {
2971
                            $hookObj->processCmdmap_preProcess($command, $table, $id, $value, $this, $pasteUpdate);
2972
                        }
2973
                    }
2974
                    // Init copyMapping array:
2975
                    // Must clear this array before call from here to those functions:
2976
                    // Contains mapping information between new and old id numbers.
2977
                    $this->copyMappingArray = [];
2978
                    // process the command
2979
                    $commandIsProcessed = false;
2980
                    foreach ($hookObjectsArr as $hookObj) {
2981
                        if (method_exists($hookObj, 'processCmdmap')) {
2982
                            $hookObj->processCmdmap($command, $table, $id, $value, $commandIsProcessed, $this, $pasteUpdate);
2983
                        }
2984
                    }
2985
                    // Only execute default commands if a hook hasn't been processed the command already
2986
                    if (!$commandIsProcessed) {
2987
                        $procId = $id;
2988
                        $backupUseTransOrigPointerField = $this->useTransOrigPointerField;
2989
                        // Branch, based on command
2990
                        switch ($command) {
2991
                            case 'move':
2992
                                $this->moveRecord($table, $id, $value);
2993
                                break;
2994
                            case 'copy':
2995
                                $target = $value['target'] ?? $value;
2996
                                $ignoreLocalization = (bool)($value['ignoreLocalization'] ?? false);
2997
                                if ($table === 'pages') {
2998
                                    $this->copyPages($id, $target);
2999
                                } else {
3000
                                    $this->copyRecord($table, $id, $target, true, [], '', 0, $ignoreLocalization);
3001
                                }
3002
                                $procId = $this->copyMappingArray[$table][$id];
3003
                                break;
3004
                            case 'localize':
3005
                                $this->useTransOrigPointerField = true;
3006
                                $this->localize($table, $id, $value);
3007
                                break;
3008
                            case 'copyToLanguage':
3009
                                $this->useTransOrigPointerField = false;
3010
                                $this->localize($table, $id, $value);
3011
                                break;
3012
                            case 'inlineLocalizeSynchronize':
3013
                                $this->inlineLocalizeSynchronize($table, $id, $value);
3014
                                break;
3015
                            case 'delete':
3016
                                $this->deleteAction($table, $id);
3017
                                break;
3018
                            case 'undelete':
3019
                                $this->undeleteRecord($table, $id);
3020
                                break;
3021
                        }
3022
                        $this->useTransOrigPointerField = $backupUseTransOrigPointerField;
3023
                        if (is_array($pasteUpdate)) {
3024
                            $pasteDatamap[$table][$procId] = $pasteUpdate;
3025
                        }
3026
                    }
3027
                    foreach ($hookObjectsArr as $hookObj) {
3028
                        if (method_exists($hookObj, 'processCmdmap_postProcess')) {
3029
                            $hookObj->processCmdmap_postProcess($command, $table, $id, $value, $this, $pasteUpdate, $pasteDatamap);
3030
                        }
3031
                    }
3032
                    // Merging the copy-array info together for remapping purposes.
3033
                    ArrayUtility::mergeRecursiveWithOverrule($this->copyMappingArray_merged, $this->copyMappingArray);
3034
                }
3035
            }
3036
        }
3037
        /** @var DataHandler $copyTCE */
3038
        $copyTCE = $this->getLocalTCE();
3039
        $copyTCE->start($pasteDatamap, [], $this->BE_USER);
3040
        $copyTCE->process_datamap();
3041
        $this->errorLog = array_merge($this->errorLog, $copyTCE->errorLog);
3042
        unset($copyTCE);
3043
3044
        // Finally, before exit, check if there are ID references to remap.
3045
        // This might be the case if versioning or copying has taken place!
3046
        $this->remapListedDBRecords();
3047
        $this->processRemapStack();
3048
        foreach ($hookObjectsArr as $hookObj) {
3049
            if (method_exists($hookObj, 'processCmdmap_afterFinish')) {
3050
                $hookObj->processCmdmap_afterFinish($this);
3051
            }
3052
        }
3053
        if ($this->isOuterMostInstance()) {
3054
            $this->referenceIndexUpdater->update();
3055
            $this->processClearCacheQueue();
3056
            $this->resetNestedElementCalls();
3057
        }
3058
    }
3059
3060
    /*********************************************
3061
     *
3062
     * Cmd: Copying
3063
     *
3064
     ********************************************/
3065
    /**
3066
     * Copying a single record
3067
     *
3068
     * @param string $table Element table
3069
     * @param int $uid Element UID
3070
     * @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
3071
     * @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
3072
     * @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!
3073
     * @param string $excludeFields Commalist of fields to exclude from the copy process (might get default values)
3074
     * @param int $language Language ID (from sys_language table)
3075
     * @param bool $ignoreLocalization If TRUE, any localization routine is skipped
3076
     * @return int|null ID of new record, if any
3077
     * @internal should only be used from within DataHandler
3078
     */
3079
    public function copyRecord($table, $uid, $destPid, $first = false, $overrideValues = [], $excludeFields = '', $language = 0, $ignoreLocalization = false)
3080
    {
3081
        $uid = ($origUid = (int)$uid);
3082
        // Only copy if the table is defined in $GLOBALS['TCA'], a uid is given and the record wasn't copied before:
3083
        if (empty($GLOBALS['TCA'][$table]) || $uid === 0) {
3084
            return null;
3085
        }
3086
        if ($this->isRecordCopied($table, $uid)) {
3087
            return null;
3088
        }
3089
3090
        // Fetch record with permission check
3091
        $row = $this->recordInfoWithPermissionCheck($table, $uid, Permission::PAGE_SHOW);
3092
3093
        // This checks if the record can be selected which is all that a copy action requires.
3094
        if ($row === false) {
3095
            $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]);
3096
            return null;
3097
        }
3098
3099
        // 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...
3100
        $tscPID = BackendUtility::getTSconfig_pidValue($table, $uid, $destPid);
3101
3102
        // Check if table is allowed on destination page
3103
        if (!$this->isTableAllowedForThisPage($tscPID, $table)) {
3104
            $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]);
3105
            return null;
3106
        }
3107
3108
        $fullLanguageCheckNeeded = $table !== 'pages';
3109
        // Used to check language and general editing rights
3110
        if (!$ignoreLocalization && ($language <= 0 || !$this->BE_USER->checkLanguageAccess($language)) && !$this->BE_USER->recordEditAccessInternals($table, $uid, false, false, $fullLanguageCheckNeeded)) {
3111
            $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]);
3112
            return null;
3113
        }
3114
3115
        $data = [];
3116
        $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));
3117
        BackendUtility::workspaceOL($table, $row, $this->BE_USER->workspace);
0 ignored issues
show
Bug introduced by
It seems like $row can also be of type true; however, parameter $row of TYPO3\CMS\Backend\Utilit...dUtility::workspaceOL() 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

3117
        BackendUtility::workspaceOL($table, /** @scrutinizer ignore-type */ $row, $this->BE_USER->workspace);
Loading history...
3118
        $row = BackendUtility::purgeComputedPropertiesFromRecord($row);
3119
3120
        // Initializing:
3121
        $theNewID = StringUtility::getUniqueId('NEW');
3122
        $enableField = isset($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']) ? $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'] : '';
3123
        $headerField = $GLOBALS['TCA'][$table]['ctrl']['label'];
3124
        // Getting "copy-after" fields if applicable:
3125
        $copyAfterFields = $destPid < 0 ? $this->fixCopyAfterDuplFields($table, $uid, abs($destPid), 0) : [];
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

3125
        $copyAfterFields = $destPid < 0 ? $this->fixCopyAfterDuplFields($table, $uid, /** @scrutinizer ignore-type */ abs($destPid), 0) : [];
Loading history...
3126
        // Page TSconfig related:
3127
        $TSConfig = BackendUtility::getPagesTSconfig($tscPID)['TCEMAIN.'] ?? [];
3128
        $tE = $this->getTableEntries($table, $TSConfig);
3129
        // Traverse ALL fields of the selected record:
3130
        foreach ($row as $field => $value) {
3131
            if (!in_array($field, $nonFields, true)) {
3132
                // Get TCA configuration for the field:
3133
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
3134
                // Preparation/Processing of the value:
3135
                // "pid" is hardcoded of course:
3136
                // isset() won't work here, since values can be NULL in each of the arrays
3137
                // except setDefaultOnCopyArray, since we exploded that from a string
3138
                if ($field === 'pid') {
3139
                    $value = $destPid;
3140
                } elseif (array_key_exists($field, $overrideValues)) {
3141
                    // Override value...
3142
                    $value = $overrideValues[$field];
3143
                } elseif (array_key_exists($field, $copyAfterFields)) {
3144
                    // Copy-after value if available:
3145
                    $value = $copyAfterFields[$field];
3146
                } else {
3147
                    // Hide at copy may override:
3148
                    if ($first && $field == $enableField && $GLOBALS['TCA'][$table]['ctrl']['hideAtCopy'] && !$this->neverHideAtCopy && !$tE['disableHideAtCopy']) {
3149
                        $value = 1;
3150
                    }
3151
                    // Prepend label on copy:
3152
                    if ($first && $field == $headerField && $GLOBALS['TCA'][$table]['ctrl']['prependAtCopy'] && !$tE['disablePrependAtCopy']) {
3153
                        $value = $this->getCopyHeader($table, $this->resolvePid($table, $destPid), $field, $this->clearPrefixFromValue($table, $value), 0);
3154
                    }
3155
                    // Processing based on the TCA config field type (files, references, flexforms...)
3156
                    $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $tscPID, $language);
3157
                }
3158
                // Add value to array.
3159
                $data[$table][$theNewID][$field] = $value;
3160
            }
3161
        }
3162
        // Overriding values:
3163
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock']) {
3164
            $data[$table][$theNewID][$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
3165
        }
3166
        // Setting original UID:
3167
        if ($GLOBALS['TCA'][$table]['ctrl']['origUid']) {
3168
            $data[$table][$theNewID][$GLOBALS['TCA'][$table]['ctrl']['origUid']] = $uid;
3169
        }
3170
        // Do the copy by simply submitting the array through DataHandler:
3171
        /** @var DataHandler $copyTCE */
3172
        $copyTCE = $this->getLocalTCE();
3173
        $copyTCE->start($data, [], $this->BE_USER);
3174
        $copyTCE->process_datamap();
3175
        // Getting the new UID:
3176
        $theNewSQLID = $copyTCE->substNEWwithIDs[$theNewID];
3177
        if ($theNewSQLID) {
3178
            $this->copyMappingArray[$table][$origUid] = $theNewSQLID;
3179
            // Keep automatically versionized record information:
3180
            if (isset($copyTCE->autoVersionIdMap[$table][$theNewSQLID])) {
3181
                $this->autoVersionIdMap[$table][$theNewSQLID] = $copyTCE->autoVersionIdMap[$table][$theNewSQLID];
3182
            }
3183
        }
3184
        $this->errorLog = array_merge($this->errorLog, $copyTCE->errorLog);
3185
        unset($copyTCE);
3186
        if (!$ignoreLocalization && $language == 0) {
3187
            //repointing the new translation records to the parent record we just created
3188
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $theNewSQLID;
3189
            if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
3190
                $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['translationSource']] = 0;
3191
            }
3192
            $this->copyL10nOverlayRecords($table, $uid, $destPid, $first, $overrideValues, $excludeFields);
3193
        }
3194
3195
        return $theNewSQLID;
3196
    }
3197
3198
    /**
3199
     * Copying pages
3200
     * Main function for copying pages.
3201
     *
3202
     * @param int $uid Page UID to copy
3203
     * @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
3204
     * @internal should only be used from within DataHandler
3205
     */
3206
    public function copyPages($uid, $destPid)
3207
    {
3208
        // Initialize:
3209
        $uid = (int)$uid;
3210
        $destPid = (int)$destPid;
3211
3212
        $copyTablesAlongWithPage = $this->getAllowedTablesToCopyWhenCopyingAPage();
3213
        // Begin to copy pages if we're allowed to:
3214
        if ($this->admin || in_array('pages', $copyTablesAlongWithPage, true)) {
3215
            // Copy this page we're on. And set first-flag (this will trigger that the record is hidden if that is configured)
3216
            // This method also copies the localizations of a page
3217
            $theNewRootID = $this->copySpecificPage($uid, $destPid, $copyTablesAlongWithPage, true);
3218
            // If we're going to copy recursively
3219
            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...
3220
                // Get ALL subpages to copy (read-permissions are respected!):
3221
                $CPtable = $this->int_pageTreeInfo([], $uid, (int)$this->copyTree, $theNewRootID);
3222
                // Now copying the subpages:
3223
                foreach ($CPtable as $thePageUid => $thePagePid) {
3224
                    $newPid = $this->copyMappingArray['pages'][$thePagePid];
3225
                    if (isset($newPid)) {
3226
                        $this->copySpecificPage($thePageUid, $newPid, $copyTablesAlongWithPage);
3227
                    } else {
3228
                        $this->log('pages', $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'Something went wrong during copying branch');
3229
                        break;
3230
                    }
3231
                }
3232
            }
3233
        } else {
3234
            $this->log('pages', $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to copy page without permission to this table');
3235
        }
3236
    }
3237
3238
    /**
3239
     * Compile a list of tables that should be copied along when a page is about to be copied.
3240
     *
3241
     * First, get the list that the user is allowed to modify (all if admin),
3242
     * and then check against a possible limitation within "DataHandler->copyWhichTables" if not set to "*"
3243
     * to limit the list further down
3244
     *
3245
     * @return array
3246
     */
3247
    protected function getAllowedTablesToCopyWhenCopyingAPage(): array
3248
    {
3249
        // Finding list of tables to copy.
3250
        // These are the tables, the user may modify
3251
        $copyTablesArray = $this->admin ? $this->compileAdminTables() : explode(',', $this->BE_USER->groupData['tables_modify']);
3252
        // If not all tables are allowed then make a list of allowed tables.
3253
        // That is the tables that figure in both allowed tables AND the copyTable-list
3254
        if (strpos($this->copyWhichTables, '*') === false) {
3255
            $definedTablesToCopy = GeneralUtility::trimExplode(',', $this->copyWhichTables, true);
3256
            // Pages are always allowed
3257
            $definedTablesToCopy[] = 'pages';
3258
            $definedTablesToCopy = array_flip($definedTablesToCopy);
3259
            foreach ($copyTablesArray as $k => $table) {
3260
                if (!$table || !isset($definedTablesToCopy[$table])) {
3261
                    unset($copyTablesArray[$k]);
3262
                }
3263
            }
3264
        }
3265
        $copyTablesArray = array_unique($copyTablesArray);
3266
        return $copyTablesArray;
3267
    }
3268
    /**
3269
     * Copying a single page ($uid) to $destPid and all tables in the array copyTablesArray.
3270
     *
3271
     * @param int $uid Page uid
3272
     * @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
3273
     * @param array $copyTablesArray Table on pages to copy along with the page.
3274
     * @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
3275
     * @return int|null The id of the new page, if applicable.
3276
     * @internal should only be used from within DataHandler
3277
     */
3278
    public function copySpecificPage($uid, $destPid, $copyTablesArray, $first = false)
3279
    {
3280
        // Copy the page itself:
3281
        $theNewRootID = $this->copyRecord('pages', $uid, $destPid, $first);
3282
        $currentWorkspaceId = (int)$this->BE_USER->workspace;
3283
        // If a new page was created upon the copy operation we will proceed with all the tables ON that page:
3284
        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...
3285
            foreach ($copyTablesArray as $table) {
3286
                // All records under the page is copied.
3287
                if ($table && is_array($GLOBALS['TCA'][$table]) && $table !== 'pages') {
3288
                    $fields = ['uid'];
3289
                    $languageField = null;
3290
                    $transOrigPointerField = null;
3291
                    $translationSourceField = null;
3292
                    if (BackendUtility::isTableLocalizable($table)) {
3293
                        $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
3294
                        $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
3295
                        $fields[] = $languageField;
3296
                        $fields[] = $transOrigPointerField;
3297
                        if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
3298
                            $translationSourceField = $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
3299
                            $fields[] = $translationSourceField;
3300
                        }
3301
                    }
3302
                    $isTableWorkspaceEnabled = BackendUtility::isTableWorkspaceEnabled($table);
3303
                    if ($isTableWorkspaceEnabled) {
3304
                        $fields[] = 't3ver_oid';
3305
                        $fields[] = 't3ver_state';
3306
                        $fields[] = 't3ver_wsid';
3307
                    }
3308
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3309
                    $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
3310
                    $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $currentWorkspaceId));
3311
                    $queryBuilder
3312
                        ->select(...$fields)
3313
                        ->from($table)
3314
                        ->where(
3315
                            $queryBuilder->expr()->eq(
3316
                                'pid',
3317
                                $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
3318
                            )
3319
                        );
3320
                    if (!empty($GLOBALS['TCA'][$table]['ctrl']['sortby'])) {
3321
                        $queryBuilder->orderBy($GLOBALS['TCA'][$table]['ctrl']['sortby'], 'DESC');
3322
                    }
3323
                    $queryBuilder->addOrderBy('uid');
3324
                    try {
3325
                        $result = $queryBuilder->execute();
3326
                        $rows = [];
3327
                        $movedLiveIds = [];
3328
                        $movedLiveRecords = [];
3329
                        while ($row = $result->fetch()) {
3330
                            if ($isTableWorkspaceEnabled && (int)$row['t3ver_state'] === VersionState::MOVE_POINTER) {
3331
                                $movedLiveIds[(int)$row['t3ver_oid']] = (int)$row['uid'];
3332
                            }
3333
                            $rows[(int)$row['uid']] = $row;
3334
                        }
3335
                        // Resolve placeholders of workspace versions
3336
                        if (!empty($rows) && $currentWorkspaceId > 0 && $isTableWorkspaceEnabled) {
3337
                            // If a record was moved within the page, the PlainDataResolver needs the moved record
3338
                            // but not the original live version, otherwise the moved record is not considered at all.
3339
                            // For this reason, we find the live ids, where there was also a moved record in the SQL
3340
                            // query above in $movedLiveIds and now we removed them before handing them over to PlainDataResolver.
3341
                            // see changeContentSortingAndCopyDraftPage test
3342
                            foreach ($movedLiveIds as $liveId => $movePlaceHolderId) {
3343
                                if (isset($rows[$liveId])) {
3344
                                    $movedLiveRecords[$movePlaceHolderId] = $rows[$liveId];
3345
                                    unset($rows[$liveId]);
3346
                                }
3347
                            }
3348
                            $rows = array_reverse(
3349
                                $this->resolveVersionedRecords(
3350
                                    $table,
3351
                                    implode(',', $fields),
3352
                                    $GLOBALS['TCA'][$table]['ctrl']['sortby'],
3353
                                    array_keys($rows)
3354
                                ),
3355
                                true
3356
                            );
3357
                            foreach ($movedLiveRecords as $movePlaceHolderId => $liveRecord) {
3358
                                $rows[$movePlaceHolderId] = $liveRecord;
3359
                            }
3360
                        }
3361
                        if (is_array($rows)) {
3362
                            $languageSourceMap = [];
3363
                            $overrideValues = $translationSourceField ? [$translationSourceField => 0] : [];
3364
                            $doRemap = false;
3365
                            foreach ($rows as $row) {
3366
                                // Skip localized records that will be processed in
3367
                                // copyL10nOverlayRecords() on copying the default language record
3368
                                $transOrigPointer = $row[$transOrigPointerField];
3369
                                if ($row[$languageField] > 0 && $transOrigPointer > 0 && (isset($rows[$transOrigPointer]) || isset($movedLiveIds[$transOrigPointer]))) {
3370
                                    continue;
3371
                                }
3372
                                // Copying each of the underlying records...
3373
                                $newUid = $this->copyRecord($table, $row['uid'], $theNewRootID, false, $overrideValues);
3374
                                if ($translationSourceField) {
3375
                                    $languageSourceMap[$row['uid']] = $newUid;
3376
                                    if ($row[$languageField] > 0) {
3377
                                        $doRemap = true;
3378
                                    }
3379
                                }
3380
                            }
3381
                            if ($doRemap) {
3382
                                //remap is needed for records in non-default language records in the "free mode"
3383
                                $this->copy_remapTranslationSourceField($table, $rows, $languageSourceMap);
3384
                            }
3385
                        }
3386
                    } catch (DBALException $e) {
3387
                        $databaseErrorMessage = $e->getPrevious()->getMessage();
3388
                        $this->log($table, $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'An SQL error occurred: ' . $databaseErrorMessage);
3389
                    }
3390
                }
3391
            }
3392
            $this->processRemapStack();
3393
            return $theNewRootID;
3394
        }
3395
        return null;
3396
    }
3397
3398
    /**
3399
     * Copying records, but makes a "raw" copy of a record.
3400
     * Basically the only thing observed is field processing like the copying of files and correction of ids. All other fields are 1-1 copied.
3401
     * 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.
3402
     * 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!?
3403
     * This function is used to create new versions of a record.
3404
     * 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.
3405
     *
3406
     * @param string $table Element table
3407
     * @param int $uid Element UID
3408
     * @param int $pid Element PID (real PID, not checked)
3409
     * @param array $overrideArray Override array - must NOT contain any fields not in the table!
3410
     * @param array $workspaceOptions Options to be forwarded if actions happen on a workspace currently
3411
     * @return int Returns the new ID of the record (if applicable)
3412
     * @internal should only be used from within DataHandler
3413
     */
3414
    public function copyRecord_raw($table, $uid, $pid, $overrideArray = [], array $workspaceOptions = [])
3415
    {
3416
        $uid = (int)$uid;
3417
        // Stop any actions if the record is marked to be deleted:
3418
        // (this can occur if IRRE elements are versionized and child elements are removed)
3419
        if ($this->isElementToBeDeleted($table, $uid)) {
3420
            return null;
3421
        }
3422
        // Only copy if the table is defined in TCA, a uid is given and the record wasn't copied before:
3423
        if (!$GLOBALS['TCA'][$table] || !$uid || $this->isRecordCopied($table, $uid)) {
3424
            return null;
3425
        }
3426
3427
        // Fetch record with permission check
3428
        $row = $this->recordInfoWithPermissionCheck($table, $uid, Permission::PAGE_SHOW);
3429
3430
        // This checks if the record can be selected which is all that a copy action requires.
3431
        if ($row === false) {
3432
            $this->log(
3433
                $table,
3434
                $uid,
3435
                SystemLogDatabaseAction::DELETE,
3436
                0,
3437
                SystemLogErrorClassification::USER_ERROR,
3438
                'Attempt to rawcopy/versionize record which either does not exist or you don\'t have permission to read'
3439
            );
3440
            return null;
3441
        }
3442
3443
        // Set up fields which should not be processed. They are still written - just passed through no-questions-asked!
3444
        $nonFields = ['uid', 'pid', 't3ver_oid', 't3ver_wsid', 't3ver_state', 't3ver_stage', 'perms_userid', 'perms_groupid', 'perms_user', 'perms_group', 'perms_everybody'];
3445
3446
        // Merge in override array.
3447
        $row = array_merge($row, $overrideArray);
0 ignored issues
show
Bug introduced by
It seems like $row can also be of type true; however, parameter $array1 of array_merge() 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

3447
        $row = array_merge(/** @scrutinizer ignore-type */ $row, $overrideArray);
Loading history...
3448
        // Traverse ALL fields of the selected record:
3449
        foreach ($row as $field => $value) {
3450
            if (!in_array($field, $nonFields, true)) {
3451
                // Get TCA configuration for the field:
3452
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
3453
                if (is_array($conf)) {
3454
                    // Processing based on the TCA config field type (files, references, flexforms...)
3455
                    $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $pid, 0, $workspaceOptions);
3456
                }
3457
                // Add value to array.
3458
                $row[$field] = $value;
3459
            }
3460
        }
3461
        $row['pid'] = $pid;
3462
        // Setting original UID:
3463
        if ($GLOBALS['TCA'][$table]['ctrl']['origUid']) {
3464
            $row[$GLOBALS['TCA'][$table]['ctrl']['origUid']] = $uid;
3465
        }
3466
        // Do the copy by internal function
3467
        $theNewSQLID = $this->insertNewCopyVersion($table, $row, $pid);
3468
3469
        // When a record is copied in workspace (eg. to create a delete placeholder record for a live record), records
3470
        // pointing to that record need a reference index update. This is for instance the case in FAL, if a sys_file_reference
3471
        // for a eg. tt_content record is marked as deleted. The tt_content record then needs a reference index update.
3472
        // This scenario seems to currently only show up if in workspaces, so the refindex update is restricted to this for now.
3473
        if (!empty($workspaceOptions)) {
3474
            $this->referenceIndexUpdater->registerUpdateForReferencesToItem($table, (int)$row['uid'], (int)$this->BE_USER->workspace);
3475
        }
3476
3477
        if ($theNewSQLID) {
3478
            $this->dbAnalysisStoreExec();
3479
            $this->dbAnalysisStore = [];
3480
            return $this->copyMappingArray[$table][$uid] = $theNewSQLID;
3481
        }
3482
        return null;
3483
    }
3484
3485
    /**
3486
     * Inserts a record in the database, passing TCA configuration values through checkValue() but otherwise does NOTHING and checks nothing regarding permissions.
3487
     * 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...
3488
     *
3489
     * @param string $table Table name
3490
     * @param array $fieldArray Field array to insert as a record
3491
     * @param int $realPid The value of PID field.
3492
     * @return int Returns the new ID of the record (if applicable)
3493
     * @internal should only be used from within DataHandler
3494
     */
3495
    public function insertNewCopyVersion($table, $fieldArray, $realPid)
3496
    {
3497
        $id = StringUtility::getUniqueId('NEW');
3498
        // $fieldArray is set as current record.
3499
        // 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...
3500
        $this->checkValue_currentRecord = $fieldArray;
3501
        // Makes sure that transformations aren't processed on the copy.
3502
        $backupDontProcessTransformations = $this->dontProcessTransformations;
3503
        $this->dontProcessTransformations = true;
3504
        // Traverse record and input-process each value:
3505
        foreach ($fieldArray as $field => $fieldValue) {
3506
            if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
3507
                // Evaluating the value.
3508
                $res = $this->checkValue($table, $field, $fieldValue, $id, 'new', $realPid, 0, $fieldArray);
3509
                if (isset($res['value'])) {
3510
                    $fieldArray[$field] = $res['value'];
3511
                }
3512
            }
3513
        }
3514
        // System fields being set:
3515
        if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
3516
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
3517
        }
3518
        if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
3519
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
3520
        }
3521
        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
3522
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
3523
        }
3524
        // Finally, insert record:
3525
        $this->insertDB($table, $id, $fieldArray, true);
3526
        // Resets dontProcessTransformations to the previous state.
3527
        $this->dontProcessTransformations = $backupDontProcessTransformations;
3528
        // Return new id:
3529
        return $this->substNEWwithIDs[$id];
3530
    }
3531
3532
    /**
3533
     * Processing/Preparing content for copyRecord() function
3534
     *
3535
     * @param string $table Table name
3536
     * @param int $uid Record uid
3537
     * @param string $field Field name being processed
3538
     * @param string $value Input value to be processed.
3539
     * @param array $row Record array
3540
     * @param array $conf TCA field configuration
3541
     * @param int $realDestPid Real page id (pid) the record is copied to
3542
     * @param int $language Language ID (from sys_language table) used in the duplicated record
3543
     * @param array $workspaceOptions Options to be forwarded if actions happen on a workspace currently
3544
     * @return array|string
3545
     * @internal
3546
     * @see copyRecord()
3547
     */
3548
    public function copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $realDestPid, $language = 0, array $workspaceOptions = [])
3549
    {
3550
        $inlineSubType = $this->getInlineFieldType($conf);
3551
        // Get the localization mode for the current (parent) record (keep|select):
3552
        // Register if there are references to take care of or MM is used on an inline field (no change to value):
3553
        if ($this->isReferenceField($conf) || $inlineSubType === 'mm') {
3554
            $value = $this->copyRecord_processManyToMany($table, $uid, $field, $value, $conf, $language);
3555
        } elseif ($inlineSubType !== false) {
3556
            $value = $this->copyRecord_processInline($table, $uid, $field, $value, $row, $conf, $realDestPid, $language, $workspaceOptions);
3557
        }
3558
        // 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())
3559
        if ($conf['type'] === 'flex') {
3560
            // Get current value array:
3561
            $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
3562
            $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
3563
                ['config' => $conf],
3564
                $table,
3565
                $field,
3566
                $row
3567
            );
3568
            $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
3569
            $currentValueArray = GeneralUtility::xml2array($value);
3570
            // Traversing the XML structure, processing files:
3571
            if (is_array($currentValueArray)) {
3572
                $currentValueArray['data'] = $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $uid, $field, $realDestPid], 'copyRecord_flexFormCallBack', $workspaceOptions);
3573
                // Setting value as an array! -> which means the input will be processed according to the 'flex' type when the new copy is created.
3574
                $value = $currentValueArray;
3575
            }
3576
        }
3577
        return $value;
3578
    }
3579
3580
    /**
3581
     * Processes the children of an MM relation field (select, group, inline) when the parent record is copied.
3582
     *
3583
     * @param string $table
3584
     * @param int $uid
3585
     * @param string $field
3586
     * @param mixed $value
3587
     * @param array $conf
3588
     * @param string $language
3589
     * @return mixed
3590
     */
3591
    protected function copyRecord_processManyToMany($table, $uid, $field, $value, $conf, $language)
3592
    {
3593
        $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
3594
        $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
3595
        $mmTable = isset($conf['MM']) && $conf['MM'] ? $conf['MM'] : '';
3596
        $localizeForeignTable = isset($conf['foreign_table']) && BackendUtility::isTableLocalizable($conf['foreign_table']);
3597
        // Localize referenced records of select fields:
3598
        $localizingNonManyToManyFieldReferences = empty($mmTable) && $localizeForeignTable && isset($conf['localizeReferencesAtParentLocalization']) && $conf['localizeReferencesAtParentLocalization'];
3599
        /** @var RelationHandler $dbAnalysis */
3600
        $dbAnalysis = $this->createRelationHandlerInstance();
3601
        $dbAnalysis->start($value, $allowedTables, $mmTable, $uid, $table, $conf);
3602
        $purgeItems = false;
3603
        if ($language > 0 && $localizingNonManyToManyFieldReferences) {
3604
            foreach ($dbAnalysis->itemArray as $index => $item) {
3605
                // Since select fields can reference many records, check whether there's already a localization:
3606
                $recordLocalization = BackendUtility::getRecordLocalization($item['table'], $item['id'], $language);
0 ignored issues
show
Bug introduced by
$language of type string is incompatible with the type integer expected by parameter $language of TYPO3\CMS\Backend\Utilit...getRecordLocalization(). ( Ignorable by Annotation )

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

3606
                $recordLocalization = BackendUtility::getRecordLocalization($item['table'], $item['id'], /** @scrutinizer ignore-type */ $language);
Loading history...
3607
                if ($recordLocalization) {
3608
                    $dbAnalysis->itemArray[$index]['id'] = $recordLocalization[0]['uid'];
3609
                } elseif ($this->isNestedElementCallRegistered($item['table'], $item['id'], 'localize-' . (string)$language) === false) {
3610
                    $dbAnalysis->itemArray[$index]['id'] = $this->localize($item['table'], $item['id'], $language);
0 ignored issues
show
Bug introduced by
$language of type string is incompatible with the type integer expected by parameter $language of TYPO3\CMS\Core\DataHandl...DataHandler::localize(). ( Ignorable by Annotation )

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

3610
                    $dbAnalysis->itemArray[$index]['id'] = $this->localize($item['table'], $item['id'], /** @scrutinizer ignore-type */ $language);
Loading history...
3611
                }
3612
            }
3613
            $purgeItems = true;
3614
        }
3615
3616
        if ($purgeItems || $mmTable) {
3617
            $dbAnalysis->purgeItemArray();
3618
            $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

3618
            $value = implode(',', $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName));
Loading history...
3619
        }
3620
        // Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
3621
        if ($value) {
3622
            $this->registerDBList[$table][$uid][$field] = $value;
3623
        }
3624
3625
        return $value;
3626
    }
3627
3628
    /**
3629
     * Processes child records in an inline (IRRE) element when the parent record is copied.
3630
     *
3631
     * @param string $table
3632
     * @param int $uid
3633
     * @param string $field
3634
     * @param mixed $value
3635
     * @param array $row
3636
     * @param array $conf
3637
     * @param int $realDestPid
3638
     * @param string $language
3639
     * @param array $workspaceOptions
3640
     * @return string
3641
     */
3642
    protected function copyRecord_processInline(
3643
        $table,
3644
        $uid,
3645
        $field,
3646
        $value,
3647
        $row,
3648
        $conf,
3649
        $realDestPid,
3650
        $language,
3651
        array $workspaceOptions
3652
    ) {
3653
        // Fetch the related child records using \TYPO3\CMS\Core\Database\RelationHandler
3654
        /** @var RelationHandler $dbAnalysis */
3655
        $dbAnalysis = $this->createRelationHandlerInstance();
3656
        $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
3657
        // Walk through the items, copy them and remember the new id:
3658
        foreach ($dbAnalysis->itemArray as $k => $v) {
3659
            $newId = null;
3660
            // If language is set and differs from original record, this isn't a copy action but a localization of our parent/ancestor:
3661
            if ($language > 0 && BackendUtility::isTableLocalizable($table) && $language != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
3662
                // Children should be localized when the parent gets localized the first time, just do it:
3663
                $newId = $this->localize($v['table'], $v['id'], $language);
0 ignored issues
show
Bug introduced by
$language of type string is incompatible with the type integer expected by parameter $language of TYPO3\CMS\Core\DataHandl...DataHandler::localize(). ( Ignorable by Annotation )

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

3663
                $newId = $this->localize($v['table'], $v['id'], /** @scrutinizer ignore-type */ $language);
Loading history...
3664
            } else {
3665
                if (!MathUtility::canBeInterpretedAsInteger($realDestPid)) {
3666
                    $newId = $this->copyRecord($v['table'], $v['id'], -$v['id']);
3667
                // If the destination page id is a NEW string, keep it on the same page
3668
                } elseif ($this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($v['table'])) {
3669
                    // A filled $workspaceOptions indicated that this call
3670
                    // has it's origin in previous versionizeRecord() processing
3671
                    if (!empty($workspaceOptions)) {
3672
                        // Versions use live default id, thus the "new"
3673
                        // id is the original live default child record
3674
                        $newId = $v['id'];
3675
                        $this->versionizeRecord(
3676
                            $v['table'],
3677
                            $v['id'],
3678
                            $workspaceOptions['label'] ?? 'Auto-created for WS #' . $this->BE_USER->workspace,
3679
                            $workspaceOptions['delete'] ?? false
3680
                        );
3681
                    // Otherwise just use plain copyRecord() to create placeholders etc.
3682
                    } else {
3683
                        // If a record has been copied already during this request,
3684
                        // prevent superfluous duplication and use the existing copy
3685
                        if (isset($this->copyMappingArray[$v['table']][$v['id']])) {
3686
                            $newId = $this->copyMappingArray[$v['table']][$v['id']];
3687
                        } else {
3688
                            $newId = $this->copyRecord($v['table'], $v['id'], $realDestPid);
3689
                        }
3690
                    }
3691
                } elseif ($this->BE_USER->workspace > 0 && !BackendUtility::isTableWorkspaceEnabled($v['table'])) {
3692
                    // We are in workspace context creating a new parent version and have a child table
3693
                    // that is not workspace aware. We don't do anything with this child.
3694
                    continue;
3695
                } else {
3696
                    // If a record has been copied already during this request,
3697
                    // prevent superfluous duplication and use the existing copy
3698
                    if (isset($this->copyMappingArray[$v['table']][$v['id']])) {
3699
                        $newId = $this->copyMappingArray[$v['table']][$v['id']];
3700
                    } else {
3701
                        $newId = $this->copyRecord_raw($v['table'], $v['id'], $realDestPid, [], $workspaceOptions);
3702
                    }
3703
                }
3704
            }
3705
            // If the current field is set on a page record, update the pid of related child records:
3706
            if ($table === 'pages') {
3707
                $this->registerDBPids[$v['table']][$v['id']] = $uid;
3708
            } elseif (isset($this->registerDBPids[$table][$uid])) {
3709
                $this->registerDBPids[$v['table']][$v['id']] = $this->registerDBPids[$table][$uid];
3710
            }
3711
            $dbAnalysis->itemArray[$k]['id'] = $newId;
3712
        }
3713
        // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
3714
        $value = implode(',', $dbAnalysis->getValueArray());
3715
        $this->registerDBList[$table][$uid][$field] = $value;
3716
3717
        return $value;
3718
    }
3719
3720
    /**
3721
     * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
3722
     *
3723
     * @param array $pParams Array of parameters in num-indexes: table, uid, field
3724
     * @param array $dsConf TCA field configuration (from Data Structure XML)
3725
     * @param string $dataValue The value of the flexForm field
3726
     * @param string $_1 Not used.
3727
     * @param string $_2 Not used.
3728
     * @param string $_3 Not used.
3729
     * @param array $workspaceOptions
3730
     * @return array Result array with key "value" containing the value of the processing.
3731
     * @see copyRecord()
3732
     * @see checkValue_flex_procInData_travDS()
3733
     * @internal should only be used from within DataHandler
3734
     */
3735
    public function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $_1, $_2, $_3, $workspaceOptions)
3736
    {
3737
        // Extract parameters:
3738
        [$table, $uid, $field, $realDestPid] = $pParams;
3739
        // If references are set for this field, set flag so they can be corrected later (in ->remapListedDBRecords())
3740
        if (($this->isReferenceField($dsConf) || $this->getInlineFieldType($dsConf) !== false) && (string)$dataValue !== '') {
3741
            $dataValue = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $dataValue, [], $dsConf, $realDestPid, 0, $workspaceOptions);
3742
            $this->registerDBList[$table][$uid][$field] = 'FlexForm_reference';
3743
        }
3744
        // Return
3745
        return ['value' => $dataValue];
3746
    }
3747
3748
    /**
3749
     * Find l10n-overlay records and perform the requested copy action for these records.
3750
     *
3751
     * @param string $table Record Table
3752
     * @param string $uid UID of the record in the default language
3753
     * @param string $destPid Position to copy to
3754
     * @param bool $first
3755
     * @param array $overrideValues
3756
     * @param string $excludeFields
3757
     * @internal should only be used from within DataHandler
3758
     */
3759
    public function copyL10nOverlayRecords($table, $uid, $destPid, $first = false, $overrideValues = [], $excludeFields = '')
3760
    {
3761
        // There's no need to perform this for tables that are not localizable
3762
        if (!BackendUtility::isTableLocalizable($table)) {
3763
            return;
3764
        }
3765
3766
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3767
        $queryBuilder->getRestrictions()
3768
            ->removeAll()
3769
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
3770
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->BE_USER->workspace));
3771
3772
        $queryBuilder->select('*')
3773
            ->from($table)
3774
            ->where(
3775
                $queryBuilder->expr()->eq(
3776
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
3777
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':pointer')
3778
                )
3779
            );
3780
3781
        // Never copy the actual placeholders around, as the newly copied records are
3782
        // always created as new record / new placeholder pairs
3783
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
3784
            $queryBuilder->andWhere(
3785
                $queryBuilder->expr()->neq(
3786
                    't3ver_state',
3787
                    VersionState::DELETE_PLACEHOLDER
3788
                )
3789
            );
3790
        }
3791
3792
        // If $destPid is < 0, get the pid of the record with uid equal to abs($destPid)
3793
        $tscPID = BackendUtility::getTSconfig_pidValue($table, $uid, $destPid);
0 ignored issues
show
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Backend\Utilit...:getTSconfig_pidValue(). ( Ignorable by Annotation )

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

3793
        $tscPID = BackendUtility::getTSconfig_pidValue($table, /** @scrutinizer ignore-type */ $uid, $destPid);
Loading history...
3794
        // Get the localized records to be copied
3795
        $l10nRecords = $queryBuilder->execute()->fetchAll();
3796
        if (is_array($l10nRecords)) {
3797
            $localizedDestPids = [];
3798
            // If $destPid < 0, then it is the uid of the original language record we are inserting after
3799
            if ($destPid < 0) {
3800
                // Get the localized records of the record we are inserting after
3801
                $queryBuilder->setParameter('pointer', abs($destPid), \PDO::PARAM_INT);
3802
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
3803
                // Index the localized record uids by language
3804
                if (is_array($destL10nRecords)) {
3805
                    foreach ($destL10nRecords as $record) {
3806
                        $localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]] = -$record['uid'];
3807
                    }
3808
                }
3809
            }
3810
            $languageSourceMap = [
3811
                $uid => $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]
3812
            ];
3813
            // Copy the localized records after the corresponding localizations of the destination record
3814
            foreach ($l10nRecords as $record) {
3815
                $localizedDestPid = (int)$localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]];
3816
                if ($localizedDestPid < 0) {
3817
                    $newUid = $this->copyRecord($table, $record['uid'], $localizedDestPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
3818
                } else {
3819
                    $newUid = $this->copyRecord($table, $record['uid'], $destPid < 0 ? $tscPID : $destPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
0 ignored issues
show
Bug introduced by
It seems like $destPid < 0 ? $tscPID : $destPid can also be of type string; however, parameter $destPid of TYPO3\CMS\Core\DataHandl...taHandler::copyRecord() 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

3819
                    $newUid = $this->copyRecord($table, $record['uid'], /** @scrutinizer ignore-type */ $destPid < 0 ? $tscPID : $destPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
Loading history...
3820
                }
3821
                $languageSourceMap[$record['uid']] = $newUid;
3822
            }
3823
            $this->copy_remapTranslationSourceField($table, $l10nRecords, $languageSourceMap);
3824
        }
3825
    }
3826
3827
    /**
3828
     * Remap languageSource field to uids of newly created records
3829
     *
3830
     * @param string $table Table name
3831
     * @param array $l10nRecords array of localized records from the page we're copying from (source records)
3832
     * @param array $languageSourceMap array mapping source records uids to newly copied uids
3833
     */
3834
    protected function copy_remapTranslationSourceField($table, $l10nRecords, $languageSourceMap)
3835
    {
3836
        if (empty($GLOBALS['TCA'][$table]['ctrl']['translationSource']) || empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])) {
3837
            return;
3838
        }
3839
        $translationSourceFieldName = $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
3840
        $translationParentFieldName = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
3841
3842
        //We can avoid running these update queries by sorting the $l10nRecords by languageSource dependency (in copyL10nOverlayRecords)
3843
        //and first copy records depending on default record (and map the field).
3844
        foreach ($l10nRecords as $record) {
3845
            $oldSourceUid = $record[$translationSourceFieldName];
3846
            if ($oldSourceUid <= 0 && $record[$translationParentFieldName] > 0) {
3847
                //BC fix - in connected mode 'translationSource' field should not be 0
3848
                $oldSourceUid = $record[$translationParentFieldName];
3849
            }
3850
            if ($oldSourceUid > 0) {
3851
                if (empty($languageSourceMap[$oldSourceUid])) {
3852
                    // we don't have mapping information available e.g when copyRecord returned null
3853
                    continue;
3854
                }
3855
                $newFieldValue = $languageSourceMap[$oldSourceUid];
3856
                $updateFields = [
3857
                    $translationSourceFieldName => $newFieldValue
3858
                ];
3859
                GeneralUtility::makeInstance(ConnectionPool::class)
3860
                    ->getConnectionForTable($table)
3861
                    ->update($table, $updateFields, ['uid' => (int)$languageSourceMap[$record['uid']]]);
3862
                if ($this->BE_USER->workspace > 0) {
3863
                    GeneralUtility::makeInstance(ConnectionPool::class)
3864
                        ->getConnectionForTable($table)
3865
                        ->update($table, $updateFields, ['t3ver_oid' => (int)$languageSourceMap[$record['uid']], 't3ver_wsid' => $this->BE_USER->workspace]);
3866
                }
3867
            }
3868
        }
3869
    }
3870
3871
    /*********************************************
3872
     *
3873
     * Cmd: Moving, Localizing
3874
     *
3875
     ********************************************/
3876
    /**
3877
     * Moving single records
3878
     *
3879
     * @param string $table Table name to move
3880
     * @param int $uid Record uid to move
3881
     * @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
3882
     * @internal should only be used from within DataHandler
3883
     */
3884
    public function moveRecord($table, $uid, $destPid)
3885
    {
3886
        if (!$GLOBALS['TCA'][$table]) {
3887
            return;
3888
        }
3889
3890
        // In case the record to be moved turns out to be an offline version,
3891
        // we have to find the live version and work on that one.
3892
        if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $uid, 'uid')) {
3893
            $uid = $lookForLiveVersion['uid'];
3894
        }
3895
        // Initialize:
3896
        $destPid = (int)$destPid;
3897
        // Get this before we change the pid (for logging)
3898
        $propArr = $this->getRecordProperties($table, $uid);
3899
        $moveRec = $this->getRecordProperties($table, $uid, true);
3900
        // This is the actual pid of the moving to destination
3901
        $resolvedPid = $this->resolvePid($table, $destPid);
3902
        // 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.
3903
        // If the record is a page, then there are two options: If the page is moved within itself,
3904
        // (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.
3905
        if ($table !== 'pages' || $resolvedPid == $moveRec['pid']) {
3906
            // Edit rights for the record...
3907
            $mayMoveAccess = $this->checkRecordUpdateAccess($table, $uid);
3908
        } else {
3909
            $mayMoveAccess = $this->doesRecordExist($table, $uid, Permission::PAGE_DELETE);
3910
        }
3911
        // Finding out, if the record may be moved TO another place. Here we check insert-rights (non-pages = edit, pages = new),
3912
        // unless the pages are moved on the same pid, then edit-rights are checked
3913
        if ($table !== 'pages' || $resolvedPid != $moveRec['pid']) {
3914
            // Insert rights for the record...
3915
            $mayInsertAccess = $this->checkRecordInsertAccess($table, $resolvedPid, SystemLogDatabaseAction::MOVE);
3916
        } else {
3917
            $mayInsertAccess = $this->checkRecordUpdateAccess($table, $uid);
3918
        }
3919
        // Checking if there is anything else disallowing moving the record by checking if editing is allowed
3920
        $fullLanguageCheckNeeded = $table !== 'pages';
3921
        $mayEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, false, false, $fullLanguageCheckNeeded);
3922
        // If moving is allowed, begin the processing:
3923
        if (!$mayEditAccess) {
3924
            $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']);
3925
            return;
3926
        }
3927
3928
        if (!$mayMoveAccess) {
3929
            $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']);
3930
            return;
3931
        }
3932
3933
        if (!$mayInsertAccess) {
3934
            $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']);
3935
            return;
3936
        }
3937
3938
        $recordWasMoved = false;
3939
        // Move the record via a hook, used e.g. for versioning
3940
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] ?? [] as $className) {
3941
            $hookObj = GeneralUtility::makeInstance($className);
3942
            if (method_exists($hookObj, 'moveRecord')) {
3943
                $hookObj->moveRecord($table, $uid, $destPid, $propArr, $moveRec, $resolvedPid, $recordWasMoved, $this);
3944
            }
3945
        }
3946
        // Move the record if a hook hasn't moved it yet
3947
        if (!$recordWasMoved) {
0 ignored issues
show
introduced by
The condition $recordWasMoved is always false.
Loading history...
3948
            $this->moveRecord_raw($table, $uid, $destPid);
3949
        }
3950
    }
3951
3952
    /**
3953
     * Moves a record without checking security of any sort.
3954
     * USE ONLY INTERNALLY
3955
     *
3956
     * @param string $table Table name to move
3957
     * @param int $uid Record uid to move
3958
     * @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
3959
     * @see moveRecord()
3960
     * @internal should only be used from within DataHandler
3961
     */
3962
    public function moveRecord_raw($table, $uid, $destPid)
3963
    {
3964
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
3965
        $origDestPid = $destPid;
3966
        // This is the actual pid of the moving to destination
3967
        $resolvedPid = $this->resolvePid($table, $destPid);
3968
        // Checking if the pid is negative, but no sorting row is defined. In that case, find the correct pid.
3969
        // Basically this check make the error message 4-13 meaning less... But you can always remove this check if you
3970
        // prefer the error instead of a no-good action (which is to move the record to its own page...)
3971
        if (($destPid < 0 && !$sortColumn) || $destPid >= 0) {
3972
            $destPid = $resolvedPid;
3973
        }
3974
        // Get this before we change the pid (for logging)
3975
        $propArr = $this->getRecordProperties($table, $uid);
3976
        $moveRec = $this->getRecordProperties($table, $uid, true);
3977
        // Prepare user defined objects (if any) for hooks which extend this function:
3978
        $hookObjectsArr = [];
3979
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] ?? [] as $className) {
3980
            $hookObjectsArr[] = GeneralUtility::makeInstance($className);
3981
        }
3982
        // Timestamp field:
3983
        $updateFields = [];
3984
        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
3985
            $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
3986
        }
3987
3988
        // Check if this is a translation of a page, if so then it just needs to be kept "sorting" in sync
3989
        // Usually called from moveL10nOverlayRecords()
3990
        if ($table === 'pages') {
3991
            $defaultLanguagePageUid = $this->getDefaultLanguagePageId((int)$uid);
3992
            // In workspaces, the default language page may have been moved to a different pid than the
3993
            // default language page record of live workspace. In this case, localized pages need to be
3994
            // moved to the pid of the workspace move record.
3995
            $defaultLanguagePageWorkspaceOverlay = BackendUtility::getWorkspaceVersionOfRecord((int)$this->BE_USER->workspace, 'pages', $defaultLanguagePageUid, 'uid');
3996
            if (is_array($defaultLanguagePageWorkspaceOverlay)) {
3997
                $defaultLanguagePageUid = (int)$defaultLanguagePageWorkspaceOverlay['uid'];
3998
            }
3999
            if ($defaultLanguagePageUid !== (int)$uid) {
4000
                // If the default language page has been moved, localized pages need to be moved to
4001
                // that pid and sorting, too.
4002
                $originalTranslationRecord = $this->recordInfo($table, $defaultLanguagePageUid, 'pid,' . $sortColumn);
4003
                $updateFields[$sortColumn] = $originalTranslationRecord[$sortColumn];
4004
                $destPid = $originalTranslationRecord['pid'];
4005
            }
4006
        }
4007
4008
        // Insert as first element on page (where uid = $destPid)
4009
        if ($destPid >= 0) {
4010
            if ($table !== 'pages' || $this->destNotInsideSelf($destPid, $uid)) {
4011
                // Clear cache before moving
4012
                [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
4013
                $this->registerRecordIdForPageCacheClearing($table, $uid, $parentUid);
4014
                // Setting PID
4015
                $updateFields['pid'] = $destPid;
4016
                // Table is sorted by 'sortby'
4017
                if ($sortColumn && !isset($updateFields[$sortColumn])) {
4018
                    $sortNumber = $this->getSortNumber($table, $uid, $destPid);
4019
                    $updateFields[$sortColumn] = $sortNumber;
4020
                }
4021
                // Check for child records that have also to be moved
4022
                $this->moveRecord_procFields($table, $uid, $destPid);
4023
                // Create query for update:
4024
                GeneralUtility::makeInstance(ConnectionPool::class)
4025
                    ->getConnectionForTable($table)
4026
                    ->update($table, $updateFields, ['uid' => (int)$uid]);
4027
                // Check for the localizations of that element
4028
                $this->moveL10nOverlayRecords($table, $uid, $destPid, $destPid);
4029
                // Call post processing hooks:
4030
                foreach ($hookObjectsArr as $hookObj) {
4031
                    if (method_exists($hookObj, 'moveRecord_firstElementPostProcess')) {
4032
                        $hookObj->moveRecord_firstElementPostProcess($table, $uid, $destPid, $moveRec, $updateFields, $this);
4033
                    }
4034
                }
4035
4036
                $this->getRecordHistoryStore()->moveRecord($table, $uid, ['oldPageId' => $propArr['pid'], 'newPageId' => $destPid, 'oldData' => $propArr, 'newData' => $updateFields], $this->correlationId);
4037
                if ($this->enableLogging) {
4038
                    // Logging...
4039
                    $oldpagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4040
                    if ($destPid != $propArr['pid']) {
4041
                        // Logged to old page
4042
                        $newPropArr = $this->getRecordProperties($table, $uid);
4043
                        $newpagePropArr = $this->getRecordProperties('pages', $destPid);
4044
                        $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']);
4045
                        // Logged to new page
4046
                        $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);
4047
                    } else {
4048
                        // Logged to new page
4049
                        $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);
4050
                    }
4051
                }
4052
                // Clear cache after moving
4053
                $this->registerRecordIdForPageCacheClearing($table, $uid);
4054
                $this->fixUniqueInPid($table, $uid);
4055
                $this->fixUniqueInSite($table, (int)$uid);
4056
                if ($table === 'pages') {
4057
                    $this->fixUniqueInSiteForSubpages((int)$uid);
4058
                }
4059
            } elseif ($this->enableLogging) {
4060
                $destPropArr = $this->getRecordProperties('pages', $destPid);
4061
                $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']);
4062
            }
4063
        } elseif ($sortColumn) {
4064
            // Put after another record
4065
            // Table is being sorted
4066
            // Save the position to which the original record is requested to be moved
4067
            $originalRecordDestinationPid = $destPid;
4068
            $sortInfo = $this->getSortNumber($table, $uid, $destPid);
4069
            // Setting the destPid to the new pid of the record.
4070
            $destPid = $sortInfo['pid'];
4071
            // If not an array, there was an error (which is already logged)
4072
            if (is_array($sortInfo)) {
4073
                if ($table !== 'pages' || $this->destNotInsideSelf($destPid, $uid)) {
4074
                    // clear cache before moving
4075
                    $this->registerRecordIdForPageCacheClearing($table, $uid);
4076
                    // We now update the pid and sortnumber (if not set for page translations)
4077
                    $updateFields['pid'] = $destPid;
4078
                    if (!isset($updateFields[$sortColumn])) {
4079
                        $updateFields[$sortColumn] = $sortInfo['sortNumber'];
4080
                    }
4081
                    // Check for child records that have also to be moved
4082
                    $this->moveRecord_procFields($table, $uid, $destPid);
4083
                    // Create query for update:
4084
                    GeneralUtility::makeInstance(ConnectionPool::class)
4085
                        ->getConnectionForTable($table)
4086
                        ->update($table, $updateFields, ['uid' => (int)$uid]);
4087
                    // Check for the localizations of that element
4088
                    $this->moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid);
4089
                    // Call post processing hooks:
4090
                    foreach ($hookObjectsArr as $hookObj) {
4091
                        if (method_exists($hookObj, 'moveRecord_afterAnotherElementPostProcess')) {
4092
                            $hookObj->moveRecord_afterAnotherElementPostProcess($table, $uid, $destPid, $origDestPid, $moveRec, $updateFields, $this);
4093
                        }
4094
                    }
4095
                    $this->getRecordHistoryStore()->moveRecord($table, $uid, ['oldPageId' => $propArr['pid'], 'newPageId' => $destPid, 'oldData' => $propArr, 'newData' => $updateFields], $this->correlationId);
4096
                    if ($this->enableLogging) {
4097
                        // Logging...
4098
                        $oldpagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4099
                        if ($destPid != $propArr['pid']) {
4100
                            // Logged to old page
4101
                            $newPropArr = $this->getRecordProperties($table, $uid);
4102
                            $newpagePropArr = $this->getRecordProperties('pages', $destPid);
4103
                            $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']);
4104
                            // Logged to old page
4105
                            $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);
4106
                        } else {
4107
                            // Logged to old page
4108
                            $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);
4109
                        }
4110
                    }
4111
                    // Clear cache after moving
4112
                    $this->registerRecordIdForPageCacheClearing($table, $uid);
4113
                    $this->fixUniqueInPid($table, $uid);
4114
                    $this->fixUniqueInSite($table, (int)$uid);
4115
                    if ($table === 'pages') {
4116
                        $this->fixUniqueInSiteForSubpages((int)$uid);
4117
                    }
4118
                } elseif ($this->enableLogging) {
4119
                    $destPropArr = $this->getRecordProperties('pages', $destPid);
4120
                    $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']);
4121
                }
4122
            } else {
4123
                $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']);
4124
            }
4125
        }
4126
    }
4127
4128
    /**
4129
     * Walk through all fields of the moved record and look for children of e.g. the inline type.
4130
     * If child records are found, they are also move to the new $destPid.
4131
     *
4132
     * @param string $table Record Table
4133
     * @param int $uid Record UID
4134
     * @param int $destPid Position to move to
4135
     * @internal should only be used from within DataHandler
4136
     */
4137
    public function moveRecord_procFields($table, $uid, $destPid)
4138
    {
4139
        $row = BackendUtility::getRecordWSOL($table, $uid);
4140
        if (is_array($row) && (int)$destPid !== (int)$row['pid']) {
4141
            $conf = $GLOBALS['TCA'][$table]['columns'];
4142
            foreach ($row as $field => $value) {
4143
                $this->moveRecord_procBasedOnFieldType($table, $uid, $destPid, $field, $value, $conf[$field]['config']);
4144
            }
4145
        }
4146
    }
4147
4148
    /**
4149
     * Move child records depending on the field type of the parent record.
4150
     *
4151
     * @param string $table Record Table
4152
     * @param string $uid Record UID
4153
     * @param string $destPid Position to move to
4154
     * @param string $field Record field
4155
     * @param string $value Record field value
4156
     * @param array $conf TCA configuration of current field
4157
     * @internal should only be used from within DataHandler
4158
     */
4159
    public function moveRecord_procBasedOnFieldType($table, $uid, $destPid, $field, $value, $conf)
4160
    {
4161
        $dbAnalysis = null;
4162
        if ($conf['type'] === 'inline') {
4163
            $foreign_table = $conf['foreign_table'];
4164
            $moveChildrenWithParent = !isset($conf['behaviour']['disableMovingChildrenWithParent']) || !$conf['behaviour']['disableMovingChildrenWithParent'];
4165
            if ($foreign_table && $moveChildrenWithParent) {
4166
                $inlineType = $this->getInlineFieldType($conf);
4167
                if ($inlineType === 'list' || $inlineType === 'field') {
4168
                    if ($table === 'pages') {
4169
                        // If the inline elements are related to a page record,
4170
                        // make sure they reside at that page and not at its parent
4171
                        $destPid = $uid;
4172
                    }
4173
                    $dbAnalysis = $this->createRelationHandlerInstance();
4174
                    $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
0 ignored issues
show
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $MMuid of TYPO3\CMS\Core\Database\RelationHandler::start(). ( Ignorable by Annotation )

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

4174
                    $dbAnalysis->start($value, $conf['foreign_table'], '', /** @scrutinizer ignore-type */ $uid, $table, $conf);
Loading history...
4175
                }
4176
            }
4177
        }
4178
        // Move the records
4179
        if (isset($dbAnalysis)) {
4180
            // Moving records to a positive destination will insert each
4181
            // record at the beginning, thus the order is reversed here:
4182
            foreach (array_reverse($dbAnalysis->itemArray) as $v) {
4183
                $this->moveRecord($v['table'], $v['id'], $destPid);
0 ignored issues
show
Bug introduced by
$destPid of type string is incompatible with the type integer expected by parameter $destPid of TYPO3\CMS\Core\DataHandl...taHandler::moveRecord(). ( Ignorable by Annotation )

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

4183
                $this->moveRecord($v['table'], $v['id'], /** @scrutinizer ignore-type */ $destPid);
Loading history...
4184
            }
4185
        }
4186
    }
4187
4188
    /**
4189
     * Find l10n-overlay records and perform the requested move action for these records.
4190
     *
4191
     * @param string $table Record Table
4192
     * @param string $uid Record UID
4193
     * @param string $destPid Position to move to
4194
     * @param string $originalRecordDestinationPid Position to move the original record to
4195
     * @internal should only be used from within DataHandler
4196
     */
4197
    public function moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid)
4198
    {
4199
        // There's no need to perform this for non-localizable tables
4200
        if (!BackendUtility::isTableLocalizable($table)) {
4201
            return;
4202
        }
4203
4204
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
4205
        $queryBuilder->getRestrictions()
4206
            ->removeAll()
4207
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
4208
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->BE_USER->workspace));
4209
4210
        $l10nRecords = $queryBuilder->select('*')
4211
            ->from($table)
4212
            ->where(
4213
                $queryBuilder->expr()->eq(
4214
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
4215
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':pointer')
4216
                )
4217
            )
4218
            ->execute()
4219
            ->fetchAll();
4220
4221
        if (is_array($l10nRecords)) {
4222
            $localizedDestPids = [];
4223
            // If $$originalRecordDestinationPid < 0, then it is the uid of the original language record we are inserting after
4224
            if ($originalRecordDestinationPid < 0) {
4225
                // Get the localized records of the record we are inserting after
4226
                $queryBuilder->setParameter('pointer', abs($originalRecordDestinationPid), \PDO::PARAM_INT);
4227
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
4228
                // Index the localized record uids by language
4229
                if (is_array($destL10nRecords)) {
4230
                    foreach ($destL10nRecords as $record) {
4231
                        $localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]] = -$record['uid'];
4232
                    }
4233
                }
4234
            }
4235
            // Move the localized records after the corresponding localizations of the destination record
4236
            foreach ($l10nRecords as $record) {
4237
                $localizedDestPid = (int)$localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]];
4238
                if ($localizedDestPid < 0) {
4239
                    $this->moveRecord($table, $record['uid'], $localizedDestPid);
4240
                } else {
4241
                    $this->moveRecord($table, $record['uid'], $destPid);
0 ignored issues
show
Bug introduced by
$destPid of type string is incompatible with the type integer expected by parameter $destPid of TYPO3\CMS\Core\DataHandl...taHandler::moveRecord(). ( Ignorable by Annotation )

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

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

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

5005
                $this->log($table, $uid, SystemLogDatabaseAction::DELETE, /** @scrutinizer ignore-type */ '', SystemLogErrorClassification::USER_ERROR, 'Record cannot be undeleted since the page containing it is deleted! Undelete page "' . $page['title'] . ' (UID: ' . $page['uid'] . ')" first');
Loading history...
5006
            }
5007
        } else {
5008
            // The page containing the record is on rootlevel, so there is no parent record to check, and the record can be undeleted:
5009
            $result = true;
5010
        }
5011
        return $result;
5012
    }
5013
5014
    /**
5015
     * Before a record is deleted, check if it has references such as inline type or MM references.
5016
     * If so, set these child records also to be deleted.
5017
     *
5018
     * @param string $table Record Table
5019
     * @param string $uid Record UID
5020
     * @param bool $undeleteRecord If a record should be undeleted (e.g. from history/undo)
5021
     * @see deleteRecord()
5022
     * @internal should only be used from within DataHandler
5023
     */
5024
    public function deleteRecord_procFields($table, $uid, $undeleteRecord = false)
5025
    {
5026
        $conf = $GLOBALS['TCA'][$table]['columns'];
5027
        $row = BackendUtility::getRecord($table, $uid, '*', '', false);
0 ignored issues
show
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Backend\Utilit...endUtility::getRecord(). ( Ignorable by Annotation )

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

5027
        $row = BackendUtility::getRecord($table, /** @scrutinizer ignore-type */ $uid, '*', '', false);
Loading history...
5028
        if (empty($row)) {
5029
            return;
5030
        }
5031
        foreach ($row as $field => $value) {
5032
            $this->deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf[$field]['config'], $undeleteRecord);
5033
        }
5034
    }
5035
5036
    /**
5037
     * Process fields of a record to be deleted and search for special handling, like
5038
     * inline type, MM records, etc.
5039
     *
5040
     * @param string $table Record Table
5041
     * @param string $uid Record UID
5042
     * @param string $field Record field
5043
     * @param string $value Record field value
5044
     * @param array $conf TCA configuration of current field
5045
     * @param bool $undeleteRecord If a record should be undeleted (e.g. from history/undo)
5046
     * @see deleteRecord()
5047
     * @internal should only be used from within DataHandler
5048
     */
5049
    public function deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf, $undeleteRecord = false)
5050
    {
5051
        if ($conf['type'] === 'inline') {
5052
            $foreign_table = $conf['foreign_table'];
5053
            if ($foreign_table) {
5054
                $inlineType = $this->getInlineFieldType($conf);
5055
                if ($inlineType === 'list' || $inlineType === 'field') {
5056
                    /** @var RelationHandler $dbAnalysis */
5057
                    $dbAnalysis = $this->createRelationHandlerInstance();
5058
                    $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
0 ignored issues
show
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $MMuid of TYPO3\CMS\Core\Database\RelationHandler::start(). ( Ignorable by Annotation )

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

5058
                    $dbAnalysis->start($value, $conf['foreign_table'], '', /** @scrutinizer ignore-type */ $uid, $table, $conf);
Loading history...
5059
                    $dbAnalysis->undeleteRecord = true;
5060
5061
                    $enableCascadingDelete = true;
5062
                    // non type save comparison is intended!
5063
                    if (isset($conf['behaviour']['enableCascadingDelete']) && $conf['behaviour']['enableCascadingDelete'] == false) {
5064
                        $enableCascadingDelete = false;
5065
                    }
5066
5067
                    // Walk through the items and remove them
5068
                    foreach ($dbAnalysis->itemArray as $v) {
5069
                        if (!$undeleteRecord) {
5070
                            if ($enableCascadingDelete) {
5071
                                $this->deleteAction($v['table'], $v['id']);
5072
                            }
5073
                        } else {
5074
                            $this->undeleteRecord($v['table'], $v['id']);
5075
                        }
5076
                    }
5077
                }
5078
            }
5079
        } elseif ($this->isReferenceField($conf)) {
5080
            $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5081
            $dbAnalysis = $this->createRelationHandlerInstance();
5082
            $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
5083
            foreach ($dbAnalysis->itemArray as $v) {
5084
                $this->updateRefIndex($v['table'], $v['id']);
5085
            }
5086
        }
5087
    }
5088
5089
    /**
5090
     * Find l10n-overlay records and perform the requested delete action for these records.
5091
     *
5092
     * @param string $table Record Table
5093
     * @param string $uid Record UID
5094
     * @internal should only be used from within DataHandler
5095
     */
5096
    public function deleteL10nOverlayRecords($table, $uid)
5097
    {
5098
        // Check whether table can be localized
5099
        if (!BackendUtility::isTableLocalizable($table)) {
5100
            return;
5101
        }
5102
5103
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5104
        $queryBuilder->getRestrictions()
5105
            ->removeAll()
5106
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
5107
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->BE_USER->workspace));
5108
5109
        $queryBuilder->select('*')
5110
            ->from($table)
5111
            ->where(
5112
                $queryBuilder->expr()->eq(
5113
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5114
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5115
                )
5116
            );
5117
5118
        $result = $queryBuilder->execute();
5119
        while ($record = $result->fetch()) {
5120
            // Ignore workspace delete placeholders. Those records have been marked for
5121
            // deletion before - deleting them again in a workspace would revert that state.
5122
            if ((int)$this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
5123
                BackendUtility::workspaceOL($table, $record, $this->BE_USER->workspace);
5124
                if (VersionState::cast($record['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)) {
5125
                    continue;
5126
                }
5127
            }
5128
            $this->deleteAction($table, (int)$record['t3ver_oid'] > 0 ? (int)$record['t3ver_oid'] : (int)$record['uid']);
5129
        }
5130
    }
5131
5132
    /*********************************************
5133
     *
5134
     * Cmd: Workspace discard & flush
5135
     *
5136
     ********************************************/
5137
5138
    /**
5139
     * Discard a versioned record from this workspace. This deletes records from the database - no soft delete.
5140
     * This main entry method is called recursive for sub pages, localizations, relations and records on a page.
5141
     * The method checks user access and gathers facts about this record to hand the deletion over to detail methods.
5142
     *
5143
     * The incoming $uid or $row can be anything: The workspace of current user is respected and only records
5144
     * of current user workspace are discarded. If giving a live record uid, the versioned overly will be fetched.
5145
     *
5146
     * @param string $table Database table name
5147
     * @param int|null $uid Uid of live or versioned record to be discarded, or null if $record is given
5148
     * @param array|null $record Record row that should be discarded. Used instead of $uid within recursion.
5149
     */
5150
    public function discard(string $table, ?int $uid, array $record = null): void
5151
    {
5152
        if ($uid === null && $record === null) {
5153
            throw new \RuntimeException('Either record $uid or $record row must be given', 1600373491);
5154
        }
5155
5156
        // Fetch record we are dealing with if not given
5157
        if ($record === null) {
5158
            $record = BackendUtility::getRecord($table, $uid);
5159
        }
5160
        if (!is_array($record)) {
5161
            return;
5162
        }
5163
        $uid = (int)$record['uid'];
5164
5165
        // Call hook and return if hook took care of the element
5166
        $recordWasDiscarded = false;
5167
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
5168
            $hookObj = GeneralUtility::makeInstance($className);
5169
            if (method_exists($hookObj, 'processCmdmap_discardAction')) {
5170
                $hookObj->processCmdmap_discardAction($table, $uid, $record, $recordWasDiscarded);
5171
            }
5172
        }
5173
5174
        $userWorkspace = (int)$this->BE_USER->workspace;
5175
        if ($recordWasDiscarded
5176
            || $userWorkspace === 0
5177
            || !BackendUtility::isTableWorkspaceEnabled($table)
5178
            || $this->hasDeletedRecord($table, $uid)
5179
        ) {
5180
            return;
5181
        }
5182
5183
        // Gather versioned record
5184
        $versionRecord = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $versionRecord is dead and can be removed.
Loading history...
5185
        if ((int)$record['t3ver_wsid'] === 0) {
5186
            $record = BackendUtility::getWorkspaceVersionOfRecord($userWorkspace, $table, $uid);
5187
        }
5188
        if (!is_array($record)) {
5189
            return;
5190
        }
5191
        $versionRecord = $record;
5192
5193
        // User access checks
5194
        if ($userWorkspace !== (int)$versionRecord['t3ver_wsid']) {
5195
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: Different workspace', SystemLogErrorClassification::USER_ERROR);
5196
            return;
5197
        }
5198
        if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $versionRecord['uid'])) {
5199
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: ' . $errorCode, SystemLogErrorClassification::USER_ERROR);
5200
            return;
5201
        }
5202
        if (!$this->checkRecordUpdateAccess($table, $versionRecord['uid'])) {
5203
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: User has no edit access', SystemLogErrorClassification::USER_ERROR);
5204
            return;
5205
        }
5206
        $fullLanguageAccessCheck = !($table === 'pages' && (int)$versionRecord[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] !== 0);
5207
        if (!$this->BE_USER->recordEditAccessInternals($table, $versionRecord, false, true, $fullLanguageAccessCheck)) {
5208
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: User has no delete access', SystemLogErrorClassification::USER_ERROR);
5209
            return;
5210
        }
5211
5212
        // Perform discard operations
5213
        $versionState = VersionState::cast($versionRecord['t3ver_state']);
5214
        if ($table === 'pages' && $versionState->equals(VersionState::NEW_PLACEHOLDER)) {
5215
            // When discarding a new page, there can be new sub pages and new records.
5216
            // Those need to be discarded, otherwise they'd end up as records without parent page.
5217
            $this->discardSubPagesAndRecordsOnPage($versionRecord);
5218
        }
5219
5220
        $this->discardLocalizationOverlayRecords($table, $versionRecord);
5221
        $this->discardRecordRelations($table, $versionRecord);
5222
        $this->hardDeleteSingleRecord($table, (int)$versionRecord['uid']);
5223
        $this->deletedRecords[$table][] = (int)$versionRecord['uid'];
5224
        $this->registerReferenceIndexRowsForDrop($table, (int)$versionRecord['uid'], $userWorkspace);
5225
        $this->getRecordHistoryStore()->deleteRecord($table, (int)$versionRecord['uid'], $this->correlationId);
5226
        $this->log(
5227
            $table,
5228
            (int)$versionRecord['uid'],
5229
            SystemLogDatabaseAction::DELETE,
5230
            0,
5231
            SystemLogErrorClassification::MESSAGE,
5232
            'Record ' . $table . ':' . $versionRecord['uid'] . ' was deleted unrecoverable from page ' . $versionRecord['pid'],
5233
            0,
5234
            [],
5235
            (int)$versionRecord['pid']
5236
        );
5237
    }
5238
5239
    /**
5240
     * Also discard any sub pages and records of a new parent page if this page is discarded.
5241
     * Discarding only in specific localization, if needed.
5242
     *
5243
     * @param array $page Page record row
5244
     */
5245
    protected function discardSubPagesAndRecordsOnPage(array $page): void
5246
    {
5247
        $isLocalizedPage = false;
5248
        $sysLanguageId = (int)$page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
5249
        $versionState = VersionState::cast($page['t3ver_state']);
5250
        if ($sysLanguageId > 0) {
5251
            // New or moved localized page.
5252
            // Discard records on this page localization, but no sub pages.
5253
            // Records of a translated page have the pid set to the default language page uid. Found in l10n_parent.
5254
            // @todo: Discard other page translations that inherit from this?! (l10n_source field)
5255
            $isLocalizedPage = true;
5256
            $pid = (int)$page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
5257
        } elseif ($versionState->equals(VersionState::NEW_PLACEHOLDER)) {
5258
            // New default language page.
5259
            // Discard any sub pages and all other records of this page, including any page localizations.
5260
            // The t3ver_state=1 record is incoming here. Records on this page have their pid field set to the uid
5261
            // of this record. So, since t3ver_state=1 does not have an online counter-part, the actual UID is used here.
5262
            $pid = (int)$page['uid'];
5263
        } else {
5264
            // Moved default language page.
5265
            // Discard any sub pages and all other records of this page, including any page localizations.
5266
            $pid = (int)$page['t3ver_oid'];
5267
        }
5268
        $tables = $this->compileAdminTables();
5269
        foreach ($tables as $table) {
5270
            if (($isLocalizedPage && $table === 'pages')
5271
                || ($isLocalizedPage && !BackendUtility::isTableLocalizable($table))
5272
                || !BackendUtility::isTableWorkspaceEnabled($table)
5273
            ) {
5274
                continue;
5275
            }
5276
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5277
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5278
            $queryBuilder->select('*')
5279
                ->from($table)
5280
                ->where(
5281
                    $queryBuilder->expr()->eq(
5282
                        'pid',
5283
                        $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
5284
                    ),
5285
                    $queryBuilder->expr()->eq(
5286
                        't3ver_wsid',
5287
                        $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5288
                    )
5289
                );
5290
            if ($isLocalizedPage) {
5291
                // Add sys_language_uid = x restriction if discarding a localized page
5292
                $queryBuilder->andWhere(
5293
                    $queryBuilder->expr()->eq(
5294
                        $GLOBALS['TCA'][$table]['ctrl']['languageField'],
5295
                        $queryBuilder->createNamedParameter($sysLanguageId, \PDO::PARAM_INT)
5296
                    )
5297
                );
5298
            }
5299
            $statement = $queryBuilder->execute();
5300
            while ($row = $statement->fetch()) {
5301
                $this->discard($table, null, $row);
5302
            }
5303
        }
5304
    }
5305
5306
    /**
5307
     * Discard record relations like inline and MM of a record.
5308
     *
5309
     * @param string $table Table name of this record
5310
     * @param array $record The record row to handle
5311
     */
5312
    protected function discardRecordRelations(string $table, array $record): void
5313
    {
5314
        foreach ($record as $field => $value) {
5315
            $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'] ?? null;
5316
            if (!isset($fieldConfig['type'])) {
5317
                continue;
5318
            }
5319
            if ($fieldConfig['type'] === 'inline') {
5320
                $foreignTable = $fieldConfig['foreign_table'] ?? null;
5321
                if (!$foreignTable
5322
                     || (isset($fieldConfig['behaviour']['enableCascadingDelete'])
5323
                        && (bool)$fieldConfig['behaviour']['enableCascadingDelete'] === false)
5324
                ) {
5325
                    continue;
5326
                }
5327
                $inlineType = $this->getInlineFieldType($fieldConfig);
5328
                if ($inlineType === 'list' || $inlineType === 'field') {
5329
                    $dbAnalysis = $this->createRelationHandlerInstance();
5330
                    $dbAnalysis->start($value, $fieldConfig['foreign_table'], '', (int)$record['uid'], $table, $fieldConfig);
5331
                    $dbAnalysis->undeleteRecord = true;
5332
                    foreach ($dbAnalysis->itemArray as $relationRecord) {
5333
                        $this->discard($relationRecord['table'], (int)$relationRecord['id']);
5334
                    }
5335
                }
5336
            } elseif ($this->isReferenceField($fieldConfig)) {
5337
                $allowedTables = $fieldConfig['type'] === 'group' ? $fieldConfig['allowed'] : $fieldConfig['foreign_table'];
5338
                $dbAnalysis = $this->createRelationHandlerInstance();
5339
                $dbAnalysis->start($value, $allowedTables, $fieldConfig['MM'], (int)$record['uid'], $table, $fieldConfig);
5340
                foreach ($dbAnalysis->itemArray as $relationRecord) {
5341
                    // @todo: Something should happen with these relations here ...
5342
                    // @todo: Can't use dropReferenceIndexRowsForRecord() here, this would drop sys_refindex entries we want to keep
5343
                    $this->updateRefIndex($relationRecord['table'], (int)$relationRecord['id']);
5344
                }
5345
            }
5346
        }
5347
    }
5348
5349
    /**
5350
     * Find localization overlays of a record and discard them.
5351
     *
5352
     * @param string $table Table of this record
5353
     * @param array $record Record row
5354
     */
5355
    protected function discardLocalizationOverlayRecords(string $table, array $record): void
5356
    {
5357
        if (!BackendUtility::isTableLocalizable($table)) {
5358
            return;
5359
        }
5360
        $uid = (int)$record['uid'];
5361
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5362
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5363
        $statement = $queryBuilder->select('*')
5364
            ->from($table)
5365
            ->where(
5366
                $queryBuilder->expr()->eq(
5367
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5368
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5369
                ),
5370
                $queryBuilder->expr()->eq(
5371
                    't3ver_wsid',
5372
                    $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5373
                )
5374
            )
5375
            ->execute();
5376
        while ($record = $statement->fetch()) {
5377
            $this->discard($table, null, $record);
5378
        }
5379
    }
5380
5381
    /*********************************************
5382
     *
5383
     * Cmd: Versioning
5384
     *
5385
     ********************************************/
5386
    /**
5387
     * Creates a new version of a record
5388
     * (Requires support in the table)
5389
     *
5390
     * @param string $table Table name
5391
     * @param int $id Record uid to versionize
5392
     * @param string $label Version label
5393
     * @param bool $delete If TRUE, the version is created to delete the record.
5394
     * @return int|null Returns the id of the new version (if any)
5395
     * @see copyRecord()
5396
     * @internal should only be used from within DataHandler
5397
     */
5398
    public function versionizeRecord($table, $id, $label, $delete = false)
5399
    {
5400
        $id = (int)$id;
5401
        // Stop any actions if the record is marked to be deleted:
5402
        // (this can occur if IRRE elements are versionized and child elements are removed)
5403
        if ($this->isElementToBeDeleted($table, $id)) {
5404
            return null;
5405
        }
5406
        if (!BackendUtility::isTableWorkspaceEnabled($table) || $id <= 0) {
5407
            $this->newlog('Versioning is not supported for this table "' . $table . '" / ' . $id, SystemLogErrorClassification::USER_ERROR);
5408
            return null;
5409
        }
5410
5411
        // Fetch record with permission check
5412
        $row = $this->recordInfoWithPermissionCheck($table, $id, Permission::PAGE_SHOW);
5413
5414
        // This checks if the record can be selected which is all that a copy action requires.
5415
        if ($row === false) {
5416
            $this->newlog(
5417
                'The record does not exist or you don\'t have correct permissions to make a new version (copy) of this record "' . $table . ':' . $id . '"',
5418
                SystemLogErrorClassification::USER_ERROR
5419
            );
5420
            return null;
5421
        }
5422
5423
        // Record must be online record, otherwise we would create a version of a version
5424
        if (($row['t3ver_oid'] ?? 0) > 0) {
5425
            $this->newlog('Record "' . $table . ':' . $id . '" you wanted to versionize was already a version in archive (record has an online ID)!', SystemLogErrorClassification::USER_ERROR);
5426
            return null;
5427
        }
5428
5429
        if ($delete && $this->cannotDeleteRecord($table, $id)) {
5430
            $this->newlog('Record cannot be deleted: ' . $this->cannotDeleteRecord($table, $id), SystemLogErrorClassification::USER_ERROR);
5431
            return null;
5432
        }
5433
5434
        // Set up the values to override when making a raw-copy:
5435
        $overrideArray = [
5436
            't3ver_oid' => $id,
5437
            't3ver_wsid' => $this->BE_USER->workspace,
5438
            't3ver_state' => (string)($delete ? new VersionState(VersionState::DELETE_PLACEHOLDER) : new VersionState(VersionState::DEFAULT_STATE)),
5439
            't3ver_stage' => 0,
5440
        ];
5441
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock']) {
5442
            $overrideArray[$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
5443
        }
5444
        // Checking if the record already has a version in the current workspace of the backend user
5445
        $versionRecord = ['uid' => null];
5446
        if ($this->BE_USER->workspace !== 0) {
5447
            // Look for version already in workspace:
5448
            $versionRecord = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid');
5449
        }
5450
        // Create new version of the record and return the new uid
5451
        if (empty($versionRecord['uid'])) {
5452
            // Create raw-copy and return result:
5453
            // The information of the label to be used for the workspace record
5454
            // as well as the information whether the record shall be removed
5455
            // must be forwarded (creating delete placeholders on a workspace are
5456
            // done by copying the record and override several fields).
5457
            $workspaceOptions = [
5458
                'delete' => $delete,
5459
                'label' => $label,
5460
            ];
5461
            return $this->copyRecord_raw($table, $id, (int)$row['pid'], $overrideArray, $workspaceOptions);
5462
        }
5463
        // Reuse the existing record and return its uid
5464
        // (prior to TYPO3 CMS 6.2, an error was thrown here, which
5465
        // did not make much sense since the information is available)
5466
        return $versionRecord['uid'];
5467
    }
5468
5469
    /**
5470
     * Swaps MM-relations for current/swap record, see version_swap()
5471
     *
5472
     * @param string $table Table for the two input records
5473
     * @param int $id Current record (about to go offline)
5474
     * @param int $swapWith Swap record (about to go online)
5475
     * @see version_swap()
5476
     * @internal should only be used from within DataHandler
5477
     */
5478
    public function version_remapMMForVersionSwap($table, $id, $swapWith)
5479
    {
5480
        // Actually, selecting the records fully is only need if flexforms are found inside... This could be optimized ...
5481
        $currentRec = BackendUtility::getRecord($table, $id);
5482
        $swapRec = BackendUtility::getRecord($table, $swapWith);
5483
        $this->version_remapMMForVersionSwap_reg = [];
5484
        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5485
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fConf) {
5486
            $conf = $fConf['config'];
5487
            if ($this->isReferenceField($conf)) {
5488
                $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5489
                $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
5490
                if ($conf['MM']) {
5491
                    /** @var RelationHandler $dbAnalysis */
5492
                    $dbAnalysis = $this->createRelationHandlerInstance();
5493
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $id, $table, $conf);
5494
                    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

5494
                    if (!empty($dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName))) {
Loading history...
5495
                        $this->version_remapMMForVersionSwap_reg[$id][$field] = [$dbAnalysis, $conf['MM'], $prependName];
5496
                    }
5497
                    /** @var RelationHandler $dbAnalysis */
5498
                    $dbAnalysis = $this->createRelationHandlerInstance();
5499
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $swapWith, $table, $conf);
5500
                    if (!empty($dbAnalysis->getValueArray($prependName))) {
5501
                        $this->version_remapMMForVersionSwap_reg[$swapWith][$field] = [$dbAnalysis, $conf['MM'], $prependName];
5502
                    }
5503
                }
5504
            } elseif ($conf['type'] === 'flex') {
5505
                // Current record
5506
                $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5507
                    $fConf,
5508
                    $table,
5509
                    $field,
5510
                    $currentRec
5511
                );
5512
                $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5513
                $currentValueArray = GeneralUtility::xml2array($currentRec[$field]);
5514
                if (is_array($currentValueArray)) {
5515
                    $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $id, $field], 'version_remapMMForVersionSwap_flexFormCallBack');
5516
                }
5517
                // Swap record
5518
                $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5519
                    $fConf,
5520
                    $table,
5521
                    $field,
5522
                    $swapRec
5523
                );
5524
                $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5525
                $currentValueArray = GeneralUtility::xml2array($swapRec[$field]);
5526
                if (is_array($currentValueArray)) {
5527
                    $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $swapWith, $field], 'version_remapMMForVersionSwap_flexFormCallBack');
5528
                }
5529
            }
5530
        }
5531
        // Execute:
5532
        $this->version_remapMMForVersionSwap_execSwap($table, $id, $swapWith);
5533
    }
5534
5535
    /**
5536
     * Callback function for traversing the FlexForm structure in relation to ...
5537
     *
5538
     * @param array $pParams Array of parameters in num-indexes: table, uid, field
5539
     * @param array $dsConf TCA field configuration (from Data Structure XML)
5540
     * @param string $dataValue The value of the flexForm field
5541
     * @param string $dataValue_ext1 Not used.
5542
     * @param string $dataValue_ext2 Not used.
5543
     * @param string $path Path in flexforms
5544
     * @see version_remapMMForVersionSwap()
5545
     * @see checkValue_flex_procInData_travDS()
5546
     * @internal should only be used from within DataHandler
5547
     */
5548
    public function version_remapMMForVersionSwap_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
5549
    {
5550
        // Extract parameters:
5551
        [$table, $uid, $field] = $pParams;
5552
        if ($this->isReferenceField($dsConf)) {
5553
            $allowedTables = $dsConf['type'] === 'group' ? $dsConf['allowed'] : $dsConf['foreign_table'];
5554
            $prependName = $dsConf['type'] === 'group' ? $dsConf['prepend_tname'] : '';
5555
            if ($dsConf['MM']) {
5556
                /** @var RelationHandler $dbAnalysis */
5557
                $dbAnalysis = $this->createRelationHandlerInstance();
5558
                $dbAnalysis->start('', $allowedTables, $dsConf['MM'], $uid, $table, $dsConf);
5559
                $this->version_remapMMForVersionSwap_reg[$uid][$field . '/' . $path] = [$dbAnalysis, $dsConf['MM'], $prependName];
5560
            }
5561
        }
5562
    }
5563
5564
    /**
5565
     * Performing the remapping operations found necessary in version_remapMMForVersionSwap()
5566
     * 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.
5567
     *
5568
     * @param string $table Table for the two input records
5569
     * @param int $id Current record (about to go offline)
5570
     * @param int $swapWith Swap record (about to go online)
5571
     * @see version_remapMMForVersionSwap()
5572
     * @internal should only be used from within DataHandler
5573
     */
5574
    public function version_remapMMForVersionSwap_execSwap($table, $id, $swapWith)
5575
    {
5576
        if (is_array($this->version_remapMMForVersionSwap_reg[$id])) {
5577
            foreach ($this->version_remapMMForVersionSwap_reg[$id] as $field => $str) {
5578
                $str[0]->remapMM($str[1], $id, -$id, $str[2]);
5579
            }
5580
        }
5581
        if (is_array($this->version_remapMMForVersionSwap_reg[$swapWith])) {
5582
            foreach ($this->version_remapMMForVersionSwap_reg[$swapWith] as $field => $str) {
5583
                $str[0]->remapMM($str[1], $swapWith, $id, $str[2]);
5584
            }
5585
        }
5586
        if (is_array($this->version_remapMMForVersionSwap_reg[$id])) {
5587
            foreach ($this->version_remapMMForVersionSwap_reg[$id] as $field => $str) {
5588
                $str[0]->remapMM($str[1], -$id, $swapWith, $str[2]);
5589
            }
5590
        }
5591
    }
5592
5593
    /*********************************************
5594
     *
5595
     * Cmd: Helper functions
5596
     *
5597
     ********************************************/
5598
5599
    /**
5600
     * Returns an instance of DataHandler for handling local datamaps/cmdmaps
5601
     *
5602
     * @return DataHandler
5603
     */
5604
    protected function getLocalTCE()
5605
    {
5606
        $copyTCE = GeneralUtility::makeInstance(DataHandler::class, $this->referenceIndexUpdater);
5607
        $copyTCE->copyTree = $this->copyTree;
5608
        $copyTCE->enableLogging = $this->enableLogging;
5609
        // Transformations should NOT be carried out during copy
5610
        $copyTCE->dontProcessTransformations = true;
5611
        // make sure the isImporting flag is transferred, so all hooks know if
5612
        // the current process is an import process
5613
        $copyTCE->isImporting = $this->isImporting;
5614
        $copyTCE->bypassAccessCheckForRecords = $this->bypassAccessCheckForRecords;
5615
        $copyTCE->bypassWorkspaceRestrictions = $this->bypassWorkspaceRestrictions;
5616
        return $copyTCE;
5617
    }
5618
5619
    /**
5620
     * Processes the fields with references as registered during the copy process. This includes all FlexForm fields which had references.
5621
     * @internal should only be used from within DataHandler
5622
     */
5623
    public function remapListedDBRecords()
5624
    {
5625
        if (!empty($this->registerDBList)) {
5626
            $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5627
            foreach ($this->registerDBList as $table => $records) {
5628
                foreach ($records as $uid => $fields) {
5629
                    $newData = [];
5630
                    $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
5631
                    $theUidToUpdate_saveTo = BackendUtility::wsMapId($table, $theUidToUpdate);
5632
                    foreach ($fields as $fieldName => $value) {
5633
                        $conf = $GLOBALS['TCA'][$table]['columns'][$fieldName]['config'];
5634
                        switch ($conf['type']) {
5635
                            case 'group':
5636
                            case 'select':
5637
                                $vArray = $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
5638
                                if (is_array($vArray)) {
5639
                                    $newData[$fieldName] = implode(',', $vArray);
5640
                                }
5641
                                break;
5642
                            case 'flex':
5643
                                if ($value === 'FlexForm_reference') {
5644
                                    // This will fetch the new row for the element
5645
                                    $origRecordRow = $this->recordInfo($table, $theUidToUpdate, '*');
5646
                                    if (is_array($origRecordRow)) {
5647
                                        BackendUtility::workspaceOL($table, $origRecordRow);
5648
                                        // Get current data structure and value array:
5649
                                        $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5650
                                            ['config' => $conf],
5651
                                            $table,
5652
                                            $fieldName,
5653
                                            $origRecordRow
5654
                                        );
5655
                                        $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5656
                                        $currentValueArray = GeneralUtility::xml2array($origRecordRow[$fieldName]);
5657
                                        // Do recursive processing of the XML data:
5658
                                        $currentValueArray['data'] = $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $theUidToUpdate, $fieldName], 'remapListedDBRecords_flexFormCallBack');
5659
                                        // The return value should be compiled back into XML, ready to insert directly in the field (as we call updateDB() directly later):
5660
                                        if (is_array($currentValueArray['data'])) {
5661
                                            $newData[$fieldName] = $this->checkValue_flexArray2Xml($currentValueArray, true);
5662
                                        }
5663
                                    }
5664
                                }
5665
                                break;
5666
                            case 'inline':
5667
                                $this->remapListedDBRecords_procInline($conf, $value, $uid, $table);
5668
                                break;
5669
                            default:
5670
                                $this->logger->debug('Field type should not appear here: ' . $conf['type']);
5671
                        }
5672
                    }
5673
                    // If any fields were changed, those fields are updated!
5674
                    if (!empty($newData)) {
5675
                        $this->updateDB($table, $theUidToUpdate_saveTo, $newData);
5676
                    }
5677
                }
5678
            }
5679
        }
5680
    }
5681
5682
    /**
5683
     * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
5684
     *
5685
     * @param array $pParams Set of parameters in numeric array: table, uid, field
5686
     * @param array $dsConf TCA config for field (from Data Structure of course)
5687
     * @param string $dataValue Field value (from FlexForm XML)
5688
     * @param string $dataValue_ext1 Not used
5689
     * @param string $dataValue_ext2 Not used
5690
     * @return array Array where the "value" key carries the value.
5691
     * @see checkValue_flex_procInData_travDS()
5692
     * @see remapListedDBRecords()
5693
     * @internal should only be used from within DataHandler
5694
     */
5695
    public function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
5696
    {
5697
        // Extract parameters:
5698
        [$table, $uid, $field] = $pParams;
5699
        // If references are set for this field, set flag so they can be corrected later:
5700
        if ($this->isReferenceField($dsConf) && (string)$dataValue !== '') {
5701
            $vArray = $this->remapListedDBRecords_procDBRefs($dsConf, $dataValue, $uid, $table);
5702
            if (is_array($vArray)) {
5703
                $dataValue = implode(',', $vArray);
5704
            }
5705
        }
5706
        // Return
5707
        return ['value' => $dataValue];
5708
    }
5709
5710
    /**
5711
     * Performs remapping of old UID values to NEW uid values for a DB reference field.
5712
     *
5713
     * @param array $conf TCA field config
5714
     * @param string $value Field value
5715
     * @param int $MM_localUid UID of local record (for MM relations - might need to change if support for FlexForms should be done!)
5716
     * @param string $table Table name
5717
     * @return array|null Returns array of items ready to implode for field content.
5718
     * @see remapListedDBRecords()
5719
     * @internal should only be used from within DataHandler
5720
     */
5721
    public function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid, $table)
5722
    {
5723
        // Initialize variables
5724
        // Will be set TRUE if an upgrade should be done...
5725
        $set = false;
5726
        // Allowed tables for references.
5727
        $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5728
        // Table name to prepend the UID
5729
        $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
5730
        // Which tables that should possibly not be remapped
5731
        $dontRemapTables = GeneralUtility::trimExplode(',', $conf['dontRemapTablesOnCopy'], true);
5732
        // Convert value to list of references:
5733
        $dbAnalysis = $this->createRelationHandlerInstance();
5734
        $dbAnalysis->registerNonTableValues = $conf['type'] === 'select' && $conf['allowNonIdValues'];
5735
        $dbAnalysis->start($value, $allowedTables, $conf['MM'], $MM_localUid, $table, $conf);
5736
        // Traverse those references and map IDs:
5737
        foreach ($dbAnalysis->itemArray as $k => $v) {
5738
            $mapID = $this->copyMappingArray_merged[$v['table']][$v['id']];
5739
            if ($mapID && !in_array($v['table'], $dontRemapTables, true)) {
5740
                $dbAnalysis->itemArray[$k]['id'] = $mapID;
5741
                $set = true;
5742
            }
5743
        }
5744
        if (!empty($conf['MM'])) {
5745
            // Purge invalid items (live/version)
5746
            $dbAnalysis->purgeItemArray();
5747
            if ($dbAnalysis->isPurged()) {
5748
                $set = true;
5749
            }
5750
5751
            // If record has been versioned/copied in this process, handle invalid relations of the live record
5752
            $liveId = BackendUtility::getLiveVersionIdOfRecord($table, $MM_localUid);
5753
            $originalId = 0;
5754
            if (!empty($this->copyMappingArray_merged[$table])) {
5755
                $originalId = array_search($MM_localUid, $this->copyMappingArray_merged[$table]);
5756
            }
5757
            if (!empty($liveId) && !empty($originalId) && (int)$liveId === (int)$originalId) {
5758
                $liveRelations = $this->createRelationHandlerInstance();
5759
                $liveRelations->setWorkspaceId(0);
5760
                $liveRelations->start('', $allowedTables, $conf['MM'], $liveId, $table, $conf);
5761
                // Purge invalid relations in the live workspace ("0")
5762
                $liveRelations->purgeItemArray(0);
5763
                if ($liveRelations->isPurged()) {
5764
                    $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

5764
                    $liveRelations->writeMM($conf['MM'], $liveId, /** @scrutinizer ignore-type */ $prependName);
Loading history...
5765
                }
5766
            }
5767
        }
5768
        // If a change has been done, set the new value(s)
5769
        if ($set) {
5770
            if ($conf['MM']) {
5771
                $dbAnalysis->writeMM($conf['MM'], $MM_localUid, $prependName);
5772
            } else {
5773
                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

5773
                return $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName);
Loading history...
5774
            }
5775
        }
5776
        return null;
5777
    }
5778
5779
    /**
5780
     * Performs remapping of old UID values to NEW uid values for an inline field.
5781
     *
5782
     * @param array $conf TCA field config
5783
     * @param string $value Field value
5784
     * @param int $uid The uid of the ORIGINAL record
5785
     * @param string $table Table name
5786
     * @internal should only be used from within DataHandler
5787
     */
5788
    public function remapListedDBRecords_procInline($conf, $value, $uid, $table)
5789
    {
5790
        $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
5791
        if ($conf['foreign_table']) {
5792
            $inlineType = $this->getInlineFieldType($conf);
5793
            if ($inlineType === 'mm') {
5794
                $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
5795
            } elseif ($inlineType !== false) {
5796
                /** @var RelationHandler $dbAnalysis */
5797
                $dbAnalysis = $this->createRelationHandlerInstance();
5798
                $dbAnalysis->start($value, $conf['foreign_table'], '', 0, $table, $conf);
5799
5800
                $updatePidForRecords = [];
5801
                // Update values for specific versioned records
5802
                foreach ($dbAnalysis->itemArray as &$item) {
5803
                    $updatePidForRecords[$item['table']][] = $item['id'];
5804
                    $versionedId = $this->getAutoVersionId($item['table'], $item['id']);
5805
                    if ($versionedId !== null) {
5806
                        $updatePidForRecords[$item['table']][] = $versionedId;
5807
                        $item['id'] = $versionedId;
5808
                    }
5809
                }
5810
5811
                // Update child records if using pointer fields ('foreign_field'):
5812
                if ($inlineType === 'field') {
5813
                    $dbAnalysis->writeForeignField($conf, $uid, $theUidToUpdate);
5814
                }
5815
                $thePidToUpdate = null;
5816
                // If the current field is set on a page record, update the pid of related child records:
5817
                if ($table === 'pages') {
5818
                    $thePidToUpdate = $theUidToUpdate;
5819
                } elseif (isset($this->registerDBPids[$table][$uid])) {
5820
                    $thePidToUpdate = $this->registerDBPids[$table][$uid];
5821
                    $thePidToUpdate = $this->copyMappingArray_merged['pages'][$thePidToUpdate];
5822
                }
5823
5824
                // Update child records if change to pid is required
5825
                if ($thePidToUpdate && !empty($updatePidForRecords)) {
5826
                    // Ensure that only the default language page is used as PID
5827
                    $thePidToUpdate = $this->getDefaultLanguagePageId($thePidToUpdate);
5828
                    // @todo: this can probably go away
5829
                    // ensure, only live page ids are used as 'pid' values
5830
                    $liveId = BackendUtility::getLiveVersionIdOfRecord('pages', $theUidToUpdate);
5831
                    if ($liveId !== null) {
5832
                        $thePidToUpdate = $liveId;
5833
                    }
5834
                    $updateValues = ['pid' => $thePidToUpdate];
5835
                    foreach ($updatePidForRecords as $tableName => $uids) {
5836
                        if (empty($tableName) || empty($uids)) {
5837
                            continue;
5838
                        }
5839
                        $conn = GeneralUtility::makeInstance(ConnectionPool::class)
5840
                            ->getConnectionForTable($tableName);
5841
                        foreach ($uids as $updateUid) {
5842
                            $conn->update($tableName, $updateValues, ['uid' => $updateUid]);
5843
                        }
5844
                    }
5845
                }
5846
            }
5847
        }
5848
    }
5849
5850
    /**
5851
     * Processes the $this->remapStack at the end of copying, inserting, etc. actions.
5852
     * The remapStack takes care about the correct mapping of new and old uids in case of relational data.
5853
     * @internal should only be used from within DataHandler
5854
     */
5855
    public function processRemapStack()
5856
    {
5857
        // Processes the remap stack:
5858
        if (is_array($this->remapStack)) {
0 ignored issues
show
introduced by
The condition is_array($this->remapStack) is always true.
Loading history...
5859
            $remapFlexForms = [];
5860
            $hookPayload = [];
5861
5862
            $newValue = null;
5863
            foreach ($this->remapStack as $remapAction) {
5864
                // If no position index for the arguments was set, skip this remap action:
5865
                if (!is_array($remapAction['pos'])) {
5866
                    continue;
5867
                }
5868
                // Load values from the argument array in remapAction:
5869
                $field = $remapAction['field'];
5870
                $id = $remapAction['args'][$remapAction['pos']['id']];
5871
                $rawId = $id;
5872
                $table = $remapAction['args'][$remapAction['pos']['table']];
5873
                $valueArray = $remapAction['args'][$remapAction['pos']['valueArray']];
5874
                $tcaFieldConf = $remapAction['args'][$remapAction['pos']['tcaFieldConf']];
5875
                $additionalData = $remapAction['additionalData'];
5876
                // The record is new and has one or more new ids (in case of versioning/workspaces):
5877
                if (strpos($id, 'NEW') !== false) {
5878
                    // Replace NEW...-ID with real uid:
5879
                    $id = $this->substNEWwithIDs[$id];
5880
                    // If the new parent record is on a non-live workspace or versionized, it has another new id:
5881
                    if (isset($this->autoVersionIdMap[$table][$id])) {
5882
                        $id = $this->autoVersionIdMap[$table][$id];
5883
                    }
5884
                    $remapAction['args'][$remapAction['pos']['id']] = $id;
5885
                }
5886
                // Replace relations to NEW...-IDs in field value (uids of child records):
5887
                if (is_array($valueArray)) {
5888
                    foreach ($valueArray as $key => $value) {
5889
                        if (strpos($value, 'NEW') !== false) {
5890
                            if (strpos($value, '_') === false) {
5891
                                $affectedTable = $tcaFieldConf['foreign_table'];
5892
                                $prependTable = false;
5893
                            } else {
5894
                                $parts = explode('_', $value);
5895
                                $value = array_pop($parts);
5896
                                $affectedTable = implode('_', $parts);
5897
                                $prependTable = true;
5898
                            }
5899
                            $value = $this->substNEWwithIDs[$value];
5900
                            // The record is new, but was also auto-versionized and has another new id:
5901
                            if (isset($this->autoVersionIdMap[$affectedTable][$value])) {
5902
                                $value = $this->autoVersionIdMap[$affectedTable][$value];
5903
                            }
5904
                            if ($prependTable) {
5905
                                $value = $affectedTable . '_' . $value;
5906
                            }
5907
                            // Set a hint that this was a new child record:
5908
                            $this->newRelatedIDs[$affectedTable][] = $value;
5909
                            $valueArray[$key] = $value;
5910
                        }
5911
                    }
5912
                    $remapAction['args'][$remapAction['pos']['valueArray']] = $valueArray;
5913
                }
5914
                // Process the arguments with the defined function:
5915
                if (!empty($remapAction['func'])) {
5916
                    $newValue = call_user_func_array([$this, $remapAction['func']], $remapAction['args']);
5917
                }
5918
                // If array is returned, check for maxitems condition, if string is returned this was already done:
5919
                if (is_array($newValue)) {
5920
                    $newValue = implode(',', $this->checkValue_checkMax($tcaFieldConf, $newValue));
5921
                    // The reference casting is only required if
5922
                    // checkValue_group_select_processDBdata() returns an array
5923
                    $newValue = $this->castReferenceValue($newValue, $tcaFieldConf);
5924
                }
5925
                // Update in database (list of children (csv) or number of relations (foreign_field)):
5926
                if (!empty($field)) {
5927
                    $fieldArray = [$field => $newValue];
5928
                    if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
5929
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
5930
                    }
5931
                    $this->updateDB($table, $id, $fieldArray);
5932
                } elseif (!empty($additionalData['flexFormId']) && !empty($additionalData['flexFormPath'])) {
5933
                    // Collect data to update FlexForms
5934
                    $flexFormId = $additionalData['flexFormId'];
5935
                    $flexFormPath = $additionalData['flexFormPath'];
5936
5937
                    if (!isset($remapFlexForms[$flexFormId])) {
5938
                        $remapFlexForms[$flexFormId] = [];
5939
                    }
5940
5941
                    $remapFlexForms[$flexFormId][$flexFormPath] = $newValue;
5942
                }
5943
5944
                // Collect elements that shall trigger processDatamap_afterDatabaseOperations
5945
                if (isset($this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'])) {
5946
                    $hookArgs = $this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'];
5947
                    if (!isset($hookPayload[$table][$rawId])) {
5948
                        $hookPayload[$table][$rawId] = [
5949
                            'status' => $hookArgs['status'],
5950
                            'fieldArray' => $hookArgs['fieldArray'],
5951
                            'hookObjects' => $hookArgs['hookObjectsArr'],
5952
                        ];
5953
                    }
5954
                    $hookPayload[$table][$rawId]['fieldArray'][$field] = $newValue;
5955
                }
5956
            }
5957
5958
            if ($remapFlexForms) {
5959
                foreach ($remapFlexForms as $flexFormId => $modifications) {
5960
                    $this->updateFlexFormData($flexFormId, $modifications);
5961
                }
5962
            }
5963
5964
            foreach ($hookPayload as $tableName => $rawIdPayload) {
5965
                foreach ($rawIdPayload as $rawId => $payload) {
5966
                    foreach ($payload['hookObjects'] as $hookObject) {
5967
                        if (!method_exists($hookObject, 'processDatamap_afterDatabaseOperations')) {
5968
                            continue;
5969
                        }
5970
                        $hookObject->processDatamap_afterDatabaseOperations(
5971
                            $payload['status'],
5972
                            $tableName,
5973
                            $rawId,
5974
                            $payload['fieldArray'],
5975
                            $this
5976
                        );
5977
                    }
5978
                }
5979
            }
5980
        }
5981
        // Processes the remap stack actions:
5982
        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...
5983
            foreach ($this->remapStackActions as $action) {
5984
                if (isset($action['callback'], $action['arguments'])) {
5985
                    call_user_func_array($action['callback'], $action['arguments']);
5986
                }
5987
            }
5988
        }
5989
        // Reset:
5990
        $this->remapStack = [];
5991
        $this->remapStackRecords = [];
5992
        $this->remapStackActions = [];
5993
    }
5994
5995
    /**
5996
     * Updates FlexForm data.
5997
     *
5998
     * @param string $flexFormId e.g. <table>:<uid>:<field>
5999
     * @param array $modifications Modifications with paths and values (e.g. 'sDEF/lDEV/field/vDEF' => 'TYPO3')
6000
     */
6001
    protected function updateFlexFormData($flexFormId, array $modifications)
6002
    {
6003
        [$table, $uid, $field] = explode(':', $flexFormId, 3);
6004
6005
        if (!MathUtility::canBeInterpretedAsInteger($uid) && !empty($this->substNEWwithIDs[$uid])) {
6006
            $uid = $this->substNEWwithIDs[$uid];
6007
        }
6008
6009
        $record = $this->recordInfo($table, $uid, '*');
6010
6011
        if (!$table || !$uid || !$field || !is_array($record)) {
6012
            return;
6013
        }
6014
6015
        BackendUtility::workspaceOL($table, $record);
6016
6017
        // Get current data structure and value array:
6018
        $valueStructure = GeneralUtility::xml2array($record[$field]);
6019
6020
        // Do recursive processing of the XML data:
6021
        foreach ($modifications as $path => $value) {
6022
            $valueStructure['data'] = ArrayUtility::setValueByPath(
6023
                $valueStructure['data'],
6024
                $path,
6025
                $value
6026
            );
6027
        }
6028
6029
        if (is_array($valueStructure['data'])) {
6030
            // The return value should be compiled back into XML
6031
            $values = [
6032
                $field => $this->checkValue_flexArray2Xml($valueStructure, true),
6033
            ];
6034
6035
            $this->updateDB($table, $uid, $values);
6036
        }
6037
    }
6038
6039
    /**
6040
     * Adds an instruction to the remap action stack (used with IRRE).
6041
     *
6042
     * @param string $table The affected table
6043
     * @param int $id The affected ID
6044
     * @param array $callback The callback information (object and method)
6045
     * @param array $arguments The arguments to be used with the callback
6046
     * @internal should only be used from within DataHandler
6047
     */
6048
    public function addRemapAction($table, $id, array $callback, array $arguments)
6049
    {
6050
        $this->remapStackActions[] = [
6051
            'affects' => [
6052
                'table' => $table,
6053
                'id' => $id
6054
            ],
6055
            'callback' => $callback,
6056
            'arguments' => $arguments
6057
        ];
6058
    }
6059
6060
    /**
6061
     * If a parent record was versionized on a workspace in $this->process_datamap,
6062
     * it might be possible, that child records (e.g. on using IRRE) were affected.
6063
     * This function finds these relations and updates their uids in the $incomingFieldArray.
6064
     * The $incomingFieldArray is updated by reference!
6065
     *
6066
     * @param string $table Table name of the parent record
6067
     * @param int $id Uid of the parent record
6068
     * @param array $incomingFieldArray Reference to the incomingFieldArray of process_datamap
6069
     * @param array $registerDBList Reference to the $registerDBList array that was created/updated by versionizing calls to DataHandler in process_datamap.
6070
     * @internal should only be used from within DataHandler
6071
     */
6072
    public function getVersionizedIncomingFieldArray($table, $id, &$incomingFieldArray, &$registerDBList)
6073
    {
6074
        if (is_array($registerDBList[$table][$id])) {
6075
            foreach ($incomingFieldArray as $field => $value) {
6076
                $fieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
6077
                if ($registerDBList[$table][$id][$field] && ($foreignTable = $fieldConf['foreign_table'])) {
6078
                    $newValueArray = [];
6079
                    $origValueArray = is_array($value) ? $value : explode(',', $value);
6080
                    // Update the uids of the copied records, but also take care about new records:
6081
                    foreach ($origValueArray as $childId) {
6082
                        $newValueArray[] = $this->autoVersionIdMap[$foreignTable][$childId] ?: $childId;
6083
                    }
6084
                    // Set the changed value to the $incomingFieldArray
6085
                    $incomingFieldArray[$field] = implode(',', $newValueArray);
6086
                }
6087
            }
6088
            // Clean up the $registerDBList array:
6089
            unset($registerDBList[$table][$id]);
6090
            if (empty($registerDBList[$table])) {
6091
                unset($registerDBList[$table]);
6092
            }
6093
        }
6094
    }
6095
6096
    /**
6097
     * Simple helper method to hard delete one row from table ignoring delete TCA field
6098
     *
6099
     * @param string $table A row from this table should be deleted
6100
     * @param int $uid Uid of row to be deleted
6101
     */
6102
    protected function hardDeleteSingleRecord(string $table, int $uid): void
6103
    {
6104
        GeneralUtility::makeInstance(ConnectionPool::class)
6105
            ->getConnectionForTable($table)
6106
            ->delete($table, ['uid' => $uid], [\PDO::PARAM_INT]);
6107
    }
6108
6109
    /*****************************
6110
     *
6111
     * Access control / Checking functions
6112
     *
6113
     *****************************/
6114
    /**
6115
     * Checking group modify_table access list
6116
     *
6117
     * @param string $table Table name
6118
     * @return bool Returns TRUE if the user has general access to modify the $table
6119
     * @internal should only be used from within DataHandler
6120
     */
6121
    public function checkModifyAccessList($table)
6122
    {
6123
        $res = $this->admin || (!$this->tableAdminOnly($table) && isset($this->BE_USER->groupData['tables_modify']) && GeneralUtility::inList($this->BE_USER->groupData['tables_modify'], $table));
6124
        // Hook 'checkModifyAccessList': Post-processing of the state of access
6125
        foreach ($this->getCheckModifyAccessListHookObjects() as $hookObject) {
6126
            /** @var DataHandlerCheckModifyAccessListHookInterface $hookObject */
6127
            $hookObject->checkModifyAccessList($res, $table, $this);
6128
        }
6129
        return $res;
6130
    }
6131
6132
    /**
6133
     * Checking if a record with uid $id from $table is in the BE_USERS webmounts which is required for editing etc.
6134
     *
6135
     * @param string $table Table name
6136
     * @param int $id UID of record
6137
     * @return bool Returns TRUE if OK. Cached results.
6138
     * @internal should only be used from within DataHandler
6139
     */
6140
    public function isRecordInWebMount($table, $id)
6141
    {
6142
        if (!isset($this->isRecordInWebMount_Cache[$table . ':' . $id])) {
6143
            $recP = $this->getRecordProperties($table, $id);
6144
            $this->isRecordInWebMount_Cache[$table . ':' . $id] = $this->isInWebMount($recP['event_pid']);
6145
        }
6146
        return $this->isRecordInWebMount_Cache[$table . ':' . $id];
6147
    }
6148
6149
    /**
6150
     * Checks if the input page ID is in the BE_USER webmounts
6151
     *
6152
     * @param int $pid Page ID to check
6153
     * @return bool TRUE if OK. Cached results.
6154
     * @internal should only be used from within DataHandler
6155
     */
6156
    public function isInWebMount($pid)
6157
    {
6158
        if (!isset($this->isInWebMount_Cache[$pid])) {
6159
            $this->isInWebMount_Cache[$pid] = $this->BE_USER->isInWebMount($pid);
6160
        }
6161
        return $this->isInWebMount_Cache[$pid];
6162
    }
6163
6164
    /**
6165
     * Checks if user may update a record with uid=$id from $table
6166
     *
6167
     * @param string $table Record table
6168
     * @param int $id Record UID
6169
     * @param array|bool $data Record data
6170
     * @param array $hookObjectsArr Hook objects
6171
     * @return bool Returns TRUE if the user may update the record given by $table and $id
6172
     * @internal should only be used from within DataHandler
6173
     */
6174
    public function checkRecordUpdateAccess($table, $id, $data = false, $hookObjectsArr = null)
6175
    {
6176
        $res = null;
6177
        if (is_array($hookObjectsArr)) {
6178
            foreach ($hookObjectsArr as $hookObj) {
6179
                if (method_exists($hookObj, 'checkRecordUpdateAccess')) {
6180
                    $res = $hookObj->checkRecordUpdateAccess($table, $id, $data, $res, $this);
6181
                }
6182
            }
6183
            if (isset($res)) {
6184
                return (bool)$res;
6185
            }
6186
        }
6187
        $res = false;
6188
6189
        if ($GLOBALS['TCA'][$table] && (int)$id > 0) {
6190
            $cacheId = 'checkRecordUpdateAccess_' . $table . '_' . $id;
6191
6192
            // If information is cached, return it
6193
            $cachedValue = $this->runtimeCache->get($cacheId);
6194
            if (!empty($cachedValue)) {
6195
                return $cachedValue;
6196
            }
6197
6198
            if ($table === 'pages' || ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap))) {
6199
                // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
6200
                $perms = Permission::PAGE_EDIT;
6201
            } else {
6202
                $perms = Permission::CONTENT_EDIT;
6203
            }
6204
            if ($this->doesRecordExist($table, $id, $perms)) {
6205
                $res = 1;
6206
            }
6207
            // Cache the result
6208
            $this->runtimeCache->set($cacheId, $res);
6209
        }
6210
        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...
6211
    }
6212
6213
    /**
6214
     * Checks if user may insert a record from $insertTable on $pid
6215
     *
6216
     * @param string $insertTable Tablename to check
6217
     * @param int $pid Integer PID
6218
     * @param int $action For logging: Action number.
6219
     * @return bool Returns TRUE if the user may insert a record from table $insertTable on page $pid
6220
     * @internal should only be used from within DataHandler
6221
     */
6222
    public function checkRecordInsertAccess($insertTable, $pid, $action = SystemLogDatabaseAction::INSERT)
6223
    {
6224
        $pid = (int)$pid;
6225
        if ($pid < 0) {
6226
            return false;
6227
        }
6228
        // If information is cached, return it
6229
        if (isset($this->recInsertAccessCache[$insertTable][$pid])) {
6230
            return $this->recInsertAccessCache[$insertTable][$pid];
6231
        }
6232
6233
        $res = false;
6234
        if ($insertTable === 'pages') {
6235
            $perms = Permission::PAGE_NEW;
6236
        } elseif (($insertTable === 'sys_file_reference') && array_key_exists('pages', $this->datamap)) {
6237
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
6238
            $perms = Permission::PAGE_EDIT;
6239
        } else {
6240
            $perms = Permission::CONTENT_EDIT;
6241
        }
6242
        $pageExists = (bool)$this->doesRecordExist('pages', $pid, $perms);
6243
        // 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
6244
        if ($pageExists || $pid === 0 && ($this->admin || BackendUtility::isRootLevelRestrictionIgnored($insertTable))) {
6245
            // Check permissions
6246
            if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
6247
                $res = true;
6248
                // Cache the result
6249
                $this->recInsertAccessCache[$insertTable][$pid] = $res;
6250
            } elseif ($this->enableLogging) {
6251
                $propArr = $this->getRecordProperties('pages', $pid);
6252
                $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']);
6253
            }
6254
        } elseif ($this->enableLogging) {
6255
            $propArr = $this->getRecordProperties('pages', $pid);
6256
            $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']);
6257
        }
6258
        return $res;
6259
    }
6260
6261
    /**
6262
     * 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.
6263
     *
6264
     * @param int $page_uid Page id for which to check, including 0 (zero) if checking for page tree root.
6265
     * @param string $checkTable Table name to check
6266
     * @return bool TRUE if OK
6267
     * @internal should only be used from within DataHandler
6268
     */
6269
    public function isTableAllowedForThisPage($page_uid, $checkTable)
6270
    {
6271
        $page_uid = (int)$page_uid;
6272
        $rootLevelSetting = (int)$GLOBALS['TCA'][$checkTable]['ctrl']['rootLevel'];
6273
        // 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.
6274
        if ($checkTable !== 'pages' && $rootLevelSetting !== -1 && ($rootLevelSetting xor !$page_uid)) {
6275
            return false;
6276
        }
6277
        $allowed = false;
6278
        // Check root-level
6279
        if (!$page_uid) {
6280
            if ($this->admin || BackendUtility::isRootLevelRestrictionIgnored($checkTable)) {
6281
                $allowed = true;
6282
            }
6283
        } else {
6284
            // Check non-root-level
6285
            $doktype = $this->pageInfo($page_uid, 'doktype');
6286
            $allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
6287
            $allowedArray = GeneralUtility::trimExplode(',', $allowedTableList, true);
6288
            // If all tables or the table is listed as an allowed type, return TRUE
6289
            if (strpos($allowedTableList, '*') !== false || in_array($checkTable, $allowedArray, true)) {
6290
                $allowed = true;
6291
            }
6292
        }
6293
        return $allowed;
6294
    }
6295
6296
    /**
6297
     * Checks if record can be selected based on given permission criteria
6298
     *
6299
     * @param string $table Record table name
6300
     * @param int $id Record UID
6301
     * @param int $perms Permission restrictions to observe: integer that will be bitwise AND'ed.
6302
     * @return bool Returns TRUE if the record given by $table, $id and $perms can be selected
6303
     *
6304
     * @throws \RuntimeException
6305
     * @internal should only be used from within DataHandler
6306
     */
6307
    public function doesRecordExist($table, $id, int $perms)
6308
    {
6309
        return $this->recordInfoWithPermissionCheck($table, $id, $perms, 'uid, pid') !== false;
6310
    }
6311
6312
    /**
6313
     * Looks up a page based on permissions.
6314
     *
6315
     * @param int $id Page id
6316
     * @param int $perms Permission integer
6317
     * @param array $columns Columns to select
6318
     * @return bool|array
6319
     * @internal
6320
     * @see doesRecordExist()
6321
     */
6322
    protected function doesRecordExist_pageLookUp($id, $perms, $columns = ['uid'])
6323
    {
6324
        $permission = new Permission($perms);
6325
        $cacheId = md5('doesRecordExist_pageLookUp_' . $id . '_' . $perms . '_' . implode(
6326
            '_',
6327
            $columns
6328
        ) . '_' . (string)$this->admin);
6329
6330
        // If result is cached, return it
6331
        $cachedResult = $this->runtimeCache->get($cacheId);
6332
        if (!empty($cachedResult)) {
6333
            return $cachedResult;
6334
        }
6335
6336
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6337
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6338
        $queryBuilder
6339
            ->select(...$columns)
6340
            ->from('pages')
6341
            ->where($queryBuilder->expr()->eq(
6342
                'uid',
6343
                $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
6344
            ));
6345
        if (!$permission->nothingIsGranted() && !$this->admin) {
6346
            $queryBuilder->andWhere($this->BE_USER->getPagePermsClause($perms));
6347
        }
6348
        if (!$this->admin && $GLOBALS['TCA']['pages']['ctrl']['editlock'] &&
6349
            ($permission->editPagePermissionIsGranted() || $permission->deletePagePermissionIsGranted() || $permission->editContentPermissionIsGranted())
6350
        ) {
6351
            $queryBuilder->andWhere($queryBuilder->expr()->eq(
6352
                $GLOBALS['TCA']['pages']['ctrl']['editlock'],
6353
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
6354
            ));
6355
        }
6356
6357
        $row = $queryBuilder->execute()->fetch();
6358
        $this->runtimeCache->set($cacheId, $row);
6359
6360
        return $row;
6361
    }
6362
6363
    /**
6364
     * Checks if a whole branch of pages exists
6365
     *
6366
     * Tests the branch under $pid like doesRecordExist(), but it doesn't test the page with $pid as uid - use doesRecordExist() for this purpose.
6367
     * 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
6368
     *
6369
     * @param string $inList List of page uids, this is added to and returned in the end
6370
     * @param int $pid Page ID to select subpages from.
6371
     * @param int $perms Perms integer to check each page record for.
6372
     * @param bool $recurse Recursion flag: If set, it will go out through the branch.
6373
     * @return string|int List of page IDs in branch, if there are subpages, empty string if there are none or -1 if no permission
6374
     * @internal should only be used from within DataHandler
6375
     */
6376
    public function doesBranchExist($inList, $pid, $perms, $recurse)
6377
    {
6378
        $pid = (int)$pid;
6379
        $perms = (int)$perms;
6380
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6381
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6382
        $result = $queryBuilder
6383
            ->select('uid', 'perms_userid', 'perms_groupid', 'perms_user', 'perms_group', 'perms_everybody')
6384
            ->from('pages')
6385
            ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
6386
            ->orderBy('sorting')
6387
            ->execute();
6388
        while ($row = $result->fetch()) {
6389
            // IF admin, then it's OK
6390
            if ($this->admin || $this->BE_USER->doesUserHaveAccess($row, $perms)) {
6391
                $inList .= $row['uid'] . ',';
6392
                if ($recurse) {
6393
                    // Follow the subpages recursively...
6394
                    $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
6395
                    if ($inList === -1) {
6396
                        return -1;
6397
                    }
6398
                }
6399
            } else {
6400
                // No permissions
6401
                return -1;
6402
            }
6403
        }
6404
        return $inList;
6405
    }
6406
6407
    /**
6408
     * Checks if the $table is readOnly
6409
     *
6410
     * @param string $table Table name
6411
     * @return bool TRUE, if readonly
6412
     * @internal should only be used from within DataHandler
6413
     */
6414
    public function tableReadOnly($table)
6415
    {
6416
        // Returns TRUE if table is readonly
6417
        return (bool)$GLOBALS['TCA'][$table]['ctrl']['readOnly'];
6418
    }
6419
6420
    /**
6421
     * Checks if the $table is only editable by admin-users
6422
     *
6423
     * @param string $table Table name
6424
     * @return bool TRUE, if readonly
6425
     * @internal should only be used from within DataHandler
6426
     */
6427
    public function tableAdminOnly($table)
6428
    {
6429
        // Returns TRUE if table is admin-only
6430
        return !empty($GLOBALS['TCA'][$table]['ctrl']['adminOnly']);
6431
    }
6432
6433
    /**
6434
     * Checks if page $id is a uid in the rootline of page id $destinationId
6435
     * Used when moving a page
6436
     *
6437
     * @param int $destinationId Destination Page ID to test
6438
     * @param int $id Page ID to test for presence inside Destination
6439
     * @return bool Returns FALSE if ID is inside destination (including equal to)
6440
     * @internal should only be used from within DataHandler
6441
     */
6442
    public function destNotInsideSelf($destinationId, $id)
6443
    {
6444
        $loopCheck = 100;
6445
        $destinationId = (int)$destinationId;
6446
        $id = (int)$id;
6447
        if ($destinationId === $id) {
6448
            return false;
6449
        }
6450
        while ($destinationId !== 0 && $loopCheck > 0) {
6451
            $loopCheck--;
6452
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6453
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6454
            $result = $queryBuilder
6455
                ->select('pid', 'uid', 't3ver_oid', 't3ver_wsid')
6456
                ->from('pages')
6457
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($destinationId, \PDO::PARAM_INT)))
6458
                ->execute();
6459
            if ($row = $result->fetch()) {
6460
                // Ensure that the moved location is used as the PID value
6461
                BackendUtility::workspaceOL('pages', $row, $this->BE_USER->workspace);
6462
                if ($row['pid'] == $id) {
6463
                    return false;
6464
                }
6465
                $destinationId = (int)$row['pid'];
6466
            } else {
6467
                return false;
6468
            }
6469
        }
6470
        return true;
6471
    }
6472
6473
    /**
6474
     * 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
6475
     * Will also generate this list for admin-users so they must be check for before calling the function
6476
     *
6477
     * @return array Array of [table]-[field] pairs to exclude from editing.
6478
     * @internal should only be used from within DataHandler
6479
     */
6480
    public function getExcludeListArray()
6481
    {
6482
        $list = [];
6483
        if (isset($this->BE_USER->groupData['non_exclude_fields'])) {
6484
            $nonExcludeFieldsArray = array_flip(GeneralUtility::trimExplode(',', $this->BE_USER->groupData['non_exclude_fields']));
6485
            foreach ($GLOBALS['TCA'] as $table => $tableConfiguration) {
6486
                if (isset($tableConfiguration['columns'])) {
6487
                    foreach ($tableConfiguration['columns'] as $field => $config) {
6488
                        $isExcludeField = ($config['exclude'] ?? false);
6489
                        $isOnlyVisibleForAdmins = ($GLOBALS['TCA'][$table]['columns'][$field]['displayCond'] ?? '') === 'HIDE_FOR_NON_ADMINS';
6490
                        $editorHasPermissionForThisField = isset($nonExcludeFieldsArray[$table . ':' . $field]);
6491
                        if ($isOnlyVisibleForAdmins || ($isExcludeField && !$editorHasPermissionForThisField)) {
6492
                            $list[] = $table . '-' . $field;
6493
                        }
6494
                    }
6495
                }
6496
            }
6497
        }
6498
6499
        return $list;
6500
    }
6501
6502
    /**
6503
     * Checks if there are records on a page from tables that are not allowed
6504
     *
6505
     * @param int $page_uid Page ID
6506
     * @param int $doktype Page doktype
6507
     * @return bool|array Returns a list of the tables that are 'present' on the page but not allowed with the page_uid/doktype
6508
     * @internal should only be used from within DataHandler
6509
     */
6510
    public function doesPageHaveUnallowedTables($page_uid, $doktype)
6511
    {
6512
        $page_uid = (int)$page_uid;
6513
        if (!$page_uid) {
6514
            // Not a number. Probably a new page
6515
            return false;
6516
        }
6517
        $allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
6518
        // If all tables are allowed, return early
6519
        if (strpos($allowedTableList, '*') !== false) {
6520
            return false;
6521
        }
6522
        $allowedArray = GeneralUtility::trimExplode(',', $allowedTableList, true);
6523
        $tableList = [];
6524
        $allTableNames = $this->compileAdminTables();
6525
        foreach ($allTableNames as $table) {
6526
            // If the table is not in the allowed list, check if there are records...
6527
            if (in_array($table, $allowedArray, true)) {
6528
                continue;
6529
            }
6530
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6531
            $queryBuilder->getRestrictions()->removeAll();
6532
            $count = $queryBuilder
6533
                ->count('uid')
6534
                ->from($table)
6535
                ->where($queryBuilder->expr()->eq(
6536
                    'pid',
6537
                    $queryBuilder->createNamedParameter($page_uid, \PDO::PARAM_INT)
6538
                ))
6539
                ->execute()
6540
                ->fetchColumn(0);
6541
            if ($count) {
6542
                $tableList[] = $table;
6543
            }
6544
        }
6545
        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...
6546
    }
6547
6548
    /*****************************
6549
     *
6550
     * Information lookup
6551
     *
6552
     *****************************/
6553
    /**
6554
     * Returns the value of the $field from page $id
6555
     * 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!
6556
     *
6557
     * @param int $id Page uid
6558
     * @param string $field Field name for which to return value
6559
     * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
6560
     * @internal should only be used from within DataHandler
6561
     */
6562
    public function pageInfo($id, $field)
6563
    {
6564
        if (!isset($this->pageCache[$id])) {
6565
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6566
            $queryBuilder->getRestrictions()->removeAll();
6567
            $row = $queryBuilder
6568
                ->select('*')
6569
                ->from('pages')
6570
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6571
                ->execute()
6572
                ->fetch();
6573
            if ($row) {
6574
                $this->pageCache[$id] = $row;
6575
            }
6576
        }
6577
        return $this->pageCache[$id][$field];
6578
    }
6579
6580
    /**
6581
     * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
6582
     * NOTICE: No check for deleted or access!
6583
     *
6584
     * @param string $table Table name
6585
     * @param int $id UID of the record from $table
6586
     * @param string $fieldList Field list for the SELECT query, eg. "*" or "uid,pid,...
6587
     * @return array|null Returns the selected record on success, otherwise NULL.
6588
     * @internal should only be used from within DataHandler
6589
     */
6590
    public function recordInfo($table, $id, $fieldList)
6591
    {
6592
        // Skip, if searching for NEW records or there's no TCA table definition
6593
        if ((int)$id === 0 || !isset($GLOBALS['TCA'][$table])) {
6594
            return null;
6595
        }
6596
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6597
        $queryBuilder->getRestrictions()->removeAll();
6598
        $result = $queryBuilder
6599
            ->select(...GeneralUtility::trimExplode(',', $fieldList))
6600
            ->from($table)
6601
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6602
            ->execute()
6603
            ->fetch();
6604
        return $result ?: null;
6605
    }
6606
6607
    /**
6608
     * Checks if record exists with and without permission check and returns that row
6609
     *
6610
     * @param string $table Record table name
6611
     * @param int $id Record UID
6612
     * @param int $perms Permission restrictions to observe: An integer that will be bitwise AND'ed.
6613
     * @param string $fieldList - fields - default is '*'
6614
     * @throws \RuntimeException
6615
     * @return array|bool Row if exists and accessible, false otherwise
6616
     */
6617
    protected function recordInfoWithPermissionCheck(string $table, int $id, int $perms, string $fieldList = '*')
6618
    {
6619
        if ($this->bypassAccessCheckForRecords) {
6620
            $columns = GeneralUtility::trimExplode(',', $fieldList, true);
6621
6622
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6623
            $queryBuilder->getRestrictions()->removeAll();
6624
6625
            $record = $queryBuilder->select(...$columns)
6626
                ->from($table)
6627
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6628
                ->execute()
6629
                ->fetch();
6630
6631
            return $record ?: false;
6632
        }
6633
        if (!$perms) {
6634
            throw new \RuntimeException('Internal ERROR: no permissions to check for non-admin user', 1270853920);
6635
        }
6636
        // For all tables: Check if record exists:
6637
        $isWebMountRestrictionIgnored = BackendUtility::isWebMountRestrictionIgnored($table);
6638
        if (is_array($GLOBALS['TCA'][$table]) && $id > 0 && ($this->admin || $isWebMountRestrictionIgnored || $this->isRecordInWebMount($table, $id))) {
6639
            $columns = GeneralUtility::trimExplode(',', $fieldList, true);
6640
            if ($table !== 'pages') {
6641
                // Find record without checking page
6642
                // @todo: This should probably check for editlock
6643
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6644
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6645
                $output = $queryBuilder
6646
                    ->select(...$columns)
6647
                    ->from($table)
6648
                    ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6649
                    ->execute()
6650
                    ->fetch();
6651
                // If record found, check page as well:
6652
                if (is_array($output)) {
6653
                    // Looking up the page for record:
6654
                    $pageRec = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
6655
                    // 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):
6656
                    $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
6657
                    if (is_array($pageRec) || !$output['pid'] && ($this->admin || $isRootLevelRestrictionIgnored)) {
6658
                        return $output;
6659
                    }
6660
                }
6661
                return false;
6662
            }
6663
            return $this->doesRecordExist_pageLookUp($id, $perms, $columns);
6664
        }
6665
        return false;
6666
    }
6667
6668
    /**
6669
     * Returns an array with record properties, like header and pid
6670
     * No check for deleted or access is done!
6671
     * For versionized records, pid is resolved to its live versions pid.
6672
     * Used for logging
6673
     *
6674
     * @param string $table Table name
6675
     * @param int $id Uid of record
6676
     * @param bool $noWSOL If set, no workspace overlay is performed
6677
     * @return array Properties of record
6678
     * @internal should only be used from within DataHandler
6679
     */
6680
    public function getRecordProperties($table, $id, $noWSOL = false)
6681
    {
6682
        $row = $table === 'pages' && !$id ? ['title' => '[root-level]', 'uid' => 0, 'pid' => 0] : $this->recordInfo($table, $id, '*');
6683
        if (!$noWSOL) {
6684
            BackendUtility::workspaceOL($table, $row);
6685
        }
6686
        return $this->getRecordPropertiesFromRow($table, $row);
6687
    }
6688
6689
    /**
6690
     * Returns an array with record properties, like header and pid, based on the row
6691
     *
6692
     * @param string $table Table name
6693
     * @param array $row Input row
6694
     * @return array|null Output array
6695
     * @internal should only be used from within DataHandler
6696
     */
6697
    public function getRecordPropertiesFromRow($table, $row)
6698
    {
6699
        if ($GLOBALS['TCA'][$table]) {
6700
            $liveUid = ($row['t3ver_oid'] ?? null) ? $row['t3ver_oid'] : $row['uid'];
6701
            return [
6702
                'header' => BackendUtility::getRecordTitle($table, $row),
6703
                'pid' => $row['pid'],
6704
                'event_pid' => $this->eventPid($table, (int)$liveUid, $row['pid']),
6705
                't3ver_state' => BackendUtility::isTableWorkspaceEnabled($table) ? $row['t3ver_state'] : ''
6706
            ];
6707
        }
6708
        return null;
6709
    }
6710
6711
    /**
6712
     * @param string $table
6713
     * @param int $uid
6714
     * @param int $pid
6715
     * @return int
6716
     * @internal should only be used from within DataHandler
6717
     */
6718
    public function eventPid($table, $uid, $pid)
6719
    {
6720
        return $table === 'pages' ? $uid : $pid;
6721
    }
6722
6723
    /*********************************************
6724
     *
6725
     * Storing data to Database Layer
6726
     *
6727
     ********************************************/
6728
    /**
6729
     * Update database record
6730
     * Does not check permissions but expects them to be verified on beforehand
6731
     *
6732
     * @param string $table Record table name
6733
     * @param int $id Record uid
6734
     * @param array $fieldArray Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
6735
     * @internal should only be used from within DataHandler
6736
     */
6737
    public function updateDB($table, $id, $fieldArray)
6738
    {
6739
        if (is_array($fieldArray) && is_array($GLOBALS['TCA'][$table]) && (int)$id) {
6740
            // Do NOT update the UID field, ever!
6741
            unset($fieldArray['uid']);
6742
            if (!empty($fieldArray)) {
6743
                $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
6744
6745
                $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
6746
6747
                $types = [];
6748
                $platform = $connection->getDatabasePlatform();
6749
                if ($platform instanceof SQLServerPlatform) {
6750
                    // mssql needs to set proper PARAM_LOB and others to update fields
6751
                    $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
6752
                    foreach ($fieldArray as $columnName => $columnValue) {
6753
                        $types[$columnName] = $tableDetails->getColumn($columnName)->getType()->getBindingType();
6754
                    }
6755
                }
6756
6757
                // Execute the UPDATE query:
6758
                $updateErrorMessage = '';
6759
                try {
6760
                    $connection->update($table, $fieldArray, ['uid' => (int)$id], $types);
6761
                } catch (DBALException $e) {
6762
                    $updateErrorMessage = $e->getPrevious()->getMessage();
6763
                }
6764
                // If succeeds, do...:
6765
                if ($updateErrorMessage === '') {
6766
                    // Update reference index:
6767
                    $this->updateRefIndex($table, $id);
6768
                    // Set History data
6769
                    $historyEntryId = 0;
6770
                    if (isset($this->historyRecords[$table . ':' . $id])) {
6771
                        $historyEntryId = $this->getRecordHistoryStore()->modifyRecord($table, $id, $this->historyRecords[$table . ':' . $id], $this->correlationId);
6772
                    }
6773
                    if ($this->enableLogging) {
6774
                        if ($this->checkStoredRecords) {
6775
                            $newRow = $this->checkStoredRecord($table, $id, $fieldArray, SystemLogDatabaseAction::UPDATE);
6776
                        } else {
6777
                            $newRow = $fieldArray;
6778
                            $newRow['uid'] = $id;
6779
                        }
6780
                        // Set log entry:
6781
                        $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
6782
                        $isOfflineVersion = (bool)($newRow['t3ver_oid'] ?? 0);
6783
                        $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']);
6784
                    }
6785
                    // Clear cache for relevant pages:
6786
                    $this->registerRecordIdForPageCacheClearing($table, $id);
6787
                    // Unset the pageCache for the id if table was page.
6788
                    if ($table === 'pages') {
6789
                        unset($this->pageCache[$id]);
6790
                    }
6791
                } else {
6792
                    $this->log($table, $id, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$updateErrorMessage, $table . ':' . $id]);
6793
                }
6794
            }
6795
        }
6796
    }
6797
6798
    /**
6799
     * Insert into database
6800
     * Does not check permissions but expects them to be verified on beforehand
6801
     *
6802
     * @param string $table Record table name
6803
     * @param string $id "NEW...." uid string
6804
     * @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!
6805
     * @param bool $newVersion Set to TRUE if new version is created.
6806
     * @param int $suggestedUid Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
6807
     * @param bool $dontSetNewIdIndex If TRUE, the ->substNEWwithIDs array is not updated. Only useful in very rare circumstances!
6808
     * @return int|null Returns ID on success.
6809
     * @internal should only be used from within DataHandler
6810
     */
6811
    public function insertDB($table, $id, $fieldArray, $newVersion = false, $suggestedUid = 0, $dontSetNewIdIndex = false)
6812
    {
6813
        if (is_array($fieldArray) && is_array($GLOBALS['TCA'][$table]) && isset($fieldArray['pid'])) {
6814
            // Do NOT insert the UID field, ever!
6815
            unset($fieldArray['uid']);
6816
            if (!empty($fieldArray)) {
6817
                // Check for "suggestedUid".
6818
                // This feature is used by the import functionality to force a new record to have a certain UID value.
6819
                // This is only recommended for use when the destination server is a passive mirror of another server.
6820
                // As a security measure this feature is available only for Admin Users (for now)
6821
                $suggestedUid = (int)$suggestedUid;
6822
                if ($this->BE_USER->isAdmin() && $suggestedUid && $this->suggestedInsertUids[$table . ':' . $suggestedUid]) {
6823
                    // When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
6824
                    if ($this->suggestedInsertUids[$table . ':' . $suggestedUid] === 'DELETE') {
6825
                        $this->hardDeleteSingleRecord($table, (int)$suggestedUid);
6826
                    }
6827
                    $fieldArray['uid'] = $suggestedUid;
6828
                }
6829
                $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
6830
                $typeArray = [];
6831
                if (!empty($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'])
6832
                    && array_key_exists($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'], $fieldArray)
6833
                ) {
6834
                    $typeArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = Connection::PARAM_LOB;
6835
                }
6836
                $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
6837
                $insertErrorMessage = '';
6838
                try {
6839
                    // Execute the INSERT query:
6840
                    $connection->insert(
6841
                        $table,
6842
                        $fieldArray,
6843
                        $typeArray
6844
                    );
6845
                } catch (DBALException $e) {
6846
                    $insertErrorMessage = $e->getPrevious()->getMessage();
6847
                }
6848
                // If succees, do...:
6849
                if ($insertErrorMessage === '') {
6850
                    // Set mapping for NEW... -> real uid:
6851
                    // the NEW_id now holds the 'NEW....' -id
6852
                    $NEW_id = $id;
6853
                    $id = $this->postProcessDatabaseInsert($connection, $table, $suggestedUid);
6854
6855
                    if (!$dontSetNewIdIndex) {
6856
                        $this->substNEWwithIDs[$NEW_id] = $id;
6857
                        $this->substNEWwithIDs_table[$NEW_id] = $table;
6858
                    }
6859
                    $newRow = [];
6860
                    if ($this->enableLogging) {
6861
                        // Checking the record is properly saved if configured
6862
                        if ($this->checkStoredRecords) {
6863
                            $newRow = $this->checkStoredRecord($table, $id, $fieldArray, SystemLogDatabaseAction::INSERT);
6864
                        } else {
6865
                            $newRow = $fieldArray;
6866
                            $newRow['uid'] = $id;
6867
                        }
6868
                    }
6869
                    // Update reference index:
6870
                    $this->updateRefIndex($table, $id);
6871
6872
                    // Store in history
6873
                    $this->getRecordHistoryStore()->addRecord($table, $id, $newRow, $this->correlationId);
0 ignored issues
show
Bug introduced by
It seems like $newRow can also be of type null; however, parameter $payload of TYPO3\CMS\Core\DataHandl...storyStore::addRecord() 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

6873
                    $this->getRecordHistoryStore()->addRecord($table, $id, /** @scrutinizer ignore-type */ $newRow, $this->correlationId);
Loading history...
6874
6875
                    if ($newVersion) {
6876
                        if ($this->enableLogging) {
6877
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
6878
                            $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);
6879
                        }
6880
                    } else {
6881
                        if ($this->enableLogging) {
6882
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
6883
                            $page_propArr = $this->getRecordProperties('pages', $propArr['pid']);
6884
                            $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);
6885
                        }
6886
                        // Clear cache for relevant pages:
6887
                        $this->registerRecordIdForPageCacheClearing($table, $id);
6888
                    }
6889
                    return $id;
6890
                }
6891
                if ($this->enableLogging) {
6892
                    $this->log($table, $id, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$insertErrorMessage, $table . ':' . $id]);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $recuid of TYPO3\CMS\Core\DataHandling\DataHandler::log(). ( Ignorable by Annotation )

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

6892
                    $this->log($table, /** @scrutinizer ignore-type */ $id, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$insertErrorMessage, $table . ':' . $id]);
Loading history...
6893
                }
6894
            }
6895
        }
6896
        return null;
6897
    }
6898
6899
    /**
6900
     * Checking stored record to see if the written values are properly updated.
6901
     *
6902
     * @param string $table Record table name
6903
     * @param int $id Record uid
6904
     * @param array $fieldArray Array of field=>value pairs to insert/update
6905
     * @param string $action Action, for logging only.
6906
     * @return array|null Selected row
6907
     * @see insertDB()
6908
     * @see updateDB()
6909
     * @internal should only be used from within DataHandler
6910
     */
6911
    public function checkStoredRecord($table, $id, $fieldArray, $action)
6912
    {
6913
        $id = (int)$id;
6914
        if (is_array($GLOBALS['TCA'][$table]) && $id) {
6915
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6916
            $queryBuilder->getRestrictions()->removeAll();
6917
6918
            $row = $queryBuilder
6919
                ->select('*')
6920
                ->from($table)
6921
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6922
                ->execute()
6923
                ->fetch();
6924
6925
            if (!empty($row)) {
6926
                // Traverse array of values that was inserted into the database and compare with the actually stored value:
6927
                $errors = [];
6928
                foreach ($fieldArray as $key => $value) {
6929
                    if (!$this->checkStoredRecords_loose || $value || $row[$key]) {
6930
                        if (is_float($row[$key])) {
6931
                            // if the database returns the value as double, compare it as double
6932
                            if ((double)$value !== (double)$row[$key]) {
6933
                                $errors[] = $key;
6934
                            }
6935
                        } else {
6936
                            $dbType = $GLOBALS['TCA'][$table]['columns'][$key]['config']['dbType'] ?? false;
6937
                            if ($dbType === 'datetime' || $dbType === 'time') {
6938
                                $row[$key] = $this->normalizeTimeFormat($table, $row[$key], $dbType);
6939
                            }
6940
                            if ((string)$value !== (string)$row[$key]) {
6941
                                // The is_numeric check catches cases where we want to store a float/double value
6942
                                // and database returns the field as a string with the least required amount of
6943
                                // significant digits, i.e. "0.00" being saved and "0" being read back.
6944
                                if (is_numeric($value) && is_numeric($row[$key])) {
6945
                                    if ((double)$value === (double)$row[$key]) {
6946
                                        continue;
6947
                                    }
6948
                                }
6949
                                $errors[] = $key;
6950
                            }
6951
                        }
6952
                    }
6953
                }
6954
                // Set log message if there were fields with unmatching values:
6955
                if (!empty($errors)) {
6956
                    $message = sprintf(
6957
                        '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.',
6958
                        $id,
6959
                        $table,
6960
                        implode(', ', $errors)
6961
                    );
6962
                    $this->log($table, $id, $action, 0, SystemLogErrorClassification::USER_ERROR, $message);
0 ignored issues
show
Bug introduced by
$action of type string is incompatible with the type integer expected by parameter $action of TYPO3\CMS\Core\DataHandling\DataHandler::log(). ( Ignorable by Annotation )

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

6962
                    $this->log($table, $id, /** @scrutinizer ignore-type */ $action, 0, SystemLogErrorClassification::USER_ERROR, $message);
Loading history...
6963
                }
6964
                // Return selected rows:
6965
                return $row;
6966
            }
6967
        }
6968
        return null;
6969
    }
6970
6971
    /**
6972
     * Setting sys_history record, based on content previously set in $this->historyRecords[$table . ':' . $id] (by compareFieldArrayWithCurrentAndUnset())
6973
     *
6974
     * This functionality is now moved into the RecordHistoryStore and can be used instead.
6975
     *
6976
     * @param string $table Table name
6977
     * @param int $id Record ID
6978
     * @internal should only be used from within DataHandler
6979
     */
6980
    public function setHistory($table, $id)
6981
    {
6982
        if (isset($this->historyRecords[$table . ':' . $id])) {
6983
            $this->getRecordHistoryStore()->modifyRecord(
6984
                $table,
6985
                $id,
6986
                $this->historyRecords[$table . ':' . $id],
6987
                $this->correlationId
6988
            );
6989
        }
6990
    }
6991
6992
    /**
6993
     * @return RecordHistoryStore
6994
     */
6995
    protected function getRecordHistoryStore(): RecordHistoryStore
6996
    {
6997
        return GeneralUtility::makeInstance(
6998
            RecordHistoryStore::class,
6999
            RecordHistoryStore::USER_BACKEND,
7000
            $this->BE_USER->user['uid'],
7001
            $this->BE_USER->user['ses_backuserid'] ?? null,
7002
            $GLOBALS['EXEC_TIME'],
7003
            $this->BE_USER->workspace
7004
        );
7005
    }
7006
7007
    /**
7008
     * Register a table/uid combination in current user workspace for reference updating.
7009
     * Should be called on almost any update to a record which could affect references inside the record.
7010
     *
7011
     * @param string $table Table name
7012
     * @param int $uid Record UID
7013
     * @param int $workspace Workspace the record lives in
7014
     * @internal should only be used from within DataHandler
7015
     */
7016
    public function updateRefIndex($table, $uid, int $workspace = null): void
7017
    {
7018
        if ($workspace === null) {
7019
            $workspace = (int)$this->BE_USER->workspace;
7020
        }
7021
        $this->referenceIndexUpdater->registerForUpdate((string)$table, (int)$uid, $workspace);
7022
    }
7023
7024
    /**
7025
     * Delete rows from sys_refindex a table / uid combination is involved in:
7026
     * Either on left side (tablename + recuid) OR right side (ref_table + ref_uid).
7027
     * Useful in scenarios like workspace-discard where parents or children are hard deleted: The
7028
     * expensive updateRefIndex() does not need to be called since we can just drop straight ahead.
7029
     *
7030
     * @param string $table Table name, used as tablename and ref_table
7031
     * @param int $uid Record uid, used as recuid and ref_uid
7032
     * @param int $workspace Workspace the record lives in
7033
     */
7034
    public function registerReferenceIndexRowsForDrop(string $table, int $uid, int $workspace): void
7035
    {
7036
        $this->referenceIndexUpdater->registerForDrop($table, $uid, $workspace);
7037
    }
7038
7039
    /*********************************************
7040
     *
7041
     * Misc functions
7042
     *
7043
     ********************************************/
7044
    /**
7045
     * Returning sorting number for tables with a "sortby" column
7046
     * Using when new records are created and existing records are moved around.
7047
     *
7048
     * The strategy is:
7049
     *  - if no record exists: set interval as sorting number
7050
     *  - if inserted before an element: put in the middle of the existing elements
7051
     *  - if inserted behind the last element: add interval to last sorting number
7052
     *  - if collision: move all subsequent records by 2 * interval, insert new record with collision + interval
7053
     *
7054
     * How to calculate the maximum possible inserts for the worst case of adding all records to the top,
7055
     * such that the sorting number stays within INT_MAX
7056
     *
7057
     * i = interval (currently 256)
7058
     * c = number of inserts until collision
7059
     * s = max sorting number to reach (INT_MAX - 32bit)
7060
     * n = number of records (~83 million)
7061
     *
7062
     * c = 2 * g
7063
     * g = log2(i) / 2 + 1
7064
     * n = g * s / i - g + 1
7065
     *
7066
     * The algorithm can be tuned by adjusting the interval value.
7067
     * Higher value means less collisions, but also less inserts are possible to stay within INT_MAX.
7068
     *
7069
     * @param string $table Table name
7070
     * @param int $uid Uid of record to find sorting number for. May be zero in case of new.
7071
     * @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)
7072
     * @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.
7073
     * @internal should only be used from within DataHandler
7074
     */
7075
    public function getSortNumber($table, $uid, $pid)
7076
    {
7077
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7078
        if (!$sortColumn) {
7079
            return null;
7080
        }
7081
7082
        $considerWorkspaces = BackendUtility::isTableWorkspaceEnabled($table);
7083
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
7084
        $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
7085
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7086
7087
        $queryBuilder
7088
            ->select($sortColumn, 'pid', 'uid')
7089
            ->from($table);
7090
        if ($considerWorkspaces) {
7091
            $queryBuilder->addSelect('t3ver_state');
7092
        }
7093
7094
        // find and return the sorting value for the first record on that pid
7095
        if ($pid >= 0) {
7096
            // Fetches the first record (lowest sorting) under this pid
7097
            $queryBuilder
7098
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)));
7099
7100
            if ($considerWorkspaces) {
7101
                $queryBuilder->andWhere(
7102
                    $queryBuilder->expr()->orX(
7103
                        $queryBuilder->expr()->eq('t3ver_oid', 0),
7104
                        $queryBuilder->expr()->eq('t3ver_state', VersionState::MOVE_POINTER)
7105
                    )
7106
                );
7107
            }
7108
            $row = $queryBuilder
7109
                ->orderBy($sortColumn, 'ASC')
7110
                ->addOrderBy('uid', 'ASC')
7111
                ->setMaxResults(1)
7112
                ->execute()
7113
                ->fetch();
7114
7115
            if (!empty($row)) {
7116
                // The top record was the record itself, so we return its current sorting value
7117
                if ($row['uid'] == $uid) {
7118
                    return $row[$sortColumn];
7119
                }
7120
                // If the record sorting value < 1 we must resort all the records under this pid
7121
                if ($row[$sortColumn] < 1) {
7122
                    $this->increaseSortingOfFollowingRecords($table, (int)$pid);
7123
                    // Lowest sorting value after full resorting is $sortIntervals
7124
                    return $this->sortIntervals;
7125
                }
7126
                // Sorting number between current top element and zero
7127
                return floor($row[$sortColumn] / 2);
7128
            }
7129
            // No records, so we choose the default value as sorting-number
7130
            return $this->sortIntervals;
7131
        }
7132
7133
        // Find and return first possible sorting value AFTER record with given uid ($pid)
7134
        // Fetches the record which is supposed to be the prev record
7135
        $row = $queryBuilder
7136
                ->where($queryBuilder->expr()->eq(
7137
                    'uid',
7138
                    $queryBuilder->createNamedParameter(abs($pid), \PDO::PARAM_INT)
7139
                ))
7140
                ->execute()
7141
                ->fetch();
7142
7143
        // There is a previous record
7144
        if (!empty($row)) {
7145
            // Look if the record UID happens to be a versioned record. If so, find its live version.
7146
            // If this is already a moved record in workspace, this is not needed
7147
            if ((int)$row['t3ver_state'] !== VersionState::MOVE_POINTER && $lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $row['uid'], $sortColumn . ',pid,uid')) {
7148
                $row = $lookForLiveVersion;
7149
            } elseif ($considerWorkspaces && $this->BE_USER->workspace > 0) {
7150
                // In case the previous record is moved in the workspace, we need to fetch the information from this specific record
7151
                $versionedRecord = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $row['uid'], $sortColumn . ',pid,uid,t3ver_state');
7152
                if (is_array($versionedRecord) && (int)$versionedRecord['t3ver_state'] === VersionState::MOVE_POINTER) {
7153
                    $row = $versionedRecord;
7154
                }
7155
            }
7156
            // If the record should be inserted after itself, keep the current sorting information:
7157
            if ((int)$row['uid'] === (int)$uid) {
7158
                $sortNumber = $row[$sortColumn];
7159
            } else {
7160
                $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
7161
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7162
7163
                $queryBuilder
7164
                        ->select($sortColumn, 'pid', 'uid')
7165
                        ->from($table)
7166
                        ->where(
7167
                            $queryBuilder->expr()->eq(
7168
                                'pid',
7169
                                $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
7170
                            ),
7171
                            $queryBuilder->expr()->gte(
7172
                                $sortColumn,
7173
                                $queryBuilder->createNamedParameter($row[$sortColumn], \PDO::PARAM_INT)
7174
                            )
7175
                        )
7176
                        ->orderBy($sortColumn, 'ASC')
7177
                        ->addOrderBy('uid', 'DESC')
7178
                        ->setMaxResults(2);
7179
7180
                if ($considerWorkspaces) {
7181
                    $queryBuilder->andWhere(
7182
                        $queryBuilder->expr()->orX(
7183
                            $queryBuilder->expr()->eq('t3ver_oid', 0),
7184
                            $queryBuilder->expr()->eq('t3ver_state', VersionState::MOVE_POINTER)
7185
                        )
7186
                    );
7187
                }
7188
7189
                $subResults = $queryBuilder
7190
                    ->execute()
7191
                    ->fetchAll();
7192
                // Fetches the next record in order to calculate the in-between sortNumber
7193
                // There was a record afterwards
7194
                if (count($subResults) === 2) {
7195
                    // There was a record afterwards, fetch that
7196
                    $subrow = array_pop($subResults);
7197
                    // The sortNumber is found in between these values
7198
                    $sortNumber = $row[$sortColumn] + floor(($subrow[$sortColumn] - $row[$sortColumn]) / 2);
7199
                    // The sortNumber happened NOT to be between the two surrounding numbers, so we'll have to resort the list
7200
                    if ($sortNumber <= $row[$sortColumn] || $sortNumber >= $subrow[$sortColumn]) {
7201
                        $this->increaseSortingOfFollowingRecords($table, (int)$row['pid'], (int)$row[$sortColumn]);
7202
                        $sortNumber = $row[$sortColumn] + $this->sortIntervals;
7203
                    }
7204
                } else {
7205
                    // If after the last record in the list, we just add the sortInterval to the last sortvalue
7206
                    $sortNumber = $row[$sortColumn] + $this->sortIntervals;
7207
                }
7208
            }
7209
            return ['pid' => $row['pid'], 'sortNumber' => $sortNumber];
7210
        }
7211
        if ($this->enableLogging) {
7212
            $propArr = $this->getRecordProperties($table, $uid);
7213
            // OK, don't insert $propArr['event_pid'] here...
7214
            $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']);
7215
        }
7216
        // There MUST be a previous record or else this cannot work
7217
        return false;
7218
    }
7219
7220
    /**
7221
     * Increases sorting field value of all records with sorting higher than $sortingValue
7222
     *
7223
     * Used internally by getSortNumber() to "make space" in sorting values when inserting new record
7224
     *
7225
     * @param string $table Table name
7226
     * @param int $pid Page Uid in which to resort records
7227
     * @param int $sortingValue All sorting numbers larger than this number will be shifted
7228
     * @see getSortNumber()
7229
     */
7230
    protected function increaseSortingOfFollowingRecords(string $table, int $pid, int $sortingValue = null): void
7231
    {
7232
        $sortBy = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7233
        if ($sortBy) {
7234
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7235
7236
            $queryBuilder
7237
                ->update($table)
7238
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
7239
                ->set($sortBy, $queryBuilder->quoteIdentifier($sortBy) . ' + ' . $this->sortIntervals . ' + ' . $this->sortIntervals, false);
7240
            if ($sortingValue !== null) {
7241
                $queryBuilder->andWhere($queryBuilder->expr()->gt($sortBy, $sortingValue));
7242
            }
7243
            if (BackendUtility::isTableWorkspaceEnabled($table)) {
7244
                $queryBuilder
7245
                    ->andWhere(
7246
                        $queryBuilder->expr()->eq('t3ver_oid', 0)
7247
                    );
7248
            }
7249
7250
            $deleteColumn = $GLOBALS['TCA'][$table]['ctrl']['delete'] ?? '';
7251
            if ($deleteColumn) {
7252
                $queryBuilder->andWhere($queryBuilder->expr()->eq($deleteColumn, 0));
7253
            }
7254
7255
            $queryBuilder->execute();
7256
        }
7257
    }
7258
7259
    /**
7260
     * Returning uid of previous localized record, if any, for tables with a "sortby" column
7261
     * Used when new localized records are created so that localized records are sorted in the same order as the default language records
7262
     *
7263
     * For a given record (A) uid (record we're translating) it finds first default language record (from the same colpos)
7264
     * with sorting smaller than given record (B).
7265
     * Then it fetches a translated version of record B and returns it's uid.
7266
     *
7267
     * If there is no record B, or it has no translation in given language, the record A uid is returned.
7268
     * The localized record will be placed the after record which uid is returned.
7269
     *
7270
     * @param string $table Table name
7271
     * @param int $uid Uid of default language record
7272
     * @param int $pid Pid of default language record
7273
     * @param int $language Language of localization
7274
     * @return int uid of record after which the localized record should be inserted
7275
     */
7276
    protected function getPreviousLocalizedRecordUid($table, $uid, $pid, $language)
7277
    {
7278
        $previousLocalizedRecordUid = $uid;
7279
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7280
        if ($sortColumn) {
7281
            $select = [$sortColumn, 'pid', 'uid'];
7282
            // For content elements, we also need the colPos
7283
            if ($table === 'tt_content') {
7284
                $select[] = 'colPos';
7285
            }
7286
            // Get the sort value of the default language record
7287
            $row = BackendUtility::getRecord($table, $uid, implode(',', $select));
7288
            if (is_array($row)) {
7289
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7290
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7291
7292
                $queryBuilder
7293
                    ->select(...$select)
7294
                    ->from($table)
7295
                    ->where(
7296
                        $queryBuilder->expr()->eq(
7297
                            'pid',
7298
                            $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
7299
                        ),
7300
                        $queryBuilder->expr()->eq(
7301
                            $GLOBALS['TCA'][$table]['ctrl']['languageField'],
7302
                            $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
7303
                        ),
7304
                        $queryBuilder->expr()->lt(
7305
                            $sortColumn,
7306
                            $queryBuilder->createNamedParameter($row[$sortColumn], \PDO::PARAM_INT)
7307
                        )
7308
                    )
7309
                    ->orderBy($sortColumn, 'DESC')
7310
                    ->addOrderBy('uid', 'DESC')
7311
                    ->setMaxResults(1);
7312
                if ($table === 'tt_content') {
7313
                    $queryBuilder
7314
                        ->andWhere(
7315
                            $queryBuilder->expr()->eq(
7316
                                'colPos',
7317
                                $queryBuilder->createNamedParameter($row['colPos'], \PDO::PARAM_INT)
7318
                            )
7319
                        );
7320
                }
7321
                // If there is an element, find its localized record in specified localization language
7322
                if ($previousRow = $queryBuilder->execute()->fetch()) {
7323
                    $previousLocalizedRecord = BackendUtility::getRecordLocalization($table, $previousRow['uid'], $language);
7324
                    if (is_array($previousLocalizedRecord[0])) {
7325
                        $previousLocalizedRecordUid = $previousLocalizedRecord[0]['uid'];
7326
                    }
7327
                }
7328
            }
7329
        }
7330
        return $previousLocalizedRecordUid;
7331
    }
7332
7333
    /**
7334
     * 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.
7335
     * Used for new records and during copy operations for defaults
7336
     *
7337
     * @param string $table Table name for which to set default values.
7338
     * @return array Array with default values.
7339
     * @internal should only be used from within DataHandler
7340
     */
7341
    public function newFieldArray($table)
7342
    {
7343
        $fieldArray = [];
7344
        if (is_array($GLOBALS['TCA'][$table]['columns'])) {
7345
            foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $content) {
7346
                if (isset($this->defaultValues[$table][$field])) {
7347
                    $fieldArray[$field] = $this->defaultValues[$table][$field];
7348
                } elseif (isset($content['config']['default'])) {
7349
                    $fieldArray[$field] = $content['config']['default'];
7350
                }
7351
            }
7352
        }
7353
        return $fieldArray;
7354
    }
7355
7356
    /**
7357
     * 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.
7358
     *
7359
     * @param string $table Table name
7360
     * @param array $incomingFieldArray Incoming array (passed by reference)
7361
     * @internal should only be used from within DataHandler
7362
     */
7363
    public function addDefaultPermittedLanguageIfNotSet($table, &$incomingFieldArray)
7364
    {
7365
        // Checking languages:
7366
        if ($GLOBALS['TCA'][$table]['ctrl']['languageField']) {
7367
            if (!isset($incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
7368
                // Language field must be found in input row - otherwise it does not make sense.
7369
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
7370
                    ->getQueryBuilderForTable('sys_language');
7371
                $queryBuilder->getRestrictions()
7372
                    ->removeAll()
7373
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7374
                $queryBuilder
7375
                    ->select('uid')
7376
                    ->from('sys_language')
7377
                    ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)));
7378
                $rows = array_merge([['uid' => 0]], $queryBuilder->execute()->fetchAll(), [['uid' => -1]]);
7379
                foreach ($rows as $r) {
7380
                    if ($this->BE_USER->checkLanguageAccess($r['uid'])) {
7381
                        $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $r['uid'];
7382
                        break;
7383
                    }
7384
                }
7385
            }
7386
        }
7387
    }
7388
7389
    /**
7390
     * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
7391
     *
7392
     * @param string $table Table name
7393
     * @param array $data Data array with fields from table. These will be overlaid with values in $this->overrideValues[$table]
7394
     * @return array Data array, processed.
7395
     * @internal should only be used from within DataHandler
7396
     */
7397
    public function overrideFieldArray($table, $data)
7398
    {
7399
        if (is_array($this->overrideValues[$table])) {
7400
            $data = array_merge($data, $this->overrideValues[$table]);
7401
        }
7402
        return $data;
7403
    }
7404
7405
    /**
7406
     * Compares the incoming field array with the current record and unsets all fields which are the same.
7407
     * Used for existing records being updated
7408
     *
7409
     * @param string $table Record table name
7410
     * @param int $id Record uid
7411
     * @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!
7412
     * @return array Returns $fieldArray. If the returned array is empty, then the record should not be updated!
7413
     * @internal should only be used from within DataHandler
7414
     */
7415
    public function compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray)
7416
    {
7417
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
7418
        $queryBuilder = $connection->createQueryBuilder();
7419
        $queryBuilder->getRestrictions()->removeAll();
7420
        $currentRecord = $queryBuilder->select('*')
7421
            ->from($table)
7422
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
7423
            ->execute()
7424
            ->fetch();
7425
        // If the current record exists (which it should...), begin comparison:
7426
        if (is_array($currentRecord)) {
7427
            $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
7428
            $columnRecordTypes = [];
7429
            foreach ($currentRecord as $columnName => $_) {
7430
                $columnRecordTypes[$columnName] = '';
7431
                $type = $tableDetails->getColumn($columnName)->getType();
7432
                if ($type instanceof IntegerType) {
7433
                    $columnRecordTypes[$columnName] = 'int';
7434
                }
7435
            }
7436
            // Unset the fields which are similar:
7437
            foreach ($fieldArray as $col => $val) {
7438
                $fieldConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
7439
                $isNullField = (!empty($fieldConfiguration['eval']) && GeneralUtility::inList($fieldConfiguration['eval'], 'null'));
7440
7441
                // Unset fields if stored and submitted values are equal - except the current field holds MM relations.
7442
                // In general this avoids to store superfluous data which also will be visualized in the editing history.
7443
                if (!$fieldConfiguration['MM'] && $this->isSubmittedValueEqualToStoredValue($val, $currentRecord[$col], $columnRecordTypes[$col], $isNullField)) {
7444
                    unset($fieldArray[$col]);
7445
                } else {
7446
                    if (!isset($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col])) {
7447
                        $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $currentRecord[$col];
7448
                    } elseif ($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col]) {
7449
                        $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col];
7450
                    }
7451
                    if (!isset($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col])) {
7452
                        $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $fieldArray[$col];
7453
                    } elseif ($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col]) {
7454
                        $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col];
7455
                    }
7456
                }
7457
            }
7458
        } else {
7459
            // If the current record does not exist this is an error anyways and we just return an empty array here.
7460
            $fieldArray = [];
7461
        }
7462
        return $fieldArray;
7463
    }
7464
7465
    /**
7466
     * Determines whether submitted values and stored values are equal.
7467
     * This prevents from adding superfluous field changes which would be shown in the record history as well.
7468
     * For NULL fields (see accordant TCA definition 'eval' = 'null'), a special handling is required since
7469
     * (!strcmp(NULL, '')) would be a false-positive.
7470
     *
7471
     * @param mixed $submittedValue Value that has submitted (e.g. from a backend form)
7472
     * @param mixed $storedValue Value that is currently stored in the database
7473
     * @param string $storedType SQL type of the stored value column (see mysql_field_type(), e.g 'int', 'string',  ...)
7474
     * @param bool $allowNull Whether NULL values are allowed by accordant TCA definition ('eval' = 'null')
7475
     * @return bool Whether both values are considered to be equal
7476
     */
7477
    protected function isSubmittedValueEqualToStoredValue($submittedValue, $storedValue, $storedType, $allowNull = false)
7478
    {
7479
        // No NULL values are allowed, this is the regular behaviour.
7480
        // Thus, check whether strings are the same or whether integer values are empty ("0" or "").
7481
        if (!$allowNull) {
7482
            $result = (string)$submittedValue === (string)$storedValue || $storedType === 'int' && (int)$storedValue === (int)$submittedValue;
7483
        // Null values are allowed, but currently there's a real (not NULL) value.
7484
        // Thus, ensure no NULL value was submitted and fallback to the regular behaviour.
7485
        } elseif ($storedValue !== null) {
7486
            $result = (
7487
                $submittedValue !== null
7488
                && $this->isSubmittedValueEqualToStoredValue($submittedValue, $storedValue, $storedType, false)
7489
            );
7490
        // Null values are allowed, and currently there's a NULL value.
7491
        // Thus, check whether a NULL value was submitted.
7492
        } else {
7493
            $result = ($submittedValue === null);
7494
        }
7495
7496
        return $result;
7497
    }
7498
7499
    /**
7500
     * Converts a HTML entity (like &#123;) to the character '123'
7501
     *
7502
     * @param string $input Input string
7503
     * @return string Output string
7504
     * @internal should only be used from within DataHandler
7505
     */
7506
    public function convNumEntityToByteValue($input)
7507
    {
7508
        $token = md5(microtime());
7509
        $parts = explode($token, preg_replace('/(&#([0-9]+);)/', $token . '\\2' . $token, $input));
7510
        foreach ($parts as $k => $v) {
7511
            if ($k % 2) {
7512
                $v = (int)$v;
7513
                // Just to make sure that control bytes are not converted.
7514
                if ($v > 32) {
7515
                    $parts[$k] = chr($v);
7516
                }
7517
            }
7518
        }
7519
        return implode('', $parts);
7520
    }
7521
7522
    /**
7523
     * Disables the delete clause for fetching records.
7524
     * In general only undeleted records will be used. If the delete
7525
     * clause is disabled, also deleted records are taken into account.
7526
     */
7527
    public function disableDeleteClause()
7528
    {
7529
        $this->disableDeleteClause = true;
7530
    }
7531
7532
    /**
7533
     * Returns delete-clause for the $table
7534
     *
7535
     * @param string $table Table name
7536
     * @return string Delete clause
7537
     * @internal should only be used from within DataHandler
7538
     */
7539
    public function deleteClause($table)
7540
    {
7541
        // Returns the proper delete-clause if any for a table from TCA
7542
        if (!$this->disableDeleteClause && $GLOBALS['TCA'][$table]['ctrl']['delete']) {
7543
            return ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
7544
        }
7545
        return '';
7546
    }
7547
7548
    /**
7549
     * Add delete restriction if not disabled
7550
     *
7551
     * @param QueryRestrictionContainerInterface $restrictions
7552
     */
7553
    protected function addDeleteRestriction(QueryRestrictionContainerInterface $restrictions)
7554
    {
7555
        if (!$this->disableDeleteClause) {
7556
            $restrictions->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7557
        }
7558
    }
7559
7560
    /**
7561
     * Gets UID of parent record. If record is deleted it will be looked up in
7562
     * an array built before the record was deleted
7563
     *
7564
     * @param string $table Table where record lives/lived
7565
     * @param int $uid Record UID
7566
     * @return int[] Parent UIDs
7567
     */
7568
    protected function getOriginalParentOfRecord($table, $uid)
7569
    {
7570
        if (isset(self::$recordPidsForDeletedRecords[$table][$uid])) {
7571
            return self::$recordPidsForDeletedRecords[$table][$uid];
7572
        }
7573
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
7574
        return [$parentUid];
7575
    }
7576
7577
    /**
7578
     * Extract entries from TSconfig for a specific table. This will merge specific and default configuration together.
7579
     *
7580
     * @param string $table Table name
7581
     * @param array $TSconfig TSconfig for page
7582
     * @return array TSconfig merged
7583
     * @internal should only be used from within DataHandler
7584
     */
7585
    public function getTableEntries($table, $TSconfig)
7586
    {
7587
        $tA = is_array($TSconfig['table.'][$table . '.']) ? $TSconfig['table.'][$table . '.'] : [];
7588
        $dA = is_array($TSconfig['default.']) ? $TSconfig['default.'] : [];
7589
        ArrayUtility::mergeRecursiveWithOverrule($dA, $tA);
7590
        return $dA;
7591
    }
7592
7593
    /**
7594
     * Returns the pid of a record from $table with $uid
7595
     *
7596
     * @param string $table Table name
7597
     * @param int $uid Record uid
7598
     * @return int|false PID value (unless the record did not exist in which case FALSE is returned)
7599
     * @internal should only be used from within DataHandler
7600
     */
7601
    public function getPID($table, $uid)
7602
    {
7603
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7604
        $queryBuilder->getRestrictions()
7605
            ->removeAll();
7606
        $queryBuilder->select('pid')
7607
            ->from($table)
7608
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)));
7609
        if ($row = $queryBuilder->execute()->fetch()) {
7610
            return $row['pid'];
7611
        }
7612
        return false;
7613
    }
7614
7615
    /**
7616
     * Executing dbAnalysisStore
7617
     * This will save MM relations for new records but is executed after records are created because we need to know the ID of them
7618
     * @internal should only be used from within DataHandler
7619
     */
7620
    public function dbAnalysisStoreExec()
7621
    {
7622
        foreach ($this->dbAnalysisStore as $action) {
7623
            $id = BackendUtility::wsMapId($action[4], MathUtility::canBeInterpretedAsInteger($action[2]) ? $action[2] : $this->substNEWwithIDs[$action[2]]);
7624
            if ($id) {
7625
                $action[0]->writeMM($action[1], $id, $action[3]);
7626
            }
7627
        }
7628
    }
7629
7630
    /**
7631
     * Returns array, $CPtable, of pages under the $pid going down to $counter levels.
7632
     * Selecting ONLY pages which the user has read-access to!
7633
     *
7634
     * @param array $CPtable Accumulation of page uid=>pid pairs in branch of $pid
7635
     * @param int $pid Page ID for which to find subpages
7636
     * @param int $counter Number of levels to go down.
7637
     * @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!
7638
     * @return array Return array.
7639
     * @internal should only be used from within DataHandler
7640
     */
7641
    public function int_pageTreeInfo($CPtable, $pid, $counter, $rootID)
7642
    {
7643
        if ($counter) {
7644
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
7645
            $restrictions = $queryBuilder->getRestrictions()->removeAll();
7646
            $this->addDeleteRestriction($restrictions);
7647
            $queryBuilder
7648
                ->select('uid')
7649
                ->from('pages')
7650
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
7651
                ->orderBy('sorting', 'DESC');
7652
            if (!$this->admin) {
7653
                $queryBuilder->andWhere($this->BE_USER->getPagePermsClause(Permission::PAGE_SHOW));
7654
            }
7655
            if ((int)$this->BE_USER->workspace === 0) {
7656
                $queryBuilder->andWhere(
7657
                    $queryBuilder->expr()->eq('t3ver_wsid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
7658
                );
7659
            } else {
7660
                $queryBuilder->andWhere($queryBuilder->expr()->in(
7661
                    't3ver_wsid',
7662
                    $queryBuilder->createNamedParameter([0, $this->BE_USER->workspace], Connection::PARAM_INT_ARRAY)
7663
                ));
7664
            }
7665
            $result = $queryBuilder->execute();
7666
7667
            $pages = [];
7668
            while ($row = $result->fetch()) {
7669
                $pages[$row['uid']] = $row;
7670
            }
7671
7672
            // Resolve placeholders of workspace versions
7673
            if (!empty($pages) && (int)$this->BE_USER->workspace !== 0) {
7674
                $pages = array_reverse(
7675
                    $this->resolveVersionedRecords(
7676
                        'pages',
7677
                        'uid',
7678
                        'sorting',
7679
                        array_keys($pages)
7680
                    ),
7681
                    true
7682
                );
7683
            }
7684
7685
            foreach ($pages as $page) {
7686
                if ($page['uid'] != $rootID) {
7687
                    $CPtable[$page['uid']] = $pid;
7688
                    // If the uid is NOT the rootID of the copyaction and if we are supposed to walk further down
7689
                    if ($counter - 1) {
7690
                        $CPtable = $this->int_pageTreeInfo($CPtable, $page['uid'], $counter - 1, $rootID);
7691
                    }
7692
                }
7693
            }
7694
        }
7695
        return $CPtable;
7696
    }
7697
7698
    /**
7699
     * List of all tables (those administrators has access to = array_keys of $GLOBALS['TCA'])
7700
     *
7701
     * @return array Array of all TCA table names
7702
     * @internal should only be used from within DataHandler
7703
     */
7704
    public function compileAdminTables()
7705
    {
7706
        return array_keys($GLOBALS['TCA']);
7707
    }
7708
7709
    /**
7710
     * Checks if any uniqueInPid eval input fields are in the record and if so, they are re-written to be correct.
7711
     *
7712
     * @param string $table Table name
7713
     * @param int $uid Record UID
7714
     * @internal should only be used from within DataHandler
7715
     */
7716
    public function fixUniqueInPid($table, $uid)
7717
    {
7718
        if (empty($GLOBALS['TCA'][$table])) {
7719
            return;
7720
        }
7721
7722
        $curData = $this->recordInfo($table, $uid, '*');
7723
        $newData = [];
7724
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
7725
            if ($conf['config']['type'] === 'input' && (string)$curData[$field] !== '') {
7726
                $evalCodesArray = GeneralUtility::trimExplode(',', $conf['config']['eval'], true);
7727
                if (in_array('uniqueInPid', $evalCodesArray, true)) {
7728
                    $newV = $this->getUnique($table, $field, $curData[$field], $uid, $curData['pid']);
7729
                    if ((string)$newV !== (string)$curData[$field]) {
7730
                        $newData[$field] = $newV;
7731
                    }
7732
                }
7733
            }
7734
        }
7735
        // IF there are changed fields, then update the database
7736
        if (!empty($newData)) {
7737
            $this->updateDB($table, $uid, $newData);
7738
        }
7739
    }
7740
7741
    /**
7742
     * Checks if any uniqueInSite eval fields are in the record and if so, they are re-written to be correct.
7743
     *
7744
     * @param string $table Table name
7745
     * @param int $uid Record UID
7746
     * @return bool whether the record had to be fixed or not
7747
     */
7748
    protected function fixUniqueInSite(string $table, int $uid): bool
7749
    {
7750
        $curData = $this->recordInfo($table, $uid, '*');
7751
        $workspaceId = $this->BE_USER->workspace;
7752
        $newData = [];
7753
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
7754
            if ($conf['config']['type'] === 'slug' && (string)$curData[$field] !== '') {
7755
                $evalCodesArray = GeneralUtility::trimExplode(',', $conf['config']['eval'], true);
7756
                if (in_array('uniqueInSite', $evalCodesArray, true)) {
7757
                    $helper = GeneralUtility::makeInstance(SlugHelper::class, $table, $field, $conf['config'], $workspaceId);
7758
                    $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

7758
                    $state = RecordStateFactory::forName($table)->fromArray(/** @scrutinizer ignore-type */ $curData);
Loading history...
7759
                    $newValue = $helper->buildSlugForUniqueInSite($curData[$field], $state);
7760
                    if ((string)$newValue !== (string)$curData[$field]) {
7761
                        $newData[$field] = $newValue;
7762
                    }
7763
                }
7764
            }
7765
        }
7766
        // IF there are changed fields, then update the database
7767
        if (!empty($newData)) {
7768
            $this->updateDB($table, $uid, $newData);
7769
            return true;
7770
        }
7771
        return false;
7772
    }
7773
7774
    /**
7775
     * Check if there are subpages that need an adoption as well
7776
     * @param int $pageId
7777
     */
7778
    protected function fixUniqueInSiteForSubpages(int $pageId)
7779
    {
7780
        // Get ALL subpages to update - read-permissions are respected
7781
        $subPages = $this->int_pageTreeInfo([], $pageId, 99, $pageId);
7782
        // Now fix uniqueInSite for subpages
7783
        foreach ($subPages as $thePageUid => $thePagePid) {
7784
            $recordWasModified = $this->fixUniqueInSite('pages', $thePageUid);
7785
            if ($recordWasModified) {
7786
                // @todo: Add logging and history - but how? we don't know the data that was in the system before
7787
            }
7788
        }
7789
    }
7790
7791
    /**
7792
     * When er record is copied you can specify fields from the previous record which should be copied into the new one
7793
     * 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)
7794
     *
7795
     * @param string $table Table name
7796
     * @param int $uid Record UID
7797
     * @param int $prevUid UID of previous record
7798
     * @param bool $update If set, updates the record
7799
     * @param array $newData Input array. If fields are already specified AND $update is not set, values are not set in output array.
7800
     * @return array Output array (For when the copying operation needs to get the information instead of updating the info)
7801
     * @internal should only be used from within DataHandler
7802
     */
7803
    public function fixCopyAfterDuplFields($table, $uid, $prevUid, $update, $newData = [])
7804
    {
7805
        if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['copyAfterDuplFields']) {
7806
            $prevData = $this->recordInfo($table, $prevUid, '*');
7807
            $theFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['copyAfterDuplFields'], true);
7808
            foreach ($theFields as $field) {
7809
                if ($GLOBALS['TCA'][$table]['columns'][$field] && ($update || !isset($newData[$field]))) {
7810
                    $newData[$field] = $prevData[$field];
7811
                }
7812
            }
7813
            if ($update && !empty($newData)) {
7814
                $this->updateDB($table, $uid, $newData);
7815
            }
7816
        }
7817
        return $newData;
7818
    }
7819
7820
    /**
7821
     * Casts a reference value. In case MM relations or foreign_field
7822
     * references are used. All other configurations, as well as
7823
     * foreign_table(!) could be stored as comma-separated-values
7824
     * as well. Since the system is not able to determine the default
7825
     * value automatically then, the TCA default value is used if
7826
     * it has been defined.
7827
     *
7828
     * @param int|string $value The value to be casted (e.g. '', '0', '1,2,3')
7829
     * @param array $configuration The TCA configuration of the accordant field
7830
     * @return int|string
7831
     */
7832
    protected function castReferenceValue($value, array $configuration)
7833
    {
7834
        if ((string)$value !== '') {
7835
            return $value;
7836
        }
7837
7838
        if (!empty($configuration['MM']) || !empty($configuration['foreign_field'])) {
7839
            return 0;
7840
        }
7841
7842
        if (array_key_exists('default', $configuration)) {
7843
            return $configuration['default'];
7844
        }
7845
7846
        return $value;
7847
    }
7848
7849
    /**
7850
     * Returns TRUE if the TCA/columns field type is a DB reference field
7851
     *
7852
     * @param array $conf Config array for TCA/columns field
7853
     * @return bool TRUE if DB reference field (group/db or select with foreign-table)
7854
     * @internal should only be used from within DataHandler
7855
     */
7856
    public function isReferenceField($conf)
7857
    {
7858
        return $conf['type'] === 'group' && $conf['internal_type'] === 'db' || $conf['type'] === 'select' && $conf['foreign_table'];
7859
    }
7860
7861
    /**
7862
     * Returns the subtype as a string of an inline field.
7863
     * If it's not an inline field at all, it returns FALSE.
7864
     *
7865
     * @param array $conf Config array for TCA/columns field
7866
     * @return string|bool string Inline subtype (field|mm|list), boolean: FALSE
7867
     * @internal should only be used from within DataHandler
7868
     */
7869
    public function getInlineFieldType($conf)
7870
    {
7871
        if ($conf['type'] !== 'inline' || !$conf['foreign_table']) {
7872
            return false;
7873
        }
7874
        if ($conf['foreign_field']) {
7875
            // The reference to the parent is stored in a pointer field in the child record
7876
            return 'field';
7877
        }
7878
        if ($conf['MM']) {
7879
            // Regular MM intermediate table is used to store data
7880
            return 'mm';
7881
        }
7882
        // An item list (separated by comma) is stored (like select type is doing)
7883
        return 'list';
7884
    }
7885
7886
    /**
7887
     * Get modified header for a copied record
7888
     *
7889
     * @param string $table Table name
7890
     * @param int $pid PID value in which other records to test might be
7891
     * @param string $field Field name to get header value for.
7892
     * @param string $value Current field value
7893
     * @param int $count Counter (number of recursions)
7894
     * @param string $prevTitle Previous title we checked for (in previous recursion)
7895
     * @return string The field value, possibly appended with a "copy label
7896
     * @internal should only be used from within DataHandler
7897
     */
7898
    public function getCopyHeader($table, $pid, $field, $value, $count, $prevTitle = '')
7899
    {
7900
        // Set title value to check for:
7901
        $checkTitle = $value;
7902
        if ($count > 0) {
7903
            $checkTitle = $value . rtrim(' ' . sprintf($this->prependLabel($table), $count));
7904
        }
7905
        // Do check:
7906
        if ($prevTitle != $checkTitle || $count < 100) {
7907
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7908
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7909
            $rowCount = $queryBuilder
7910
                ->count('uid')
7911
                ->from($table)
7912
                ->where(
7913
                    $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)),
7914
                    $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($checkTitle, \PDO::PARAM_STR))
7915
                )
7916
                ->execute()
7917
                ->fetchColumn(0);
7918
            if ($rowCount) {
7919
                return $this->getCopyHeader($table, $pid, $field, $value, $count + 1, $checkTitle);
7920
            }
7921
        }
7922
        // Default is to just return the current input title if no other was returned before:
7923
        return $checkTitle;
7924
    }
7925
7926
    /**
7927
     * Return "copy" label for a table. Although the name is "prepend" it actually APPENDs the label (after ...)
7928
     *
7929
     * @param string $table Table name
7930
     * @return string Label to append, containing "%s" for the number
7931
     * @see getCopyHeader()
7932
     * @internal should only be used from within DataHandler
7933
     */
7934
    public function prependLabel($table)
7935
    {
7936
        return $this->getLanguageService()->sL($GLOBALS['TCA'][$table]['ctrl']['prependAtCopy']);
7937
    }
7938
7939
    /**
7940
     * Get the final pid based on $table and $pid ($destPid type... pos/neg)
7941
     *
7942
     * @param string $table Table name
7943
     * @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!
7944
     * @return int
7945
     * @internal should only be used from within DataHandler
7946
     */
7947
    public function resolvePid($table, $pid)
7948
    {
7949
        $pid = (int)$pid;
7950
        if ($pid < 0) {
7951
            $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7952
            $query->getRestrictions()
7953
                ->removeAll();
7954
            $row = $query
7955
                ->select('pid')
7956
                ->from($table)
7957
                ->where($query->expr()->eq('uid', $query->createNamedParameter(abs($pid), \PDO::PARAM_INT)))
7958
                ->execute()
7959
                ->fetch();
7960
            $pid = (int)$row['pid'];
7961
        }
7962
        return $pid;
7963
    }
7964
7965
    /**
7966
     * Removes the prependAtCopy prefix on values
7967
     *
7968
     * @param string $table Table name
7969
     * @param string $value The value to fix
7970
     * @return string Clean name
7971
     * @internal should only be used from within DataHandler
7972
     */
7973
    public function clearPrefixFromValue($table, $value)
7974
    {
7975
        $regex = '/\s' . sprintf(preg_quote($this->prependLabel($table)), '[0-9]*') . '$/';
7976
        return @preg_replace($regex, '', $value);
7977
    }
7978
7979
    /**
7980
     * Check if there are records from tables on the pages to be deleted which the current user is not allowed to
7981
     *
7982
     * @param int[] $pageIds IDs of pages which should be checked
7983
     * @return string[]|null Return null, if permission granted, otherwise an array with the tables that are not allowed to be deleted
7984
     * @see canDeletePage()
7985
     */
7986
    protected function checkForRecordsFromDisallowedTables(array $pageIds): ?array
7987
    {
7988
        if ($this->admin) {
7989
            return null;
7990
        }
7991
7992
        $disallowedTables = [];
7993
        if (!empty($pageIds)) {
7994
            $tableNames = $this->compileAdminTables();
7995
            foreach ($tableNames as $table) {
7996
                $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7997
                $query->getRestrictions()
7998
                    ->removeAll()
7999
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8000
                $count = $query->count('uid')
8001
                    ->from($table)
8002
                    ->where($query->expr()->in(
8003
                        'pid',
8004
                        $query->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
8005
                    ))
8006
                    ->execute()
8007
                    ->fetchColumn(0);
8008
                if ($count && ($this->tableReadOnly($table) || !$this->checkModifyAccessList($table))) {
8009
                    $disallowedTables[] = $table;
8010
                }
8011
            }
8012
        }
8013
        return !empty($disallowedTables) ? $disallowedTables : null;
8014
    }
8015
8016
    /**
8017
     * Determine if a record was copied or if a record is the result of a copy action.
8018
     *
8019
     * @param string $table The tablename of the record
8020
     * @param int $uid The uid of the record
8021
     * @return bool Returns TRUE if the record is copied or is the result of a copy action
8022
     * @internal should only be used from within DataHandler
8023
     */
8024
    public function isRecordCopied($table, $uid)
8025
    {
8026
        // If the record was copied:
8027
        if (isset($this->copyMappingArray[$table][$uid])) {
8028
            return true;
8029
        }
8030
        if (isset($this->copyMappingArray[$table]) && in_array($uid, array_values($this->copyMappingArray[$table]))) {
8031
            return true;
8032
        }
8033
        return false;
8034
    }
8035
8036
    /******************************
8037
     *
8038
     * Clearing cache
8039
     *
8040
     ******************************/
8041
8042
    /**
8043
     * Clearing the cache based on a page being updated
8044
     * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
8045
     * Else just clear the cache for the parent page of the record.
8046
     *
8047
     * @param string $table Table name of record that was just updated.
8048
     * @param int $uid UID of updated / inserted record
8049
     * @param int $pid REAL PID of page of a deleted/moved record to get TSconfig in ClearCache.
8050
     * @internal This method is not meant to be called directly but only from the core itself or from hooks
8051
     */
8052
    public function registerRecordIdForPageCacheClearing($table, $uid, $pid = null)
8053
    {
8054
        if (!is_array(static::$recordsToClearCacheFor[$table])) {
8055
            static::$recordsToClearCacheFor[$table] = [];
8056
        }
8057
        static::$recordsToClearCacheFor[$table][] = (int)$uid;
8058
        if ($pid !== null) {
8059
            if (!is_array(static::$recordPidsForDeletedRecords[$table])) {
8060
                static::$recordPidsForDeletedRecords[$table] = [];
8061
            }
8062
            static::$recordPidsForDeletedRecords[$table][$uid][] = (int)$pid;
8063
        }
8064
    }
8065
8066
    /**
8067
     * Do the actual clear cache
8068
     */
8069
    protected function processClearCacheQueue()
8070
    {
8071
        $tagsToClear = [];
8072
        $clearCacheCommands = [];
8073
8074
        foreach (static::$recordsToClearCacheFor as $table => $uids) {
8075
            foreach (array_unique($uids) as $uid) {
8076
                if (!isset($GLOBALS['TCA'][$table]) || $uid <= 0) {
8077
                    return;
8078
                }
8079
                // For move commands we may get more then 1 parent.
8080
                $pageUids = $this->getOriginalParentOfRecord($table, $uid);
8081
                foreach ($pageUids as $originalParent) {
8082
                    [$tagsToClearFromPrepare, $clearCacheCommandsFromPrepare]
8083
                        = $this->prepareCacheFlush($table, $uid, $originalParent);
8084
                    $tagsToClear = array_merge($tagsToClear, $tagsToClearFromPrepare);
8085
                    $clearCacheCommands = array_merge($clearCacheCommands, $clearCacheCommandsFromPrepare);
8086
                }
8087
            }
8088
        }
8089
8090
        /** @var CacheManager $cacheManager */
8091
        $cacheManager = $this->getCacheManager();
8092
        $cacheManager->flushCachesInGroupByTags('pages', array_keys($tagsToClear));
8093
8094
        // Filter duplicate cache commands from cacheQueue
8095
        $clearCacheCommands = array_unique($clearCacheCommands);
8096
        // Execute collected clear cache commands from page TSConfig
8097
        foreach ($clearCacheCommands as $command) {
8098
            $this->clear_cacheCmd($command);
8099
        }
8100
8101
        // Reset the cache clearing array
8102
        static::$recordsToClearCacheFor = [];
8103
8104
        // Reset the original pid array
8105
        static::$recordPidsForDeletedRecords = [];
8106
    }
8107
8108
    /**
8109
     * Prepare the cache clearing
8110
     *
8111
     * @param string $table Table name of record that needs to be cleared
8112
     * @param int $uid UID of record for which the cache needs to be cleared
8113
     * @param int $pid Original pid of the page of the record which the cache needs to be cleared
8114
     * @return array Array with tagsToClear and clearCacheCommands
8115
     * @internal This function is internal only it may be changed/removed also in minor version numbers.
8116
     */
8117
    protected function prepareCacheFlush($table, $uid, $pid)
8118
    {
8119
        $tagsToClear = [];
8120
        $clearCacheCommands = [];
8121
        $pageUid = 0;
8122
        // Get Page TSconfig relevant:
8123
        $TSConfig = BackendUtility::getPagesTSconfig($pid)['TCEMAIN.'] ?? [];
8124
        if (empty($TSConfig['clearCache_disable']) && $this->BE_USER->workspace === 0) {
8125
            $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
8126
            // If table is "pages":
8127
            $pageIdsThatNeedCacheFlush = [];
8128
            if ($table === 'pages') {
8129
                // Find out if the record is a get the original page
8130
                $pageUid = $this->getDefaultLanguagePageId($uid);
8131
8132
                // Builds list of pages on the SAME level as this page (siblings)
8133
                $queryBuilder = $connectionPool->getQueryBuilderForTable('pages');
8134
                $queryBuilder->getRestrictions()
8135
                    ->removeAll()
8136
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8137
                $siblings = $queryBuilder
8138
                    ->select('A.pid AS pid', 'B.uid AS uid')
8139
                    ->from('pages', 'A')
8140
                    ->from('pages', 'B')
8141
                    ->where(
8142
                        $queryBuilder->expr()->eq('A.uid', $queryBuilder->createNamedParameter($pageUid, \PDO::PARAM_INT)),
8143
                        $queryBuilder->expr()->eq('B.pid', $queryBuilder->quoteIdentifier('A.pid')),
8144
                        $queryBuilder->expr()->gte('A.pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
8145
                    )
8146
                    ->execute();
8147
8148
                $parentPageId = 0;
8149
                while ($row_tmp = $siblings->fetch()) {
8150
                    $pageIdsThatNeedCacheFlush[] = (int)$row_tmp['uid'];
8151
                    $parentPageId = (int)$row_tmp['pid'];
8152
                    // Add children as well:
8153
                    if ($TSConfig['clearCache_pageSiblingChildren']) {
8154
                        $siblingChildrenQuery = $connectionPool->getQueryBuilderForTable('pages');
8155
                        $siblingChildrenQuery->getRestrictions()
8156
                            ->removeAll()
8157
                            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8158
                        $siblingChildren = $siblingChildrenQuery
8159
                            ->select('uid')
8160
                            ->from('pages')
8161
                            ->where($siblingChildrenQuery->expr()->eq(
8162
                                'pid',
8163
                                $siblingChildrenQuery->createNamedParameter($row_tmp['uid'], \PDO::PARAM_INT)
8164
                            ))
8165
                            ->execute();
8166
                        while ($row_tmp2 = $siblingChildren->fetch()) {
8167
                            $pageIdsThatNeedCacheFlush[] = (int)$row_tmp2['uid'];
8168
                        }
8169
                    }
8170
                }
8171
                // Finally, add the parent page as well when clearing a specific page
8172
                if ($parentPageId > 0) {
8173
                    $pageIdsThatNeedCacheFlush[] = $parentPageId;
8174
                }
8175
                // Add grand-parent as well if configured
8176
                if ($TSConfig['clearCache_pageGrandParent']) {
8177
                    $parentQuery = $connectionPool->getQueryBuilderForTable('pages');
8178
                    $parentQuery->getRestrictions()
8179
                        ->removeAll()
8180
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8181
                    $row_tmp = $parentQuery
8182
                        ->select('pid')
8183
                        ->from('pages')
8184
                        ->where($parentQuery->expr()->eq(
8185
                            'uid',
8186
                            $parentQuery->createNamedParameter($parentPageId, \PDO::PARAM_INT)
8187
                        ))
8188
                        ->execute()
8189
                        ->fetch();
8190
                    if (!empty($row_tmp)) {
8191
                        $pageIdsThatNeedCacheFlush[] = (int)$row_tmp['pid'];
8192
                    }
8193
                }
8194
            } else {
8195
                // For other tables than "pages", delete cache for the records "parent page".
8196
                $pageIdsThatNeedCacheFlush[] = $pageUid = (int)$this->getPID($table, $uid);
8197
                // Add the parent page as well
8198
                if ($TSConfig['clearCache_pageGrandParent']) {
8199
                    $parentQuery = $connectionPool->getQueryBuilderForTable('pages');
8200
                    $parentQuery->getRestrictions()
8201
                        ->removeAll()
8202
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8203
                    $parentPageRecord = $parentQuery
8204
                        ->select('pid')
8205
                        ->from('pages')
8206
                        ->where($parentQuery->expr()->eq(
8207
                            'uid',
8208
                            $parentQuery->createNamedParameter($pageUid, \PDO::PARAM_INT)
8209
                        ))
8210
                        ->execute()
8211
                        ->fetch();
8212
                    if (!empty($parentPageRecord)) {
8213
                        $pageIdsThatNeedCacheFlush[] = (int)$parentPageRecord['pid'];
8214
                    }
8215
                }
8216
            }
8217
            // Call pre-processing function for clearing of cache for page ids:
8218
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] ?? [] as $funcName) {
8219
                $_params = ['pageIdArray' => &$pageIdsThatNeedCacheFlush, 'table' => $table, 'uid' => $uid, 'functionID' => 'clear_cache()'];
8220
                // Returns the array of ids to clear, FALSE if nothing should be cleared! Never an empty array!
8221
                GeneralUtility::callUserFunction($funcName, $_params, $this);
8222
            }
8223
            // Delete cache for selected pages:
8224
            foreach ($pageIdsThatNeedCacheFlush as $pageId) {
8225
                $tagsToClear['pageId_' . $pageId] = true;
8226
            }
8227
            // Queue delete cache for current table and record
8228
            $tagsToClear[$table] = true;
8229
            $tagsToClear[$table . '_' . $uid] = true;
8230
        }
8231
        // Clear cache for pages entered in TSconfig:
8232
        if (!empty($TSConfig['clearCacheCmd'])) {
8233
            $commands = GeneralUtility::trimExplode(',', $TSConfig['clearCacheCmd'], true);
8234
            $clearCacheCommands = array_unique($commands);
8235
        }
8236
        // Call post processing function for clear-cache:
8237
        $_params = ['table' => $table, 'uid' => $uid, 'uid_page' => $pageUid, 'TSConfig' => $TSConfig, 'tags' => $tagsToClear];
8238
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] ?? [] as $_funcRef) {
8239
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
8240
        }
8241
        return [
8242
            $tagsToClear,
8243
            $clearCacheCommands
8244
        ];
8245
    }
8246
8247
    /**
8248
     * Clears the cache based on the command $cacheCmd.
8249
     *
8250
     * $cacheCmd='pages'
8251
     * Clears cache for all pages and page-based caches inside the cache manager.
8252
     * Requires admin-flag to be set for BE_USER.
8253
     *
8254
     * $cacheCmd='all'
8255
     * Clears all cache_tables. This is necessary if templates are updated.
8256
     * Requires admin-flag to be set for BE_USER.
8257
     *
8258
     * The following cache_* are intentionally not cleared by 'all'
8259
     *
8260
     * - imagesizes:	Clearing this table would cause a lot of unneeded
8261
     * Imagemagick calls because the size information has
8262
     * to be fetched again after clearing.
8263
     * - all caches inside the cache manager that are inside the group "system"
8264
     * - they are only needed to build up the core system and templates.
8265
     *   If the group of system caches needs to be deleted explicitly, use
8266
     *   flushCachesInGroup('system') of CacheManager directly.
8267
     *
8268
     * $cacheCmd=[integer]
8269
     * Clears cache for the page pointed to by $cacheCmd (an integer).
8270
     *
8271
     * $cacheCmd='cacheTag:[string]'
8272
     * Flush page and pagesection cache by given tag
8273
     *
8274
     * $cacheCmd='cacheId:[string]'
8275
     * Removes cache identifier from page and page section cache
8276
     *
8277
     * Can call a list of post processing functions as defined in
8278
     * $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc']
8279
     * (numeric array with values being the function references, called by
8280
     * GeneralUtility::callUserFunction()).
8281
     *
8282
     *
8283
     * @param string $cacheCmd The cache command, see above description
8284
     */
8285
    public function clear_cacheCmd($cacheCmd)
8286
    {
8287
        if (is_object($this->BE_USER)) {
8288
            $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]);
8289
        }
8290
        $userTsConfig = $this->BE_USER->getTSConfig();
8291
        switch (strtolower($cacheCmd)) {
8292
            case 'pages':
8293
                if ($this->admin || ($userTsConfig['options.']['clearCache.']['pages'] ?? false)) {
8294
                    $this->getCacheManager()->flushCachesInGroup('pages');
8295
                }
8296
                break;
8297
            case 'all':
8298
                // allow to clear all caches if the TS config option is enabled or the option is not explicitly
8299
                // disabled for admins (which could clear all caches by default). The latter option is useful
8300
                // for big production sites where it should be possible to restrict the cache clearing for some admins.
8301
                if (($userTsConfig['options.']['clearCache.']['all'] ?? false)
8302
                    || ($this->admin && (bool)($userTsConfig['options.']['clearCache.']['all'] ?? true))
8303
                ) {
8304
                    $this->getCacheManager()->flushCaches();
8305
                    GeneralUtility::makeInstance(ConnectionPool::class)
8306
                        ->getConnectionForTable('cache_treelist')
8307
                        ->truncate('cache_treelist');
8308
8309
                    // Delete Opcode Cache
8310
                    GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive();
8311
                }
8312
                break;
8313
        }
8314
8315
        $tagsToFlush = [];
8316
        // Clear cache for a page ID!
8317
        if (MathUtility::canBeInterpretedAsInteger($cacheCmd)) {
8318
            $list_cache = [$cacheCmd];
8319
            // Call pre-processing function for clearing of cache for page ids:
8320
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] ?? [] as $funcName) {
8321
                $_params = ['pageIdArray' => &$list_cache, 'cacheCmd' => $cacheCmd, 'functionID' => 'clear_cacheCmd()'];
8322
                // Returns the array of ids to clear, FALSE if nothing should be cleared! Never an empty array!
8323
                GeneralUtility::callUserFunction($funcName, $_params, $this);
8324
            }
8325
            // Delete cache for selected pages:
8326
            if (is_array($list_cache)) {
0 ignored issues
show
introduced by
The condition is_array($list_cache) is always true.
Loading history...
8327
                foreach ($list_cache as $pageId) {
8328
                    $tagsToFlush[] = 'pageId_' . (int)$pageId;
8329
                }
8330
            }
8331
        }
8332
        // flush cache by tag
8333
        if (GeneralUtility::isFirstPartOfStr(strtolower($cacheCmd), 'cachetag:')) {
8334
            $cacheTag = substr($cacheCmd, 9);
8335
            $tagsToFlush[] = $cacheTag;
8336
        }
8337
        // process caching framework operations
8338
        if (!empty($tagsToFlush)) {
8339
            $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

8339
            $this->/** @scrutinizer ignore-call */ 
8340
                   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...
8340
        }
8341
8342
        // Call post processing function for clear-cache:
8343
        $_params = ['cacheCmd' => strtolower($cacheCmd), 'tags' => $tagsToFlush];
8344
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] ?? [] as $_funcRef) {
8345
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
8346
        }
8347
    }
8348
8349
    /*****************************
8350
     *
8351
     * Logging
8352
     *
8353
     *****************************/
8354
    /**
8355
     * Logging actions from DataHandler
8356
     *
8357
     * @param string $table Table name the log entry is concerned with. Blank if NA
8358
     * @param int $recuid Record UID. Zero if NA
8359
     * @param int $action Action number: 0=No category, 1=new record, 2=update record, 3= delete record, 4= move record, 5= Check/evaluate
8360
     * @param int $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
8361
     * @param int $error The severity: 0 = message, 1 = error, 2 = System Error, 3 = security notice (admin), 4 warning
8362
     * @param string $details Default error message in english
8363
     * @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
8364
     * @param array $data Array with special information that may go into $details by '%s' marks / sprintf() when the log is shown
8365
     * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
8366
     * @param string $NEWid NEW id for new records
8367
     * @return int Log entry UID (0 if no log entry was written or logging is disabled)
8368
     * @see \TYPO3\CMS\Core\SysLog\Action\Database for all available values of argument $action
8369
     * @see \TYPO3\CMS\Core\SysLog\Error for all available values of argument $error
8370
     * @internal should only be used from within TYPO3 Core
8371
     */
8372
    public function log($table, $recuid, $action, $recpid, $error, $details, $details_nr = -1, $data = [], $event_pid = -1, $NEWid = '')
8373
    {
8374
        if (!$this->enableLogging) {
8375
            return 0;
8376
        }
8377
        // Type value for DataHandler
8378
        if (!$this->storeLogMessages) {
8379
            $details = '';
8380
        }
8381
        if ($error > 0) {
8382
            $detailMessage = $details;
8383
            if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
8384
                $detailMessage = vsprintf($details, $data);
8385
            }
8386
            $this->errorLog[] = '[' . SystemLogType::DB . '.' . $action . '.' . $details_nr . ']: ' . $detailMessage;
8387
        }
8388
        return $this->BE_USER->writelog(SystemLogType::DB, $action, $error, $details_nr, $details, $data, $table, $recuid, $recpid, $event_pid, $NEWid);
8389
    }
8390
8391
    /**
8392
     * Simple logging function meant to be used when logging messages is not yet fixed.
8393
     *
8394
     * @param string $message Message string
8395
     * @param int $error Error code, see log()
8396
     * @return int Log entry UID
8397
     * @see log()
8398
     * @internal should only be used from within TYPO3 Core
8399
     */
8400
    public function newlog($message, $error = SystemLogErrorClassification::MESSAGE)
8401
    {
8402
        return $this->log('', 0, SystemLogGenericAction::UNDEFINED, 0, $error, $message, -1);
8403
    }
8404
8405
    /**
8406
     * Print log error messages from the operations of this script instance
8407
     * @internal should only be used from within TYPO3 Core
8408
     */
8409
    public function printLogErrorMessages()
8410
    {
8411
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_log');
8412
        $queryBuilder->getRestrictions()->removeAll();
8413
        $result = $queryBuilder
8414
            ->select('*')
8415
            ->from('sys_log')
8416
            ->where(
8417
                $queryBuilder->expr()->eq('type', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT)),
8418
                $queryBuilder->expr()->lt('action', $queryBuilder->createNamedParameter(256, \PDO::PARAM_INT)),
8419
                $queryBuilder->expr()->eq(
8420
                    'userid',
8421
                    $queryBuilder->createNamedParameter($this->BE_USER->user['uid'], \PDO::PARAM_INT)
8422
                ),
8423
                $queryBuilder->expr()->eq(
8424
                    'tstamp',
8425
                    $queryBuilder->createNamedParameter($GLOBALS['EXEC_TIME'], \PDO::PARAM_INT)
8426
                ),
8427
                $queryBuilder->expr()->neq('error', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
8428
            )
8429
            ->execute();
8430
8431
        while ($row = $result->fetch()) {
8432
            $log_data = unserialize($row['log_data']);
8433
            $msg = $row['error'] . ': ' . sprintf($row['details'], $log_data[0], $log_data[1], $log_data[2], $log_data[3], $log_data[4]);
8434
            /** @var FlashMessage $flashMessage */
8435
            $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $msg, '', $row['error'] === 4 ? FlashMessage::WARNING : FlashMessage::ERROR, true);
8436
            /** @var FlashMessageService $flashMessageService */
8437
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
8438
            $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
8439
            $defaultFlashMessageQueue->enqueue($flashMessage);
8440
        }
8441
    }
8442
8443
    /*****************************
8444
     *
8445
     * Internal (do not use outside Core!)
8446
     *
8447
     *****************************/
8448
8449
    /**
8450
     * Find out if the record is a localization. If so, get the uid of the default language page.
8451
     * Always returns the uid of the workspace live record: No explicit workspace overlay is applied.
8452
     *
8453
     * @param int $pageId Page UID, can be the default page record, or a page translation record ID
8454
     * @return int UID of the default page record in live workspace
8455
     */
8456
    protected function getDefaultLanguagePageId(int $pageId): int
8457
    {
8458
        $localizationParentFieldName = $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'];
8459
        $row = $this->recordInfo('pages', $pageId, $localizationParentFieldName);
8460
        $localizationParent = (int)$row[$localizationParentFieldName];
8461
        if ($localizationParent > 0) {
8462
            return $localizationParent;
8463
        }
8464
        return $pageId;
8465
    }
8466
8467
    /**
8468
     * Preprocesses field array based on field type. Some fields must be adjusted
8469
     * before going to database. This is done on the copy of the field array because
8470
     * original values are used in remap action later.
8471
     *
8472
     * @param string $table	Table name
8473
     * @param array $fieldArray	Field array to check
8474
     * @return array Updated field array
8475
     * @internal should only be used from within TYPO3 Core
8476
     */
8477
    public function insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray)
8478
    {
8479
        $result = $fieldArray;
8480
        foreach ($fieldArray as $field => $value) {
8481
            if (!MathUtility::canBeInterpretedAsInteger($value)
8482
                && $GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'inline'
8483
                && $GLOBALS['TCA'][$table]['columns'][$field]['config']['foreign_field']) {
8484
                $result[$field] = count(GeneralUtility::trimExplode(',', $value, true));
8485
            }
8486
        }
8487
        return $result;
8488
    }
8489
8490
    /**
8491
     * Determines whether a particular record has been deleted
8492
     * using DataHandler::deleteRecord() in this instance.
8493
     *
8494
     * @param string $tableName
8495
     * @param string $uid
8496
     * @return bool
8497
     * @internal should only be used from within TYPO3 Core
8498
     */
8499
    public function hasDeletedRecord($tableName, $uid)
8500
    {
8501
        return
8502
            !empty($this->deletedRecords[$tableName])
8503
            && in_array($uid, $this->deletedRecords[$tableName])
8504
        ;
8505
    }
8506
8507
    /**
8508
     * Gets the automatically versionized id of a record.
8509
     *
8510
     * @param string $table Name of the table
8511
     * @param int $id Uid of the record
8512
     * @return int|null
8513
     * @internal should only be used from within TYPO3 Core
8514
     */
8515
    public function getAutoVersionId($table, $id): ?int
8516
    {
8517
        $result = null;
8518
        if (isset($this->autoVersionIdMap[$table][$id])) {
8519
            $result = (int)trim($this->autoVersionIdMap[$table][$id]);
8520
        }
8521
        return $result;
8522
    }
8523
8524
    /**
8525
     * Overlays the automatically versionized id of a record.
8526
     *
8527
     * @param string $table Name of the table
8528
     * @param int $id Uid of the record
8529
     * @return int
8530
     */
8531
    protected function overlayAutoVersionId($table, $id)
8532
    {
8533
        $autoVersionId = $this->getAutoVersionId($table, $id);
8534
        if ($autoVersionId !== null) {
8535
            $id = $autoVersionId;
8536
        }
8537
        return $id;
8538
    }
8539
8540
    /**
8541
     * Adds new values to the remapStackChildIds array.
8542
     *
8543
     * @param array $idValues uid values
8544
     */
8545
    protected function addNewValuesToRemapStackChildIds(array $idValues)
8546
    {
8547
        foreach ($idValues as $idValue) {
8548
            if (strpos($idValue, 'NEW') === 0) {
8549
                $this->remapStackChildIds[$idValue] = true;
8550
            }
8551
        }
8552
    }
8553
8554
    /**
8555
     * Resolves versioned records for the current workspace scope.
8556
     * Delete placeholders are substituted and removed.
8557
     *
8558
     * @param string $tableName Name of the table to be processed
8559
     * @param string $fieldNames List of the field names to be fetched
8560
     * @param string $sortingField Name of the sorting field to be used
8561
     * @param array $liveIds Flat array of (live) record ids
8562
     * @return array
8563
     */
8564
    protected function resolveVersionedRecords($tableName, $fieldNames, $sortingField, array $liveIds)
8565
    {
8566
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)
8567
            ->getConnectionForTable($tableName);
8568
        $sortingStatement = !empty($sortingField)
8569
            ? [$connection->quoteIdentifier($sortingField)]
8570
            : null;
8571
        /** @var PlainDataResolver $resolver */
8572
        $resolver = GeneralUtility::makeInstance(
8573
            PlainDataResolver::class,
8574
            $tableName,
8575
            $liveIds,
8576
            $sortingStatement
8577
        );
8578
8579
        $resolver->setWorkspaceId($this->BE_USER->workspace);
8580
        $resolver->setKeepDeletePlaceholder(false);
8581
        $resolver->setKeepMovePlaceholder(false);
8582
        $resolver->setKeepLiveIds(true);
8583
        $recordIds = $resolver->get();
8584
8585
        $records = [];
8586
        foreach ($recordIds as $recordId) {
8587
            $records[$recordId] = BackendUtility::getRecord($tableName, $recordId, $fieldNames);
8588
        }
8589
8590
        return $records;
8591
    }
8592
8593
    /**
8594
     * Gets the outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler
8595
     * Since \TYPO3\CMS\Core\DataHandling\DataHandler can create nested objects of itself,
8596
     * this method helps to determine the first (= outer most) one.
8597
     *
8598
     * @return DataHandler
8599
     */
8600
    protected function getOuterMostInstance()
8601
    {
8602
        if (!isset($this->outerMostInstance)) {
8603
            $stack = array_reverse(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS));
8604
            foreach ($stack as $stackItem) {
8605
                if (isset($stackItem['object']) && $stackItem['object'] instanceof self) {
8606
                    $this->outerMostInstance = $stackItem['object'];
8607
                    break;
8608
                }
8609
            }
8610
        }
8611
        return $this->outerMostInstance;
8612
    }
8613
8614
    /**
8615
     * Determines whether the this object is the outer most instance of itself
8616
     * Since DataHandler can create nested objects of itself,
8617
     * this method helps to determine the first (= outer most) one.
8618
     *
8619
     * @return bool
8620
     */
8621
    public function isOuterMostInstance()
8622
    {
8623
        return $this->getOuterMostInstance() === $this;
8624
    }
8625
8626
    /**
8627
     * Gets an instance of the runtime cache.
8628
     *
8629
     * @return FrontendInterface
8630
     */
8631
    protected function getRuntimeCache()
8632
    {
8633
        return $this->getCacheManager()->getCache('runtime');
8634
    }
8635
8636
    /**
8637
     * Determines nested element calls.
8638
     *
8639
     * @param string $table Name of the table
8640
     * @param int $id Uid of the record
8641
     * @param string $identifier Name of the action to be checked
8642
     * @return bool
8643
     */
8644
    protected function isNestedElementCallRegistered($table, $id, $identifier)
8645
    {
8646
        $nestedElementCalls = (array)$this->runtimeCache->get($this->cachePrefixNestedElementCalls);
8647
        return isset($nestedElementCalls[$identifier][$table][$id]);
8648
    }
8649
8650
    /**
8651
     * Registers nested elements calls.
8652
     * This is used to track nested calls (e.g. for following m:n relations).
8653
     *
8654
     * @param string $table Name of the table
8655
     * @param int $id Uid of the record
8656
     * @param string $identifier Name of the action to be tracked
8657
     */
8658
    protected function registerNestedElementCall($table, $id, $identifier)
8659
    {
8660
        $nestedElementCalls = (array)$this->runtimeCache->get($this->cachePrefixNestedElementCalls);
8661
        $nestedElementCalls[$identifier][$table][$id] = true;
8662
        $this->runtimeCache->set($this->cachePrefixNestedElementCalls, $nestedElementCalls);
8663
    }
8664
8665
    /**
8666
     * Resets the nested element calls.
8667
     */
8668
    protected function resetNestedElementCalls()
8669
    {
8670
        $this->runtimeCache->remove($this->cachePrefixNestedElementCalls);
8671
    }
8672
8673
    /**
8674
     * Determines whether an element was registered to be deleted in the registry.
8675
     *
8676
     * @param string $table Name of the table
8677
     * @param int $id Uid of the record
8678
     * @return bool
8679
     * @see registerElementsToBeDeleted
8680
     * @see resetElementsToBeDeleted
8681
     * @see copyRecord_raw
8682
     * @see versionizeRecord
8683
     */
8684
    protected function isElementToBeDeleted($table, $id)
8685
    {
8686
        $elementsToBeDeleted = (array)$this->runtimeCache->get('core-datahandler-elementsToBeDeleted');
8687
        return isset($elementsToBeDeleted[$table][$id]);
8688
    }
8689
8690
    /**
8691
     * Registers elements to be deleted in the registry.
8692
     *
8693
     * @see process_datamap
8694
     */
8695
    protected function registerElementsToBeDeleted()
8696
    {
8697
        $elementsToBeDeleted = (array)$this->runtimeCache->get('core-datahandler-elementsToBeDeleted');
8698
        $this->runtimeCache->set('core-datahandler-elementsToBeDeleted', array_merge($elementsToBeDeleted, $this->getCommandMapElements('delete')));
8699
    }
8700
8701
    /**
8702
     * Resets the elements to be deleted in the registry.
8703
     *
8704
     * @see process_datamap
8705
     */
8706
    protected function resetElementsToBeDeleted()
8707
    {
8708
        $this->runtimeCache->remove('core-datahandler-elementsToBeDeleted');
8709
    }
8710
8711
    /**
8712
     * Unsets elements (e.g. of the data map) that shall be deleted.
8713
     * This avoids to modify records that will be deleted later on.
8714
     *
8715
     * @param array $elements Elements to be modified
8716
     * @return array
8717
     */
8718
    protected function unsetElementsToBeDeleted(array $elements)
8719
    {
8720
        $elements = ArrayUtility::arrayDiffAssocRecursive($elements, $this->getCommandMapElements('delete'));
8721
        foreach ($elements as $key => $value) {
8722
            if (empty($value)) {
8723
                unset($elements[$key]);
8724
            }
8725
        }
8726
        return $elements;
8727
    }
8728
8729
    /**
8730
     * Gets elements of the command map that match a particular command.
8731
     *
8732
     * @param string $needle The command to be matched
8733
     * @return array
8734
     */
8735
    protected function getCommandMapElements($needle)
8736
    {
8737
        $elements = [];
8738
        foreach ($this->cmdmap as $tableName => $idArray) {
8739
            foreach ($idArray as $id => $commandArray) {
8740
                foreach ($commandArray as $command => $value) {
8741
                    if ($value && $command == $needle) {
8742
                        $elements[$tableName][$id] = true;
8743
                    }
8744
                }
8745
            }
8746
        }
8747
        return $elements;
8748
    }
8749
8750
    /**
8751
     * Controls active elements and sets NULL values if not active.
8752
     * Datamap is modified accordant to submitted control values.
8753
     */
8754
    protected function controlActiveElements()
8755
    {
8756
        if (!empty($this->control['active'])) {
8757
            $this->setNullValues(
8758
                $this->control['active'],
8759
                $this->datamap
8760
            );
8761
        }
8762
    }
8763
8764
    /**
8765
     * Sets NULL values in haystack array.
8766
     * The general behaviour in the user interface is to enable/activate fields.
8767
     * Thus, this method uses NULL as value to be stored if a field is not active.
8768
     *
8769
     * @param array $active hierarchical array with active elements
8770
     * @param array $haystack hierarchical array with haystack to be modified
8771
     */
8772
    protected function setNullValues(array $active, array &$haystack)
8773
    {
8774
        foreach ($active as $key => $value) {
8775
            // Nested data is processes recursively
8776
            if (is_array($value)) {
8777
                $this->setNullValues(
8778
                    $value,
8779
                    $haystack[$key]
8780
                );
8781
            } elseif ($value == 0) {
8782
                // Field has not been activated in the user interface,
8783
                // thus a NULL value shall be stored in the database
8784
                $haystack[$key] = null;
8785
            }
8786
        }
8787
    }
8788
8789
    /**
8790
     * @param CorrelationId $correlationId
8791
     */
8792
    public function setCorrelationId(CorrelationId $correlationId): void
8793
    {
8794
        $this->correlationId = $correlationId;
8795
    }
8796
8797
    /**
8798
     * @return CorrelationId|null
8799
     */
8800
    public function getCorrelationId(): ?CorrelationId
8801
    {
8802
        return $this->correlationId;
8803
    }
8804
8805
    /**
8806
     * Entry point to post process a database insert. Currently bails early unless a UID has been forced
8807
     * and the database platform is not MySQL.
8808
     *
8809
     * @param \TYPO3\CMS\Core\Database\Connection $connection
8810
     * @param string $tableName
8811
     * @param int $suggestedUid
8812
     * @return int
8813
     */
8814
    protected function postProcessDatabaseInsert(Connection $connection, string $tableName, int $suggestedUid): int
8815
    {
8816
        if ($suggestedUid !== 0 && $connection->getDatabasePlatform() instanceof PostgreSqlPlatform) {
8817
            $this->postProcessPostgresqlInsert($connection, $tableName);
8818
            // The last inserted id on postgresql is actually the last value generated by the sequence.
8819
            // On a forced UID insert this might not be the actual value or the sequence might not even
8820
            // have generated a value yet.
8821
            // Return the actual ID we forced on insert as a surrogate.
8822
            return $suggestedUid;
8823
        }
8824
        if ($connection->getDatabasePlatform() instanceof SQLServerPlatform) {
8825
            return $this->postProcessSqlServerInsert($connection, $tableName);
8826
        }
8827
        $id = $connection->lastInsertId($tableName);
8828
        return (int)$id;
8829
    }
8830
8831
    /**
8832
     * Get the last insert ID from sql server
8833
     *
8834
     * - first checks whether doctrine might be able to fetch the ID from the
8835
     * sequence table
8836
     * - if that does not succeed it manually selects the current IDENTITY value
8837
     * from a table
8838
     * - returns 0 if both fail
8839
     *
8840
     * @param \TYPO3\CMS\Core\Database\Connection $connection
8841
     * @param string $tableName
8842
     * @return int
8843
     * @throws \Doctrine\DBAL\DBALException
8844
     */
8845
    protected function postProcessSqlServerInsert(Connection $connection, string $tableName): int
8846
    {
8847
        $id = $connection->lastInsertId($tableName);
8848
        if (!((int)$id > 0)) {
8849
            $table = $connection->quoteIdentifier($tableName);
8850
            $result = $connection->executeQuery('SELECT IDENT_CURRENT(\'' . $table . '\') AS id')->fetch();
8851
            if (isset($result['id']) && $result['id'] > 0) {
8852
                $id = $result['id'];
8853
            }
8854
        }
8855
        return (int)$id;
8856
    }
8857
8858
    /**
8859
     * PostgreSQL works with sequences for auto increment columns. A sequence is not updated when a value is
8860
     * written to such a column. To avoid clashes when the sequence returns an existing ID this helper will
8861
     * update the sequence to the current max value of the column.
8862
     *
8863
     * @param \TYPO3\CMS\Core\Database\Connection $connection
8864
     * @param string $tableName
8865
     */
8866
    protected function postProcessPostgresqlInsert(Connection $connection, string $tableName)
8867
    {
8868
        $queryBuilder = $connection->createQueryBuilder();
8869
        $queryBuilder->getRestrictions()->removeAll();
8870
        $row = $queryBuilder->select('PGT.schemaname', 'S.relname', 'C.attname', 'T.relname AS tablename')
8871
            ->from('pg_class', 'S')
8872
            ->from('pg_depend', 'D')
8873
            ->from('pg_class', 'T')
8874
            ->from('pg_attribute', 'C')
8875
            ->from('pg_tables', 'PGT')
8876
            ->where(
8877
                $queryBuilder->expr()->eq('S.relkind', $queryBuilder->quote('S')),
8878
                $queryBuilder->expr()->eq('S.oid', $queryBuilder->quoteIdentifier('D.objid')),
8879
                $queryBuilder->expr()->eq('D.refobjid', $queryBuilder->quoteIdentifier('T.oid')),
8880
                $queryBuilder->expr()->eq('D.refobjid', $queryBuilder->quoteIdentifier('C.attrelid')),
8881
                $queryBuilder->expr()->eq('D.refobjsubid', $queryBuilder->quoteIdentifier('C.attnum')),
8882
                $queryBuilder->expr()->eq('T.relname', $queryBuilder->quoteIdentifier('PGT.tablename')),
8883
                $queryBuilder->expr()->eq('PGT.tablename', $queryBuilder->quote($tableName))
8884
            )
8885
            ->setMaxResults(1)
8886
            ->execute()
8887
            ->fetch();
8888
8889
        if ($row !== false) {
8890
            $connection->exec(
8891
                sprintf(
8892
                    'SELECT SETVAL(%s, COALESCE(MAX(%s), 0)+1, FALSE) FROM %s',
8893
                    $connection->quote($row['schemaname'] . '.' . $row['relname']),
8894
                    $connection->quoteIdentifier($row['attname']),
8895
                    $connection->quoteIdentifier($row['schemaname'] . '.' . $row['tablename'])
8896
                )
8897
            );
8898
        }
8899
    }
8900
8901
    /**
8902
     * Return the cache entry identifier for field evals
8903
     *
8904
     * @param string $additionalIdentifier
8905
     * @return string
8906
     */
8907
    protected function getFieldEvalCacheIdentifier($additionalIdentifier)
8908
    {
8909
        return 'core-datahandler-eval-' . md5($additionalIdentifier);
8910
    }
8911
8912
    /**
8913
     * @return RelationHandler
8914
     */
8915
    protected function createRelationHandlerInstance()
8916
    {
8917
        $isWorkspacesLoaded = ExtensionManagementUtility::isLoaded('workspaces');
8918
        $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
8919
        $relationHandler->setWorkspaceId($this->BE_USER->workspace);
8920
        $relationHandler->setUseLiveReferenceIds($isWorkspacesLoaded);
8921
        $relationHandler->setUseLiveParentIds($isWorkspacesLoaded);
8922
        $relationHandler->setReferenceIndexUpdater($this->referenceIndexUpdater);
8923
        return $relationHandler;
8924
    }
8925
8926
    /**
8927
     * Create and returns an instance of the CacheManager
8928
     *
8929
     * @return CacheManager
8930
     */
8931
    protected function getCacheManager()
8932
    {
8933
        return GeneralUtility::makeInstance(CacheManager::class);
8934
    }
8935
8936
    /**
8937
     * Gets the resourceFactory
8938
     *
8939
     * @return ResourceFactory
8940
     */
8941
    protected function getResourceFactory()
8942
    {
8943
        return GeneralUtility::makeInstance(ResourceFactory::class);
8944
    }
8945
8946
    /**
8947
     * @return LanguageService
8948
     */
8949
    protected function getLanguageService()
8950
    {
8951
        return $GLOBALS['LANG'];
8952
    }
8953
8954
    /**
8955
     * @internal should only be used from within TYPO3 Core
8956
     * @return array
8957
     */
8958
    public function getHistoryRecords(): array
8959
    {
8960
        return $this->historyRecords;
8961
    }
8962
}
8963