Passed
Push — master ( 14b865...72c82f )
by
unknown
16:26
created

DataHandler::isRecordLocalized()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4299
                $queryBuilder->setParameter('pointer', abs(/** @scrutinizer ignore-type */ $originalRecordDestinationPid), \PDO::PARAM_INT);
Loading history...
4300
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
4301
                // Index the localized record uids by language
4302
                if (is_array($destL10nRecords)) {
4303
                    foreach ($destL10nRecords as $record) {
4304
                        $localizedDestPids[$record[$languageField]] = -$record['uid'];
4305
                    }
4306
                }
4307
            }
4308
            // Move the localized records after the corresponding localizations of the destination record
4309
            foreach ($l10nRecords as $record) {
4310
                $localizedDestPid = (int)($localizedDestPids[$record[$languageField]] ?? 0);
4311
                if ($localizedDestPid < 0) {
4312
                    $this->moveRecord($table, $record['uid'], $localizedDestPid);
4313
                } else {
4314
                    $this->moveRecord($table, $record['uid'], $destPid);
4315
                }
4316
            }
4317
        }
4318
    }
4319
4320
    /**
4321
     * Localizes a record to another system language
4322
     *
4323
     * @param string $table Table name
4324
     * @param int $uid Record uid (to be localized)
4325
     * @param int $language Language ID (from sys_language table)
4326
     * @return int|bool The uid (int) of the new translated record or FALSE (bool) if something went wrong
4327
     * @internal should only be used from within DataHandler
4328
     */
4329
    public function localize($table, $uid, $language)
4330
    {
4331
        $newId = false;
4332
        $uid = (int)$uid;
4333
        if (!$GLOBALS['TCA'][$table] || !$uid || $this->isNestedElementCallRegistered($table, $uid, 'localize-' . (string)$language) !== false) {
4334
            return false;
4335
        }
4336
4337
        $this->registerNestedElementCall($table, $uid, 'localize-' . (string)$language);
4338
        if (!$GLOBALS['TCA'][$table]['ctrl']['languageField'] || !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
4339
            $this->newlog('Localization failed; "languageField" and "transOrigPointerField" must be defined for the table ' . $table, SystemLogErrorClassification::USER_ERROR);
4340
            return false;
4341
        }
4342
        $langRec = BackendUtility::getRecord('sys_language', (int)$language, 'uid,title');
4343
        if (!$langRec) {
4344
            $this->newlog('Sys language UID "' . $language . '" not found valid!', SystemLogErrorClassification::USER_ERROR);
4345
            return false;
4346
        }
4347
4348
        if (!$this->doesRecordExist($table, $uid, Permission::PAGE_SHOW)) {
4349
            $this->newlog('Attempt to localize record ' . $table . ':' . $uid . ' without permission.', SystemLogErrorClassification::USER_ERROR);
4350
            return false;
4351
        }
4352
4353
        // Getting workspace overlay if possible - this will localize versions in workspace if any
4354
        $row = BackendUtility::getRecordWSOL($table, $uid);
4355
        if (!is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
4356
            $this->newlog('Attempt to localize record ' . $table . ':' . $uid . ' that did not exist!', SystemLogErrorClassification::USER_ERROR);
4357
            return false;
4358
        }
4359
4360
        // Make sure that records which are translated from another language than the default language have a correct
4361
        // localization source set themselves, before translating them to another language.
4362
        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] !== 0
4363
            && $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
4364
            $localizationParentRecord = BackendUtility::getRecord(
4365
                $table,
4366
                $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]
4367
            );
4368
            if ((int)$localizationParentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] !== 0) {
4369
                $this->newlog('Localization failed; Source record ' . $table . ':' . $localizationParentRecord['uid'] . ' contained a reference to an original record that is not a default record (which is strange)!', SystemLogErrorClassification::USER_ERROR);
4370
                return false;
4371
            }
4372
        }
4373
4374
        // Default language records must never have a localization parent as they are the origin of any translation.
4375
        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] !== 0
4376
            && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
4377
            $this->newlog('Localization failed; Source record ' . $table . ':' . $row['uid'] . ' contained a reference to an original default record but is a default record itself (which is strange)!', SystemLogErrorClassification::USER_ERROR);
4378
            return false;
4379
        }
4380
4381
        $recordLocalizations = BackendUtility::getRecordLocalization($table, $uid, $language, 'AND pid=' . (int)$row['pid']);
4382
4383
        if (!empty($recordLocalizations)) {
4384
            $this->newlog(sprintf(
4385
                'Localization failed: there already are localizations (%s) for language %d of the "%s" record %d!',
4386
                implode(', ', array_column($recordLocalizations, 'uid')),
4387
                $language,
4388
                $table,
4389
                $uid
4390
            ), 1);
4391
            return false;
4392
        }
4393
4394
        // Initialize:
4395
        $overrideValues = [];
4396
        // Set override values:
4397
        $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $langRec['uid'];
4398
        // If the translated record is a default language record, set it's uid as localization parent of the new record.
4399
        // If translating from any other language, no override is needed; we just can copy the localization parent of
4400
        // the original record (which is pointing to the correspondent default language record) to the new record.
4401
        // In copy / free mode the TransOrigPointer field is always set to 0, as no connection to the localization parent is wanted in that case.
4402
        // For pages, there is no "copy/free mode".
4403
        if (($this->useTransOrigPointerField || $table === 'pages') && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
4404
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $uid;
4405
        } elseif (!$this->useTransOrigPointerField) {
4406
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = 0;
4407
        }
4408
        if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
4409
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['translationSource']] = $uid;
4410
        }
4411
        // Copy the type (if defined in both tables) from the original record so that translation has same type as original record
4412
        if (isset($GLOBALS['TCA'][$table]['ctrl']['type'])) {
4413
            // @todo: Possible bug here? type can be something like 'table:field', which is then null in $row, writing null to $overrideValues
4414
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['type']] = $row[$GLOBALS['TCA'][$table]['ctrl']['type']] ?? null;
4415
        }
4416
        // Set exclude Fields:
4417
        foreach ($GLOBALS['TCA'][$table]['columns'] as $fN => $fCfg) {
4418
            $translateToMsg = '';
4419
            // Check if we are just prefixing:
4420
            if (isset($fCfg['l10n_mode']) && $fCfg['l10n_mode'] === 'prefixLangTitle') {
4421
                if (($fCfg['config']['type'] === 'text' || $fCfg['config']['type'] === 'input') && (string)$row[$fN] !== '') {
4422
                    [$tscPID] = BackendUtility::getTSCpid($table, $uid, '');
4423
                    $TSConfig = BackendUtility::getPagesTSconfig($tscPID)['TCEMAIN.'] ?? [];
4424
                    $tE = $this->getTableEntries($table, $TSConfig);
4425
                    if (!empty($TSConfig['translateToMessage']) && !($tE['disablePrependAtCopy'] ?? false)) {
4426
                        $translateToMsg = $this->getLanguageService()->sL($TSConfig['translateToMessage']);
4427
                        $translateToMsg = @sprintf($translateToMsg, $langRec['title']);
4428
                    }
4429
4430
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processTranslateToClass'] ?? [] as $className) {
4431
                        $hookObj = GeneralUtility::makeInstance($className);
4432
                        if (method_exists($hookObj, 'processTranslateTo_copyAction')) {
4433
                            $hookObj->processTranslateTo_copyAction($row[$fN], $langRec, $this, $fN);
4434
                        }
4435
                    }
4436
                    if (!empty($translateToMsg)) {
4437
                        $overrideValues[$fN] = '[' . $translateToMsg . '] ' . $row[$fN];
4438
                    } else {
4439
                        $overrideValues[$fN] = $row[$fN];
4440
                    }
4441
                }
4442
            }
4443
        }
4444
4445
        if ($table !== 'pages') {
4446
            // Get the uid of record after which this localized record should be inserted
4447
            $previousUid = $this->getPreviousLocalizedRecordUid($table, $uid, $row['pid'], $language);
4448
            // Execute the copy:
4449
            $newId = $this->copyRecord($table, $uid, -$previousUid, true, $overrideValues, '', $language);
4450
        } else {
4451
            // Create new page which needs to contain the same pid as the original page
4452
            $overrideValues['pid'] = $row['pid'];
4453
            // Take over the hidden state of the original language state, this is done due to legacy reasons where-as
4454
            // pages_language_overlay was set to "hidden -> default=0" but pages hidden -> default 1"
4455
            if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'])) {
4456
                $hiddenFieldName = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
4457
                $overrideValues[$hiddenFieldName] = $row[$hiddenFieldName] ?? $GLOBALS['TCA'][$table]['columns'][$hiddenFieldName]['config']['default'];
4458
            }
