Passed
Push — master ( 35f6e8...efa49d )
by
unknown
13:05
created

DataHandler::overlayAutoVersionId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 7
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) && !empty($fieldConfig['MM'])) {
5337
                $this->discardMmRelations($table, $fieldConfig, $record);
5338
            }
5339
            // @todo not inline and not mm - probably not handled correctly and has no proper test coverage yet
5340
        }
5341
    }
5342
5343
    /**
5344
     * When a workspace record row is discarded that has mm relations, existing mm table rows need
5345
     * to be deleted. The method performs the delete operation depending on TCA field configuration.
5346
     *
5347
     * @param string $table Handled table name
5348
     * @param array $fieldConfig TCA configuration of this field
5349
     * @param array $record The full record of a left- or ride-side relation
5350
     */
5351
    protected function discardMmRelations(string $table, array $fieldConfig, array $record): void
5352
    {
5353
        $recordUid = (int)$record['uid'];
5354
        $mmTableName = $fieldConfig['MM'];
5355
        // left - non foreign - uid_local vs. right - foreign - uid_foreign decision
5356
        $relationUidFieldName = isset($fieldConfig['MM_opposite_field']) ? 'uid_foreign' : 'uid_local';
5357
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($mmTableName);
5358
        $queryBuilder->delete($mmTableName)->where(
5359
            // uid_local = given uid OR uid_foreign = given uid
5360
            $queryBuilder->expr()->eq($relationUidFieldName, $queryBuilder->createNamedParameter($recordUid, \PDO::PARAM_INT))
5361
        );
5362
        if ($relationUidFieldName === 'uid_foreign') {
5363
            // When discarding a local-side record - eg. sys_category - it does not matter who points to it,
5364
            // all relations can be dropped. If on foreign side - eg. tt_content to sys_category - "tablenames"
5365
            // field has to be taken into account to not delete rows with same uid from other tables.
5366
            $queryBuilder->andWhere(
5367
                $queryBuilder->expr()->eq('tablenames', $queryBuilder->createNamedParameter($table, \PDO::PARAM_STR))
5368
            );
5369
        }
5370
        if (!empty($fieldConfig['MM_table_where']) && is_string($fieldConfig['MM_table_where'])) {
5371
            $queryBuilder->andWhere(
5372
                QueryHelper::stripLogicalOperatorPrefix(str_replace('###THIS_UID###', (string)$recordUid, $fieldConfig['MM_table_where']))
5373
            );
5374
        }
5375
        $mmMatchFields = $fieldConfig['MM_match_fields'] ?? [];
5376
        foreach ($mmMatchFields as $fieldName => $fieldValue) {
5377
            $queryBuilder->andWhere(
5378
                $queryBuilder->expr()->eq($fieldName, $queryBuilder->createNamedParameter($fieldValue, \PDO::PARAM_STR))
5379
            );
5380
        }
5381
        $queryBuilder->execute();
5382
    }
5383
5384
    /**
5385
     * Find localization overlays of a record and discard them.
5386
     *
5387
     * @param string $table Table of this record
5388
     * @param array $record Record row
5389
     */
5390
    protected function discardLocalizationOverlayRecords(string $table, array $record): void
5391
    {
5392
        if (!BackendUtility::isTableLocalizable($table)) {
5393
            return;
5394
        }
5395
        $uid = (int)$record['uid'];
5396
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5397
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5398
        $statement = $queryBuilder->select('*')
5399
            ->from($table)
5400
            ->where(
5401
                $queryBuilder->expr()->eq(
5402
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5403
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5404
                ),
5405
                $queryBuilder->expr()->eq(
5406
                    't3ver_wsid',
5407
                    $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5408
                )
5409
            )
5410
            ->execute();
5411
        while ($record = $statement->fetch()) {
5412
            $this->discard($table, null, $record);
5413
        }
5414
    }
5415
5416
    /*********************************************
5417
     *
5418
     * Cmd: Versioning
5419
     *
5420
     ********************************************/
5421
    /**
5422
     * Creates a new version of a record
5423
     * (Requires support in the table)
5424
     *
5425
     * @param string $table Table name
5426
     * @param int $id Record uid to versionize
5427
     * @param string $label Version label
5428
     * @param bool $delete If TRUE, the version is created to delete the record.
5429
     * @return int|null Returns the id of the new version (if any)
5430
     * @see copyRecord()
5431
     * @internal should only be used from within DataHandler
5432
     */