4459
            $temporaryId = StringUtility::getUniqueId('NEW');
4460
            $copyTCE = $this->getLocalTCE();
4461
            $copyTCE->start([$table => [$temporaryId => $overrideValues]], [], $this->BE_USER);
4462
            $copyTCE->process_datamap();
4463
            // Getting the new UID as if it had been copied:
4464
            $theNewSQLID = $copyTCE->substNEWwithIDs[$temporaryId];
4465
            if ($theNewSQLID) {
4466
                $this->copyMappingArray[$table][$uid] = $theNewSQLID;
4467
                $newId = $theNewSQLID;
4468
            }
4469
        }
4470
4471
        return $newId;
4472
    }
4473
4474
    /**
4475
     * Performs localization or synchronization of child records.
4476
     * The $command argument expects an array, but supports a string for backward-compatibility.
4477
     *
4478
     * $command = array(
4479
     *   'field' => 'tx_myfieldname',
4480
     *   'language' => 2,
4481
     *   // either the key 'action' or 'ids' must be set
4482
     *   'action' => 'synchronize', // or 'localize'
4483
     *   'ids' => array(1, 2, 3, 4) // child element ids
4484
     * );
4485
     *
4486
     * @param string $table The table of the localized parent record
4487
     * @param int $id The uid of the localized parent record
4488
     * @param array|string $command Defines the command to be performed (see example above)
4489
     */
4490
    protected function inlineLocalizeSynchronize($table, $id, $command)
4491
    {
4492
        $parentRecord = BackendUtility::getRecordWSOL($table, $id);
4493
4494
        // Backward-compatibility handling
4495
        if (!is_array($command)) {
4496
            // <field>, (localize | synchronize | <uid>):
4497
            $parts = GeneralUtility::trimExplode(',', $command);
4498
            $command = [
4499
                'field' => $parts[0],
4500
                // The previous process expected $id to point to the localized record already
4501
                'language' => (int)$parentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']]
4502
            ];
4503
            if (!MathUtility::canBeInterpretedAsInteger($parts[1])) {
4504
                $command['action'] = $parts[1];
4505
            } else {
4506
                $command['ids'] = [$parts[1]];
4507
            }
4508
        }
4509
4510
        // In case the parent record is the default language record, fetch the localization
4511
        if (empty($parentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
4512
            // Fetch the live record
4513
            // @todo: this needs to be revisited, as getRecordLocalization() does a BackendWorkspaceRestriction
4514
            // based on $GLOBALS[BE_USER], which could differ from the $this->BE_USER->workspace value
4515
            $parentRecordLocalization = BackendUtility::getRecordLocalization($table, $id, $command['language'], 'AND t3ver_oid=0');
4516
            if (empty($parentRecordLocalization)) {
4517
                if ($this->enableLogging) {
4518
                    $this->log($table, $id, SystemLogGenericAction::UNDEFINED, 0, SystemLogErrorClassification::MESSAGE, 'Localization for parent record ' . $table . ':' . $id . '" cannot be fetched', -1, [], $this->eventPid($table, $id, $parentRecord['pid']));
4519
                }
4520
                return;
4521
            }
4522
            $parentRecord = $parentRecordLocalization[0];
4523
            $id = $parentRecord['uid'];
4524
            // Process overlay for current selected workspace
4525
            BackendUtility::workspaceOL($table, $parentRecord);
4526
        }
4527
4528
        $field = $command['field'];
4529
        $language = $command['language'];
4530
        $action = $command['action'];
4531
        $ids = $command['ids'];
4532
4533
        if (!$field || !($action === 'localize' || $action === 'synchronize') && empty($ids) || !isset($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
4534
            return;
4535
        }
4536
4537
        $config = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
4538
        $foreignTable = $config['foreign_table'];
4539
4540
        $transOrigPointer = (int)$parentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
4541
        $childTransOrigPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
4542
4543
        if (!$parentRecord || !is_array($parentRecord) || $language <= 0 || !$transOrigPointer) {
4544
            return;
4545
        }
4546
4547
        $inlineSubType = $this->getInlineFieldType($config);
4548
        if ($inlineSubType === false) {
4549
            return;
4550
        }
4551
4552
        $transOrigRecord = BackendUtility::getRecordWSOL($table, $transOrigPointer);
4553
4554
        $removeArray = [];
4555
        $mmTable = $inlineSubType === 'mm' && isset($config['MM']) && $config['MM'] ? $config['MM'] : '';
4556
        // Fetch children from original language parent:
4557
        /** @var RelationHandler $dbAnalysisOriginal */
4558
        $dbAnalysisOriginal = $this->createRelationHandlerInstance();
4559
        $dbAnalysisOriginal->start($transOrigRecord[$field], $foreignTable, $mmTable, $transOrigRecord['uid'], $table, $config);
4560
        $elementsOriginal = [];
4561
        foreach ($dbAnalysisOriginal->itemArray as $item) {
4562
            $elementsOriginal[$item['id']] = $item;
4563
        }
4564
        unset($dbAnalysisOriginal);
4565
        // Fetch children from current localized parent:
4566
        /** @var RelationHandler $dbAnalysisCurrent */
4567
        $dbAnalysisCurrent = $this->createRelationHandlerInstance();
4568
        $dbAnalysisCurrent->start($parentRecord[$field], $foreignTable, $mmTable, $id, $table, $config);
4569
        // Perform synchronization: Possibly removal of already localized records:
4570
        if ($action === 'synchronize') {
4571
            foreach ($dbAnalysisCurrent->itemArray as $index => $item) {
4572
                $childRecord = BackendUtility::getRecordWSOL($item['table'], $item['id']);
4573
                if (isset($childRecord[$childTransOrigPointerField]) && $childRecord[$childTransOrigPointerField] > 0) {
4574
                    $childTransOrigPointer = $childRecord[$childTransOrigPointerField];
4575
                    // If synchronization is requested, child record was translated once, but original record does not exist anymore, remove it:
4576
                    if (!isset($elementsOriginal[$childTransOrigPointer])) {
4577
                        unset($dbAnalysisCurrent->itemArray[$index]);
4578
                        $removeArray[$item['table']][$item['id']]['delete'] = 1;
4579
                    }
4580
                }
4581
            }
4582
        }
4583
        // Perform synchronization/localization: Possibly add unlocalized records for original language:
4584
        if ($action === 'localize' || $action === 'synchronize') {
4585
            foreach ($elementsOriginal as $originalId => $item) {
4586
                if ($this->isRecordLocalized((string)$item['table'], (int)$item['id'], (int)$language)) {
4587
                    continue;
4588
                }
4589
                $item['id'] = $this->localize($item['table'], $item['id'], $language);
4590
                $item['id'] = $this->overlayAutoVersionId($item['table'], $item['id']);
4591
                $dbAnalysisCurrent->itemArray[] = $item;
4592
            }
4593
        } elseif (!empty($ids)) {
4594
            foreach ($ids as $childId) {
4595
                if (!MathUtility::canBeInterpretedAsInteger($childId) || !isset($elementsOriginal[$childId])) {
4596
                    continue;
4597
                }
4598
                $item = $elementsOriginal[$childId];
4599
                if ($this->isRecordLocalized((string)$item['table'], (int)$item['id'], (int)$language)) {
4600
                    continue;
4601
                }
4602
                $item['id'] = $this->localize($item['table'], $item['id'], $language);
4603
                $item['id'] = $this->overlayAutoVersionId($item['table'], $item['id']);
4604
                $dbAnalysisCurrent->itemArray[] = $item;
4605
            }
4606
        }
4607
        // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
4608
        $value = implode(',', $dbAnalysisCurrent->getValueArray());
4609
        $this->registerDBList[$table][$id][$field] = $value;
4610
        // Remove child records (if synchronization requested it):
4611
        if (is_array($removeArray) && !empty($removeArray)) {
4612
            /** @var DataHandler $tce */
4613
            $tce = GeneralUtility::makeInstance(__CLASS__, $this->referenceIndexUpdater);
4614
            $tce->enableLogging = $this->enableLogging;
4615
            $tce->start([], $removeArray, $this->BE_USER);
4616
            $tce->process_cmdmap();
4617
            unset($tce);
4618
        }
4619
        $updateFields = [];
4620
        // Handle, reorder and store relations:
4621
        if ($inlineSubType === 'list') {
4622
            $updateFields = [$field => $value];
4623
        } elseif ($inlineSubType === 'field') {
4624
            $dbAnalysisCurrent->writeForeignField($config, $id);
4625
            $updateFields = [$field => $dbAnalysisCurrent->countItems(false)];
4626
        } elseif ($inlineSubType === 'mm') {
4627
            $dbAnalysisCurrent->writeMM($config['MM'], $id);
4628
            $updateFields = [$field => $dbAnalysisCurrent->countItems(false)];
4629
        }
4630
        // Update field referencing to child records of localized parent record:
4631
        if (!empty($updateFields)) {
4632
            $this->updateDB($table, $id, $updateFields);
4633
        }
4634
    }
4635
4636
    /**
4637
     * Returns true if a localization of a record exists.
4638
     *
4639
     * @param string $table
4640
     * @param int $uid
4641
     * @param int $language
4642
     * @return bool
4643
     */
4644
    protected function isRecordLocalized(string $table, int $uid, int $language): bool
4645
    {
4646
        $row = BackendUtility::getRecordWSOL($table, $uid);
4647
        $localizations = BackendUtility::getRecordLocalization($table, $uid, $language, 'pid=' . (int)$row['pid']);
4648
        return !empty($localizations);
4649
    }
4650
4651
    /*********************************************
4652
     *
4653
     * Cmd: delete
4654
     *
4655
     ********************************************/
4656
    /**
4657
     * Delete a single record
4658
     *
4659
     * @param string $table Table name
4660
     * @param int $id Record UID
4661
     * @internal should only be used from within DataHandler
4662
     */
4663
    public function deleteAction($table, $id)
4664
    {
4665
        $recordToDelete = BackendUtility::getRecord($table, $id);
4666
4667
        if (is_array($recordToDelete) && isset($recordToDelete['t3ver_wsid']) && (int)$recordToDelete['t3ver_wsid'] !== 0) {
4668
            // When dealing with a workspace record, use discard.
4669
            $this->discard($table, null, $recordToDelete);
4670
            return;
4671
        }
4672
4673
        // Record asked to be deleted was found:
4674
        if (is_array($recordToDelete)) {
4675
            $recordWasDeleted = false;
4676
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
4677
                $hookObj = GeneralUtility::makeInstance($className);
4678
                if (method_exists($hookObj, 'processCmdmap_deleteAction')) {
4679
                    $hookObj->processCmdmap_deleteAction($table, $id, $recordToDelete, $recordWasDeleted, $this);
4680
                }
4681
            }
4682
            // Delete the record if a hook hasn't deleted it yet
4683
            if (!$recordWasDeleted) {
0 ignored issues
show
introduced by
The condition $recordWasDeleted is always false.
Loading history...
4684
                $this->deleteEl($table, $id);
4685
            }
4686
        }
4687
    }
4688
4689
    /**
4690
     * Delete element from any table
4691
     *
4692
     * @param string $table Table name
4693
     * @param int $uid Record UID
4694
     * @param bool $noRecordCheck Flag: If $noRecordCheck is set, then the function does not check permission to delete record
4695
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4696
     * @param bool $deleteRecordsOnPage If false and if deleting pages, records on the page will not be deleted (edge case while swapping workspaces)
4697
     * @internal should only be used from within DataHandler
4698
     */
4699
    public function deleteEl($table, $uid, $noRecordCheck = false, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4700
    {
4701
        if ($table === 'pages') {
4702
            $this->deletePages($uid, $noRecordCheck, $forceHardDelete, $deleteRecordsOnPage);
4703
        } else {
4704
            $this->discardWorkspaceVersionsOfRecord($table, $uid);
4705
            $this->deleteRecord($table, $uid, $noRecordCheck, $forceHardDelete);
4706
        }
4707
    }
4708
4709
    /**
4710
     * Discard workspace overlays of a live record: When a live row
4711
     * is deleted, all existing workspace overlays are discarded.
4712
     *
4713
     * @param string $table Table name
4714
     * @param int $uid Record UID
4715
     * @internal should only be used from within DataHandler
4716
     */
4717
    protected function discardWorkspaceVersionsOfRecord($table, $uid): void
4718
    {
4719
        $versions = BackendUtility::selectVersionsOfRecord($table, $uid, '*', null);
4720
        if ($versions === null) {
4721
            // Null is returned by selectVersionsOfRecord() when table is not workspace aware.
4722
            return;
4723
        }
4724
        foreach ($versions as $record) {
4725
            if ($record['_CURRENT_VERSION'] ?? false) {
4726
                // The live record is included in the result from selectVersionsOfRecord()
4727
                // and marked as '_CURRENT_VERSION'. Skip this one.
4728
                continue;
4729
            }
4730
            // BE user must be put into this workspace temporarily so stuff like refindex updating
4731
            // is properly registered for this workspace when discarding records in there.
4732
            $currentUserWorkspace = $this->BE_USER->workspace;
4733
            $this->BE_USER->workspace = (int)$record['t3ver_wsid'];
4734
            $this->discard($table, null, $record);
4735
            // Switch user back to original workspace
4736
            $this->BE_USER->workspace = $currentUserWorkspace;
4737
        }
4738
    }
4739
4740
    /**
4741
     * Deleting a record
4742
     * This function may not be used to delete pages-records unless the underlying records are already deleted
4743
     * Deletes a record regardless of versioning state (live or offline, doesn't matter, the uid decides)
4744
     * If both $noRecordCheck and $forceHardDelete are set it could even delete a "deleted"-flagged record!
4745
     *
4746
     * @param string $table Table name
4747
     * @param int $uid Record UID
4748
     * @param bool $noRecordCheck Flag: If $noRecordCheck is set, then the function does not check permission to delete record
4749
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4750
     * @internal should only be used from within DataHandler
4751
     */
4752
    public function deleteRecord($table, $uid, $noRecordCheck = false, $forceHardDelete = false)
4753
    {
4754
        $currentUserWorkspace = (int)$this->BE_USER->workspace;
4755
        $uid = (int)$uid;
4756
        if (!$GLOBALS['TCA'][$table] || !$uid) {
4757
            $this->log($table, $uid, SystemLogDatabaseAction::DELETE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to delete record without delete-permissions. [' . $this->BE_USER->errorMsg . ']');
4758
            return;
4759
        }
4760
        // Skip processing already deleted records
4761
        if (!$forceHardDelete && $this->hasDeletedRecord($table, $uid)) {
4762
            return;
4763
        }
4764
4765
        // Checking if there is anything else disallowing deleting the record by checking if editing is allowed
4766
        $fullLanguageAccessCheck = true;
4767
        if ($table === 'pages') {
4768
            // If this is a page translation, the full language access check should not be done
4769
            $defaultLanguagePageId = $this->getDefaultLanguagePageId($uid);
4770
            if ($defaultLanguagePageId !== $uid) {
4771
                $fullLanguageAccessCheck = false;
4772
            }
4773
        }
4774
        $hasEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, false, $forceHardDelete, $fullLanguageAccessCheck);
4775
        if (!$hasEditAccess) {
4776
            $this->log($table, $uid, SystemLogDatabaseAction::DELETE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to delete record without delete-permissions');
4777
            return;
4778
        }
4779
        if ($table === 'pages') {
4780
            $perms = Permission::PAGE_DELETE;
4781
        } elseif ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap)) {
4782
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
4783
            $perms = Permission::PAGE_EDIT;
4784
        } else {
4785
            $perms = Permission::CONTENT_EDIT;
4786
        }
4787
        if (!$noRecordCheck && !$this->doesRecordExist($table, $uid, $perms)) {
4788
            return;
4789
        }
4790
4791
        $recordToDelete = [];
4792
        $recordWorkspaceId = 0;
4793
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
4794
            $recordToDelete = BackendUtility::getRecord($table, $uid);
4795
            $recordWorkspaceId = (int)$recordToDelete['t3ver_wsid'];
4796
        }
4797
4798
        // Clear cache before deleting the record, else the correct page cannot be identified by clear_cache
4799
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
4800
        $this->registerRecordIdForPageCacheClearing($table, $uid, $parentUid);
4801
        $deleteField = $GLOBALS['TCA'][$table]['ctrl']['delete'];
4802
        $databaseErrorMessage = '';
4803
        if ($recordWorkspaceId > 0) {
4804
            // If this is a workspace record, use discard
4805
            $this->BE_USER->workspace = $recordWorkspaceId;
4806
            $this->discard($table, null, $recordToDelete);
4807
            // Switch user back to original workspace
4808
            $this->BE_USER->workspace = $currentUserWorkspace;
4809
        } elseif ($deleteField && !$forceHardDelete) {
4810
            $updateFields = [
4811
                $deleteField => 1
4812
            ];
4813
            if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
4814
                $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
4815
            }
4816
            // before deleting this record, check for child records or references
4817
            $this->deleteRecord_procFields($table, $uid);
4818
            try {
4819
                // Delete all l10n records as well
4820
                $this->deletedRecords[$table][] = (int)$uid;
4821
                $this->deleteL10nOverlayRecords($table, $uid);
4822
                GeneralUtility::makeInstance(ConnectionPool::class)
4823
                    ->getConnectionForTable($table)
4824
                    ->update($table, $updateFields, ['uid' => (int)$uid]);
4825
            } catch (DBALException $e) {
4826
                $databaseErrorMessage = $e->getPrevious()->getMessage();
4827
            }
4828
        } else {
4829
            // Delete the hard way...:
4830
            try {
4831
                $this->hardDeleteSingleRecord($table, (int)$uid);
4832
                $this->deletedRecords[$table][] = (int)$uid;
4833
                $this->deleteL10nOverlayRecords($table, $uid);
4834
            } catch (DBALException $e) {
4835
                $databaseErrorMessage = $e->getPrevious()->getMessage();
4836
            }
4837
        }