5433
    public function versionizeRecord($table, $id, $label, $delete = false)
5434
    {
5435
        $id = (int)$id;
5436
        // Stop any actions if the record is marked to be deleted:
5437
        // (this can occur if IRRE elements are versionized and child elements are removed)
5438
        if ($this->isElementToBeDeleted($table, $id)) {
5439
            return null;
5440
        }
5441
        if (!BackendUtility::isTableWorkspaceEnabled($table) || $id <= 0) {
5442
            $this->newlog('Versioning is not supported for this table "' . $table . '" / ' . $id, SystemLogErrorClassification::USER_ERROR);
5443
            return null;
5444
        }
5445
5446
        // Fetch record with permission check
5447
        $row = $this->recordInfoWithPermissionCheck($table, $id, Permission::PAGE_SHOW);
5448
5449
        // This checks if the record can be selected which is all that a copy action requires.
5450
        if ($row === false) {
5451
            $this->newlog(
5452
                'The record does not exist or you don\'t have correct permissions to make a new version (copy) of this record "' . $table . ':' . $id . '"',
5453
                SystemLogErrorClassification::USER_ERROR
5454
            );
5455
            return null;
5456
        }
5457
5458
        // Record must be online record, otherwise we would create a version of a version
5459
        if (($row['t3ver_oid'] ?? 0) > 0) {
5460
            $this->newlog('Record "' . $table . ':' . $id . '" you wanted to versionize was already a version in archive (record has an online ID)!', SystemLogErrorClassification::USER_ERROR);
5461
            return null;
5462
        }
5463
5464
        if ($delete && $this->cannotDeleteRecord($table, $id)) {
5465
            $this->newlog('Record cannot be deleted: ' . $this->cannotDeleteRecord($table, $id), SystemLogErrorClassification::USER_ERROR);
5466
            return null;
5467
        }
5468
5469
        // Set up the values to override when making a raw-copy:
5470
        $overrideArray = [
5471
            't3ver_oid' => $id,
5472
            't3ver_wsid' => $this->BE_USER->workspace,
5473
            't3ver_state' => (string)($delete ? new VersionState(VersionState::DELETE_PLACEHOLDER) : new VersionState(VersionState::DEFAULT_STATE)),
5474
            't3ver_stage' => 0,
5475
        ];
5476
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock']) {
5477
            $overrideArray[$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
5478
        }
5479
        // Checking if the record already has a version in the current workspace of the backend user
5480
        $versionRecord = ['uid' => null];
5481
        if ($this->BE_USER->workspace !== 0) {
5482
            // Look for version already in workspace:
5483
            $versionRecord = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid');
5484
        }
5485
        // Create new version of the record and return the new uid
5486
        if (empty($versionRecord['uid'])) {
5487
            // Create raw-copy and return result:
5488
            // The information of the label to be used for the workspace record
5489
            // as well as the information whether the record shall be removed
5490
            // must be forwarded (creating delete placeholders on a workspace are
5491
            // done by copying the record and override several fields).
5492
            $workspaceOptions = [
5493
                'delete' => $delete,
5494
                'label' => $label,
5495
            ];
5496
            return $this->copyRecord_raw($table, $id, (int)$row['pid'], $overrideArray, $workspaceOptions);
5497
        }
5498
        // Reuse the existing record and return its uid
5499
        // (prior to TYPO3 CMS 6.2, an error was thrown here, which
5500
        // did not make much sense since the information is available)
5501
        return $versionRecord['uid'];
5502
    }
5503
5504
    /**
5505
     * Swaps MM-relations for current/swap record, see version_swap()
5506
     *
5507
     * @param string $table Table for the two input records
5508
     * @param int $id Current record (about to go offline)
5509
     * @param int $swapWith Swap record (about to go online)
5510
     * @see version_swap()
5511
     * @internal should only be used from within DataHandler
5512
     */
5513
    public function version_remapMMForVersionSwap($table, $id, $swapWith)