4838
        if ($this->enableLogging) {
4839
            $state = SystemLogDatabaseAction::DELETE;
4840
            if ($databaseErrorMessage === '') {
4841
                if ($forceHardDelete) {
4842
                    $message = 'Record \'%s\' (%s) was deleted unrecoverable from page \'%s\' (%s)';
4843
                } else {
4844
                    $message = 'Record \'%s\' (%s) was deleted from page \'%s\' (%s)';
4845
                }
4846
                $propArr = $this->getRecordProperties($table, $uid);
4847
                $pagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4848
4849
                $this->log($table, $uid, $state, 0, SystemLogErrorClassification::MESSAGE, $message, 0, [
4850
                    $propArr['header'],
4851
                    $table . ':' . $uid,
4852
                    $pagePropArr['header'],
4853
                    $propArr['pid']
4854
                ], $propArr['event_pid']);
4855
            } else {
4856
                $this->log($table, $uid, $state, 0, SystemLogErrorClassification::TODAYS_SPECIAL, $databaseErrorMessage);
4857
            }
4858
        }
4859
4860
        // Add history entry
4861
        $this->getRecordHistoryStore()->deleteRecord($table, $uid, $this->correlationId);
4862
4863
        // Update reference index with table/uid on left side (recuid)
4864
        $this->updateRefIndex($table, $uid);
4865
        // Update reference index with table/uid on right side (ref_uid). Important if children of a relation are deleted.
4866
        $this->referenceIndexUpdater->registerUpdateForReferencesToItem($table, $uid, $currentUserWorkspace);
4867
    }
4868
4869
    /**
4870
     * Used to delete page because it will check for branch below pages and disallowed tables on the page as well.
4871
     *
4872
     * @param int $uid Page id
4873
     * @param bool $force If TRUE, pages are not checked for permission.
4874
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4875
     * @param bool $deleteRecordsOnPage If false, records on the page will not be deleted (edge case while swapping workspaces)
4876
     * @internal should only be used from within DataHandler
4877
     */
4878
    public function deletePages($uid, $force = false, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4879
    {
4880
        $uid = (int)$uid;
4881
        if ($uid === 0) {
4882
            if ($this->enableLogging) {
4883
                $this->log('pages', $uid, SystemLogGenericAction::UNDEFINED, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'Deleting all pages starting from the root-page is disabled.', -1, [], 0);
4884
            }
4885
            return;
4886
        }
4887
        // Getting list of pages to delete:
4888
        if ($force) {
4889
            // Returns the branch WITHOUT permission checks (0 secures that), so it cannot return -1
4890
            $pageIdsInBranch = $this->doesBranchExist('', $uid, 0, true);
4891
            $res = GeneralUtility::intExplode(',', $pageIdsInBranch . $uid, true);
4892
        } else {
4893
            $res = $this->canDeletePage($uid);
4894
        }
4895
        // Perform deletion if not error:
4896
        if (is_array($res)) {
4897
            foreach ($res as $deleteId) {
4898
                $this->deleteSpecificPage($deleteId, $forceHardDelete, $deleteRecordsOnPage);
4899
            }
4900
        } else {
4901
            /** @var FlashMessage $flashMessage */
4902
            $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $res, '', FlashMessage::ERROR, true);
4903
            /** @var FlashMessageService $flashMessageService */
4904
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
4905
            $flashMessageService->getMessageQueueByIdentifier()->addMessage($flashMessage);
4906
            $this->newlog($res, SystemLogErrorClassification::USER_ERROR);
4907
        }
4908
    }
4909
4910
    /**
4911
     * Delete a page (or set deleted field to 1) and all records on it.
4912
     *
4913
     * @param int $uid Page id
4914
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4915
     * @param bool $deleteRecordsOnPage If false, records on the page will not be deleted (edge case while swapping workspaces)
4916
     * @internal
4917
     * @see deletePages()
4918
     */
4919
    public function deleteSpecificPage($uid, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4920
    {
4921
        $uid = (int)$uid;
4922
        if (!$uid) {
4923
            // Early void return on invalid uid
4924
            return;
4925
        }
4926
        $forceHardDelete = (bool)$forceHardDelete;
4927
4928
        // Delete either a default language page or a translated page
4929
        $pageIdInDefaultLanguage = $this->getDefaultLanguagePageId($uid);
4930
        $isPageTranslation = false;
4931
        $pageLanguageId = 0;
4932
        if ($pageIdInDefaultLanguage !== $uid) {
4933
            // For translated pages, translated records in other tables (eg. tt_content) for the
4934
            // to-delete translated page have their pid field set to the uid of the default language record,
4935
            // NOT the uid of the translated page record.
4936
            // If a translated page is deleted, only translations of records in other tables of this language
4937
            // should be deleted. The code checks if the to-delete page is a translated page and
4938
            // adapts the query for other tables to use the uid of the default language page as pid together
4939
            // with the language id of the translated page.
4940
            $isPageTranslation = true;
4941
            $pageLanguageId = $this->pageInfo($uid, $GLOBALS['TCA']['pages']['ctrl']['languageField']);
4942
        }
4943
4944
        if ($deleteRecordsOnPage) {
4945
            $tableNames = $this->compileAdminTables();
4946
            foreach ($tableNames as $table) {
4947
                if ($table === 'pages' || ($isPageTranslation && !BackendUtility::isTableLocalizable($table))) {
4948
                    // Skip pages table. And skip table if not translatable, but a translated page is deleted
4949
                    continue;
4950
                }
4951
4952
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
4953
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
4954
                $queryBuilder
4955
                    ->select('uid')
4956
                    ->from($table)
4957
                    // order by uid is needed here to process possible live records first - overlays always
4958
                    // have a higher uid. Otherwise dbms like postgres may return rows in arbitrary order,
4959
                    // leading to hard to debug issues. This is especially relevant for the
4960
                    // discardWorkspaceVersionsOfRecord() call below.
4961
                    ->addOrderBy('uid');
4962
4963
                if ($isPageTranslation) {
4964
                    // Only delete records in the specified language
4965
                    $queryBuilder->where(
4966
                        $queryBuilder->expr()->eq(
4967
                            'pid',
4968
                            $queryBuilder->createNamedParameter($pageIdInDefaultLanguage, \PDO::PARAM_INT)
4969
                        ),
4970
                        $queryBuilder->expr()->eq(
4971
                            $GLOBALS['TCA'][$table]['ctrl']['languageField'],
4972
                            $queryBuilder->createNamedParameter($pageLanguageId, \PDO::PARAM_INT)
4973
                        )
4974
                    );
4975
                } else {
4976
                    // Delete all records on this page
4977
                    $queryBuilder->where(
4978
                        $queryBuilder->expr()->eq(
4979
                            'pid',
4980
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
4981
                        )
4982
                    );
4983
                }
4984
4985
                $currentUserWorkspace = (int)$this->BE_USER->workspace;
4986
                if ($currentUserWorkspace !== 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
4987
                    // If we are in a workspace, make sure only records of this workspace are deleted.
4988
                    $queryBuilder->andWhere(
4989
                        $queryBuilder->expr()->eq(
4990
                            't3ver_wsid',
4991
                            $queryBuilder->createNamedParameter($currentUserWorkspace, \PDO::PARAM_INT)
4992
                        )
4993
                    );
4994
                }
4995
4996
                $statement = $queryBuilder->execute();
4997
4998
                while ($row = $statement->fetch()) {
4999
                    // Delete any further workspace overlays of the record in question, then delete the record.
5000
                    $this->discardWorkspaceVersionsOfRecord($table, $row['uid']);
5001
                    $this->deleteRecord($table, $row['uid'], true, $forceHardDelete);
5002
                }
5003
            }
5004
        }
5005
5006
        // Delete any further workspace overlays of the record in question, then delete the record.
5007
        $this->discardWorkspaceVersionsOfRecord('pages', $uid);
5008
        $this->deleteRecord('pages', $uid, true, $forceHardDelete);
5009
    }
5010
5011
    /**
5012
     * Used to evaluate if a page can be deleted
5013
     *
5014
     * @param int $uid Page id
5015
     * @return int[]|string If array: List of page uids to traverse and delete (means OK), if string: error message.
5016
     * @internal should only be used from within DataHandler
5017
     */
5018
    public function canDeletePage($uid)
5019
    {
5020
        $uid = (int)$uid;
5021
        $isTranslatedPage = null;
5022
5023
        // If we may at all delete this page
5024
        // If this is a page translation, do the check against the perms_* of the default page
5025
        // Because it is currently only deleting the translation
5026
        $defaultLanguagePageId = $this->getDefaultLanguagePageId($uid);
5027
        if ($defaultLanguagePageId !== $uid) {
5028
            if ($this->doesRecordExist('pages', (int)$defaultLanguagePageId, Permission::PAGE_DELETE)) {
5029
                $isTranslatedPage = true;
5030
            } else {
5031
                return 'Attempt to delete page without permissions';
5032
            }
5033
        } elseif (!$this->doesRecordExist('pages', $uid, Permission::PAGE_DELETE)) {
5034
            return 'Attempt to delete page without permissions';
5035
        }
5036
5037
        $pageIdsInBranch = $this->doesBranchExist('', $uid, Permission::PAGE_DELETE, true);
5038
5039
        if ($pageIdsInBranch === -1) {
5040
            return 'Attempt to delete pages in branch without permissions';
5041
        }
5042
5043
        $pagesInBranch = GeneralUtility::intExplode(',', $pageIdsInBranch . $uid, true);
5044
5045
        if ($disallowedTables = $this->checkForRecordsFromDisallowedTables($pagesInBranch)) {
5046
            return 'Attempt to delete records from disallowed tables (' . implode(', ', $disallowedTables) . ')';
5047
        }
5048
5049
        foreach ($pagesInBranch as $pageInBranch) {
5050
            if (!$this->BE_USER->recordEditAccessInternals('pages', $pageInBranch, false, false, $isTranslatedPage ? false : true)) {
5051
                return 'Attempt to delete page which has prohibited localizations.';
5052
            }
5053
        }
5054
        return $pagesInBranch;
5055
    }
5056
5057
    /**
5058
     * Returns TRUE if record CANNOT be deleted, otherwise FALSE. Used to check before the versioning API allows a record to be marked for deletion.
5059
     *
5060
     * @param string $table Record Table
5061
     * @param int $id Record UID
5062
     * @return string Returns a string IF there is an error (error string explaining). FALSE means record can be deleted
5063
     * @internal should only be used from within DataHandler
5064
     */
5065
    public function cannotDeleteRecord($table, $id)
5066
    {
5067
        if ($table === 'pages') {
5068
            $res = $this->canDeletePage($id);
5069
            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...
5070
        }
5071
        if ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap)) {
5072
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
5073
            $perms = Permission::PAGE_EDIT;
5074
        } else {
5075
            $perms = Permission::CONTENT_EDIT;
5076
        }
5077
        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...
5078
    }
5079
5080
    /**
5081
     * Before a record is deleted, check if it has references such as inline type or MM references.
5082
     * If so, set these child records also to be deleted.
5083
     *
5084
     * @param string $table Record Table
5085
     * @param int $uid Record UID
5086
     * @see deleteRecord()
5087
     * @internal should only be used from within DataHandler
5088
     */
5089
    public function deleteRecord_procFields($table, $uid)
5090
    {
5091
        $conf = $GLOBALS['TCA'][$table]['columns'];
5092
        $row = BackendUtility::getRecord($table, $uid, '*', '', false);
5093
        if (empty($row)) {
5094
            return;
5095
        }
5096
        foreach ($row as $field => $value) {
5097
            $this->deleteRecord_procBasedOnFieldType($table, $uid, $value, $conf[$field]['config'] ?? []);
5098
        }
5099
    }
5100
5101
    /**
5102
     * Process fields of a record to be deleted and search for special handling, like
5103
     * inline type, MM records, etc.
5104
     *
5105
     * @param string $table Record Table
5106
     * @param int $uid Record UID
5107
     * @param string $value Record field value
5108
     * @param array $conf TCA configuration of current field
5109
     * @see deleteRecord()
5110
     * @internal should only be used from within DataHandler
5111
     */
5112
    public function deleteRecord_procBasedOnFieldType($table, $uid, $value, $conf): void
5113
    {
5114
        if (!isset($conf['type'])) {
5115
            return;
5116
        }
5117
        if ($conf['type'] === 'inline') {
5118
            $foreign_table = $conf['foreign_table'];
5119
            if ($foreign_table) {
5120
                $inlineType = $this->getInlineFieldType($conf);
5121
                if ($inlineType === 'list' || $inlineType === 'field') {
5122
                    /** @var RelationHandler $dbAnalysis */
5123
                    $dbAnalysis = $this->createRelationHandlerInstance();
5124
                    $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
5125
                    $dbAnalysis->undeleteRecord = true;
5126
5127
                    $enableCascadingDelete = true;
5128
                    // non type save comparison is intended!
5129
                    if (isset($conf['behaviour']['enableCascadingDelete']) && $conf['behaviour']['enableCascadingDelete'] == false) {
5130
                        $enableCascadingDelete = false;
5131
                    }
5132
5133
                    // Walk through the items and remove them
5134
                    foreach ($dbAnalysis->itemArray as $v) {
5135
                        if ($enableCascadingDelete) {
5136
                            $this->deleteAction($v['table'], $v['id']);
5137
                        }
5138
                    }
5139
                }
5140
            }
5141
        } elseif ($this->isReferenceField($conf)) {
5142
            $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5143
            $dbAnalysis = $this->createRelationHandlerInstance();
5144
            $dbAnalysis->start($value, $allowedTables, $conf['MM'] ?? '', $uid, $table, $conf);
5145
            foreach ($dbAnalysis->itemArray as $v) {
5146
                $this->updateRefIndex($v['table'], $v['id']);
5147
            }
5148
        }
5149
    }
5150
5151
    /**
5152
     * Find l10n-overlay records and perform the requested delete action for these records.
5153
     *
5154
     * @param string $table Record Table
5155
     * @param int $uid Record UID
5156
     * @internal should only be used from within DataHandler
5157
     */
5158
    public function deleteL10nOverlayRecords($table, $uid)
5159
    {
5160
        // Check whether table can be localized
5161
        if (!BackendUtility::isTableLocalizable($table)) {
5162
            return;
5163
        }
5164
5165
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5166
        $queryBuilder->getRestrictions()
5167
            ->removeAll()
5168
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
5169
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->BE_USER->workspace));
5170
5171
        $queryBuilder->select('*')
5172
            ->from($table)
5173
            ->where(
5174
                $queryBuilder->expr()->eq(
5175
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5176
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5177
                )
5178
            );
5179
5180
        $result = $queryBuilder->execute();