5514
    {
5515
        // Actually, selecting the records fully is only need if flexforms are found inside... This could be optimized ...
5516
        $currentRec = BackendUtility::getRecord($table, $id);
5517
        $swapRec = BackendUtility::getRecord($table, $swapWith);
5518
        $this->version_remapMMForVersionSwap_reg = [];
5519
        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5520
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fConf) {
5521
            $conf = $fConf['config'];
5522
            if ($this->isReferenceField($conf)) {
5523
                $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5524
                $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
5525
                if ($conf['MM']) {
5526
                    /** @var RelationHandler $dbAnalysis */
5527
                    $dbAnalysis = $this->createRelationHandlerInstance();
5528
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $id, $table, $conf);
5529
                    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

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

5799
                    $liveRelations->writeMM($conf['MM'], $liveId, /** @scrutinizer ignore-type */ $prependName);
Loading history...
5800
                }
5801
            }
5802
        }
5803
        // If a change has been done, set the new value(s)
5804
        if ($set) {
5805
            if ($conf['MM']) {
5806
                $dbAnalysis->writeMM($conf['MM'], $MM_localUid, $prependName);
5807
            } else {
5808
                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

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

6908
                    $this->getRecordHistoryStore()->addRecord($table, $id, /** @scrutinizer ignore-type */ $newRow, $this->correlationId);
Loading history...
6909
6910
                    if ($newVersion) {
6911
                        if ($this->enableLogging) {
6912
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
6913
                            $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);
6914
                        }
6915
                    } else {
6916
                        if ($this->enableLogging) {
6917
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
6918
                            $page_propArr = $this->getRecordProperties('pages', $propArr['pid']);
6919
                            $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);
6920
                        }
6921
                        // Clear cache for relevant pages:
6922
                        $this->registerRecordIdForPageCacheClearing($table, $id);
6923
                    }
6924
                    return $id;
6925
                }
6926
                if ($this->enableLogging) {
6927
                    $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

6927
                    $this->log($table, /** @scrutinizer ignore-type */ $id, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$insertErrorMessage, $table . ':' . $id]);
Loading history...
6928
                }
6929
            }
6930
        }
6931
        return null;
6932
    }
6933
6934
    /**
6935
     * Checking stored record to see if the written values are properly updated.
6936
     *
6937
     * @param string $table Record table name
6938
     * @param int $id Record uid
6939
     * @param array $fieldArray Array of field=>value pairs to insert/update
6940
     * @param string $action Action, for logging only.
6941
     * @return array|null Selected row
6942
     * @see insertDB()
6943
     * @see updateDB()
6944
     * @internal should only be used from within DataHandler
6945
     */
6946
    public function checkStoredRecord($table, $id, $fieldArray, $action)
6947
    {
6948
        $id = (int)$id;
6949
        if (is_array($GLOBALS['TCA'][$table]) && $id) {
6950
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6951
            $queryBuilder->getRestrictions()->removeAll();
6952
6953
            $row = $queryBuilder
6954
                ->select('*')
6955
                ->from($table)
6956
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6957
                ->execute()
6958
                ->fetch();
6959
6960
            if (!empty($row)) {
6961
                // Traverse array of values that was inserted into the database and compare with the actually stored value:
6962
                $errors = [];
6963
                foreach ($fieldArray as $key => $value) {
6964
                    if (!$this->checkStoredRecords_loose || $value || $row[$key]) {
6965
                        if (is_float($row[$key])) {
6966
                            // if the database returns the value as double, compare it as double
6967
                            if ((double)$value !== (double)$row[$key]) {
6968
                                $errors[] = $key;
6969
                            }
6970
                        } else {
6971
                            $dbType = $GLOBALS['TCA'][$table]['columns'][$key]['config']['dbType'] ?? false;
6972
                            if ($dbType === 'datetime' || $dbType === 'time') {
6973
                                $row[$key] = $this->normalizeTimeFormat($table, $row[$key], $dbType);
6974
                            }
6975
                            if ((string)$value !== (string)$row[$key]) {
6976
                                // The is_numeric check catches cases where we want to store a float/double value
6977
                                // and database returns the field as a string with the least required amount of
6978
                                // significant digits, i.e. "0.00" being saved and "0" being read back.
6979
                                if (is_numeric($value) && is_numeric($row[$key])) {
6980
                                    if ((double)$value === (double)$row[$key]) {
6981
                                        continue;
6982
                                    }
6983
                                }
6984
                                $errors[] = $key;
6985
                            }
6986
                        }
6987
                    }
6988
                }
6989
                // Set log message if there were fields with unmatching values:
6990
                if (!empty($errors)) {
6991
                    $message = sprintf(
6992
                        '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.',
6993
                        $id,
6994
                        $table,
6995
                        implode(', ', $errors)
6996
                    );
6997
                    $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

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

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

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