5181
        while ($record = $result->fetch()) {
5182
            // Ignore workspace delete placeholders. Those records have been marked for
5183
            // deletion before - deleting them again in a workspace would revert that state.
5184
            if ((int)$this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
5185
                BackendUtility::workspaceOL($table, $record, $this->BE_USER->workspace);
5186
                if (VersionState::cast($record['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)) {
5187
                    continue;
5188
                }
5189
            }
5190
            $this->deleteAction($table, (int)$record['t3ver_oid'] > 0 ? (int)$record['t3ver_oid'] : (int)$record['uid']);
5191
        }
5192
    }
5193
5194
    /*********************************************
5195
     *
5196
     * Cmd: undelete / restore
5197
     *
5198
     ********************************************/
5199
5200
    /**
5201
     * Restore live records by setting soft-delete flag to 0.
5202
     *
5203
     * Usually only used by ext:recycler.
5204
     * Connected relations (eg. inline) are restored, too.
5205
     * Additional existing localizations are not restored.
5206
     *
5207
     * @param string $table Record table name
5208
     * @param int $uid Record uid
5209
     */
5210
    protected function undeleteRecord(string $table, int $uid): void
5211
    {
5212
        $record = BackendUtility::getRecord($table, $uid, '*', '', false);
5213
        $deleteField = (string)($GLOBALS['TCA'][$table]['ctrl']['delete'] ?? '');
5214
        $timestampField = (string)($GLOBALS['TCA'][$table]['ctrl']['tstamp'] ?? '');
5215
5216
        if ($record === null
5217
            || $deleteField === ''
5218
            || !isset($record[$deleteField])
5219
            || (bool)$record[$deleteField] === false
5220
            || ($timestampField !== '' && !isset($record[$timestampField]))
5221
            || (int)$this->BE_USER->workspace > 0
5222
            || (BackendUtility::isTableWorkspaceEnabled($table) && (int)($record['t3ver_wsid'] ?? 0) > 0)
5223
        ) {
5224
            // Return early and silently, if:
5225
            // * Record not found
5226
            // * Table is not soft-delete aware
5227
            // * Record does not have deleted field - db analyzer not up-to-date?
5228
            // * Record is not deleted - may eventually happen via recursion with self referencing records?
5229
            // * Table is tstamp aware, but field does not exist - db analyzer not up-to-date?
5230
            // * User is in a workspace - does not make sense
5231
            // * Record is in a workspace - workspace records are not soft-delete aware
5232
            return;
5233
        }
5234
5235
        $recordPid = (int)($record['pid'] ?? 0);
5236
        if ($recordPid > 0) {
5237
            // Record is not on root level. Parent page record must exist and must not be deleted itself.
5238
            $page = BackendUtility::getRecord('pages', $recordPid, 'deleted', '', false);
5239
            if ($page === null || !isset($page['deleted']) || (bool)$page['deleted'] === true) {
5240
                $this->log(
5241
                    $table,
5242
                    $uid,
5243
                    SystemLogDatabaseAction::DELETE,
5244
                    0,
5245
                    SystemLogErrorClassification::USER_ERROR,
5246
                    sprintf('Record "%s:%s" can\'t be restored: The page:%s containing it does not exist or is soft-deleted.', $table, $uid, $recordPid),
5247
                    0,
5248
                    [],
5249
                    $recordPid
5250
                );
5251
                return;
5252
            }
5253
        }
5254
5255
        // @todo: When restoring a not-default language record, it should be verified the default language
5256
        // @todo: record is *not* set to deleted. Maybe even verify a possible l10n_source chain is not deleted?
5257
5258
        if (!$this->BE_USER->recordEditAccessInternals($table, $record, false, true)) {
5259
            // User misses access permissions to record
5260
            $this->log(
5261
                $table,
5262
                $uid,
5263
                SystemLogDatabaseAction::DELETE,
5264
                0,
5265
                SystemLogErrorClassification::USER_ERROR,
5266
                sprintf('Record "%s:%s" can\'t be restored: Insufficient user permissions.', $table, $uid),
5267
                0,
5268
                [],
5269
                $recordPid
5270
            );
5271
            return;
5272
        }
5273
5274
        // Restore referenced child records
5275
        $this->undeleteRecordRelations($table, $uid, $record);
5276
5277
        // Restore record
5278
        $updateFields[$deleteField] = 0;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$updateFields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $updateFields = array(); before regardless.
Loading history...
5279
        if ($timestampField !== '') {
5280
            $updateFields[$timestampField] = $GLOBALS['EXEC_TIME'];
5281
        }
5282
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table)
5283
            ->update(
5284
                $table,
5285
                $updateFields,
5286
                ['uid' => $uid]
5287
            );
5288
5289
        if ($this->enableLogging) {
5290
            $this->log(
5291
                $table,
5292
                $uid,
5293
                SystemLogDatabaseAction::INSERT,
5294
                0,
5295
                SystemLogErrorClassification::MESSAGE,
5296
                sprintf('Record "%s:%s" was restored on page:%s', $table, $uid, $recordPid),
5297
                0,
5298
                [],
5299
                $recordPid
5300
            );
5301
        }
5302
5303
        // Register cache clearing of page, or parent page if a page is restored.
5304
        $this->registerRecordIdForPageCacheClearing($table, $uid, $recordPid);
5305
        // Add history entry
5306
        $this->getRecordHistoryStore()->undeleteRecord($table, $uid, $this->correlationId);
5307
        // Update reference index with table/uid on left side (recuid)
5308
        $this->updateRefIndex($table, $uid);
5309
        // Update reference index with table/uid on right side (ref_uid). Important if children of a relation were restored.
5310
        $this->referenceIndexUpdater->registerUpdateForReferencesToItem($table, $uid, 0);
5311
    }
5312
5313
    /**
5314
     * Check if a to-restore record has inline references and restore them.
5315
     *
5316
     * @param string $table Record table name
5317
     * @param int $uid Record uid
5318
     * @param array $record Record row
5319
     * @todo: Add functional test undelete coverage to verify details, some details seem to be missing.
5320
     */
5321
    protected function undeleteRecordRelations(string $table, int $uid, array $record): void
5322
    {
5323
        foreach ($record as $fieldName => $value) {
5324
            $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$fieldName]['config'] ?? [];
5325
            $fieldType = (string)($fieldConfig['type'] ?? '');
5326
            if (empty($fieldConfig) || !is_array($fieldConfig) || $fieldType === '') {
5327
                continue;
5328
            }
5329
            $foreignTable = (string)($fieldConfig['foreign_table'] ?? '');
5330
            if ($fieldType === 'inline') {
5331
                // @todo: Inline MM not handled here, and what about group / select?
5332
                if ($foreignTable === ''
5333
                    || !in_array($this->getInlineFieldType($fieldConfig), ['list', 'field'], true)
5334
                ) {
5335
                    continue;
5336
                }
5337
                $relationHandler = $this->createRelationHandlerInstance();
5338
                $relationHandler->start($value, $foreignTable, '', $uid, $table, $fieldConfig);
5339
                $relationHandler->undeleteRecord = true;
5340
                foreach ($relationHandler->itemArray as $reference) {
5341
                    $this->undeleteRecord($reference['table'], (int)$reference['id']);
5342
                }
5343
            } elseif ($this->isReferenceField($fieldConfig)) {
5344
                $allowedTables = $fieldType === 'group' ? ($fieldConfig['allowed'] ?? '') : $foreignTable;
5345
                $relationHandler = $this->createRelationHandlerInstance();
5346
                $relationHandler->start($value, $allowedTables, $fieldConfig['MM'] ?? '', $uid, $table, $fieldConfig);
5347
                foreach ($relationHandler->itemArray as $reference) {
5348
                    // @todo: Unsure if this is ok / enough. Needs coverage.
5349
                    $this->updateRefIndex($reference['table'], $reference['id']);
5350
                }
5351
            }
5352
        }
5353
    }
5354
5355
    /*********************************************
5356
     *
5357
     * Cmd: Workspace discard & flush
5358
     *
5359
     ********************************************/
5360
5361
    /**
5362
     * Discard a versioned record from this workspace. This deletes records from the database - no soft delete.
5363
     * This main entry method is called recursive for sub pages, localizations, relations and records on a page.
5364
     * The method checks user access and gathers facts about this record to hand the deletion over to detail methods.
5365
     *
5366
     * The incoming $uid or $row can be anything: The workspace of current user is respected and only records
5367
     * of current user workspace are discarded. If giving a live record uid, the versioned overly will be fetched.
5368
     *
5369
     * @param string $table Database table name
5370
     * @param int|null $uid Uid of live or versioned record to be discarded, or null if $record is given
5371
     * @param array|null $record Record row that should be discarded. Used instead of $uid within recursion.
5372
     * @internal should only be used from within DataHandler
5373
     */
5374
    public function discard(string $table, ?int $uid, array $record = null): void
5375
    {
5376
        if ($uid === null && $record === null) {
5377
            throw new \RuntimeException('Either record $uid or $record row must be given', 1600373491);
5378
        }
5379
5380
        // Fetch record we are dealing with if not given
5381
        if ($record === null) {
5382
            $record = BackendUtility::getRecord($table, (int)$uid);
5383
        }
5384
        if (!is_array($record)) {
5385
            return;
5386
        }
5387
        $uid = (int)$record['uid'];
5388
5389
        // Call hook and return if hook took care of the element
5390
        $recordWasDiscarded = false;
5391
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
5392
            $hookObj = GeneralUtility::makeInstance($className);
5393
            if (method_exists($hookObj, 'processCmdmap_discardAction')) {
5394
                $hookObj->processCmdmap_discardAction($table, $uid, $record, $recordWasDiscarded);
5395
            }
5396
        }
5397
5398
        $userWorkspace = (int)$this->BE_USER->workspace;
5399
        if ($recordWasDiscarded
5400
            || $userWorkspace === 0
5401
            || !BackendUtility::isTableWorkspaceEnabled($table)
5402
            || $this->hasDeletedRecord($table, $uid)
5403
        ) {
5404
            return;
5405
        }
5406
5407
        // Gather versioned record
5408
        $versionRecord = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $versionRecord is dead and can be removed.
Loading history...
5409
        if ((int)$record['t3ver_wsid'] === 0) {
5410
            $record = BackendUtility::getWorkspaceVersionOfRecord($userWorkspace, $table, $uid);
5411
        }
5412
        if (!is_array($record)) {
5413
            return;
5414
        }
5415
        $versionRecord = $record;
5416
5417
        // User access checks
5418
        if ($userWorkspace !== (int)$versionRecord['t3ver_wsid']) {
5419
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: Different workspace', SystemLogErrorClassification::USER_ERROR);
5420
            return;
5421
        }
5422
        if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $versionRecord['uid'])) {
5423
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: ' . $errorCode, SystemLogErrorClassification::USER_ERROR);
5424
            return;
5425
        }
5426
        if (!$this->checkRecordUpdateAccess($table, $versionRecord['uid'])) {
5427
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: User has no edit access', SystemLogErrorClassification::USER_ERROR);
5428
            return;
5429
        }
5430
        $fullLanguageAccessCheck = !($table === 'pages' && (int)$versionRecord[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] !== 0);
5431
        if (!$this->BE_USER->recordEditAccessInternals($table, $versionRecord, false, true, $fullLanguageAccessCheck)) {
5432
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: User has no delete access', SystemLogErrorClassification::USER_ERROR);
5433
            return;
5434
        }
5435
5436
        // Perform discard operations
5437
        $versionState = VersionState::cast($versionRecord['t3ver_state']);
5438
        if ($table === 'pages' && $versionState->equals(VersionState::NEW_PLACEHOLDER)) {
5439
            // When discarding a new page, there can be new sub pages and new records.
5440
            // Those need to be discarded, otherwise they'd end up as records without parent page.
5441
            $this->discardSubPagesAndRecordsOnPage($versionRecord);
5442
        }
5443
5444
        $this->discardLocalizationOverlayRecords($table, $versionRecord);
5445
        $this->discardRecordRelations($table, $versionRecord);
5446
        $this->hardDeleteSingleRecord($table, (int)$versionRecord['uid']);
5447
        $this->deletedRecords[$table][] = (int)$versionRecord['uid'];
5448
        $this->registerReferenceIndexRowsForDrop($table, (int)$versionRecord['uid'], $userWorkspace);
5449
        $this->getRecordHistoryStore()->deleteRecord($table, (int)$versionRecord['uid'], $this->correlationId);
5450
        $this->log(
5451
            $table,
5452
            (int)$versionRecord['uid'],
5453
            SystemLogDatabaseAction::DELETE,
5454
            0,
5455
            SystemLogErrorClassification::MESSAGE,
5456
            'Record ' . $table . ':' . $versionRecord['uid'] . ' was deleted unrecoverable from page ' . $versionRecord['pid'],
5457
            0,
5458
            [],
5459
            (int)$versionRecord['pid']
5460
        );
5461
    }
5462
5463
    /**
5464
     * Also discard any sub pages and records of a new parent page if this page is discarded.
5465
     * Discarding only in specific localization, if needed.
5466
     *
5467
     * @param array $page Page record row
5468
     */
5469
    protected function discardSubPagesAndRecordsOnPage(array $page): void
5470
    {
5471
        $isLocalizedPage = false;
5472
        $sysLanguageId = (int)$page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
5473
        $versionState = VersionState::cast($page['t3ver_state']);
5474
        if ($sysLanguageId > 0) {
5475
            // New or moved localized page.
5476
            // Discard records on this page localization, but no sub pages.
5477
            // Records of a translated page have the pid set to the default language page uid. Found in l10n_parent.
5478
            // @todo: Discard other page translations that inherit from this?! (l10n_source field)
5479
            $isLocalizedPage = true;
5480
            $pid = (int)$page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
5481
        } elseif ($versionState->equals(VersionState::NEW_PLACEHOLDER)) {
5482
            // New default language page.
5483
            // Discard any sub pages and all other records of this page, including any page localizations.
5484
            // The t3ver_state=1 record is incoming here. Records on this page have their pid field set to the uid
5485
            // of this record. So, since t3ver_state=1 does not have an online counter-part, the actual UID is used here.
5486
            $pid = (int)$page['uid'];
5487
        } else {
5488
            // Moved default language page.
5489
            // Discard any sub pages and all other records of this page, including any page localizations.
5490
            $pid = (int)$page['t3ver_oid'];
5491
        }
5492
        $tables = $this->compileAdminTables();
5493
        foreach ($tables as $table) {
5494
            if (($isLocalizedPage && $table === 'pages')
5495
                || ($isLocalizedPage && !BackendUtility::isTableLocalizable($table))
5496
                || !BackendUtility::isTableWorkspaceEnabled($table)
5497
            ) {
5498
                continue;
5499
            }
5500
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5501
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5502
            $queryBuilder->select('*')
5503
                ->from($table)
5504
                ->where(
5505
                    $queryBuilder->expr()->eq(
5506
                        'pid',
5507
                        $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
5508
                    ),
5509
                    $queryBuilder->expr()->eq(
5510
                        't3ver_wsid',
5511
                        $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5512
                    )
5513
                );
5514
            if ($isLocalizedPage) {
5515
                // Add sys_language_uid = x restriction if discarding a localized page
5516
                $queryBuilder->andWhere(
5517
                    $queryBuilder->expr()->eq(
5518
                        $GLOBALS['TCA'][$table]['ctrl']['languageField'],
5519
                        $queryBuilder->createNamedParameter($sysLanguageId, \PDO::PARAM_INT)
5520
                    )
5521
                );
5522
            }
5523
            $statement = $queryBuilder->execute();
5524
            while ($row = $statement->fetch()) {
5525
                $this->discard($table, null, $row);
5526
            }
5527
        }
5528
    }
5529
5530
    /**
5531
     * Discard record relations like inline and MM of a record.
5532
     *
5533
     * @param string $table Table name of this record
5534
     * @param array $record The record row to handle
5535
     */
5536
    protected function discardRecordRelations(string $table, array $record): void
5537
    {
5538
        foreach ($record as $field => $value) {
5539
            $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'] ?? null;
5540
            if (!isset($fieldConfig['type'])) {
5541
                continue;
5542
            }
5543
            if ($fieldConfig['type'] === 'inline') {
5544
                $foreignTable = $fieldConfig['foreign_table'] ?? null;
5545
                if (!$foreignTable
5546
                     || (isset($fieldConfig['behaviour']['enableCascadingDelete'])
5547
                        && (bool)$fieldConfig['behaviour']['enableCascadingDelete'] === false)
5548
                ) {
5549
                    continue;
5550
                }
5551
                $inlineType = $this->getInlineFieldType($fieldConfig);
5552
                if ($inlineType === 'list' || $inlineType === 'field') {
5553
                    $dbAnalysis = $this->createRelationHandlerInstance();
5554
                    $dbAnalysis->start($value, $fieldConfig['foreign_table'], '', (int)$record['uid'], $table, $fieldConfig);
5555
                    $dbAnalysis->undeleteRecord = true;
5556
                    foreach ($dbAnalysis->itemArray as $relationRecord) {
5557
                        $this->discard($relationRecord['table'], (int)$relationRecord['id']);
5558
                    }
5559
                }
5560
            } elseif ($this->isReferenceField($fieldConfig) && !empty($fieldConfig['MM'])) {
5561
                $this->discardMmRelations($fieldConfig, $record);
5562
            }
5563
            // @todo not inline and not mm - probably not handled correctly and has no proper test coverage yet
5564
        }
5565
    }
5566
5567
    /**
5568
     * When a workspace record row is discarded that has mm relations, existing mm table rows need
5569
     * to be deleted. The method performs the delete operation depending on TCA field configuration.
5570
     *
5571
     * @param array $fieldConfig TCA configuration of this field
5572
     * @param array $record The full record of a left- or ride-side relation
5573
     */
5574
    protected function discardMmRelations(array $fieldConfig, array $record): void
5575
    {
5576
        $recordUid = (int)$record['uid'];
5577
        $mmTableName = $fieldConfig['MM'];
5578
        // left - non foreign - uid_local vs. right - foreign - uid_foreign decision
5579
        $relationUidFieldName = isset($fieldConfig['MM_opposite_field']) ? 'uid_foreign' : 'uid_local';
5580
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($mmTableName);
5581
        $queryBuilder->delete($mmTableName)->where(
5582
            // uid_local = given uid OR uid_foreign = given uid
5583
            $queryBuilder->expr()->eq($relationUidFieldName, $queryBuilder->createNamedParameter($recordUid, \PDO::PARAM_INT))
5584
        );
5585
        if (!empty($fieldConfig['MM_table_where']) && is_string($fieldConfig['MM_table_where'])) {
5586
            $queryBuilder->andWhere(
5587
                QueryHelper::stripLogicalOperatorPrefix(str_replace('###THIS_UID###', (string)$recordUid, $fieldConfig['MM_table_where']))
5588
            );
5589
        }
5590
        $mmMatchFields = $fieldConfig['MM_match_fields'] ?? [];
5591
        foreach ($mmMatchFields as $fieldName => $fieldValue) {
5592
            $queryBuilder->andWhere(
5593
                $queryBuilder->expr()->eq($fieldName, $queryBuilder->createNamedParameter($fieldValue, \PDO::PARAM_STR))
5594
            );
5595
        }
5596
        $queryBuilder->execute();
5597
    }
5598
5599
    /**
5600
     * Find localization overlays of a record and discard them.
5601
     *
5602
     * @param string $table Table of this record
5603
     * @param array $record Record row
5604
     */
5605
    protected function discardLocalizationOverlayRecords(string $table, array $record): void
5606
    {
5607
        if (!BackendUtility::isTableLocalizable($table)) {
5608
            return;
5609
        }
5610
        $uid = (int)$record['uid'];
5611
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5612
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5613
        $statement = $queryBuilder->select('*')
5614
            ->from($table)
5615
            ->where(
5616
                $queryBuilder->expr()->eq(
5617
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5618
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5619
                ),
5620
                $queryBuilder->expr()->eq(
5621
                    't3ver_wsid',
5622
                    $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5623
                )
5624
            )
5625
            ->execute();
5626
        while ($record = $statement->fetch()) {
5627
            $this->discard($table, null, $record);
5628
        }
5629
    }
5630
5631
    /*********************************************
5632
     *
5633
     * Cmd: Versioning
5634
     *
5635
     ********************************************/
5636
    /**
5637
     * Creates a new version of a record
5638
     * (Requires support in the table)
5639
     *
5640
     * @param string $table Table name
5641
     * @param int $id Record uid to versionize
5642
     * @param string $label Version label
5643
     * @param bool $delete If TRUE, the version is created to delete the record.
5644
     * @return int|null Returns the id of the new version (if any)
5645
     * @see copyRecord()
5646
     * @internal should only be used from within DataHandler
5647
     */
5648
    public function versionizeRecord($table, $id, $label, $delete = false)
5649
    {
5650
        $id = (int)$id;
5651
        // Stop any actions if the record is marked to be deleted:
5652
        // (this can occur if IRRE elements are versionized and child elements are removed)
5653
        if ($this->isElementToBeDeleted($table, $id)) {
5654
            return null;
5655
        }
5656
        if (!BackendUtility::isTableWorkspaceEnabled($table) || $id <= 0) {
5657
            $this->newlog('Versioning is not supported for this table "' . $table . '" / ' . $id, SystemLogErrorClassification::USER_ERROR);
5658
            return null;
5659
        }
5660
5661
        // Fetch record with permission check
5662
        $row = $this->recordInfoWithPermissionCheck($table, $id, Permission::PAGE_SHOW);
5663
5664
        // This checks if the record can be selected which is all that a copy action requires.
5665
        if ($row === false) {
5666
            $this->newlog(
5667
                'The record does not exist or you don\'t have correct permissions to make a new version (copy) of this record "' . $table . ':' . $id . '"',
5668
                SystemLogErrorClassification::USER_ERROR
5669
            );
5670
            return null;
5671
        }
5672
5673
        // Record must be online record, otherwise we would create a version of a version
5674
        if (($row['t3ver_oid'] ?? 0) > 0) {
5675
            $this->newlog('Record "' . $table . ':' . $id . '" you wanted to versionize was already a version in archive (record has an online ID)!', SystemLogErrorClassification::USER_ERROR);
5676
            return null;
5677
        }
5678
5679
        if ($delete && $this->cannotDeleteRecord($table, $id)) {
5680
            $this->newlog('Record cannot be deleted: ' . $this->cannotDeleteRecord($table, $id), SystemLogErrorClassification::USER_ERROR);
5681
            return null;
5682
        }
5683
5684
        // Set up the values to override when making a raw-copy:
5685
        $overrideArray = [
5686
            't3ver_oid' => $id,
5687
            't3ver_wsid' => $this->BE_USER->workspace,
5688
            't3ver_state' => (string)($delete ? new VersionState(VersionState::DELETE_PLACEHOLDER) : new VersionState(VersionState::DEFAULT_STATE)),
5689
            't3ver_stage' => 0,
5690
        ];
5691
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock'] ?? false) {
5692
            $overrideArray[$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
5693
        }
5694
        // Checking if the record already has a version in the current workspace of the backend user
5695
        $versionRecord = ['uid' => null];
5696
        if ($this->BE_USER->workspace !== 0) {
5697
            // Look for version already in workspace:
5698
            $versionRecord = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid');
5699
        }
5700
        // Create new version of the record and return the new uid
5701
        if (empty($versionRecord['uid'])) {
5702
            // Create raw-copy and return result:
5703
            // The information of the label to be used for the workspace record
5704
            // as well as the information whether the record shall be removed
5705
            // must be forwarded (creating delete placeholders on a workspace are
5706
            // done by copying the record and override several fields).
5707
            $workspaceOptions = [
5708
                'delete' => $delete,
5709
                'label' => $label,
5710
            ];
5711
            return $this->copyRecord_raw($table, $id, (int)$row['pid'], $overrideArray, $workspaceOptions);
5712
        }
5713
        // Reuse the existing record and return its uid
5714
        // (prior to TYPO3 CMS 6.2, an error was thrown here, which
5715
        // did not make much sense since the information is available)
5716
        return $versionRecord['uid'];
5717
    }
5718
5719
    /**
5720
     * Swaps MM-relations for current/swap record, see version_swap()
5721
     *
5722
     * @param string $table Table for the two input records
5723
     * @param int $id Current record (about to go offline)
5724
     * @param int $swapWith Swap record (about to go online)
5725
     * @see version_swap()
5726
     * @internal should only be used from within DataHandler
5727
     */
5728
    public function version_remapMMForVersionSwap($table, $id, $swapWith)
5729
    {
5730
        // Actually, selecting the records fully is only need if flexforms are found inside... This could be optimized ...
5731
        $currentRec = BackendUtility::getRecord($table, $id);
5732
        $swapRec = BackendUtility::getRecord($table, $swapWith);
5733
        $this->version_remapMMForVersionSwap_reg = [];
5734
        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5735
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fConf) {
5736
            $conf = $fConf['config'];
5737
            if ($this->isReferenceField($conf)) {
5738
                $allowedTables = $conf['type'] === 'group' ? ($conf['allowed'] ?? '') : $conf['foreign_table'];
5739
                $prependName = $conf['type'] === 'group' ? ($conf['prepend_tname'] ?? '') : '';
5740
                if ($conf['MM'] ?? false) {
5741
                    $dbAnalysis = $this->createRelationHandlerInstance();
5742
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $id, $table, $conf);
5743
                    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

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

6012
                    $liveRelations->writeMM($conf['MM'], $liveId, /** @scrutinizer ignore-type */ $prependName);
Loading history...
6013
                }
6014
            }
6015
        }
6016
        // If a change has been done, set the new value(s)
6017
        if ($set) {
6018
            if ($conf['MM'] ?? false) {
6019
                $dbAnalysis->writeMM($conf['MM'], $MM_localUid, $prependName);
6020
            } else {
6021
                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

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

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

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