Completed
Push — master ( 76a80d...a62bd5 )
by
unknown
17:53
created

DataHandler::addRemapStackRefIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Core\DataHandling;
17
18
use Doctrine\DBAL\DBALException;
19
use Doctrine\DBAL\Driver\Statement;
20
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
21
use Doctrine\DBAL\Platforms\SQLServerPlatform;
22
use Doctrine\DBAL\Types\IntegerType;
23
use Psr\Log\LoggerAwareInterface;
24
use Psr\Log\LoggerAwareTrait;
25
use TYPO3\CMS\Backend\Utility\BackendUtility;
26
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
27
use TYPO3\CMS\Core\Cache\CacheManager;
28
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
29
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidIdentifierException;
30
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowException;
31
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowLoopException;
32
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowRootException;
33
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidPointerFieldValueException;
34
use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
35
use TYPO3\CMS\Core\Configuration\Richtext;
36
use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException;
37
use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;
38
use TYPO3\CMS\Core\Database\Connection;
39
use TYPO3\CMS\Core\Database\ConnectionPool;
40
use TYPO3\CMS\Core\Database\Query\QueryHelper;
41
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
42
use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
43
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
44
use TYPO3\CMS\Core\Database\RelationHandler;
45
use TYPO3\CMS\Core\DataHandling\History\RecordHistoryStore;
46
use TYPO3\CMS\Core\DataHandling\Localization\DataMapProcessor;
47
use TYPO3\CMS\Core\DataHandling\Model\CorrelationId;
48
use TYPO3\CMS\Core\DataHandling\Model\RecordStateFactory;
49
use TYPO3\CMS\Core\Html\RteHtmlParser;
50
use TYPO3\CMS\Core\Localization\LanguageService;
51
use TYPO3\CMS\Core\Messaging\FlashMessage;
52
use TYPO3\CMS\Core\Messaging\FlashMessageService;
53
use TYPO3\CMS\Core\Resource\ResourceFactory;
54
use TYPO3\CMS\Core\Service\OpcodeCacheService;
55
use TYPO3\CMS\Core\SysLog\Action as SystemLogGenericAction;
56
use TYPO3\CMS\Core\SysLog\Action\Cache as SystemLogCacheAction;
57
use TYPO3\CMS\Core\SysLog\Action\Database as SystemLogDatabaseAction;
58
use TYPO3\CMS\Core\SysLog\Error as SystemLogErrorClassification;
59
use TYPO3\CMS\Core\SysLog\Type as SystemLogType;
60
use TYPO3\CMS\Core\Type\Bitmask\Permission;
61
use TYPO3\CMS\Core\Utility\ArrayUtility;
62
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
63
use TYPO3\CMS\Core\Utility\GeneralUtility;
64
use TYPO3\CMS\Core\Utility\HttpUtility;
65
use TYPO3\CMS\Core\Utility\MathUtility;
66
use TYPO3\CMS\Core\Utility\StringUtility;
67
use TYPO3\CMS\Core\Versioning\VersionState;
68
69
/**
70
 * The main data handler class which takes care of correctly updating and inserting records.
71
 * This class was formerly known as TCEmain.
72
 *
73
 * This is the TYPO3 Core Engine class for manipulation of the database
74
 * This class is used by eg. the tce_db BE route (SimpleDataHandlerController) which provides an interface for POST forms to this class.
75
 *
76
 * Dependencies:
77
 * - $GLOBALS['TCA'] must exist
78
 * - $GLOBALS['LANG'] must exist
79
 *
80
 * Also see document 'TYPO3 Core API' for details.
81
 */
82
class DataHandler implements LoggerAwareInterface
83
{
84
    use LoggerAwareTrait;
85
86
    // *********************
87
    // Public variables you can configure before using the class:
88
    // *********************
89
    /**
90
     * If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the
91
     * log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
92
     *
93
     * @var bool
94
     */
95
    public $storeLogMessages = true;
96
97
    /**
98
     * If TRUE, actions are logged to sys_log.
99
     *
100
     * @var bool
101
     */
102
    public $enableLogging = true;
103
104
    /**
105
     * If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new
106
     * bunch of records.
107
     *
108
     * @var bool
109
     */
110
    public $reverseOrder = false;
111
112
    /**
113
     * If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array
114
     * is similar, it's not saved then.
115
     *
116
     * @var bool
117
     * @internal should only be used from within TYPO3 Core
118
     */
119
    public $checkSimilar = true;
120
121
    /**
122
     * This will read the record after having updated or inserted it. If anything is not properly submitted an error
123
     * is written to the log. This feature consumes extra time by selecting records
124
     *
125
     * @var bool
126
     */
127
    public $checkStoredRecords = true;
128
129
    /**
130
     * If set, values '' and 0 will equal each other when the stored records are checked.
131
     *
132
     * @var bool
133
     */
134
    public $checkStoredRecords_loose = true;
135
136
    /**
137
     * If this is set, then a page is deleted by deleting the whole branch under it (user must have
138
     * delete permissions to it all). If not set, then the page is deleted ONLY if it has no branch.
139
     *
140
     * @var bool
141
     */
142
    public $deleteTree = false;
143
144
    /**
145
     * If set, then the 'hideAtCopy' flag for tables will be ignored.
146
     *
147
     * @var bool
148
     */
149
    public $neverHideAtCopy = false;
150
151
    /**
152
     * If set, then the TCE class has been instantiated during an import action of a T3D
153
     *
154
     * @var bool
155
     */
156
    public $isImporting = false;
157
158
    /**
159
     * If set, then transformations are NOT performed on the input.
160
     *
161
     * @var bool
162
     */
163
    public $dontProcessTransformations = false;
164
165
    /**
166
     * Will distinguish between translations (with parent) and localizations (without parent) while still using the same methods to copy the records
167
     * TRUE: translation of a record connected to the default language
168
     * FALSE: localization of a record without connection to the default language
169
     *
170
     * @var bool
171
     */
172
    protected $useTransOrigPointerField = true;
173
174
    /**
175
     * If TRUE, workspace restrictions are bypassed on edit and create actions (process_datamap()).
176
     * YOU MUST KNOW what you do if you use this feature!
177
     *
178
     * @var bool
179
     * @internal should only be used from within TYPO3 Core
180
     */
181
    public $bypassWorkspaceRestrictions = false;
182
183
    /**
184
     * If TRUE, access check, check for deleted etc. for records is bypassed.
185
     * YOU MUST KNOW what you are doing if you use this feature!
186
     *
187
     * @var bool
188
     */
189
    public $bypassAccessCheckForRecords = false;
190
191
    /**
192
     * Comma-separated list. This list of tables decides which tables will be copied. If empty then none will.
193
     * If '*' then all will (that the user has permission to of course)
194
     *
195
     * @var string
196
     * @internal should only be used from within TYPO3 Core
197
     */
198
    public $copyWhichTables = '*';
199
200
    /**
201
     * If 0 then branch is NOT copied.
202
     * If 1 then pages on the 1st level is copied.
203
     * If 2 then pages on the second level is copied ... and so on
204
     *
205
     * @var int
206
     */
207
    public $copyTree = 0;
208
209
    /**
210
     * [table][fields]=value: New records are created with default values and you can set this array on the
211
     * form $defaultValues[$table][$field] = $value to override the default values fetched from TCA.
212
     * If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array
213
     * (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
214
     *
215
     * @var array
216
     * @internal should only be used from within TYPO3 Core
217
     */
218
    public $defaultValues = [];
219
220
    /**
221
     * [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to
222
     * override the incoming data. You must set this externally. You must make sure the fields in this array are also
223
     * found in the table, because it's not checked. All columns can be set by this array!
224
     *
225
     * @var array
226
     * @internal should only be used from within TYPO3 Core
227
     */
228
    public $overrideValues = [];
229
230
    /**
231
     * If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated.
232
     * You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1.
233
     * Then an empty checkbox will disable the field.
234
     *
235
     * @var array
236
     * @internal should only be used from within TYPO3 Core
237
     */
238
    public $data_disableFields = [];
239
240
    /**
241
     * Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option
242
     * since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set
243
     * it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete).
244
     * The option is used for import of T3D files when synchronizing between two mirrored servers.
245
     * As a security measure this feature is available only for Admin Users (for now)
246
     *
247
     * @var array
248
     */
249
    public $suggestedInsertUids = [];
250
251
    /**
252
     * Object. Call back object for FlexForm traversal. Useful when external classes wants to use the
253
     * iteration functions inside DataHandler for traversing a FlexForm structure.
254
     *
255
     * @var object
256
     * @internal should only be used from within TYPO3 Core
257
     */
258
    public $callBackObj;
259
260
    /**
261
     * A string which can be used as correlationId for RecordHistory entries.
262
     * The string can later be used to rollback multiple changes at once.
263
     *
264
     * @var CorrelationId|null
265
     */
266
    protected $correlationId;
267
268
    // *********************
269
    // Internal variables (mapping arrays) which can be used (read-only) from outside
270
    // *********************
271
    /**
272
     * Contains mapping of auto-versionized records.
273
     *
274
     * @var array
275
     * @internal should only be used from within TYPO3 Core
276
     */
277
    public $autoVersionIdMap = [];
278
279
    /**
280
     * 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
281
     *
282
     * @var array
283
     */
284
    public $substNEWwithIDs = [];
285
286
    /**
287
     * Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
288
     *
289
     * @var array
290
     * @internal should only be used from within TYPO3 Core
291
     */
292
    public $substNEWwithIDs_table = [];
293
294
    /**
295
     * Holds the tables and there the ids of newly created child records from IRRE
296
     *
297
     * @var array
298
     * @internal should only be used from within TYPO3 Core
299
     */
300
    public $newRelatedIDs = [];
301
302
    /**
303
     * This array is the sum of all copying operations in this class.
304
     *
305
     * @var array
306
     * @internal should only be used from within TYPO3 Core
307
     */
308
    public $copyMappingArray_merged = [];
309
310
    /**
311
     * Per-table array with UIDs that have been deleted.
312
     *
313
     * @var array
314
     */
315
    protected $deletedRecords = [];
316
317
    /**
318
     * Errors are collected in this variable.
319
     *
320
     * @var array
321
     * @internal should only be used from within TYPO3 Core
322
     */
323
    public $errorLog = [];
324
325
    /**
326
     * Fields from the pages-table for which changes will trigger a pagetree refresh
327
     *
328
     * @var array
329
     */
330
    public $pagetreeRefreshFieldsFromPages = ['pid', 'sorting', 'deleted', 'hidden', 'title', 'doktype', 'is_siteroot', 'fe_group', 'nav_hide', 'nav_title', 'module', 'starttime', 'endtime', 'content_from_pid', 'extendToSubpages'];
331
332
    /**
333
     * Indicates whether the pagetree needs a refresh because of important changes
334
     *
335
     * @var bool
336
     * @internal should only be used from within TYPO3 Core
337
     */
338
    public $pagetreeNeedsRefresh = false;
339
340
    // *********************
341
    // Internal Variables, do not touch.
342
    // *********************
343
344
    // Variables set in init() function:
345
346
    /**
347
     * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
348
     *
349
     * @var BackendUserAuthentication
350
     */
351
    public $BE_USER;
352
353
    /**
354
     * Will be set to uid of be_user executing this script
355
     *
356
     * @var int
357
     * @internal should only be used from within TYPO3 Core
358
     */
359
    public $userid;
360
361
    /**
362
     * Will be set to username of be_user executing this script
363
     *
364
     * @var string
365
     * @internal should only be used from within TYPO3 Core
366
     */
367
    public $username;
368
369
    /**
370
     * Will be set if user is admin
371
     *
372
     * @var bool
373
     * @internal should only be used from within TYPO3 Core
374
     */
375
    public $admin;
376
377
    /**
378
     * @var PagePermissionAssembler
379
     */
380
    protected $pagePermissionAssembler;
381
382
    /**
383
     * 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.
384
     *
385
     * @var array
386
     */
387
    protected $excludedTablesAndFields = [];
388
389
    /**
390
     * Data submitted from the form view, used to control behaviours,
391
     * e.g. this is used to activate/deactivate fields and thus store NULL values
392
     *
393
     * @var array
394
     */
395
    protected $control = [];
396
397
    /**
398
     * Set with incoming data array
399
     *
400
     * @var array
401
     */
402
    public $datamap = [];
403
404
    /**
405
     * Set with incoming cmd array
406
     *
407
     * @var array
408
     */
409
    public $cmdmap = [];
410
411
    /**
412
     * List of changed old record ids to new records ids
413
     *
414
     * @var array
415
     */
416
    protected $mmHistoryRecords = [];
417
418
    /**
419
     * List of changed old record ids to new records ids
420
     *
421
     * @var array
422
     */
423
    protected $historyRecords = [];
424
425
    // Internal static:
426
427
    /**
428
     * The interval between sorting numbers used with tables with a 'sorting' field defined.
429
     *
430
     * Min 1, should be power of 2
431
     *
432
     * @var int
433
     * @internal should only be used from within TYPO3 Core
434
     */
435
    public $sortIntervals = 256;
436
437
    // Internal caching arrays
438
    /**
439
     * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
440
     *
441
     * @var array
442
     */
443
    protected $recInsertAccessCache = [];
444
445
    /**
446
     * Caching array for check of whether records are in a webmount
447
     *
448
     * @var array
449
     */
450
    protected $isRecordInWebMount_Cache = [];
451
452
    /**
453
     * Caching array for page ids in webmounts
454
     *
455
     * @var array
456
     */
457
    protected $isInWebMount_Cache = [];
458
459
    /**
460
     * Used for caching page records in pageInfo()
461
     *
462
     * @var array
463
     */
464
    protected $pageCache = [];
465
466
    // Other arrays:
467
    /**
468
     * For accumulation of MM relations that must be written after new records are created.
469
     *
470
     * @var array
471
     * @internal
472
     */
473
    public $dbAnalysisStore = [];
474
475
    /**
476
     * Used for tracking references that might need correction after operations
477
     *
478
     * @var array
479
     * @internal
480
     */
481
    public $registerDBList = [];
482
483
    /**
484
     * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
485
     *
486
     * @var array
487
     * @internal
488
     */
489
    public $registerDBPids = [];
490
491
    /**
492
     * Used by the copy action to track the ids of new pages so subpages are correctly inserted!
493
     * THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE!
494
     * Read from copyMappingArray_merged instead which is accumulating this information.
495
     *
496
     * NOTE: This is used by some outside scripts (e.g. hooks), as the results in $copyMappingArray_merged
497
     * are only available after an action has been completed.
498
     *
499
     * @var array
500
     * @internal
501
     */
502
    public $copyMappingArray = [];
503
504
    /**
505
     * Array used for remapping uids and values at the end of process_datamap
506
     *
507
     * @var array
508
     * @internal
509
     */
510
    public $remapStack = [];
511
512
    /**
513
     * Array used for remapping uids and values at the end of process_datamap
514
     * (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
515
     *
516
     * @var array
517
     * @internal
518
     */
519
    public $remapStackRecords = [];
520
521
    /**
522
     * Array used for checking whether new children need to be remapped
523
     *
524
     * @var array
525
     */
526
    protected $remapStackChildIds = [];
527
528
    /**
529
     * Array used for executing addition actions after remapping happened (set processRemapStack())
530
     *
531
     * @var array
532
     */
533
    protected $remapStackActions = [];
534
535
    /**
536
     * Registry object to gather reference index update requests and perform updates after
537
     * main processing has been done. The first call to start() instantiates this object.
538
     * Recursive sub instances receive this instance via __construct().
539
     * The final update() call is done at the end of process_cmdmap() or process_datamap()
540
     * in the outer most instance.
541
     *
542
     * @var ReferenceIndexUpdater
543
     */
544
    protected $referenceIndexUpdater;
545
546
    /**
547
     * Tells, that this DataHandler instance was called from \TYPO3\CMS\Impext\ImportExport.
548
     * This variable is set by \TYPO3\CMS\Impext\ImportExport
549
     *
550
     * @var bool
551
     * @internal only used within TYPO3 Core
552
     */
553
    public $callFromImpExp = false;
554
555
    // Various
556
557
    /**
558
     * Set to "currentRecord" during checking of values.
559
     *
560
     * @var array
561
     * @internal
562
     */
563
    public $checkValue_currentRecord = [];
564
565
    /**
566
     * Disable delete clause
567
     *
568
     * @var bool
569
     */
570
    protected $disableDeleteClause = false;
571
572
    /**
573
     * @var array
574
     */
575
    protected $checkModifyAccessListHookObjects;
576
577
    /**
578
     * @var array
579
     */
580
    protected $version_remapMMForVersionSwap_reg;
581
582
    /**
583
     * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
584
     * This object instantiates itself on versioning and localization ...
585
     *
586
     * @var \TYPO3\CMS\Core\DataHandling\DataHandler
587
     */
588
    protected $outerMostInstance;
589
590
    /**
591
     * Internal cache for collecting records that should trigger cache clearing
592
     *
593
     * @var array
594
     */
595
    protected static $recordsToClearCacheFor = [];
596
597
    /**
598
     * Internal cache for pids of records which were deleted. It's not possible
599
     * to retrieve the parent folder/page at a later stage
600
     *
601
     * @var array
602
     */
603
    protected static $recordPidsForDeletedRecords = [];
604
605
    /**
606
     * Runtime Cache to store and retrieve data computed for a single request
607
     *
608
     * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
609
     */
610
    protected $runtimeCache;
611
612
    /**
613
     * Prefix for the cache entries of nested element calls since the runtimeCache has a global scope.
614
     *
615
     * @var string
616
     */
617
    protected $cachePrefixNestedElementCalls = 'core-datahandler-nestedElementCalls-';
618
619
    /**
620
     * Sets up the data handler cache and some additional options, the main logic is done in the start() method.
621
     *
622
     * @param ReferenceIndexUpdater|null $referenceIndexUpdater Hand over from outer most instance to sub instances
623
     */
624
    public function __construct(ReferenceIndexUpdater $referenceIndexUpdater = null)
625
    {
626
        $this->checkStoredRecords = (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecords'];
627
        $this->checkStoredRecords_loose = (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecordsLoose'];
628
        $this->runtimeCache = $this->getRuntimeCache();
629
        $this->pagePermissionAssembler = GeneralUtility::makeInstance(PagePermissionAssembler::class, $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions']);
630
        if ($referenceIndexUpdater === null) {
631
            // Create ReferenceIndexUpdater object. This should only happen on outer most instance,
632
            // sub instances should receive the reference index updater from a parent.
633
            $referenceIndexUpdater = GeneralUtility::makeInstance(ReferenceIndexUpdater::class);
634
        }
635
        $this->referenceIndexUpdater = $referenceIndexUpdater;
636
    }
637
638
    /**
639
     * @param array $control
640
     * @internal
641
     */
642
    public function setControl(array $control)
643
    {
644
        $this->control = $control;
645
    }
646
647
    /**
648
     * Initializing.
649
     * For details, see 'TYPO3 Core API' document.
650
     * This function does not start the processing of data, but merely initializes the object
651
     *
652
     * @param array $data Data to be modified or inserted in the database
653
     * @param array $cmd Commands to copy, move, delete, localize, versionize records.
654
     * @param BackendUserAuthentication|null $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
655
     */
656
    public function start($data, $cmd, $altUserObject = null)
657
    {
658
        // Initializing BE_USER
659
        $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
660
        $this->userid = $this->BE_USER->user['uid'] ?? 0;
661
        $this->username = $this->BE_USER->user['username'] ?? '';
662
        $this->admin = $this->BE_USER->user['admin'] ?? false;
663
        if ($this->BE_USER->uc['recursiveDelete'] ?? false) {
664
            $this->deleteTree = 1;
0 ignored issues
show
Documentation Bug introduced by
The property $deleteTree was declared of type boolean, but 1 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
665
        }
666
667
        // set correlation id for each new set of data or commands
668
        $this->correlationId = CorrelationId::forScope(
669
            md5(StringUtility::getUniqueId(self::class))
670
        );
671
672
        // Get default values from user TSconfig
673
        $tcaDefaultOverride = $this->BE_USER->getTSConfig()['TCAdefaults.'] ?? null;
674
        if (is_array($tcaDefaultOverride)) {
675
            $this->setDefaultsFromUserTS($tcaDefaultOverride);
676
        }
677
678
        // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
679
        if (!$this->admin) {
680
            $this->excludedTablesAndFields = array_flip($this->getExcludeListArray());
681
        }
682
        // Setting the data and cmd arrays
683
        if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
684
            reset($data);
685
            $this->datamap = $data;
686
        }
687
        if (is_array($cmd)) {
0 ignored issues
show
introduced by
The condition is_array($cmd) is always true.
Loading history...
688
            reset($cmd);
689
            $this->cmdmap = $cmd;
690
        }
691
    }
692
693
    /**
694
     * Function that can mirror input values in datamap-array to other uid numbers.
695
     * 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]
696
     *
697
     * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
698
     * @internal
699
     */
700
    public function setMirror($mirror)
701
    {
702
        if (!is_array($mirror)) {
0 ignored issues
show
introduced by
The condition is_array($mirror) is always true.
Loading history...
703
            return;
704
        }
705
706
        foreach ($mirror as $table => $uid_array) {
707
            if (!isset($this->datamap[$table])) {
708
                continue;
709
            }
710
711
            foreach ($uid_array as $id => $uidList) {
712
                if (!isset($this->datamap[$table][$id])) {
713
                    continue;
714
                }
715
716
                $theIdsInArray = GeneralUtility::trimExplode(',', $uidList, true);
717
                foreach ($theIdsInArray as $copyToUid) {
718
                    $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
719
                }
720
            }
721
        }
722
    }
723
724
    /**
725
     * Initializes default values coming from User TSconfig
726
     *
727
     * @param array $userTS User TSconfig array
728
     * @internal should only be used from within DataHandler
729
     */
730
    public function setDefaultsFromUserTS($userTS)
731
    {
732
        if (!is_array($userTS)) {
0 ignored issues
show
introduced by
The condition is_array($userTS) is always true.
Loading history...
733
            return;
734
        }
735
736
        foreach ($userTS as $k => $v) {
737
            $k = mb_substr($k, 0, -1);
738
            if (!$k || !is_array($v) || !isset($GLOBALS['TCA'][$k])) {
739
                continue;
740
            }
741
742
            if (is_array($this->defaultValues[$k])) {
743
                $this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
744
            } else {
745
                $this->defaultValues[$k] = $v;
746
            }
747
        }
748
    }
749
750
    /**
751
     * When a new record is created, all values that haven't been set but are set via PageTSconfig / UserTSconfig
752
     * get applied here.
753
     *
754
     * This is only executed for new records. The most important part is that the pageTS of the actual resolved $pid
755
     * is taken, and a new field array with empty defaults is set again.
756
     *
757
     * @param string $table
758
     * @param int $pageId
759
     * @param array $prepopulatedFieldArray
760
     * @return array
761
     */
762
    protected function applyDefaultsForFieldArray(string $table, int $pageId, array $prepopulatedFieldArray): array
763
    {
764
        // First set TCAdefaults respecting the given PageID
765
        $tcaDefaults = BackendUtility::getPagesTSconfig($pageId)['TCAdefaults.'] ?? null;
766
        // Re-apply $this->defaultValues settings
767
        $this->setDefaultsFromUserTS($tcaDefaults);
768
        $cleanFieldArray = $this->newFieldArray($table);
769
        if (isset($prepopulatedFieldArray['pid'])) {
770
            $cleanFieldArray['pid'] = $prepopulatedFieldArray['pid'];
771
        }
772
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? null;
773
        if ($sortColumn !== null && isset($prepopulatedFieldArray[$sortColumn])) {
774
            $cleanFieldArray[$sortColumn] = $prepopulatedFieldArray[$sortColumn];
775
        }
776
        return $cleanFieldArray;
777
    }
778
779
    /*********************************************
780
     *
781
     * HOOKS
782
     *
783
     *********************************************/
784
    /**
785
     * Hook: processDatamap_afterDatabaseOperations
786
     * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
787
     *
788
     * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
789
     * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
790
     *
791
     * @param array $hookObjectsArr (reference) Array with hook objects
792
     * @param string $status (reference) Status of the current operation, 'new' or 'update
793
     * @param string $table (reference) The table currently processing data for
794
     * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
795
     * @param array $fieldArray (reference) The field array of a record
796
     * @internal should only be used from within DataHandler
797
     */
798
    public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray)
799
    {
800
        // Process hook directly:
801
        if (!isset($this->remapStackRecords[$table][$id])) {
802
            foreach ($hookObjectsArr as $hookObj) {
803
                if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
804
                    $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
805
                }
806
            }
807
        } else {
808
            $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = [
809
                'status' => $status,
810
                'fieldArray' => $fieldArray,
811
                'hookObjectsArr' => $hookObjectsArr
812
            ];
813
        }
814
    }
815
816
    /**
817
     * Gets the 'checkModifyAccessList' hook objects.
818
     * The first call initializes the accordant objects.
819
     *
820
     * @return array The 'checkModifyAccessList' hook objects (if any)
821
     * @throws \UnexpectedValueException
822
     */
823
    protected function getCheckModifyAccessListHookObjects()
824
    {
825
        if (!isset($this->checkModifyAccessListHookObjects)) {
826
            $this->checkModifyAccessListHookObjects = [];
827
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] ?? [] as $className) {
828
                $hookObject = GeneralUtility::makeInstance($className);
829
                if (!$hookObject instanceof DataHandlerCheckModifyAccessListHookInterface) {
830
                    throw new \UnexpectedValueException($className . ' must implement interface ' . DataHandlerCheckModifyAccessListHookInterface::class, 1251892472);
831
                }
832
                $this->checkModifyAccessListHookObjects[] = $hookObject;
833
            }
834
        }
835
        return $this->checkModifyAccessListHookObjects;
836
    }
837
838
    /*********************************************
839
     *
840
     * PROCESSING DATA
841
     *
842
     *********************************************/
843
    /**
844
     * Processing the data-array
845
     * Call this function to process the data-array set by start()
846
     *
847
     * @return bool|void
848
     */
849
    public function process_datamap()
850
    {
851
        $this->controlActiveElements();
852
853
        // Keep versionized(!) relations here locally:
854
        $registerDBList = [];
855
        $this->registerElementsToBeDeleted();
856
        $this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
857
        // Editing frozen:
858
        if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
859
            $this->newlog('All editing in this workspace has been frozen!', SystemLogErrorClassification::USER_ERROR);
860
            return false;
861
        }
862
        // First prepare user defined objects (if any) for hooks which extend this function:
863
        $hookObjectsArr = [];
864
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] ?? [] as $className) {
865
            $hookObject = GeneralUtility::makeInstance($className);
866
            if (method_exists($hookObject, 'processDatamap_beforeStart')) {
867
                $hookObject->processDatamap_beforeStart($this);
868
            }
869
            $hookObjectsArr[] = $hookObject;
870
        }
871
        // Pre-process data-map and synchronize localization states
872
        $this->datamap = GeneralUtility::makeInstance(SlugEnricher::class)->enrichDataMap($this->datamap);
873
        $this->datamap = DataMapProcessor::instance($this->datamap, $this->BE_USER, $this->referenceIndexUpdater)->process();
874
        // 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.
875
        $orderOfTables = [];
876
        // Set pages first.
877
        if (isset($this->datamap['pages'])) {
878
            $orderOfTables[] = 'pages';
879
        }
880
        $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
881
        // Process the tables...
882
        foreach ($orderOfTables as $table) {
883
            // Check if
884
            //	   - table is set in $GLOBALS['TCA'],
885
            //	   - table is NOT readOnly
886
            //	   - the table is set with content in the data-array (if not, there's nothing to process...)
887
            //	   - permissions for tableaccess OK
888
            $modifyAccessList = $this->checkModifyAccessList($table);
889
            if (!$modifyAccessList) {
890
                $this->log($table, 0, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
891
            }
892
            if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->datamap[$table]) || !$modifyAccessList) {
893
                continue;
894
            }
895
896
            if ($this->reverseOrder) {
897
                $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
898
            }
899
            // For each record from the table, do:
900
            // $id is the record uid, may be a string if new records...
901
            // $incomingFieldArray is the array of fields
902
            foreach ($this->datamap[$table] as $id => $incomingFieldArray) {
903
                if (!is_array($incomingFieldArray)) {
904
                    continue;
905
                }
906
                $theRealPid = null;
907
908
                // Hook: processDatamap_preProcessFieldArray
909
                foreach ($hookObjectsArr as $hookObj) {
910
                    if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
911
                        $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
912
                    }
913
                }
914
                // ******************************
915
                // Checking access to the record
916
                // ******************************
917
                $createNewVersion = false;
918
                $recordAccess = false;
919
                $old_pid_value = '';
920
                // Is it a new record? (Then Id is a string)
921
                if (!MathUtility::canBeInterpretedAsInteger($id)) {
922
                    // Get a fieldArray with tca default values
923
                    $fieldArray = $this->newFieldArray($table);
924
                    // A pid must be set for new records.
925
                    if (isset($incomingFieldArray['pid'])) {
926
                        $pid_value = $incomingFieldArray['pid'];
927
                        // Checking and finding numerical pid, it may be a string-reference to another value
928
                        $canProceed = true;
929
                        // If a NEW... id
930
                        if (strpos($pid_value, 'NEW') !== false) {
931
                            if ($pid_value[0] === '-') {
932
                                $negFlag = -1;
933
                                $pid_value = substr($pid_value, 1);
934
                            } else {
935
                                $negFlag = 1;
936
                            }
937
                            // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
938
                            if (isset($this->substNEWwithIDs[$pid_value])) {
939
                                if ($negFlag === 1) {
940
                                    $old_pid_value = $this->substNEWwithIDs[$pid_value];
941
                                }
942
                                $pid_value = (int)($negFlag * $this->substNEWwithIDs[$pid_value]);
943
                            } else {
944
                                $canProceed = false;
945
                            }
946
                        }
947
                        $pid_value = (int)$pid_value;
948
                        if ($canProceed) {
949
                            $fieldArray = $this->resolveSortingAndPidForNewRecord($table, $pid_value, $fieldArray);
950
                        }
951
                    }
952
                    $theRealPid = $fieldArray['pid'];
953
                    // Checks if records can be inserted on this $pid.
954
                    // If this is a page translation, the check needs to be done for the l10n_parent record
955
                    if ($table === 'pages' && $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0 && $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0) {
956
                        $recordAccess = $this->checkRecordInsertAccess($table, $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
957
                    } else {
958
                        $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
959
                    }
960
                    if ($recordAccess) {
961
                        $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
962
                        $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, true);
963
                        if (!$recordAccess) {
964
                            $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', SystemLogErrorClassification::USER_ERROR);
965
                        } elseif (!$this->bypassWorkspaceRestrictions && !$this->BE_USER->workspaceAllowsLiveEditingInTable($table)) {
966
                            // If LIVE records cannot be created due to workspace restrictions, prepare creation of placeholder-record
967
                            // So, if no live records were allowed in the current workspace, we have to create a new version of this record
968
                            if (BackendUtility::isTableWorkspaceEnabled($table)) {
969
                                $createNewVersion = true;
970
                            } else {
971
                                $recordAccess = false;
972
                                $this->newlog('Record could not be created in this workspace', SystemLogErrorClassification::USER_ERROR);
973
                            }
974
                        }
975
                    }
976
                    // Yes new record, change $record_status to 'insert'
977
                    $status = 'new';
978
                } else {
979
                    // Nope... $id is a number
980
                    $fieldArray = [];
981
                    $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
982
                    if (!$recordAccess) {
983
                        if ($this->enableLogging) {
984
                            $propArr = $this->getRecordProperties($table, $id);
985
                            $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']);
986
                        }
987
                        continue;
988
                    }
989
                    // Next check of the record permissions (internals)
990
                    $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
991
                    if (!$recordAccess) {
992
                        $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', SystemLogErrorClassification::USER_ERROR);
993
                    } else {
994
                        // Here we fetch the PID of the record that we point to...
995
                        $tempdata = $this->recordInfo($table, $id, 'pid' . (BackendUtility::isTableWorkspaceEnabled($table) ? ',t3ver_oid,t3ver_wsid,t3ver_stage' : ''));
996
                        $theRealPid = $tempdata['pid'] ?? null;
997
                        // Use the new id of the versionized record we're trying to write to:
998
                        // (This record is a child record of a parent and has already been versionized.)
999
                        if (!empty($this->autoVersionIdMap[$table][$id])) {
1000
                            // For the reason that creating a new version of this record, automatically
1001
                            // created related child records (e.g. "IRRE"), update the accordant field:
1002
                            $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1003
                            // Use the new id of the copied/versionized record:
1004
                            $id = $this->autoVersionIdMap[$table][$id];
1005
                            $recordAccess = true;
1006
                        } elseif (!$this->bypassWorkspaceRestrictions && ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $tempdata))) {
1007
                            $recordAccess = false;
1008
                            // Versioning is required and it must be offline version!
1009
                            // Check if there already is a workspace version
1010
                            $workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid,t3ver_oid');
1011
                            if ($workspaceVersion) {
1012
                                $id = $workspaceVersion['uid'];
1013
                                $recordAccess = true;
1014
                            } elseif ($this->BE_USER->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1015
                                // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1016
                                $this->pagetreeNeedsRefresh = true;
1017
1018
                                /** @var DataHandler $tce */
1019
                                $tce = GeneralUtility::makeInstance(__CLASS__, $this->referenceIndexUpdater);
1020
                                $tce->enableLogging = $this->enableLogging;
1021
                                // Setting up command for creating a new version of the record:
1022
                                $cmd = [];
1023
                                $cmd[$table][$id]['version'] = [
1024
                                    'action' => 'new',
1025
                                    // Default is to create a version of the individual records
1026
                                    'label' => 'Auto-created for WS #' . $this->BE_USER->workspace
1027
                                ];
1028
                                $tce->start([], $cmd, $this->BE_USER);
1029
                                $tce->process_cmdmap();
1030
                                $this->errorLog = array_merge($this->errorLog, $tce->errorLog);
1031
                                // If copying was successful, share the new uids (also of related children):
1032
                                if (!empty($tce->copyMappingArray[$table][$id])) {
1033
                                    foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
1034
                                        foreach ($origIdArray as $origId => $newId) {
1035
                                            $this->autoVersionIdMap[$origTable][$origId] = $newId;
1036
                                        }
1037
                                    }
1038
                                    // Update registerDBList, that holds the copied relations to child records:
1039
                                    $registerDBList = array_merge($registerDBList, $tce->registerDBList);
1040
                                    // For the reason that creating a new version of this record, automatically
1041
                                    // created related child records (e.g. "IRRE"), update the accordant field:
1042
                                    $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1043
                                    // Use the new id of the copied/versionized record:
1044
                                    $id = $this->autoVersionIdMap[$table][$id];
1045
                                    $recordAccess = true;
1046
                                } else {
1047
                                    $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);
1048
                                }
1049
                            } else {
1050
                                $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);
1051
                            }
1052
                        }
1053
                    }
1054
                    // The default is 'update'
1055
                    $status = 'update';
1056
                }
1057
                // If access was granted above, proceed to create or update record:
1058
                if (!$recordAccess) {
1059
                    continue;
1060
                }
1061
1062
                // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1063
                [$tscPID] = BackendUtility::getTSCpid($table, $id, $old_pid_value ?: $fieldArray['pid']);
1064
                if ($status === 'new') {
1065
                    // Apply TCAdefaults from pageTS
1066
                    $fieldArray = $this->applyDefaultsForFieldArray($table, (int)$tscPID, $fieldArray);
1067
                    // Apply page permissions as well
1068
                    if ($table === 'pages') {
1069
                        $fieldArray = $this->pagePermissionAssembler->applyDefaults(
1070
                            $fieldArray,
1071
                            (int)$tscPID,
1072
                            (int)$this->userid,
1073
                            (int)$this->BE_USER->firstMainGroup
1074
                        );
1075
                    }
1076
                }
1077
                // Processing of all fields in incomingFieldArray and setting them in $fieldArray
1078
                $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1079
                $newVersion_placeholderFieldArray = [];
1080
                if ($createNewVersion) {
1081
                    // create a placeholder array with already processed field content
1082
                    $newVersion_placeholderFieldArray = $fieldArray;
1083
                }
1084
                // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations to field!
1085
                // Forcing some values unto field array:
1086
                // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
1087
                $fieldArray = $this->overrideFieldArray($table, $fieldArray);
1088
                if ($createNewVersion) {
1089
                    $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
1090
                }
1091
                // Setting system fields
1092
                if ($status === 'new') {
1093
                    if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1094
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1095
                        if ($createNewVersion) {
1096
                            $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1097
                        }
1098
                    }
1099
                    if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1100
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
1101
                        if ($createNewVersion) {
1102
                            $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
1103
                        }
1104
                    }
1105
                } elseif ($this->checkSimilar) {
1106
                    // Removing fields which are equal to the current value:
1107
                    $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
1108
                }
1109
                if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && !empty($fieldArray)) {
1110
                    $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1111
                    if ($createNewVersion) {
1112
                        $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1113
                    }
1114
                }
1115
                // Set stage to "Editing" to make sure we restart the workflow
1116
                if (BackendUtility::isTableWorkspaceEnabled($table)) {
1117
                    $fieldArray['t3ver_stage'] = 0;
1118
                }
1119
                // Hook: processDatamap_postProcessFieldArray
1120
                foreach ($hookObjectsArr as $hookObj) {
1121
                    if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
1122
                        $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
1123
                    }
1124
                }
1125
                // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1126
                // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already
1127
                if (is_array($fieldArray)) {
1128
                    if ($status === 'new') {
1129
                        if ($table === 'pages') {
1130
                            // for new pages always a refresh is needed
1131
                            $this->pagetreeNeedsRefresh = true;
1132
                        }
1133
1134
                        // This creates a new version of the record with online placeholder and offline version
1135
                        if ($createNewVersion) {
1136
                            // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1137
                            $this->pagetreeNeedsRefresh = true;
1138
1139
                            // Setting placeholder state value for temporary record
1140
                            $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER);
1141
                            // Setting workspace - only so display of placeholders can filter out those from other workspaces.
1142
                            $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1143
                            // Only set a label if it is an input field
1144
                            $labelField = $GLOBALS['TCA'][$table]['ctrl']['label'];
1145
                            if ($GLOBALS['TCA'][$table]['columns'][$labelField]['config']['type'] === 'input') {
1146
                                $newVersion_placeholderFieldArray[$labelField] = $this->getPlaceholderTitleForTableLabel($table);
1147
                            }
1148
                            // Saving placeholder as 'original'
1149
                            $this->insertDB($table, $id, $newVersion_placeholderFieldArray, false, (int)($incomingFieldArray['uid'] ?? 0));
1150
                            // For the actual new offline version, set versioning values to point to placeholder
1151
                            $fieldArray['pid'] = $theRealPid;
1152
                            $fieldArray['t3ver_oid'] = $this->substNEWwithIDs[$id];
1153
                            // Setting placeholder state value for version (so it can know it is currently a new version...)
1154
                            $fieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER_VERSION);
1155
                            $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1156
                            // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
1157
                            $phShadowId = $this->insertDB($table, $id, $fieldArray, true, 0, true);
1158
                            if ($phShadowId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $phShadowId 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...
1159
                                // Processes fields of the placeholder record:
1160
                                $this->triggerRemapAction($table, $id, [$this, 'placeholderShadowing'], [$table, $phShadowId]);
1161
                                // Hold auto-versionized ids of placeholders:
1162
                                $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $phShadowId;
1163
                            }
1164
                        } else {
1165
                            $this->insertDB($table, $id, $fieldArray, false, (int)($incomingFieldArray['uid'] ?? 0));
1166
                        }
1167
                    } else {
1168
                        if ($table === 'pages') {
1169
                            // only a certain number of fields needs to be checked for updates
1170
                            // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
1171
                            $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages, array_keys($fieldArray));
1172
                            if (!empty($fieldsToCheck)) {
1173
                                $this->pagetreeNeedsRefresh = true;
1174
                            }
1175
                        }
1176
                        $this->updateDB($table, $id, $fieldArray);
1177
                        $this->placeholderShadowing($table, $id);
1178
                    }
1179
                }
1180
                // Hook: processDatamap_afterDatabaseOperations
1181
                // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
1182
                // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
1183
                $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
1184
            }
1185
        }
1186
        // Process the stack of relations to remap/correct
1187
        $this->processRemapStack();
1188
        $this->dbAnalysisStoreExec();
1189
        // Hook: processDatamap_afterAllOperations
1190
        // Note: When this hook gets called, all operations on the submitted data have been finished.
1191
        foreach ($hookObjectsArr as $hookObj) {
1192
            if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
1193
                $hookObj->processDatamap_afterAllOperations($this);
1194
            }
1195
        }
1196
1197
        if ($this->isOuterMostInstance()) {
1198
            $this->referenceIndexUpdater->update();
1199
            $this->processClearCacheQueue();
1200
            $this->resetElementsToBeDeleted();
1201
        }
1202
    }
1203
1204
    /**
1205
     * @param string $table
1206
     * @param string $value
1207
     * @param string $dbType
1208
     * @return string
1209
     */
1210
    protected function normalizeTimeFormat(string $table, string $value, string $dbType): string
1211
    {
1212
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
1213
        $platform = $connection->getDatabasePlatform();
1214
        if ($platform instanceof SQLServerPlatform) {
1215
            $defaultLength = QueryHelper::getDateTimeFormats()[$dbType]['empty'];
1216
            $value = substr(
1217
                $value,
1218
                0,
1219
                strlen($defaultLength)
1220
            );
1221
        }
1222
        return $value;
1223
    }
1224
1225
    /**
1226
     * Sets the "sorting" DB field and the "pid" field of an incoming record that should be added (NEW1234)
1227
     * depending on the record that should be added or where it should be added.
1228
     *
1229
     * This method is called from process_datamap()
1230
     *
1231
     * @param string $table the table name of the record to insert
1232
     * @param int $pid the real PID (numeric) where the record should be
1233
     * @param array $fieldArray field+value pairs to add
1234
     * @return array the modified field array
1235
     */
1236
    protected function resolveSortingAndPidForNewRecord(string $table, int $pid, array $fieldArray): array
1237
    {
1238
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
1239
        // Points to a page on which to insert the element, possibly in the top of the page
1240
        if ($pid >= 0) {
1241
            // Ensure that the "pid" is not a translated page ID, but the default page ID
1242
            $pid = $this->getDefaultLanguagePageId($pid);
1243
            // The numerical pid is inserted in the data array
1244
            $fieldArray['pid'] = $pid;
1245
            // If this table is sorted we better find the top sorting number
1246
            if ($sortColumn) {
1247
                $fieldArray[$sortColumn] = $this->getSortNumber($table, 0, $pid);
1248
            }
1249
        } elseif ($sortColumn) {
1250
            // Points to another record before itself
1251
            // If this table is sorted we better find the top sorting number
1252
            // Because $pid is < 0, getSortNumber() returns an array
1253
            $sortingInfo = $this->getSortNumber($table, 0, $pid);
1254
            $fieldArray['pid'] = $sortingInfo['pid'];
1255
            $fieldArray[$sortColumn] = $sortingInfo['sortNumber'];
1256
        } else {
1257
            // Here we fetch the PID of the record that we point to
1258
            $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

1258
            $record = $this->recordInfo($table, /** @scrutinizer ignore-type */ abs($pid), 'pid');
Loading history...
1259
            // Ensure that the "pid" is not a translated page ID, but the default page ID
1260
            $fieldArray['pid'] = $this->getDefaultLanguagePageId($record['pid']);
1261
        }
1262
        return $fieldArray;
1263
    }
1264
1265
    /**
1266
     * Fix shadowing of data in case we are editing an offline version of a live "New" placeholder record.
1267
     *
1268
     * @param string $table Table name
1269
     * @param int $id Record uid
1270
     * @internal should only be used from within DataHandler
1271
     */
1272
    public function placeholderShadowing($table, $id)
1273
    {
1274
        $liveRecord = BackendUtility::getLiveVersionOfRecord($table, $id, '*');
1275
        if (empty($liveRecord)) {
1276
            return;
1277
        }
1278
1279
        $liveState = VersionState::cast($liveRecord['t3ver_state']);
1280
        $versionRecord = BackendUtility::getRecord($table, $id);
1281
        $versionState = VersionState::cast($versionRecord['t3ver_state']);
1282
1283
        if (!$liveState->indicatesPlaceholder() && !$versionState->indicatesPlaceholder()) {
1284
            return;
1285
        }
1286
        $factory = GeneralUtility::makeInstance(
1287
            PlaceholderShadowColumnsResolver::class,
1288
            $table,
1289
            $GLOBALS['TCA'][$table] ?? []
1290
        );
1291
1292
        if ($versionState->equals(VersionState::MOVE_POINTER)) {
1293
            $placeholderRecord = BackendUtility::getMovePlaceholder($table, $liveRecord['uid'], '*', $versionRecord['t3ver_wsid']);
1294
            $shadowColumns = $factory->forMovePlaceholder();
1295
        } elseif ($liveState->indicatesPlaceholder()) {
1296
            $placeholderRecord = $liveRecord;
1297
            $shadowColumns = $factory->forNewPlaceholder();
1298
        } else {
1299
            return;
1300
        }
1301
        if (empty($shadowColumns)) {
1302
            return;
1303
        }
1304
1305
        $placeholderValues = [];
1306
        foreach ($shadowColumns as $fieldName) {
1307
            if ((string)$versionRecord[$fieldName] !== (string)$placeholderRecord[$fieldName]) {
1308
                $placeholderValues[$fieldName] = $versionRecord[$fieldName];
1309
            }
1310
        }
1311
        if (empty($placeholderValues)) {
1312
            return;
1313
        }
1314
1315
        if ($this->enableLogging) {
1316
            $this->log($table, $placeholderRecord['uid'], SystemLogGenericAction::UNDEFINED, 0, SystemLogErrorClassification::MESSAGE, 'Shadowing done on fields <i>' . implode(',', array_keys($placeholderValues)) . '</i> in placeholder record ' . $table . ':' . $liveRecord['uid'] . ' (offline version UID=' . $id . ')', -1, [], $this->eventPid($table, $liveRecord['uid'], $liveRecord['pid']));
1317
        }
1318
        $this->updateDB($table, $placeholderRecord['uid'], $placeholderValues);
1319
    }
1320
1321
    /**
1322
     * Create a placeholder title for the label field that does match the field requirements
1323
     *
1324
     * @param string $table The table name
1325
     * @param string $placeholderContent Placeholder content to be used
1326
     * @return string placeholder value
1327
     * @internal should only be used from within DataHandler
1328
     */
1329
    public function getPlaceholderTitleForTableLabel($table, $placeholderContent = null)
1330
    {
1331
        if ($placeholderContent === null) {
1332
            $placeholderContent = 'PLACEHOLDER';
1333
        }
1334
1335
        $labelPlaceholder = '[' . $placeholderContent . ', WS#' . $this->BE_USER->workspace . ']';
1336
        $labelField = $GLOBALS['TCA'][$table]['ctrl']['label'];
1337
        if (!isset($GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'])) {
1338
            return $labelPlaceholder;
1339
        }
1340
        $evalCodesArray = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'], true);
1341
        $transformedLabel = $this->checkValue_input_Eval($labelPlaceholder, $evalCodesArray, '', $table);
1342
        return $transformedLabel['value'] ?? $labelPlaceholder;
1343
    }
1344
1345
    /**
1346
     * Filling in the field array
1347
     * $this->excludedTablesAndFields is used to filter fields if needed.
1348
     *
1349
     * @param string $table Table name
1350
     * @param int $id Record ID
1351
     * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1352
     * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
1353
     * @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.
1354
     * @param string $status Is 'new' or 'update'
1355
     * @param int $tscPID TSconfig PID
1356
     * @return array Field Array
1357
     * @internal should only be used from within DataHandler
1358
     */
1359
    public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
1360
    {
1361
        // Initialize:
1362
        $originalLanguageRecord = null;
1363
        $originalLanguage_diffStorage = null;
1364
        $diffStorageFlag = false;
1365
        // Setting 'currentRecord' and 'checkValueRecord':
1366
        if (strpos($id, 'NEW') !== false) {
1367
            // Must have the 'current' array - not the values after processing below...
1368
            $checkValueRecord = $fieldArray;
1369
            // IF $incomingFieldArray is an array, overlay it.
1370
            // 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...
1371
            if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
0 ignored issues
show
introduced by
The condition is_array($checkValueRecord) is always true.
Loading history...
1372
                ArrayUtility::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
1373
            }
1374
            $currentRecord = $checkValueRecord;
1375
        } else {
1376
            // We must use the current values as basis for this!
1377
            $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
1378
            // This is done to make the pid positive for offline versions; Necessary to have diff-view for page translations in workspaces.
1379
            BackendUtility::fixVersioningPid($table, $currentRecord);
1380
        }
1381
1382
        // Get original language record if available:
1383
        if (is_array($currentRecord)
1384
            && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']
1385
            && $GLOBALS['TCA'][$table]['ctrl']['languageField']
1386
            && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
1387
            && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
1388
            && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0
1389
        ) {
1390
            $originalLanguageRecord = $this->recordInfo($table, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1391
            BackendUtility::workspaceOL($table, $originalLanguageRecord);
1392
            $originalLanguage_diffStorage = json_decode(
1393
                (string)($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] ?? ''),
1394
                true
1395
            );
1396
        }
1397
1398
        $this->checkValue_currentRecord = $checkValueRecord;
1399
        // In the following all incoming value-fields are tested:
1400
        // - Are the user allowed to change the field?
1401
        // - Is the field uid/pid (which are already set)
1402
        // - perms-fields for pages-table, then do special things...
1403
        // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1404
        // If everything is OK, the field is entered into $fieldArray[]
1405
        foreach ($incomingFieldArray as $field => $fieldValue) {
1406
            if (isset($this->excludedTablesAndFields[$table . '-' . $field]) || $this->data_disableFields[$table][$id][$field]) {
1407
                continue;
1408
            }
1409
1410
            // The field must be editable.
1411
            // Checking if a value for language can be changed:
1412
            $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField'] && (string)$GLOBALS['TCA'][$table]['ctrl']['languageField'] === (string)$field && !$this->BE_USER->checkLanguageAccess($fieldValue);
1413
            if ($languageDeny) {
1414
                continue;
1415
            }
1416
1417
            switch ($field) {
1418
                case 'uid':
1419
                case 'pid':
1420
                    // Nothing happens, already set
1421
                    break;
1422
                case 'perms_userid':
1423
                case 'perms_groupid':
1424
                case 'perms_user':
1425
                case 'perms_group':
1426
                case 'perms_everybody':
1427
                    // Permissions can be edited by the owner or the administrator
1428
                    if ($table === 'pages' && ($this->admin || $status === 'new' || $this->pageInfo($id, 'perms_userid') == $this->userid)) {
1429
                        $value = (int)$fieldValue;
1430
                        switch ($field) {
1431
                            case 'perms_userid':
1432
                            case 'perms_groupid':
1433
                                $fieldArray[$field] = $value;
1434
                                break;
1435
                            default:
1436
                                if ($value >= 0 && $value < (2 ** 5)) {
1437
                                    $fieldArray[$field] = $value;
1438
                                }
1439
                        }
1440
                    }
1441
                    break;
1442
                case 't3ver_oid':
1443
                case 't3ver_wsid':
1444
                case 't3ver_state':
1445
                case 't3ver_stage':
1446
                    break;
1447
                case 'l10n_state':
1448
                    $fieldArray[$field] = $fieldValue;
1449
                    break;
1450
                default:
1451
                    if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1452
                        // Evaluating the value
1453
                        $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID, $incomingFieldArray);
1454
                        if (array_key_exists('value', $res)) {
1455
                            $fieldArray[$field] = $res['value'];
1456
                        }
1457
                        // Add the value of the original record to the diff-storage content:
1458
                        if ($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1459
                            $originalLanguage_diffStorage[$field] = (string)$originalLanguageRecord[$field];
1460
                            $diffStorageFlag = true;
1461
                        }
1462
                    } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1463
                        // Allow value for original UID to pass by...
1464
                        $fieldArray[$field] = $fieldValue;
1465
                    }
1466
            }
1467
        }
1468
1469
        // Dealing with a page translation, setting "sorting", "pid", "perms_*" to the same values as the original record
1470
        if ($table === 'pages' && is_array($originalLanguageRecord)) {
1471
            $fieldArray['sorting'] = $originalLanguageRecord['sorting'];
1472
            $fieldArray['perms_userid'] = $originalLanguageRecord['perms_userid'];
1473
            $fieldArray['perms_groupid'] = $originalLanguageRecord['perms_groupid'];
1474
            $fieldArray['perms_user'] = $originalLanguageRecord['perms_user'];
1475
            $fieldArray['perms_group'] = $originalLanguageRecord['perms_group'];
1476
            $fieldArray['perms_everybody'] = $originalLanguageRecord['perms_everybody'];
1477
        }
1478
1479
        // Add diff-storage information:
1480
        if ($diffStorageFlag
1481
            && !array_key_exists($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'], $fieldArray)
1482
        ) {
1483
            // 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...
1484
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = json_encode($originalLanguage_diffStorage);
1485
        }
1486
        // Return fieldArray
1487
        return $fieldArray;
1488
    }
1489
1490
    /*********************************************
1491
     *
1492
     * Evaluation of input values
1493
     *
1494
     ********************************************/
1495
    /**
1496
     * Evaluates a value according to $table/$field settings.
1497
     * This function is for real database fields - NOT FlexForm "pseudo" fields.
1498
     * NOTICE: Calling this function expects this: 1) That the data is saved!
1499
     *
1500
     * @param string $table Table name
1501
     * @param string $field Field name
1502
     * @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.
1503
     * @param string $id The record-uid, mainly - but not exclusively - used for logging
1504
     * @param string $status 'update' or 'new' flag
1505
     * @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.
1506
     * @param int $tscPID TSconfig PID
1507
     * @param array $incomingFieldArray the fields being explicitly set by the outside (unlike $fieldArray)
1508
     * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1509
     * @internal should only be used from within DataHandler
1510
     */
1511
    public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID, $incomingFieldArray = [])
1512
    {
1513
        $curValueRec = null;
1514
        // Result array
1515
        $res = [];
1516
1517
        // Processing special case of field pages.doktype
1518
        if ($table === 'pages' && $field === 'doktype') {
1519
            // If the user may not use this specific doktype, we issue a warning
1520
            if (!($this->admin || GeneralUtility::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
1521
                if ($this->enableLogging) {
1522
                    $propArr = $this->getRecordProperties($table, $id);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $id of TYPO3\CMS\Core\DataHandl...::getRecordProperties(). ( Ignorable by Annotation )

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

1522
                    $propArr = $this->getRecordProperties($table, /** @scrutinizer ignore-type */ $id);
Loading history...
1523
                    $this->log($table, $id, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'You cannot change the \'doktype\' of page \'%s\' to the desired value.', 1, [$propArr['header']], $propArr['event_pid']);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $recuid of TYPO3\CMS\Core\DataHandling\DataHandler::log(). ( Ignorable by Annotation )

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

1523
                    $this->log($table, /** @scrutinizer ignore-type */ $id, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'You cannot change the \'doktype\' of page \'%s\' to the desired value.', 1, [$propArr['header']], $propArr['event_pid']);
Loading history...
1524
                }
1525
                return $res;
1526
            }
1527
            if ($status === 'update') {
1528
                // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1529
                $onlyAllowedTables = $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1530
                if ($onlyAllowedTables) {
1531
                    // use the real page id (default language)
1532
                    $recordId = $this->getDefaultLanguagePageId($id);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $pageId of TYPO3\CMS\Core\DataHandl...DefaultLanguagePageId(). ( Ignorable by Annotation )

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

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

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

1533
                    $theWrongTables = $this->doesPageHaveUnallowedTables($recordId, /** @scrutinizer ignore-type */ $value);
Loading history...
1534
                    if ($theWrongTables) {
1535
                        if ($this->enableLogging) {
1536
                            $propArr = $this->getRecordProperties($table, $id);
1537
                            $this->log($table, $id, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, '\'doktype\' of page \'%s\' could not be changed because the page contains records from disallowed tables; %s', 2, [$propArr['header'], $theWrongTables], $propArr['event_pid']);
1538
                        }
1539
                        return $res;
1540
                    }
1541
                }
1542
            }
1543
        }
1544
1545
        $curValue = null;
1546
        if ((int)$id !== 0) {
1547
            // Get current value:
1548
            $curValueRec = $this->recordInfo($table, $id, $field);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $id of TYPO3\CMS\Core\DataHandl...taHandler::recordInfo(). ( Ignorable by Annotation )

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

1548
            $curValueRec = $this->recordInfo($table, /** @scrutinizer ignore-type */ $id, $field);
Loading history...
1549
            // isset() won't work here, since values can be NULL
1550
            if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1551
                $curValue = $curValueRec[$field];
1552
            }
1553
        }
1554
1555
        if ($table === 'be_users'
1556
            && ($field === 'admin' || $field === 'password')
1557
            && $status === 'update'
1558
        ) {
1559
            // Do not allow a non system maintainer admin to change admin flag and password of system maintainers
1560
            $systemMaintainers = array_map('intval', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? []);
1561
            // False if current user is not in system maintainer list or if switch to user mode is active
1562
            $isCurrentUserSystemMaintainer = $this->BE_USER->isSystemMaintainer();
1563
            $isTargetUserInSystemMaintainerList = in_array((int)$id, $systemMaintainers, true);
1564
            if ($field === 'admin') {
1565
                $isFieldChanged = (int)$curValueRec[$field] !== (int)$value;
1566
            } else {
1567
                $isFieldChanged = $curValueRec[$field] !== $value;
1568
            }
1569
            if (!$isCurrentUserSystemMaintainer && $isTargetUserInSystemMaintainerList && $isFieldChanged) {
1570
                $value = $curValueRec[$field];
1571
                $message = GeneralUtility::makeInstance(
1572
                    FlashMessage::class,
1573
                    $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.adminCanNotChangeSystemMaintainer'),
1574
                    '',
1575
                    FlashMessage::ERROR,
1576
                    true
1577
                );
1578
                $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1579
                $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
1580
            }
1581
        }
1582
1583
        // Getting config for the field
1584
        $tcaFieldConf = $this->resolveFieldConfigurationAndRespectColumnsOverrides($table, $field);
1585
1586
        // Create $recFID only for those types that need it
1587
        if ($tcaFieldConf['type'] === 'flex') {
1588
            $recFID = $table . ':' . $id . ':' . $field;
1589
        } else {
1590
            $recFID = null;
1591
        }
1592
1593
        // Perform processing:
1594
        $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, [], $tscPID, ['incomingFieldArray' => $incomingFieldArray]);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $id of TYPO3\CMS\Core\DataHandl...andler::checkValue_SW(). ( Ignorable by Annotation )

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

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

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

2646
                    $value = number_format(/** @scrutinizer ignore-type */ $value, 2, '.', '');
Loading history...
2647
                    break;
2648
                case 'md5':
2649
                    if (strlen($value) !== 32) {
2650
                        $set = false;
2651
                    }
2652
                    break;
2653
                case 'trim':
2654
                    $value = trim($value);
2655
                    break;
2656
                case 'upper':
2657
                    $value = mb_strtoupper($value, 'utf-8');
2658
                    break;
2659
                case 'lower':
2660
                    $value = mb_strtolower($value, 'utf-8');
2661
                    break;
2662
                case 'required':
2663
                    if (!isset($value) || $value === '') {
2664
                        $set = false;
2665
                    }
2666
                    break;
2667
                case 'is_in':
2668
                    $c = mb_strlen($value);
2669
                    if ($c) {
2670
                        $newVal = '';
2671
                        for ($a = 0; $a < $c; $a++) {
2672
                            $char = mb_substr($value, $a, 1);
2673
                            if (mb_strpos($is_in, $char) !== false) {
2674
                                $newVal .= $char;
2675
                            }
2676
                        }
2677
                        $value = $newVal;
2678
                    }
2679
                    break;
2680
                case 'nospace':
2681
                    $value = str_replace(' ', '', $value);
2682
                    break;
2683
                case 'alpha':
2684
                    $value = preg_replace('/[^a-zA-Z]/', '', $value);
2685
                    break;
2686
                case 'num':
2687
                    $value = preg_replace('/[^0-9]/', '', $value);
2688
                    break;
2689
                case 'alphanum':
2690
                    $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2691
                    break;
2692
                case 'alphanum_x':
2693
                    $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2694
                    break;
2695
                case 'domainname':
2696
                    if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2697
                        $value = (string)HttpUtility::idn_to_ascii($value);
2698
                    }
2699
                    break;
2700
                case 'email':
2701
                    if ((string)$value !== '') {
2702
                        $this->checkValue_input_ValidateEmail($value, $set);
2703
                    }
2704
                    break;
2705
                case 'saltedPassword':
2706
                    // An incoming value is either the salted password if the user did not change existing password
2707
                    // when submitting the form, or a plaintext new password that needs to be turned into a salted password now.
2708
                    // The strategy is to see if a salt instance can be created from the incoming value. If so,
2709
                    // no new password was submitted and we keep the value. If no salting instance can be created,
2710
                    // incoming value must be a new plain text value that needs to be hashed.
2711
                    $hashFactory = GeneralUtility::makeInstance(PasswordHashFactory::class);
2712
                    $mode = $table === 'fe_users' ? 'FE' : 'BE';
2713
                    try {
2714
                        $hashFactory->get($value, $mode);
2715
                    } catch (InvalidPasswordHashException $e) {
2716
                        // We got no salted password instance, incoming value must be a new plaintext password
2717
                        // Get an instance of the current configured salted password strategy and hash the value
2718
                        $newHashInstance = $hashFactory->getDefaultHashInstance($mode);
2719
                        $value = $newHashInstance->getHashedPassword($value);
2720
                    }
2721
                    break;
2722
                default:
2723
                    if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2724
                        if (class_exists($func)) {
2725
                            $evalObj = GeneralUtility::makeInstance($func);
2726
                            if (method_exists($evalObj, 'evaluateFieldValue')) {
2727
                                $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2728
                            }
2729
                        }
2730
                    }
2731
            }
2732
        }
2733
        if ($set) {
2734
            $res['value'] = $value;
2735
        }
2736
        return $res;
2737
    }
2738
2739
    /**
2740
     * If $value is not a valid e-mail address,
2741
     * $set will be set to false and a flash error
2742
     * message will be added
2743
     *
2744
     * @param string $value Value to evaluate
2745
     * @param bool $set TRUE if an update should be done
2746
     * @throws \InvalidArgumentException
2747
     * @throws \TYPO3\CMS\Core\Exception
2748
     */
2749
    protected function checkValue_input_ValidateEmail($value, &$set)
2750
    {
2751
        if (GeneralUtility::validEmail($value)) {
2752
            return;
2753
        }
2754
2755
        $set = false;
2756
        /** @var FlashMessage $message */
2757
        $message = GeneralUtility::makeInstance(
2758
            FlashMessage::class,
2759
            sprintf($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.invalidEmail'), $value),
2760
            '', // header is optional
2761
            FlashMessage::ERROR,
2762
            true // whether message should be stored in session
2763
        );
2764
        /** @var FlashMessageService $flashMessageService */
2765
        $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
2766
        $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
2767
    }
2768
2769
    /**
2770
     * Returns data for group/db and select fields
2771
     *
2772
     * @param array $valueArray Current value array
2773
     * @param array $tcaFieldConf TCA field config
2774
     * @param int $id Record id, used for look-up of MM relations (local_uid)
2775
     * @param string $status Status string ('update' or 'new')
2776
     * @param string $type The type, either 'select', 'group' or 'inline'
2777
     * @param string $currentTable Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2778
     * @param string $currentField field name, needs to be set for writing to sys_history
2779
     * @return array Modified value array
2780
     * @internal should only be used from within DataHandler
2781
     */
2782
    public function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField)
2783
    {
2784
        if ($type === 'group') {
2785
            $tables = $tcaFieldConf['allowed'];
2786
        } elseif (!empty($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages') {
2787
            $tables = 'sys_language';
2788
        } else {
2789
            $tables = $tcaFieldConf['foreign_table'];
2790
        }
2791
        $prep = $type === 'group' ? $tcaFieldConf['prepend_tname'] : '';
2792
        $newRelations = implode(',', $valueArray);
2793
        /** @var RelationHandler $dbAnalysis */
2794
        $dbAnalysis = $this->createRelationHandlerInstance();
2795
        $dbAnalysis->registerNonTableValues = !empty($tcaFieldConf['allowNonIdValues']);
2796
        $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2797
        if ($tcaFieldConf['MM']) {
2798
            // convert submitted items to use version ids instead of live ids
2799
            // (only required for MM relations in a workspace context)
2800
            $dbAnalysis->convertItemArray();
2801
            if ($status === 'update') {
2802
                /** @var RelationHandler $oldRelations_dbAnalysis */
2803
                $oldRelations_dbAnalysis = $this->createRelationHandlerInstance();
2804
                $oldRelations_dbAnalysis->registerNonTableValues = !empty($tcaFieldConf['allowNonIdValues']);
2805
                // Db analysis with $id will initialize with the existing relations
2806
                $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2807
                $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2808
                $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

2808
                $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, /** @scrutinizer ignore-type */ $prep);
Loading history...
2809
                if ($oldRelations != $newRelations) {
2810
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2811
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2812
                } else {
2813
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2814
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2815
                }
2816
            } else {
2817
                $this->dbAnalysisStore[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable];
2818
            }
2819
            $valueArray = $dbAnalysis->countItems();
2820
        } else {
2821
            $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

2821
            $valueArray = $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prep);
Loading history...
2822
        }
2823
        // 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.
2824
        return $valueArray;
2825
    }
2826
2827
    /**
2828
     * Explodes the $value, which is a list of files/uids (group select)
2829
     *
2830
     * @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.
2831
     * @return array The value array.
2832
     * @internal should only be used from within DataHandler
2833
     */
2834
    public function checkValue_group_select_explodeSelectGroupValue($value)
2835
    {
2836
        $valueArray = GeneralUtility::trimExplode(',', $value, true);
2837
        foreach ($valueArray as &$newVal) {
2838
            $temp = explode('|', $newVal, 2);
2839
            $newVal = str_replace(['|', ','], '', rawurldecode($temp[0]));
2840
        }
2841
        unset($newVal);
2842
        return $valueArray;
2843
    }
2844
2845
    /**
2846
     * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2847
     * See checkValue_flex_procInData_travDS() for more details.
2848
     * 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
2849
     *
2850
     * @param array $dataPart The 'data' part of the INPUT flexform data
2851
     * @param array $dataPart_current The 'data' part of the CURRENT flexform data
2852
     * @param array $uploadedFiles The uploaded files for the 'data' part of the INPUT flexform data
2853
     * @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.
2854
     * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions
2855
     * @param string $callBackFunc Optional call back function, see checkValue_flex_procInData_travDS()  DEPRECATED, use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools instead for traversal!
2856
     * @param array $workspaceOptions
2857
     * @return array The modified 'data' part.
2858
     * @see checkValue_flex_procInData_travDS()
2859
     * @internal should only be used from within DataHandler
2860
     */
2861
    public function checkValue_flex_procInData($dataPart, $dataPart_current, $uploadedFiles, $dataStructure, $pParams, $callBackFunc = '', array $workspaceOptions = [])
2862
    {
2863
        if (is_array($dataPart)) {
0 ignored issues
show
introduced by
The condition is_array($dataPart) is always true.
Loading history...
2864
            foreach ($dataPart as $sKey => $sheetDef) {
2865
                if (isset($dataStructure['sheets'][$sKey]) && is_array($dataStructure['sheets'][$sKey]) && is_array($sheetDef)) {
2866
                    foreach ($sheetDef as $lKey => $lData) {
2867
                        $this->checkValue_flex_procInData_travDS(
2868
                            $dataPart[$sKey][$lKey],
2869
                            $dataPart_current[$sKey][$lKey],
2870
                            $uploadedFiles[$sKey][$lKey],
2871
                            $dataStructure['sheets'][$sKey]['ROOT']['el'],
2872
                            $pParams,
2873
                            $callBackFunc,
2874
                            $sKey . '/' . $lKey . '/',
2875
                            $workspaceOptions
2876
                        );
2877
                    }
2878
                }
2879
            }
2880
        }
2881
        return $dataPart;
2882
    }
2883
2884
    /**
2885
     * Processing of the sheet/language data array
2886
     * 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.
2887
     *
2888
     * @param array $dataValues New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2889
     * @param array $dataValues_current Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2890
     * @param array $uploadedFiles Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2891
     * @param array $DSelements Data structure which fits the data array
2892
     * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions / call back function
2893
     * @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.
2894
     * @param string $structurePath
2895
     * @param array $workspaceOptions
2896
     * @see checkValue_flex_procInData()
2897
     * @internal should only be used from within DataHandler
2898
     */
2899
    public function checkValue_flex_procInData_travDS(&$dataValues, $dataValues_current, $uploadedFiles, $DSelements, $pParams, $callBackFunc, $structurePath, array $workspaceOptions = [])
2900
    {
2901
        if (!is_array($DSelements)) {
0 ignored issues
show
introduced by
The condition is_array($DSelements) is always true.
Loading history...
2902
            return;
2903
        }
2904
2905
        // For each DS element:
2906
        foreach ($DSelements as $key => $dsConf) {
2907
            // Array/Section:
2908
            if ($DSelements[$key]['type'] === 'array') {
2909
                if (!is_array($dataValues[$key]['el'])) {
2910
                    continue;
2911
                }
2912
2913
                if ($DSelements[$key]['section']) {
2914
                    foreach ($dataValues[$key]['el'] as $ik => $el) {
2915
                        if (!is_array($el)) {
2916
                            continue;
2917
                        }
2918
2919
                        if (!is_array($dataValues_current[$key]['el'])) {
2920
                            $dataValues_current[$key]['el'] = [];
2921
                        }
2922
                        $theKey = key($el);
2923
                        if (!is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2924
                            continue;
2925
                        }
2926
2927
                        $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);
2928
                    }
2929
                } else {
2930
                    if (!isset($dataValues[$key]['el'])) {
2931
                        $dataValues[$key]['el'] = [];
2932
                    }
2933
                    $this->checkValue_flex_procInData_travDS($dataValues[$key]['el'], $dataValues_current[$key]['el'], $uploadedFiles[$key]['el'], $DSelements[$key]['el'], $pParams, $callBackFunc, $structurePath . $key . '/el/', $workspaceOptions);
2934
                }
2935
            } else {
2936
                // When having no specific sheets, it's "TCEforms.config", when having a sheet, it's just "config"
2937
                $fieldConfiguration = $dsConf['TCEforms']['config'] ?? $dsConf['config'] ?? null;
2938
                // init with value from config for passthrough fields
2939
                if (!empty($fieldConfiguration['type']) && $fieldConfiguration['type'] === 'passthrough') {
2940
                    if (!empty($dataValues_current[$key]['vDEF'])) {
2941
                        // If there is existing value, keep it
2942
                        $dataValues[$key]['vDEF'] = $dataValues_current[$key]['vDEF'];
2943
                    } elseif (
2944
                        !empty($fieldConfiguration['default'])
2945
                        && isset($pParams[1])
2946
                        && !MathUtility::canBeInterpretedAsInteger($pParams[1])
2947
                    ) {
2948
                        // If is new record and a default is specified for field, use it.
2949
                        $dataValues[$key]['vDEF'] = $fieldConfiguration['default'];
2950
                    }
2951
                }
2952
                if (!is_array($fieldConfiguration) || !is_array($dataValues[$key])) {
2953
                    continue;
2954
                }
2955
2956
                foreach ($dataValues[$key] as $vKey => $data) {
2957
                    if ($callBackFunc) {
2958
                        if (is_object($this->callBackObj)) {
2959
                            $res = $this->callBackObj->{$callBackFunc}($pParams, $fieldConfiguration, $dataValues[$key][$vKey], $dataValues_current[$key][$vKey], $uploadedFiles[$key][$vKey], $structurePath . $key . '/' . $vKey . '/', $workspaceOptions);
2960
                        } else {
2961
                            $res = $this->{$callBackFunc}($pParams, $fieldConfiguration, $dataValues[$key][$vKey], $dataValues_current[$key][$vKey], $uploadedFiles[$key][$vKey], $structurePath . $key . '/' . $vKey . '/', $workspaceOptions);
2962
                        }
2963
                    } else {
2964
                        // Default
2965
                        [$CVtable, $CVid, $CVcurValue, $CVstatus, $CVrealPid, $CVrecFID, $CVtscPID] = $pParams;
2966
2967
                        $additionalData = [
2968
                            'flexFormId' => $CVrecFID,
2969
                            'flexFormPath' => trim(rtrim($structurePath, '/') . '/' . $key . '/' . $vKey, '/'),
2970
                        ];
2971
2972
                        $res = $this->checkValue_SW([], $dataValues[$key][$vKey], $fieldConfiguration, $CVtable, $CVid, $dataValues_current[$key][$vKey], $CVstatus, $CVrealPid, $CVrecFID, '', $uploadedFiles[$key][$vKey], $CVtscPID, $additionalData);
2973
                    }
2974
                    // Adding the value:
2975
                    if (isset($res['value'])) {
2976
                        $dataValues[$key][$vKey] = $res['value'];
2977
                    }
2978
                    // 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.
2979
                    // 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).
2980
                    if (mb_substr($vKey, -9) !== '.vDEFbase') {
2981
                        if ($GLOBALS['TYPO3_CONF_VARS']['BE']['flexFormXMLincludeDiffBase'] && $vKey !== 'vDEF' && ((string)$dataValues[$key][$vKey] !== (string)$dataValues_current[$key][$vKey] || !isset($dataValues_current[$key][$vKey . '.vDEFbase']))) {
2982
                            // 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:
2983
                            if (isset($dataValues[$key]['vDEF'])) {
2984
                                $diffValue = $dataValues[$key]['vDEF'];
2985
                            } else {
2986
                                // If not found (for translators with no access to the default language) we use the one from the current-value data set:
2987
                                $diffValue = $dataValues_current[$key]['vDEF'];
2988
                            }
2989
                            // 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.
2990
                            $dataValues[$key][$vKey . '.vDEFbase'] = $diffValue;
2991
                        }
2992
                    }
2993
                }
2994
            }
2995
        }
2996
    }
2997
2998
    /**
2999
     * Returns data for inline fields.
3000
     *
3001
     * @param array $valueArray Current value array
3002
     * @param array $tcaFieldConf TCA field config
3003
     * @param int $id Record id
3004
     * @param string $status Status string ('update' or 'new')
3005
     * @param string $table Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
3006
     * @param string $field The current field the values are modified for
3007
     * @param array $additionalData Additional data to be forwarded to sub-processors
3008
     * @return string Modified values
3009
     */
3010
    protected function checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, array $additionalData = null)
3011
    {
3012
        $foreignTable = $tcaFieldConf['foreign_table'];
3013
        $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
3014
        // Fetch the related child records using \TYPO3\CMS\Core\Database\RelationHandler
3015
        /** @var RelationHandler $dbAnalysis */
3016
        $dbAnalysis = $this->createRelationHandlerInstance();
3017
        $dbAnalysis->start(implode(',', $valueArray), $foreignTable, '', 0, $table, $tcaFieldConf);
3018
        // IRRE with a pointer field (database normalization):
3019
        if ($tcaFieldConf['foreign_field']) {
3020
            // if the record was imported, sorting was also imported, so skip this
3021
            $skipSorting = (bool)$this->callFromImpExp;
3022
            // update record in intermediate table (sorting & pointer uid to parent record)
3023
            $dbAnalysis->writeForeignField($tcaFieldConf, $id, 0, $skipSorting);
3024
            $newValue = $dbAnalysis->countItems(false);
3025
        } elseif ($this->getInlineFieldType($tcaFieldConf) === 'mm') {
3026
            // In order to fully support all the MM stuff, directly call checkValue_group_select_processDBdata instead of repeating the needed code here
3027
            $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
3028
            $newValue = $valueArray[0];
3029
        } else {
3030
            $valueArray = $dbAnalysis->getValueArray();
3031
            // Checking that the number of items is correct:
3032
            $valueArray = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
3033
            $newValue = $this->castReferenceValue(implode(',', $valueArray), $tcaFieldConf);
3034
        }
3035
        return $newValue;
3036
    }
3037
3038
    /*********************************************
3039
     *
3040
     * PROCESSING COMMANDS
3041
     *
3042
     ********************************************/
3043
    /**
3044
     * Processing the cmd-array
3045
     * See "TYPO3 Core API" for a description of the options.
3046
     *
3047
     * @return void|bool
3048
     */
3049
    public function process_cmdmap()
3050
    {
3051
        // Editing frozen:
3052
        if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
3053
            $this->newlog('All editing in this workspace has been frozen!', SystemLogErrorClassification::USER_ERROR);
3054
            return false;
3055
        }
3056
        // Hook initialization:
3057
        $hookObjectsArr = [];
3058
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
3059
            $hookObj = GeneralUtility::makeInstance($className);
3060
            if (method_exists($hookObj, 'processCmdmap_beforeStart')) {
3061
                $hookObj->processCmdmap_beforeStart($this);
3062
            }
3063
            $hookObjectsArr[] = $hookObj;
3064
        }
3065
        $pasteDatamap = [];
3066
        // Traverse command map:
3067
        foreach ($this->cmdmap as $table => $_) {
3068
            // Check if the table may be modified!
3069
            $modifyAccessList = $this->checkModifyAccessList($table);
3070
            if (!$modifyAccessList) {
3071
                $this->log($table, 0, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
3072
            }
3073
            // Check basic permissions and circumstances:
3074
            if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->cmdmap[$table]) || !$modifyAccessList) {
3075
                continue;
3076
            }
3077
3078
            // Traverse the command map:
3079
            foreach ($this->cmdmap[$table] as $id => $incomingCmdArray) {
3080
                if (!is_array($incomingCmdArray)) {
3081
                    continue;
3082
                }
3083
3084
                if ($table === 'pages') {
3085
                    // for commands on pages do a pagetree-refresh
3086
                    $this->pagetreeNeedsRefresh = true;
3087
                }
3088
3089
                foreach ($incomingCmdArray as $command => $value) {
3090
                    $pasteUpdate = false;
3091
                    if (is_array($value) && isset($value['action']) && $value['action'] === 'paste') {
3092
                        // Extended paste command: $command is set to "move" or "copy"
3093
                        // $value['update'] holds field/value pairs which should be updated after copy/move operation
3094
                        // $value['target'] holds original $value (target of move/copy)
3095
                        $pasteUpdate = $value['update'];
3096
                        $value = $value['target'];
3097
                    }
3098
                    foreach ($hookObjectsArr as $hookObj) {
3099
                        if (method_exists($hookObj, 'processCmdmap_preProcess')) {
3100
                            $hookObj->processCmdmap_preProcess($command, $table, $id, $value, $this, $pasteUpdate);
3101
                        }
3102
                    }
3103
                    // Init copyMapping array:
3104
                    // Must clear this array before call from here to those functions:
3105
                    // Contains mapping information between new and old id numbers.
3106
                    $this->copyMappingArray = [];
3107
                    // process the command
3108
                    $commandIsProcessed = false;
3109
                    foreach ($hookObjectsArr as $hookObj) {
3110
                        if (method_exists($hookObj, 'processCmdmap')) {
3111
                            $hookObj->processCmdmap($command, $table, $id, $value, $commandIsProcessed, $this, $pasteUpdate);
3112
                        }
3113
                    }
3114
                    // Only execute default commands if a hook hasn't been processed the command already
3115
                    if (!$commandIsProcessed) {
3116
                        $procId = $id;
3117
                        $backupUseTransOrigPointerField = $this->useTransOrigPointerField;
3118
                        // Branch, based on command
3119
                        switch ($command) {
3120
                            case 'move':
3121
                                $this->moveRecord($table, $id, $value);
3122
                                break;
3123
                            case 'copy':
3124
                                $target = $value['target'] ?? $value;
3125
                                $ignoreLocalization = (bool)($value['ignoreLocalization'] ?? false);
3126
                                if ($table === 'pages') {
3127
                                    $this->copyPages($id, $target);
3128
                                } else {
3129
                                    $this->copyRecord($table, $id, $target, true, [], '', 0, $ignoreLocalization);
3130
                                }
3131
                                $procId = $this->copyMappingArray[$table][$id];
3132
                                break;
3133
                            case 'localize':
3134
                                $this->useTransOrigPointerField = true;
3135
                                $this->localize($table, $id, $value);
3136
                                break;
3137
                            case 'copyToLanguage':
3138
                                $this->useTransOrigPointerField = false;
3139
                                $this->localize($table, $id, $value);
3140
                                break;
3141
                            case 'inlineLocalizeSynchronize':
3142
                                $this->inlineLocalizeSynchronize($table, $id, $value);
3143
                                break;
3144
                            case 'delete':
3145
                                $this->deleteAction($table, $id);
3146
                                break;
3147
                            case 'undelete':
3148
                                $this->undeleteRecord($table, $id);
3149
                                break;
3150
                        }
3151
                        $this->useTransOrigPointerField = $backupUseTransOrigPointerField;
3152
                        if (is_array($pasteUpdate)) {
3153
                            $pasteDatamap[$table][$procId] = $pasteUpdate;
3154
                        }
3155
                    }
3156
                    foreach ($hookObjectsArr as $hookObj) {
3157
                        if (method_exists($hookObj, 'processCmdmap_postProcess')) {
3158
                            $hookObj->processCmdmap_postProcess($command, $table, $id, $value, $this, $pasteUpdate, $pasteDatamap);
3159
                        }
3160
                    }
3161
                    // Merging the copy-array info together for remapping purposes.
3162
                    ArrayUtility::mergeRecursiveWithOverrule($this->copyMappingArray_merged, $this->copyMappingArray);
3163
                }
3164
            }
3165
        }
3166
        /** @var DataHandler $copyTCE */
3167
        $copyTCE = $this->getLocalTCE();
3168
        $copyTCE->start($pasteDatamap, [], $this->BE_USER);
3169
        $copyTCE->process_datamap();
3170
        $this->errorLog = array_merge($this->errorLog, $copyTCE->errorLog);
3171
        unset($copyTCE);
3172
3173
        // Finally, before exit, check if there are ID references to remap.
3174
        // This might be the case if versioning or copying has taken place!
3175
        $this->remapListedDBRecords();
3176
        $this->processRemapStack();
3177
        foreach ($hookObjectsArr as $hookObj) {
3178
            if (method_exists($hookObj, 'processCmdmap_afterFinish')) {
3179
                $hookObj->processCmdmap_afterFinish($this);
3180
            }
3181
        }
3182
        if ($this->isOuterMostInstance()) {
3183
            $this->referenceIndexUpdater->update();
3184
            $this->processClearCacheQueue();
3185
            $this->resetNestedElementCalls();
3186
        }
3187
    }
3188
3189
    /*********************************************
3190
     *
3191
     * Cmd: Copying
3192
     *
3193
     ********************************************/
3194
    /**
3195
     * Copying a single record
3196
     *
3197
     * @param string $table Element table
3198
     * @param int $uid Element UID
3199
     * @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
3200
     * @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
3201
     * @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!
3202
     * @param string $excludeFields Commalist of fields to exclude from the copy process (might get default values)
3203
     * @param int $language Language ID (from sys_language table)
3204
     * @param bool $ignoreLocalization If TRUE, any localization routine is skipped
3205
     * @return int|null ID of new record, if any
3206
     * @internal should only be used from within DataHandler
3207
     */
3208
    public function copyRecord($table, $uid, $destPid, $first = false, $overrideValues = [], $excludeFields = '', $language = 0, $ignoreLocalization = false)
3209
    {
3210
        $uid = ($origUid = (int)$uid);
3211
        // Only copy if the table is defined in $GLOBALS['TCA'], a uid is given and the record wasn't copied before:
3212
        if (empty($GLOBALS['TCA'][$table]) || $uid === 0) {
3213
            return null;
3214
        }
3215
        if ($this->isRecordCopied($table, $uid)) {
3216
            return null;
3217
        }
3218
3219
        // Fetch record with permission check
3220
        $row = $this->recordInfoWithPermissionCheck($table, $uid, Permission::PAGE_SHOW);
3221
3222
        // This checks if the record can be selected which is all that a copy action requires.
3223
        if ($row === false) {
3224
            $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]);
3225
            return null;
3226
        }
3227
3228
        // 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...
3229
        $tscPID = BackendUtility::getTSconfig_pidValue($table, $uid, $destPid);
3230
3231
        // Check if table is allowed on destination page
3232
        if (!$this->isTableAllowedForThisPage($tscPID, $table)) {
3233
            $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]);
3234
            return null;
3235
        }
3236
3237
        $fullLanguageCheckNeeded = $table !== 'pages';
3238
        // Used to check language and general editing rights
3239
        if (!$ignoreLocalization && ($language <= 0 || !$this->BE_USER->checkLanguageAccess($language)) && !$this->BE_USER->recordEditAccessInternals($table, $uid, false, false, $fullLanguageCheckNeeded)) {
3240
            $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]);
3241
            return null;
3242
        }
3243
3244
        $data = [];
3245
        $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));
3246
        BackendUtility::workspaceOL($table, $row, $this->BE_USER->workspace);
0 ignored issues
show
Bug introduced by
It seems like $row can also be of type true; however, parameter $row of TYPO3\CMS\Backend\Utilit...dUtility::workspaceOL() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

3246
        BackendUtility::workspaceOL($table, /** @scrutinizer ignore-type */ $row, $this->BE_USER->workspace);
Loading history...
3247
        $row = BackendUtility::purgeComputedPropertiesFromRecord($row);
3248
3249
        // Initializing:
3250
        $theNewID = StringUtility::getUniqueId('NEW');
3251
        $enableField = isset($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']) ? $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'] : '';
3252
        $headerField = $GLOBALS['TCA'][$table]['ctrl']['label'];
3253
        // Getting "copy-after" fields if applicable:
3254
        $copyAfterFields = $destPid < 0 ? $this->fixCopyAfterDuplFields($table, $uid, abs($destPid), 0) : [];
0 ignored issues
show
Bug introduced by
It seems like abs($destPid) can also be of type double; however, parameter $prevUid of TYPO3\CMS\Core\DataHandl...ixCopyAfterDuplFields() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

3254
        $copyAfterFields = $destPid < 0 ? $this->fixCopyAfterDuplFields($table, $uid, /** @scrutinizer ignore-type */ abs($destPid), 0) : [];
Loading history...
3255
        // Page TSconfig related:
3256
        $TSConfig = BackendUtility::getPagesTSconfig($tscPID)['TCEMAIN.'] ?? [];
3257
        $tE = $this->getTableEntries($table, $TSConfig);
3258
        // Traverse ALL fields of the selected record:
3259
        foreach ($row as $field => $value) {
3260
            if (!in_array($field, $nonFields, true)) {
3261
                // Get TCA configuration for the field:
3262
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
3263
                // Preparation/Processing of the value:
3264
                // "pid" is hardcoded of course:
3265
                // isset() won't work here, since values can be NULL in each of the arrays
3266
                // except setDefaultOnCopyArray, since we exploded that from a string
3267
                if ($field === 'pid') {
3268
                    $value = $destPid;
3269
                } elseif (array_key_exists($field, $overrideValues)) {
3270
                    // Override value...
3271
                    $value = $overrideValues[$field];
3272
                } elseif (array_key_exists($field, $copyAfterFields)) {
3273
                    // Copy-after value if available:
3274
                    $value = $copyAfterFields[$field];
3275
                } else {
3276
                    // Hide at copy may override:
3277
                    if ($first && $field == $enableField && $GLOBALS['TCA'][$table]['ctrl']['hideAtCopy'] && !$this->neverHideAtCopy && !$tE['disableHideAtCopy']) {
3278
                        $value = 1;
3279
                    }
3280
                    // Prepend label on copy:
3281
                    if ($first && $field == $headerField && $GLOBALS['TCA'][$table]['ctrl']['prependAtCopy'] && !$tE['disablePrependAtCopy']) {
3282
                        $value = $this->getCopyHeader($table, $this->resolvePid($table, $destPid), $field, $this->clearPrefixFromValue($table, $value), 0);
3283
                    }
3284
                    // Processing based on the TCA config field type (files, references, flexforms...)
3285
                    $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $tscPID, $language);
3286
                }
3287
                // Add value to array.
3288
                $data[$table][$theNewID][$field] = $value;
3289
            }
3290
        }
3291
        // Overriding values:
3292
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock']) {
3293
            $data[$table][$theNewID][$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
3294
        }
3295
        // Setting original UID:
3296
        if ($GLOBALS['TCA'][$table]['ctrl']['origUid']) {
3297
            $data[$table][$theNewID][$GLOBALS['TCA'][$table]['ctrl']['origUid']] = $uid;
3298
        }
3299
        // Do the copy by simply submitting the array through DataHandler:
3300
        /** @var DataHandler $copyTCE */
3301
        $copyTCE = $this->getLocalTCE();
3302
        $copyTCE->start($data, [], $this->BE_USER);
3303
        $copyTCE->process_datamap();
3304
        // Getting the new UID:
3305
        $theNewSQLID = $copyTCE->substNEWwithIDs[$theNewID];
3306
        if ($theNewSQLID) {
3307
            $this->copyMappingArray[$table][$origUid] = $theNewSQLID;
3308
            // Keep automatically versionized record information:
3309
            if (isset($copyTCE->autoVersionIdMap[$table][$theNewSQLID])) {
3310
                $this->autoVersionIdMap[$table][$theNewSQLID] = $copyTCE->autoVersionIdMap[$table][$theNewSQLID];
3311
            }
3312
        }
3313
        $this->errorLog = array_merge($this->errorLog, $copyTCE->errorLog);
3314
        unset($copyTCE);
3315
        if (!$ignoreLocalization && $language == 0) {
3316
            //repointing the new translation records to the parent record we just created
3317
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $theNewSQLID;
3318
            if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
3319
                $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['translationSource']] = 0;
3320
            }
3321
            $this->copyL10nOverlayRecords($table, $uid, $destPid, $first, $overrideValues, $excludeFields);
3322
        }
3323
3324
        return $theNewSQLID;
3325
    }
3326
3327
    /**
3328
     * Copying pages
3329
     * Main function for copying pages.
3330
     *
3331
     * @param int $uid Page UID to copy
3332
     * @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
3333
     * @internal should only be used from within DataHandler
3334
     */
3335
    public function copyPages($uid, $destPid)
3336
    {
3337
        // Initialize:
3338
        $uid = (int)$uid;
3339
        $destPid = (int)$destPid;
3340
3341
        $copyTablesAlongWithPage = $this->getAllowedTablesToCopyWhenCopyingAPage();
3342
        // Begin to copy pages if we're allowed to:
3343
        if ($this->admin || in_array('pages', $copyTablesAlongWithPage, true)) {
3344
            // Copy this page we're on. And set first-flag (this will trigger that the record is hidden if that is configured)
3345
            // This method also copies the localizations of a page
3346
            $theNewRootID = $this->copySpecificPage($uid, $destPid, $copyTablesAlongWithPage, true);
3347
            // If we're going to copy recursively
3348
            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...
3349
                // Get ALL subpages to copy (read-permissions are respected!):
3350
                $CPtable = $this->int_pageTreeInfo([], $uid, (int)$this->copyTree, $theNewRootID);
3351
                // Now copying the subpages:
3352
                foreach ($CPtable as $thePageUid => $thePagePid) {
3353
                    $newPid = $this->copyMappingArray['pages'][$thePagePid];
3354
                    if (isset($newPid)) {
3355
                        $this->copySpecificPage($thePageUid, $newPid, $copyTablesAlongWithPage);
3356
                    } else {
3357
                        $this->log('pages', $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'Something went wrong during copying branch');
3358
                        break;
3359
                    }
3360
                }
3361
            }
3362
        } else {
3363
            $this->log('pages', $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to copy page without permission to this table');
3364
        }
3365
    }
3366
3367
    /**
3368
     * Compile a list of tables that should be copied along when a page is about to be copied.
3369
     *
3370
     * First, get the list that the user is allowed to modify (all if admin),
3371
     * and then check against a possible limitation within "DataHandler->copyWhichTables" if not set to "*"
3372
     * to limit the list further down
3373
     *
3374
     * @return array
3375
     */
3376
    protected function getAllowedTablesToCopyWhenCopyingAPage(): array
3377
    {
3378
        // Finding list of tables to copy.
3379
        // These are the tables, the user may modify
3380
        $copyTablesArray = $this->admin ? $this->compileAdminTables() : explode(',', $this->BE_USER->groupData['tables_modify']);
3381
        // If not all tables are allowed then make a list of allowed tables.
3382
        // That is the tables that figure in both allowed tables AND the copyTable-list
3383
        if (strpos($this->copyWhichTables, '*') === false) {
3384
            $definedTablesToCopy = GeneralUtility::trimExplode(',', $this->copyWhichTables, true);
3385
            // Pages are always allowed
3386
            $definedTablesToCopy[] = 'pages';
3387
            $definedTablesToCopy = array_flip($definedTablesToCopy);
3388
            foreach ($copyTablesArray as $k => $table) {
3389
                if (!$table || !isset($definedTablesToCopy[$table])) {
3390
                    unset($copyTablesArray[$k]);
3391
                }
3392
            }
3393
        }
3394
        $copyTablesArray = array_unique($copyTablesArray);
3395
        return $copyTablesArray;
3396
    }
3397
    /**
3398
     * Copying a single page ($uid) to $destPid and all tables in the array copyTablesArray.
3399
     *
3400
     * @param int $uid Page uid
3401
     * @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
3402
     * @param array $copyTablesArray Table on pages to copy along with the page.
3403
     * @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
3404
     * @return int|null The id of the new page, if applicable.
3405
     * @internal should only be used from within DataHandler
3406
     */
3407
    public function copySpecificPage($uid, $destPid, $copyTablesArray, $first = false)
3408
    {
3409
        // Copy the page itself:
3410
        $theNewRootID = $this->copyRecord('pages', $uid, $destPid, $first);
3411
        $currentWorkspaceId = (int)$this->BE_USER->workspace;
3412
        // If a new page was created upon the copy operation we will proceed with all the tables ON that page:
3413
        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...
3414
            foreach ($copyTablesArray as $table) {
3415
                // All records under the page is copied.
3416
                if ($table && is_array($GLOBALS['TCA'][$table]) && $table !== 'pages') {
3417
                    $fields = ['uid'];
3418
                    $languageField = null;
3419
                    $transOrigPointerField = null;
3420
                    $translationSourceField = null;
3421
                    if (BackendUtility::isTableLocalizable($table)) {
3422
                        $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
3423
                        $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
3424
                        $fields[] = $languageField;
3425
                        $fields[] = $transOrigPointerField;
3426
                        if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
3427
                            $translationSourceField = $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
3428
                            $fields[] = $translationSourceField;
3429
                        }
3430
                    }
3431
                    $isTableWorkspaceEnabled = BackendUtility::isTableWorkspaceEnabled($table);
3432
                    if ($isTableWorkspaceEnabled) {
3433
                        $fields[] = 't3ver_oid';
3434
                        $fields[] = 't3ver_state';
3435
                        $fields[] = 't3ver_wsid';
3436
                        $fields[] = 't3ver_move_id';
3437
                    }
3438
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3439
                    $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
3440
                    $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $currentWorkspaceId));
3441
                    $queryBuilder
3442
                        ->select(...$fields)
3443
                        ->from($table)
3444
                        ->where(
3445
                            $queryBuilder->expr()->eq(
3446
                                'pid',
3447
                                $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
3448
                            )
3449
                        );
3450
                    if (!empty($GLOBALS['TCA'][$table]['ctrl']['sortby'])) {
3451
                        $queryBuilder->orderBy($GLOBALS['TCA'][$table]['ctrl']['sortby'], 'DESC');
3452
                    }
3453
                    $queryBuilder->addOrderBy('uid');
3454
                    try {
3455
                        $result = $queryBuilder->execute();
3456
                        $rows = [];
3457
                        $movedLiveIds = [];
3458
                        $movedLiveRecords = [];
3459
                        while ($row = $result->fetch()) {
3460
                            if ($isTableWorkspaceEnabled && (int)$row['t3ver_state'] === VersionState::MOVE_PLACEHOLDER) {
3461
                                $movedLiveIds[(int)$row['t3ver_move_id']] = (int)$row['uid'];
3462
                            }
3463
                            $rows[(int)$row['uid']] = $row;
3464
                        }
3465
                        // Resolve placeholders of workspace versions
3466
                        if (!empty($rows) && $currentWorkspaceId > 0 && $isTableWorkspaceEnabled) {
3467
                            // If a record was moved within the page, the PlainDataResolver needs the move placeholder
3468
                            // but not the original live version, otherwise the move placeholder is not considered at all
3469
                            // For this reason, we find the live ids, where there was also a move placeholder in the SQL
3470
                            // query above in $movedLiveIds and now we removed them before handing them over to PlainDataResolver.
3471
                            // see changeContentSortingAndCopyDraftPage test
3472
                            foreach ($movedLiveIds as $liveId => $movePlaceHolderId) {
3473
                                if (isset($rows[$liveId])) {
3474
                                    $movedLiveRecords[$movePlaceHolderId] = $rows[$liveId];
3475
                                    unset($rows[$liveId]);
3476
                                }
3477
                            }
3478
                            $rows = array_reverse(
3479
                                $this->resolveVersionedRecords(
3480
                                    $table,
3481
                                    implode(',', $fields),
3482
                                    $GLOBALS['TCA'][$table]['ctrl']['sortby'],
3483
                                    array_keys($rows)
3484
                                ),
3485
                                true
3486
                            );
3487
                            foreach ($movedLiveRecords as $movePlaceHolderId => $liveRecord) {
3488
                                $rows[$movePlaceHolderId] = $liveRecord;
3489
                            }
3490
                        }
3491
                        if (is_array($rows)) {
3492
                            $languageSourceMap = [];
3493
                            $overrideValues = $translationSourceField ? [$translationSourceField => 0] : [];
3494
                            $doRemap = false;
3495
                            foreach ($rows as $row) {
3496
                                // Skip localized records that will be processed in
3497
                                // copyL10nOverlayRecords() on copying the default language record
3498
                                $transOrigPointer = $row[$transOrigPointerField];
3499
                                if ($row[$languageField] > 0 && $transOrigPointer > 0 && (isset($rows[$transOrigPointer]) || isset($movedLiveIds[$transOrigPointer]))) {
3500
                                    continue;
3501
                                }
3502
                                // Copying each of the underlying records...
3503
                                $newUid = $this->copyRecord($table, $row['uid'], $theNewRootID, false, $overrideValues);
3504
                                if ($translationSourceField) {
3505
                                    $languageSourceMap[$row['uid']] = $newUid;
3506
                                    if ($row[$languageField] > 0) {
3507
                                        $doRemap = true;
3508
                                    }
3509
                                }
3510
                            }
3511
                            if ($doRemap) {
3512
                                //remap is needed for records in non-default language records in the "free mode"
3513
                                $this->copy_remapTranslationSourceField($table, $rows, $languageSourceMap);
3514
                            }
3515
                        }
3516
                    } catch (DBALException $e) {
3517
                        $databaseErrorMessage = $e->getPrevious()->getMessage();
3518
                        $this->log($table, $uid, SystemLogDatabaseAction::CHECK, 0, SystemLogErrorClassification::USER_ERROR, 'An SQL error occurred: ' . $databaseErrorMessage);
3519
                    }
3520
                }
3521
            }
3522
            $this->processRemapStack();
3523
            return $theNewRootID;
3524
        }
3525
        return null;
3526
    }
3527
3528
    /**
3529
     * Copying records, but makes a "raw" copy of a record.
3530
     * Basically the only thing observed is field processing like the copying of files and correction of ids. All other fields are 1-1 copied.
3531
     * 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.
3532
     * 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!?
3533
     * This function is used to create new versions of a record.
3534
     * 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.
3535
     *
3536
     * @param string $table Element table
3537
     * @param int $uid Element UID
3538
     * @param int $pid Element PID (real PID, not checked)
3539
     * @param array $overrideArray Override array - must NOT contain any fields not in the table!
3540
     * @param array $workspaceOptions Options to be forwarded if actions happen on a workspace currently
3541
     * @return int Returns the new ID of the record (if applicable)
3542
     * @internal should only be used from within DataHandler
3543
     */
3544
    public function copyRecord_raw($table, $uid, $pid, $overrideArray = [], array $workspaceOptions = [])
3545
    {
3546
        $uid = (int)$uid;
3547
        // Stop any actions if the record is marked to be deleted:
3548
        // (this can occur if IRRE elements are versionized and child elements are removed)
3549
        if ($this->isElementToBeDeleted($table, $uid)) {
3550
            return null;
3551
        }
3552
        // Only copy if the table is defined in TCA, a uid is given and the record wasn't copied before:
3553
        if (!$GLOBALS['TCA'][$table] || !$uid || $this->isRecordCopied($table, $uid)) {
3554
            return null;
3555
        }
3556
3557
        // Fetch record with permission check
3558
        $row = $this->recordInfoWithPermissionCheck($table, $uid, Permission::PAGE_SHOW);
3559
3560
        // This checks if the record can be selected which is all that a copy action requires.
3561
        if ($row === false) {
3562
            $this->log(
3563
                $table,
3564
                $uid,
3565
                SystemLogDatabaseAction::DELETE,
3566
                0,
3567
                SystemLogErrorClassification::USER_ERROR,
3568
                'Attempt to rawcopy/versionize record which either does not exist or you don\'t have permission to read'
3569
            );
3570
            return null;
3571
        }
3572
3573
        // Set up fields which should not be processed. They are still written - just passed through no-questions-asked!
3574
        $nonFields = ['uid', 'pid', 't3ver_oid', 't3ver_wsid', 't3ver_state', 't3ver_stage', 'perms_userid', 'perms_groupid', 'perms_user', 'perms_group', 'perms_everybody'];
3575
3576
        // Merge in override array.
3577
        $row = array_merge($row, $overrideArray);
0 ignored issues
show
Bug introduced by
It seems like $row can also be of type true; however, parameter $array1 of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

3577
        $row = array_merge(/** @scrutinizer ignore-type */ $row, $overrideArray);
Loading history...
3578
        // Traverse ALL fields of the selected record:
3579
        foreach ($row as $field => $value) {
3580
            if (!in_array($field, $nonFields, true)) {
3581
                // Get TCA configuration for the field:
3582
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
3583
                if (is_array($conf)) {
3584
                    // Processing based on the TCA config field type (files, references, flexforms...)
3585
                    $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $pid, 0, $workspaceOptions);
3586
                }
3587
                // Add value to array.
3588
                $row[$field] = $value;
3589
            }
3590
        }
3591
        $row['pid'] = $pid;
3592
        // Setting original UID:
3593
        if ($GLOBALS['TCA'][$table]['ctrl']['origUid']) {
3594
            $row[$GLOBALS['TCA'][$table]['ctrl']['origUid']] = $uid;
3595
        }
3596
        // Do the copy by internal function
3597
        $theNewSQLID = $this->insertNewCopyVersion($table, $row, $pid);
3598
        if ($theNewSQLID) {
3599
            $this->dbAnalysisStoreExec();
3600
            $this->dbAnalysisStore = [];
3601
            return $this->copyMappingArray[$table][$uid] = $theNewSQLID;
3602
        }
3603
        return null;
3604
    }
3605
3606
    /**
3607
     * Inserts a record in the database, passing TCA configuration values through checkValue() but otherwise does NOTHING and checks nothing regarding permissions.
3608
     * 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...
3609
     *
3610
     * @param string $table Table name
3611
     * @param array $fieldArray Field array to insert as a record
3612
     * @param int $realPid The value of PID field.
3613
     * @return int Returns the new ID of the record (if applicable)
3614
     * @internal should only be used from within DataHandler
3615
     */
3616
    public function insertNewCopyVersion($table, $fieldArray, $realPid)
3617
    {
3618
        $id = StringUtility::getUniqueId('NEW');
3619
        // $fieldArray is set as current record.
3620
        // 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...
3621
        $this->checkValue_currentRecord = $fieldArray;
3622
        // Makes sure that transformations aren't processed on the copy.
3623
        $backupDontProcessTransformations = $this->dontProcessTransformations;
3624
        $this->dontProcessTransformations = true;
3625
        // Traverse record and input-process each value:
3626
        foreach ($fieldArray as $field => $fieldValue) {
3627
            if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
3628
                // Evaluating the value.
3629
                $res = $this->checkValue($table, $field, $fieldValue, $id, 'new', $realPid, 0, $fieldArray);
3630
                if (isset($res['value'])) {
3631
                    $fieldArray[$field] = $res['value'];
3632
                }
3633
            }
3634
        }
3635
        // System fields being set:
3636
        if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
3637
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
3638
        }
3639
        if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
3640
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
3641
        }
3642
        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
3643
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
3644
        }
3645
        // Finally, insert record:
3646
        $this->insertDB($table, $id, $fieldArray, true);
3647
        // Resets dontProcessTransformations to the previous state.
3648
        $this->dontProcessTransformations = $backupDontProcessTransformations;
3649
        // Return new id:
3650
        return $this->substNEWwithIDs[$id];
3651
    }
3652
3653
    /**
3654
     * Processing/Preparing content for copyRecord() function
3655
     *
3656
     * @param string $table Table name
3657
     * @param int $uid Record uid
3658
     * @param string $field Field name being processed
3659
     * @param string $value Input value to be processed.
3660
     * @param array $row Record array
3661
     * @param array $conf TCA field configuration
3662
     * @param int $realDestPid Real page id (pid) the record is copied to
3663
     * @param int $language Language ID (from sys_language table) used in the duplicated record
3664
     * @param array $workspaceOptions Options to be forwarded if actions happen on a workspace currently
3665
     * @return array|string
3666
     * @internal
3667
     * @see copyRecord()
3668
     */
3669
    public function copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $realDestPid, $language = 0, array $workspaceOptions = [])
3670
    {
3671
        $inlineSubType = $this->getInlineFieldType($conf);
3672
        // Get the localization mode for the current (parent) record (keep|select):
3673
        // Register if there are references to take care of or MM is used on an inline field (no change to value):
3674
        if ($this->isReferenceField($conf) || $inlineSubType === 'mm') {
3675
            $value = $this->copyRecord_processManyToMany($table, $uid, $field, $value, $conf, $language);
3676
        } elseif ($inlineSubType !== false) {
3677
            $value = $this->copyRecord_processInline($table, $uid, $field, $value, $row, $conf, $realDestPid, $language, $workspaceOptions);
3678
        }
3679
        // 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())
3680
        if ($conf['type'] === 'flex') {
3681
            // Get current value array:
3682
            $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
3683
            $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
3684
                ['config' => $conf],
3685
                $table,
3686
                $field,
3687
                $row
3688
            );
3689
            $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
3690
            $currentValueArray = GeneralUtility::xml2array($value);
3691
            // Traversing the XML structure, processing files:
3692
            if (is_array($currentValueArray)) {
3693
                $currentValueArray['data'] = $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $uid, $field, $realDestPid], 'copyRecord_flexFormCallBack', $workspaceOptions);
3694
                // Setting value as an array! -> which means the input will be processed according to the 'flex' type when the new copy is created.
3695
                $value = $currentValueArray;
3696
            }
3697
        }
3698
        return $value;
3699
    }
3700
3701
    /**
3702
     * Processes the children of an MM relation field (select, group, inline) when the parent record is copied.
3703
     *
3704
     * @param string $table
3705
     * @param int $uid
3706
     * @param string $field
3707
     * @param mixed $value
3708
     * @param array $conf
3709
     * @param string $language
3710
     * @return mixed
3711
     */
3712
    protected function copyRecord_processManyToMany($table, $uid, $field, $value, $conf, $language)
3713
    {
3714
        $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
3715
        $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
3716
        $mmTable = isset($conf['MM']) && $conf['MM'] ? $conf['MM'] : '';
3717
        $localizeForeignTable = isset($conf['foreign_table']) && BackendUtility::isTableLocalizable($conf['foreign_table']);
3718
        // Localize referenced records of select fields:
3719
        $localizingNonManyToManyFieldReferences = empty($mmTable) && $localizeForeignTable && isset($conf['localizeReferencesAtParentLocalization']) && $conf['localizeReferencesAtParentLocalization'];
3720
        /** @var RelationHandler $dbAnalysis */
3721
        $dbAnalysis = $this->createRelationHandlerInstance();
3722
        $dbAnalysis->start($value, $allowedTables, $mmTable, $uid, $table, $conf);
3723
        $purgeItems = false;
3724
        if ($language > 0 && $localizingNonManyToManyFieldReferences) {
3725
            foreach ($dbAnalysis->itemArray as $index => $item) {
3726
                // Since select fields can reference many records, check whether there's already a localization:
3727
                $recordLocalization = BackendUtility::getRecordLocalization($item['table'], $item['id'], $language);
0 ignored issues
show
Bug introduced by
$language of type string is incompatible with the type integer expected by parameter $language of TYPO3\CMS\Backend\Utilit...getRecordLocalization(). ( Ignorable by Annotation )

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

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

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

3731
                    $dbAnalysis->itemArray[$index]['id'] = $this->localize($item['table'], $item['id'], /** @scrutinizer ignore-type */ $language);
Loading history...
3732
                }
3733
            }
3734
            $purgeItems = true;
3735
        }
3736
3737
        if ($purgeItems || $mmTable) {
3738
            $dbAnalysis->purgeItemArray();
3739
            $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

3739
            $value = implode(',', $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName));
Loading history...
3740
        }
3741
        // Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
3742
        if ($value) {
3743
            $this->registerDBList[$table][$uid][$field] = $value;
3744
        }
3745
3746
        return $value;
3747
    }
3748
3749
    /**
3750
     * Processes child records in an inline (IRRE) element when the parent record is copied.
3751
     *
3752
     * @param string $table
3753
     * @param int $uid
3754
     * @param string $field
3755
     * @param mixed $value
3756
     * @param array $row
3757
     * @param array $conf
3758
     * @param int $realDestPid
3759
     * @param string $language
3760
     * @param array $workspaceOptions
3761
     * @return string
3762
     */
3763
    protected function copyRecord_processInline(
3764
        $table,
3765
        $uid,
3766
        $field,
3767
        $value,
3768
        $row,
3769
        $conf,
3770
        $realDestPid,
3771
        $language,
3772
        array $workspaceOptions
3773
    ) {
3774
        // Fetch the related child records using \TYPO3\CMS\Core\Database\RelationHandler
3775
        /** @var RelationHandler $dbAnalysis */
3776
        $dbAnalysis = $this->createRelationHandlerInstance();
3777
        $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
3778
        // Walk through the items, copy them and remember the new id:
3779
        foreach ($dbAnalysis->itemArray as $k => $v) {
3780
            $newId = null;
3781
            // If language is set and differs from original record, this isn't a copy action but a localization of our parent/ancestor:
3782
            if ($language > 0 && BackendUtility::isTableLocalizable($table) && $language != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
3783
                // Children should be localized when the parent gets localized the first time, just do it:
3784
                $newId = $this->localize($v['table'], $v['id'], $language);
0 ignored issues
show
Bug introduced by
$language of type string is incompatible with the type integer expected by parameter $language of TYPO3\CMS\Core\DataHandl...DataHandler::localize(). ( Ignorable by Annotation )

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

3784
                $newId = $this->localize($v['table'], $v['id'], /** @scrutinizer ignore-type */ $language);
Loading history...
3785
            } else {
3786
                if (!MathUtility::canBeInterpretedAsInteger($realDestPid)) {
3787
                    $newId = $this->copyRecord($v['table'], $v['id'], -$v['id']);
3788
                // If the destination page id is a NEW string, keep it on the same page
3789
                } elseif ($this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($v['table'])) {
3790
                    // A filled $workspaceOptions indicated that this call
3791
                    // has it's origin in previous versionizeRecord() processing
3792
                    if (!empty($workspaceOptions)) {
3793
                        // Versions use live default id, thus the "new"
3794
                        // id is the original live default child record
3795
                        $newId = $v['id'];
3796
                        $this->versionizeRecord(
3797
                            $v['table'],
3798
                            $v['id'],
3799
                            $workspaceOptions['label'] ?? 'Auto-created for WS #' . $this->BE_USER->workspace,
3800
                            $workspaceOptions['delete'] ?? false
3801
                        );
3802
                    // Otherwise just use plain copyRecord() to create placeholders etc.
3803
                    } else {
3804
                        // If a record has been copied already during this request,
3805
                        // prevent superfluous duplication and use the existing copy
3806
                        if (isset($this->copyMappingArray[$v['table']][$v['id']])) {
3807
                            $newId = $this->copyMappingArray[$v['table']][$v['id']];
3808
                        } else {
3809
                            $newId = $this->copyRecord($v['table'], $v['id'], $realDestPid);
3810
                        }
3811
                    }
3812
                } elseif ($this->BE_USER->workspace > 0 && !BackendUtility::isTableWorkspaceEnabled($v['table'])) {
3813
                    // We are in workspace context creating a new parent version and have a child table
3814
                    // that is not workspace aware. We don't do anything with this child.
3815
                    continue;
3816
                } else {
3817
                    // If a record has been copied already during this request,
3818
                    // prevent superfluous duplication and use the existing copy
3819
                    if (isset($this->copyMappingArray[$v['table']][$v['id']])) {
3820
                        $newId = $this->copyMappingArray[$v['table']][$v['id']];
3821
                    } else {
3822
                        $newId = $this->copyRecord_raw($v['table'], $v['id'], $realDestPid, [], $workspaceOptions);
3823
                    }
3824
                }
3825
            }
3826
            // If the current field is set on a page record, update the pid of related child records:
3827
            if ($table === 'pages') {
3828
                $this->registerDBPids[$v['table']][$v['id']] = $uid;
3829
            } elseif (isset($this->registerDBPids[$table][$uid])) {
3830
                $this->registerDBPids[$v['table']][$v['id']] = $this->registerDBPids[$table][$uid];
3831
            }
3832
            $dbAnalysis->itemArray[$k]['id'] = $newId;
3833
        }
3834
        // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
3835
        $value = implode(',', $dbAnalysis->getValueArray());
3836
        $this->registerDBList[$table][$uid][$field] = $value;
3837
3838
        return $value;
3839
    }
3840
3841
    /**
3842
     * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
3843
     *
3844
     * @param array $pParams Array of parameters in num-indexes: table, uid, field
3845
     * @param array $dsConf TCA field configuration (from Data Structure XML)
3846
     * @param string $dataValue The value of the flexForm field
3847
     * @param string $_1 Not used.
3848
     * @param string $_2 Not used.
3849
     * @param string $_3 Not used.
3850
     * @param array $workspaceOptions
3851
     * @return array Result array with key "value" containing the value of the processing.
3852
     * @see copyRecord()
3853
     * @see checkValue_flex_procInData_travDS()
3854
     * @internal should only be used from within DataHandler
3855
     */
3856
    public function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $_1, $_2, $_3, $workspaceOptions)
3857
    {
3858
        // Extract parameters:
3859
        [$table, $uid, $field, $realDestPid] = $pParams;
3860
        // If references are set for this field, set flag so they can be corrected later (in ->remapListedDBRecords())
3861
        if (($this->isReferenceField($dsConf) || $this->getInlineFieldType($dsConf) !== false) && (string)$dataValue !== '') {
3862
            $dataValue = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $dataValue, [], $dsConf, $realDestPid, 0, $workspaceOptions);
3863
            $this->registerDBList[$table][$uid][$field] = 'FlexForm_reference';
3864
        }
3865
        // Return
3866
        return ['value' => $dataValue];
3867
    }
3868
3869
    /**
3870
     * Find l10n-overlay records and perform the requested copy action for these records.
3871
     *
3872
     * @param string $table Record Table
3873
     * @param string $uid UID of the record in the default language
3874
     * @param string $destPid Position to copy to
3875
     * @param bool $first
3876
     * @param array $overrideValues
3877
     * @param string $excludeFields
3878
     * @internal should only be used from within DataHandler
3879
     */
3880
    public function copyL10nOverlayRecords($table, $uid, $destPid, $first = false, $overrideValues = [], $excludeFields = '')
3881
    {
3882
        // There's no need to perform this for tables that are not localizable
3883
        if (!BackendUtility::isTableLocalizable($table)) {
3884
            return;
3885
        }
3886
3887
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3888
        $queryBuilder->getRestrictions()
3889
            ->removeAll()
3890
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
3891
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->BE_USER->workspace));
3892
3893
        $queryBuilder->select('*')
3894
            ->from($table)
3895
            ->where(
3896
                $queryBuilder->expr()->eq(
3897
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
3898
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':pointer')
3899
                )
3900
            );
3901
3902
        // Never copy the actual move placeholders around, as the newly copied records are
3903
        // Always created as new record / new placeholder pairs
3904
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
3905
            $queryBuilder->andWhere(
3906
                $queryBuilder->expr()->notIn(
3907
                    't3ver_state',
3908
                    [VersionState::MOVE_PLACEHOLDER, VersionState::DELETE_PLACEHOLDER]
3909
                )
3910
            );
3911
        }
3912
3913
        // If $destPid is < 0, get the pid of the record with uid equal to abs($destPid)
3914
        $tscPID = BackendUtility::getTSconfig_pidValue($table, $uid, $destPid);
0 ignored issues
show
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Backend\Utilit...:getTSconfig_pidValue(). ( Ignorable by Annotation )

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

3914
        $tscPID = BackendUtility::getTSconfig_pidValue($table, /** @scrutinizer ignore-type */ $uid, $destPid);
Loading history...
Bug introduced by
$destPid of type string is incompatible with the type integer expected by parameter $pid of TYPO3\CMS\Backend\Utilit...:getTSconfig_pidValue(). ( Ignorable by Annotation )

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

3914
        $tscPID = BackendUtility::getTSconfig_pidValue($table, $uid, /** @scrutinizer ignore-type */ $destPid);
Loading history...
3915
        // Get the localized records to be copied
3916
        $l10nRecords = $queryBuilder->execute()->fetchAll();
3917
        if (is_array($l10nRecords)) {
3918
            $localizedDestPids = [];
3919
            // If $destPid < 0, then it is the uid of the original language record we are inserting after
3920
            if ($destPid < 0) {
3921
                // Get the localized records of the record we are inserting after
3922
                $queryBuilder->setParameter('pointer', abs($destPid), \PDO::PARAM_INT);
3923
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
3924
                // Index the localized record uids by language
3925
                if (is_array($destL10nRecords)) {
3926
                    foreach ($destL10nRecords as $record) {
3927
                        $localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]] = -$record['uid'];
3928
                    }
3929
                }
3930
            }
3931
            $languageSourceMap = [
3932
                $uid => $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]
3933
            ];
3934
            // Copy the localized records after the corresponding localizations of the destination record
3935
            foreach ($l10nRecords as $record) {
3936
                $localizedDestPid = (int)$localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]];
3937
                if ($localizedDestPid < 0) {
3938
                    $newUid = $this->copyRecord($table, $record['uid'], $localizedDestPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
3939
                } else {
3940
                    $newUid = $this->copyRecord($table, $record['uid'], $destPid < 0 ? $tscPID : $destPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
0 ignored issues
show
Bug introduced by
It seems like $destPid < 0 ? $tscPID : $destPid can also be of type string; however, parameter $destPid of TYPO3\CMS\Core\DataHandl...taHandler::copyRecord() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

3940
                    $newUid = $this->copyRecord($table, $record['uid'], /** @scrutinizer ignore-type */ $destPid < 0 ? $tscPID : $destPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
Loading history...
3941
                }
3942
                $languageSourceMap[$record['uid']] = $newUid;
3943
            }
3944
            $this->copy_remapTranslationSourceField($table, $l10nRecords, $languageSourceMap);
3945
        }
3946
    }
3947
3948
    /**
3949
     * Remap languageSource field to uids of newly created records
3950
     *
3951
     * @param string $table Table name
3952
     * @param array $l10nRecords array of localized records from the page we're copying from (source records)
3953
     * @param array $languageSourceMap array mapping source records uids to newly copied uids
3954
     */
3955
    protected function copy_remapTranslationSourceField($table, $l10nRecords, $languageSourceMap)
3956
    {
3957
        if (empty($GLOBALS['TCA'][$table]['ctrl']['translationSource']) || empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])) {
3958
            return;
3959
        }
3960
        $translationSourceFieldName = $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
3961
        $translationParentFieldName = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
3962
3963
        //We can avoid running these update queries by sorting the $l10nRecords by languageSource dependency (in copyL10nOverlayRecords)
3964
        //and first copy records depending on default record (and map the field).
3965
        foreach ($l10nRecords as $record) {
3966
            $oldSourceUid = $record[$translationSourceFieldName];
3967
            if ($oldSourceUid <= 0 && $record[$translationParentFieldName] > 0) {
3968
                //BC fix - in connected mode 'translationSource' field should not be 0
3969
                $oldSourceUid = $record[$translationParentFieldName];
3970
            }
3971
            if ($oldSourceUid > 0) {
3972
                if (empty($languageSourceMap[$oldSourceUid])) {
3973
                    // we don't have mapping information available e.g when copyRecord returned null
3974
                    continue;
3975
                }
3976
                $newFieldValue = $languageSourceMap[$oldSourceUid];
3977
                $updateFields = [
3978
                    $translationSourceFieldName => $newFieldValue
3979
                ];
3980
                GeneralUtility::makeInstance(ConnectionPool::class)
3981
                    ->getConnectionForTable($table)
3982
                    ->update($table, $updateFields, ['uid' => (int)$languageSourceMap[$record['uid']]]);
3983
                if ($this->BE_USER->workspace > 0) {
3984
                    GeneralUtility::makeInstance(ConnectionPool::class)
3985
                        ->getConnectionForTable($table)
3986
                        ->update($table, $updateFields, ['t3ver_oid' => (int)$languageSourceMap[$record['uid']], 't3ver_wsid' => $this->BE_USER->workspace]);
3987
                }
3988
            }
3989
        }
3990
    }
3991
3992
    /*********************************************
3993
     *
3994
     * Cmd: Moving, Localizing
3995
     *
3996
     ********************************************/
3997
    /**
3998
     * Moving single records
3999
     *
4000
     * @param string $table Table name to move
4001
     * @param int $uid Record uid to move
4002
     * @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
4003
     * @internal should only be used from within DataHandler
4004
     */
4005
    public function moveRecord($table, $uid, $destPid)
4006
    {
4007
        if (!$GLOBALS['TCA'][$table]) {
4008
            return;
4009
        }
4010
4011
        // In case the record to be moved turns out to be an offline version,
4012
        // we have to find the live version and work on that one.
4013
        if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $uid, 'uid')) {
4014
            $uid = $lookForLiveVersion['uid'];
4015
        }
4016
        // Initialize:
4017
        $destPid = (int)$destPid;
4018
        // Get this before we change the pid (for logging)
4019
        $propArr = $this->getRecordProperties($table, $uid);
4020
        $moveRec = $this->getRecordProperties($table, $uid, true);
4021
        // This is the actual pid of the moving to destination
4022
        $resolvedPid = $this->resolvePid($table, $destPid);
4023
        // 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.
4024
        // If the record is a page, then there are two options: If the page is moved within itself,
4025
        // (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.
4026
        if ($table !== 'pages' || $resolvedPid == $moveRec['pid']) {
4027
            // Edit rights for the record...
4028
            $mayMoveAccess = $this->checkRecordUpdateAccess($table, $uid);
4029
        } else {
4030
            $mayMoveAccess = $this->doesRecordExist($table, $uid, Permission::PAGE_DELETE);
4031
        }
4032
        // Finding out, if the record may be moved TO another place. Here we check insert-rights (non-pages = edit, pages = new),
4033
        // unless the pages are moved on the same pid, then edit-rights are checked
4034
        if ($table !== 'pages' || $resolvedPid != $moveRec['pid']) {
4035
            // Insert rights for the record...
4036
            $mayInsertAccess = $this->checkRecordInsertAccess($table, $resolvedPid, SystemLogDatabaseAction::MOVE);
4037
        } else {
4038
            $mayInsertAccess = $this->checkRecordUpdateAccess($table, $uid);
4039
        }
4040
        // Checking if there is anything else disallowing moving the record by checking if editing is allowed
4041
        $fullLanguageCheckNeeded = $table !== 'pages';
4042
        $mayEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, false, false, $fullLanguageCheckNeeded);
4043
        // If moving is allowed, begin the processing:
4044
        if (!$mayEditAccess) {
4045
            $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']);
4046
            return;
4047
        }
4048
4049
        if (!$mayMoveAccess) {
4050
            $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']);
4051
            return;
4052
        }
4053
4054
        if (!$mayInsertAccess) {
4055
            $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']);
4056
            return;
4057
        }
4058
4059
        $recordWasMoved = false;
4060
        // Move the record via a hook, used e.g. for versioning
4061
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] ?? [] as $className) {
4062
            $hookObj = GeneralUtility::makeInstance($className);
4063
            if (method_exists($hookObj, 'moveRecord')) {
4064
                $hookObj->moveRecord($table, $uid, $destPid, $propArr, $moveRec, $resolvedPid, $recordWasMoved, $this);
4065
            }
4066
        }
4067
        // Move the record if a hook hasn't moved it yet
4068
        if (!$recordWasMoved) {
0 ignored issues
show
introduced by
The condition $recordWasMoved is always false.
Loading history...
4069
            $this->moveRecord_raw($table, $uid, $destPid);
4070
        }
4071
    }
4072
4073
    /**
4074
     * Moves a record without checking security of any sort.
4075
     * USE ONLY INTERNALLY
4076
     *
4077
     * @param string $table Table name to move
4078
     * @param int $uid Record uid to move
4079
     * @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
4080
     * @see moveRecord()
4081
     * @internal should only be used from within DataHandler
4082
     */
4083
    public function moveRecord_raw($table, $uid, $destPid)
4084
    {
4085
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
4086
        $origDestPid = $destPid;
4087
        // This is the actual pid of the moving to destination
4088
        $resolvedPid = $this->resolvePid($table, $destPid);
4089
        // Checking if the pid is negative, but no sorting row is defined. In that case, find the correct pid.
4090
        // Basically this check make the error message 4-13 meaning less... But you can always remove this check if you
4091
        // prefer the error instead of a no-good action (which is to move the record to its own page...)
4092
        if (($destPid < 0 && !$sortColumn) || $destPid >= 0) {
4093
            $destPid = $resolvedPid;
4094
        }
4095
        // Get this before we change the pid (for logging)
4096
        $propArr = $this->getRecordProperties($table, $uid);
4097
        $moveRec = $this->getRecordProperties($table, $uid, true);
4098
        // Prepare user defined objects (if any) for hooks which extend this function:
4099
        $hookObjectsArr = [];
4100
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] ?? [] as $className) {
4101
            $hookObjectsArr[] = GeneralUtility::makeInstance($className);
4102
        }
4103
        // Timestamp field:
4104
        $updateFields = [];
4105
        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
4106
            $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
4107
        }
4108
4109
        // Check if this is a translation of a page, if so then it just needs to be kept "sorting" in sync
4110
        // Usually called from moveL10nOverlayRecords()
4111
        if ($table === 'pages') {
4112
            $defaultLanguagePageId = $this->getDefaultLanguagePageId((int)$uid);
4113
            if ($defaultLanguagePageId !== (int)$uid) {
4114
                $originalTranslationRecord = $this->recordInfo($table, $defaultLanguagePageId, 'pid,' . $sortColumn);
4115
                $updateFields[$sortColumn] = $originalTranslationRecord[$sortColumn];
4116
                // Ensure that the PID is always the same as the default language page
4117
                $destPid = $originalTranslationRecord['pid'];
4118
            }
4119
        }
4120
4121
        // Insert as first element on page (where uid = $destPid)
4122
        if ($destPid >= 0) {
4123
            if ($table !== 'pages' || $this->destNotInsideSelf($destPid, $uid)) {
4124
                // Clear cache before moving
4125
                [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
0 ignored issues
show
Bug introduced by
'' of type string is incompatible with the type integer expected by parameter $pid of TYPO3\CMS\Backend\Utilit...endUtility::getTSCpid(). ( Ignorable by Annotation )

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

4125
                [$parentUid] = BackendUtility::getTSCpid($table, $uid, /** @scrutinizer ignore-type */ '');
Loading history...
4126
                $this->registerRecordIdForPageCacheClearing($table, $uid, $parentUid);
4127
                // Setting PID
4128
                $updateFields['pid'] = $destPid;
4129
                // Table is sorted by 'sortby'
4130
                if ($sortColumn && !isset($updateFields[$sortColumn])) {
4131
                    $sortNumber = $this->getSortNumber($table, $uid, $destPid);
4132
                    $updateFields[$sortColumn] = $sortNumber;
4133
                }
4134
                // Check for child records that have also to be moved
4135
                $this->moveRecord_procFields($table, $uid, $destPid);
4136
                // Create query for update:
4137
                GeneralUtility::makeInstance(ConnectionPool::class)
4138
                    ->getConnectionForTable($table)
4139
                    ->update($table, $updateFields, ['uid' => (int)$uid]);
4140
                // Check for the localizations of that element
4141
                $this->moveL10nOverlayRecords($table, $uid, $destPid, $destPid);
4142
                // Call post processing hooks:
4143
                foreach ($hookObjectsArr as $hookObj) {
4144
                    if (method_exists($hookObj, 'moveRecord_firstElementPostProcess')) {
4145
                        $hookObj->moveRecord_firstElementPostProcess($table, $uid, $destPid, $moveRec, $updateFields, $this);
4146
                    }
4147
                }
4148
4149
                $this->getRecordHistoryStore()->moveRecord($table, $uid, ['oldPageId' => $propArr['pid'], 'newPageId' => $destPid, 'oldData' => $propArr, 'newData' => $updateFields], $this->correlationId);
4150
                if ($this->enableLogging) {
4151
                    // Logging...
4152
                    $oldpagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4153
                    if ($destPid != $propArr['pid']) {
4154
                        // Logged to old page
4155
                        $newPropArr = $this->getRecordProperties($table, $uid);
4156
                        $newpagePropArr = $this->getRecordProperties('pages', $destPid);
4157
                        $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']);
4158
                        // Logged to new page
4159
                        $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);
4160
                    } else {
4161
                        // Logged to new page
4162
                        $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);
4163
                    }
4164
                }
4165
                // Clear cache after moving
4166
                $this->registerRecordIdForPageCacheClearing($table, $uid);
4167
                $this->fixUniqueInPid($table, $uid);
4168
                $this->fixUniqueInSite($table, (int)$uid);
4169
                if ($table === 'pages') {
4170
                    $this->fixUniqueInSiteForSubpages((int)$uid);
4171
                }
4172
            } elseif ($this->enableLogging) {
4173
                $destPropArr = $this->getRecordProperties('pages', $destPid);
4174
                $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']);
4175
            }
4176
        } elseif ($sortColumn) {
4177
            // Put after another record
4178
            // Table is being sorted
4179
            // Save the position to which the original record is requested to be moved
4180
            $originalRecordDestinationPid = $destPid;
4181
            $sortInfo = $this->getSortNumber($table, $uid, $destPid);
4182
            // Setting the destPid to the new pid of the record.
4183
            $destPid = $sortInfo['pid'];
4184
            // If not an array, there was an error (which is already logged)
4185
            if (is_array($sortInfo)) {
4186
                if ($table !== 'pages' || $this->destNotInsideSelf($destPid, $uid)) {
4187
                    // clear cache before moving
4188
                    $this->registerRecordIdForPageCacheClearing($table, $uid);
4189
                    // We now update the pid and sortnumber (if not set for page translations)
4190
                    $updateFields['pid'] = $destPid;
4191
                    if (!isset($updateFields[$sortColumn])) {
4192
                        $updateFields[$sortColumn] = $sortInfo['sortNumber'];
4193
                    }
4194
                    // Check for child records that have also to be moved
4195
                    $this->moveRecord_procFields($table, $uid, $destPid);
4196
                    // Create query for update:
4197
                    GeneralUtility::makeInstance(ConnectionPool::class)
4198
                        ->getConnectionForTable($table)
4199
                        ->update($table, $updateFields, ['uid' => (int)$uid]);
4200
                    // Check for the localizations of that element
4201
                    $this->moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid);
4202
                    // Call post processing hooks:
4203
                    foreach ($hookObjectsArr as $hookObj) {
4204
                        if (method_exists($hookObj, 'moveRecord_afterAnotherElementPostProcess')) {
4205
                            $hookObj->moveRecord_afterAnotherElementPostProcess($table, $uid, $destPid, $origDestPid, $moveRec, $updateFields, $this);
4206
                        }
4207
                    }
4208
                    $this->getRecordHistoryStore()->moveRecord($table, $uid, ['oldPageId' => $propArr['pid'], 'newPageId' => $destPid, 'oldData' => $propArr, 'newData' => $updateFields], $this->correlationId);
4209
                    if ($this->enableLogging) {
4210
                        // Logging...
4211
                        $oldpagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4212
                        if ($destPid != $propArr['pid']) {
4213
                            // Logged to old page
4214
                            $newPropArr = $this->getRecordProperties($table, $uid);
4215
                            $newpagePropArr = $this->getRecordProperties('pages', $destPid);
4216
                            $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']);
4217
                            // Logged to old page
4218
                            $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);
4219
                        } else {
4220
                            // Logged to old page
4221
                            $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);
4222
                        }
4223
                    }
4224
                    // Clear cache after moving
4225
                    $this->registerRecordIdForPageCacheClearing($table, $uid);
4226
                    $this->fixUniqueInPid($table, $uid);
4227
                    $this->fixUniqueInSite($table, (int)$uid);
4228
                    if ($table === 'pages') {
4229
                        $this->fixUniqueInSiteForSubpages((int)$uid);
4230
                    }
4231
                } elseif ($this->enableLogging) {
4232
                    $destPropArr = $this->getRecordProperties('pages', $destPid);
4233
                    $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']);
4234
                }
4235
            } else {
4236
                $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']);
4237
            }
4238
        }
4239
    }
4240
4241
    /**
4242
     * Walk through all fields of the moved record and look for children of e.g. the inline type.
4243
     * If child records are found, they are also move to the new $destPid.
4244
     *
4245
     * @param string $table Record Table
4246
     * @param int $uid Record UID
4247
     * @param int $destPid Position to move to
4248
     * @internal should only be used from within DataHandler
4249
     */
4250
    public function moveRecord_procFields($table, $uid, $destPid)
4251
    {
4252
        $row = BackendUtility::getRecordWSOL($table, $uid);
4253
        if (is_array($row) && (int)$destPid !== (int)$row['pid']) {
4254
            $conf = $GLOBALS['TCA'][$table]['columns'];
4255
            foreach ($row as $field => $value) {
4256
                $this->moveRecord_procBasedOnFieldType($table, $uid, $destPid, $field, $value, $conf[$field]['config']);
4257
            }
4258
        }
4259
    }
4260
4261
    /**
4262
     * Move child records depending on the field type of the parent record.
4263
     *
4264
     * @param string $table Record Table
4265
     * @param string $uid Record UID
4266
     * @param string $destPid Position to move to
4267
     * @param string $field Record field
4268
     * @param string $value Record field value
4269
     * @param array $conf TCA configuration of current field
4270
     * @internal should only be used from within DataHandler
4271
     */
4272
    public function moveRecord_procBasedOnFieldType($table, $uid, $destPid, $field, $value, $conf)
4273
    {
4274
        $dbAnalysis = null;
4275
        if ($conf['type'] === 'inline') {
4276
            $foreign_table = $conf['foreign_table'];
4277
            $moveChildrenWithParent = !isset($conf['behaviour']['disableMovingChildrenWithParent']) || !$conf['behaviour']['disableMovingChildrenWithParent'];
4278
            if ($foreign_table && $moveChildrenWithParent) {
4279
                $inlineType = $this->getInlineFieldType($conf);
4280
                if ($inlineType === 'list' || $inlineType === 'field') {
4281
                    if ($table === 'pages') {
4282
                        // If the inline elements are related to a page record,
4283
                        // make sure they reside at that page and not at its parent
4284
                        $destPid = $uid;
4285
                    }
4286
                    $dbAnalysis = $this->createRelationHandlerInstance();
4287
                    $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
0 ignored issues
show
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $MMuid of TYPO3\CMS\Core\Database\RelationHandler::start(). ( Ignorable by Annotation )

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

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

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

4296
                $this->moveRecord($v['table'], $v['id'], /** @scrutinizer ignore-type */ $destPid);
Loading history...
4297
            }
4298
        }
4299
    }
4300
4301
    /**
4302
     * Find l10n-overlay records and perform the requested move action for these records.
4303
     *
4304
     * @param string $table Record Table
4305
     * @param string $uid Record UID
4306
     * @param string $destPid Position to move to
4307
     * @param string $originalRecordDestinationPid Position to move the original record to
4308
     * @internal should only be used from within DataHandler
4309
     */
4310
    public function moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid)
4311
    {
4312
        // There's no need to perform this for non-localizable tables
4313
        if (!BackendUtility::isTableLocalizable($table)) {
4314
            return;
4315
        }
4316
4317
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
4318
        $queryBuilder->getRestrictions()
4319
            ->removeAll()
4320
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
4321
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->BE_USER->workspace));
4322
4323
        $l10nRecords = $queryBuilder->select('*')
4324
            ->from($table)
4325
            ->where(
4326
                $queryBuilder->expr()->eq(
4327
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
4328
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':pointer')
4329
                )
4330
            )
4331
            ->execute()
4332
            ->fetchAll();
4333
4334
        if (is_array($l10nRecords)) {
4335
            $localizedDestPids = [];
4336
            // If $$originalRecordDestinationPid < 0, then it is the uid of the original language record we are inserting after
4337
            if ($originalRecordDestinationPid < 0) {
4338
                // Get the localized records of the record we are inserting after
4339
                $queryBuilder->setParameter('pointer', abs($originalRecordDestinationPid), \PDO::PARAM_INT);
4340
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
4341
                // Index the localized record uids by language
4342
                if (is_array($destL10nRecords)) {
4343
                    foreach ($destL10nRecords as $record) {
4344
                        $localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]] = -$record['uid'];
4345
                    }
4346
                }
4347
            }
4348
            // Move the localized records after the corresponding localizations of the destination record
4349
            foreach ($l10nRecords as $record) {
4350
                $localizedDestPid = (int)$localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]];
4351
                if ($localizedDestPid < 0) {
4352
                    $this->moveRecord($table, $record['uid'], $localizedDestPid);
4353
                } else {
4354
                    $this->moveRecord($table, $record['uid'], $destPid);
0 ignored issues
show
Bug introduced by
$destPid of type string is incompatible with the type integer expected by parameter $destPid of TYPO3\CMS\Core\DataHandl...taHandler::moveRecord(). ( Ignorable by Annotation )

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

4354
                    $this->moveRecord($table, $record['uid'], /** @scrutinizer ignore-type */ $destPid);
Loading history...
4355
                }
4356
            }
4357
        }
4358
    }
4359
4360
    /**
4361
     * Localizes a record to another system language
4362
     *
4363
     * @param string $table Table name
4364
     * @param int $uid Record uid (to be localized)
4365
     * @param int $language Language ID (from sys_language table)
4366
     * @return int|bool The uid (int) of the new translated record or FALSE (bool) if something went wrong
4367
     * @internal should only be used from within DataHandler
4368
     */
4369
    public function localize($table, $uid, $language)
4370
    {
4371
        $newId = false;
4372
        $uid = (int)$uid;
4373
        if (!$GLOBALS['TCA'][$table] || !$uid || $this->isNestedElementCallRegistered($table, $uid, 'localize-' . (string)$language) !== false) {
4374
            return false;
4375
        }
4376
4377
        $this->registerNestedElementCall($table, $uid, 'localize-' . (string)$language);
4378
        if (!$GLOBALS['TCA'][$table]['ctrl']['languageField'] || !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
4379
            $this->newlog('Localization failed; "languageField" and "transOrigPointerField" must be defined for the table ' . $table, SystemLogErrorClassification::USER_ERROR);
4380
            return false;
4381
        }
4382
        $langRec = BackendUtility::getRecord('sys_language', (int)$language, 'uid,title');
4383
        if (!$langRec) {
4384
            $this->newlog('Sys language UID "' . $language . '" not found valid!', SystemLogErrorClassification::USER_ERROR);
4385
            return false;
4386
        }
4387
4388
        if (!$this->doesRecordExist($table, $uid, Permission::PAGE_SHOW)) {
4389
            $this->newlog('Attempt to localize record ' . $table . ':' . $uid . ' without permission.', SystemLogErrorClassification::USER_ERROR);
4390
            return false;
4391
        }
4392
4393
        // Getting workspace overlay if possible - this will localize versions in workspace if any
4394
        $row = BackendUtility::getRecordWSOL($table, $uid);
4395
        if (!is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
4396
            $this->newlog('Attempt to localize record ' . $table . ':' . $uid . ' that did not exist!', SystemLogErrorClassification::USER_ERROR);
4397
            return false;
4398
        }
4399
4400
        // Make sure that records which are translated from another language than the default language have a correct
4401
        // localization source set themselves, before translating them to another language.
4402
        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] !== 0
4403
            && $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
4404
            $localizationParentRecord = BackendUtility::getRecord(
4405
                $table,
4406
                $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]
4407
            );
4408
            if ((int)$localizationParentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] !== 0) {
4409
                $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);
4410
                return false;
4411
            }
4412
        }
4413
4414
        // Default language records must never have a localization parent as they are the origin of any translation.
4415
        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] !== 0
4416
            && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
4417
            $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);
4418
            return false;
4419
        }
4420
4421
        $recordLocalizations = BackendUtility::getRecordLocalization($table, $uid, $language, 'AND pid=' . (int)$row['pid']);
4422
4423
        if (!empty($recordLocalizations)) {
4424
            $this->newlog(sprintf(
4425
                'Localization failed: there already are localizations (%s) for language %d of the "%s" record %d!',
4426
                implode(', ', array_column($recordLocalizations, 'uid')),
4427
                $language,
4428
                $table,
4429
                $uid
4430
            ), 1);
4431
            return false;
4432
        }
4433
4434
        // Initialize:
4435
        $overrideValues = [];
4436
        // Set override values:
4437
        $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $langRec['uid'];
4438
        // If the translated record is a default language record, set it's uid as localization parent of the new record.
4439
        // If translating from any other language, no override is needed; we just can copy the localization parent of
4440
        // the original record (which is pointing to the correspondent default language record) to the new record.
4441
        // In copy / free mode the TransOrigPointer field is always set to 0, as no connection to the localization parent is wanted in that case.
4442
        // For pages, there is no "copy/free mode".
4443
        if (($this->useTransOrigPointerField || $table === 'pages') && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
4444
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $uid;
4445
        } elseif (!$this->useTransOrigPointerField) {
4446
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = 0;
4447
        }
4448
        if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
4449
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['translationSource']] = $uid;
4450
        }
4451
        // Copy the type (if defined in both tables) from the original record so that translation has same type as original record
4452
        if (isset($GLOBALS['TCA'][$table]['ctrl']['type'])) {
4453
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['type']] = $row[$GLOBALS['TCA'][$table]['ctrl']['type']];
4454
        }
4455
        // Set exclude Fields:
4456
        foreach ($GLOBALS['TCA'][$table]['columns'] as $fN => $fCfg) {
4457
            $translateToMsg = '';
4458
            // Check if we are just prefixing:
4459
            if ($fCfg['l10n_mode'] === 'prefixLangTitle') {
4460
                if (($fCfg['config']['type'] === 'text' || $fCfg['config']['type'] === 'input') && (string)$row[$fN] !== '') {
4461
                    [$tscPID] = BackendUtility::getTSCpid($table, $uid, '');
0 ignored issues
show
Bug introduced by
'' of type string is incompatible with the type integer expected by parameter $pid of TYPO3\CMS\Backend\Utilit...endUtility::getTSCpid(). ( Ignorable by Annotation )

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

4461
                    [$tscPID] = BackendUtility::getTSCpid($table, $uid, /** @scrutinizer ignore-type */ '');
Loading history...
4462
                    $TSConfig = BackendUtility::getPagesTSconfig($tscPID)['TCEMAIN.'] ?? [];
4463
                    $tE = $this->getTableEntries($table, $TSConfig);
4464
                    if (!empty($TSConfig['translateToMessage']) && !$tE['disablePrependAtCopy']) {
4465
                        $translateToMsg = $this->getLanguageService()->sL($TSConfig['translateToMessage']);
4466
                        $translateToMsg = @sprintf($translateToMsg, $langRec['title']);
4467
                    }
4468
4469
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processTranslateToClass'] ?? [] as $className) {
4470
                        $hookObj = GeneralUtility::makeInstance($className);
4471
                        if (method_exists($hookObj, 'processTranslateTo_copyAction')) {
4472
                            $hookObj->processTranslateTo_copyAction($row[$fN], $langRec, $this, $fN);
4473
                        }
4474
                    }
4475
                    if (!empty($translateToMsg)) {
4476
                        $overrideValues[$fN] = '[' . $translateToMsg . '] ' . $row[$fN];
4477
                    } else {
4478
                        $overrideValues[$fN] = $row[$fN];
4479
                    }
4480
                }
4481
            }
4482
        }
4483
4484
        if ($table !== 'pages') {
4485
            // Get the uid of record after which this localized record should be inserted
4486
            $previousUid = $this->getPreviousLocalizedRecordUid($table, $uid, $row['pid'], $language);
4487
            // Execute the copy:
4488
            $newId = $this->copyRecord($table, $uid, -$previousUid, true, $overrideValues, '', $language);
4489
            $autoVersionNewId = $this->getAutoVersionId($table, $newId);
4490
            if ($autoVersionNewId !== null) {
4491
                $this->triggerRemapAction($table, $newId, [$this, 'placeholderShadowing'], [$table, $autoVersionNewId], true);
4492
            }
4493
        } else {
4494
            // Create new page which needs to contain the same pid as the original page
4495
            $overrideValues['pid'] = $row['pid'];
4496
            // Take over the hidden state of the original language state, this is done due to legacy reasons where-as
4497
            // pages_language_overlay was set to "hidden -> default=0" but pages hidden -> default 1"
4498
            if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'])) {
4499
                $hiddenFieldName = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
4500
                $overrideValues[$hiddenFieldName] = $row[$hiddenFieldName] ?? $GLOBALS['TCA'][$table]['columns'][$hiddenFieldName]['config']['default'];
4501
            }
4502
            $temporaryId = StringUtility::getUniqueId('NEW');
4503
            $copyTCE = $this->getLocalTCE();
4504
            $copyTCE->start([$table => [$temporaryId => $overrideValues]], [], $this->BE_USER);
4505
            $copyTCE->process_datamap();
4506
            // Getting the new UID as if it had been copied:
4507
            $theNewSQLID = $copyTCE->substNEWwithIDs[$temporaryId];
4508
            if ($theNewSQLID) {
4509
                $this->copyMappingArray[$table][$uid] = $theNewSQLID;
4510
                $newId = $theNewSQLID;
4511
            }
4512
        }
4513
4514
        return $newId;
4515
    }
4516
4517
    /**
4518
     * Performs localization or synchronization of child records.
4519
     * The $command argument expects an array, but supports a string for backward-compatibility.
4520
     *
4521
     * $command = array(
4522
     *   'field' => 'tx_myfieldname',
4523
     *   'language' => 2,
4524
     *   // either the key 'action' or 'ids' must be set
4525
     *   'action' => 'synchronize', // or 'localize'
4526
     *   'ids' => array(1, 2, 3, 4) // child element ids
4527
     * );
4528
     *
4529
     * @param string $table The table of the localized parent record
4530
     * @param int $id The uid of the localized parent record
4531
     * @param array|string $command Defines the command to be performed (see example above)
4532
     */
4533
    protected function inlineLocalizeSynchronize($table, $id, $command)
4534
    {
4535
        $parentRecord = BackendUtility::getRecordWSOL($table, $id);
4536
4537
        // Backward-compatibility handling
4538
        if (!is_array($command)) {
4539
            // <field>, (localize | synchronize | <uid>):
4540
            $parts = GeneralUtility::trimExplode(',', $command);
4541
            $command = [
4542
                'field' => $parts[0],
4543
                // The previous process expected $id to point to the localized record already
4544
                'language' => (int)$parentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']]
4545
            ];
4546
            if (!MathUtility::canBeInterpretedAsInteger($parts[1])) {
4547
                $command['action'] = $parts[1];
4548
            } else {
4549
                $command['ids'] = [$parts[1]];
4550
            }
4551
        }
4552
4553
        // In case the parent record is the default language record, fetch the localization
4554
        if (empty($parentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
4555
            // Fetch the live record
4556
            // @todo: this needs to be revisited, as getRecordLocalization() does a BackendWorkspaceRestriction
4557
            // based on $GLOBALS[BE_USER], which could differ from the $this->BE_USER->workspace value
4558
            $parentRecordLocalization = BackendUtility::getRecordLocalization($table, $id, $command['language'], 'AND t3ver_oid=0');
4559
            if (empty($parentRecordLocalization)) {
4560
                if ($this->enableLogging) {
4561
                    $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']));
4562
                }
4563
                return;
4564
            }
4565
            $parentRecord = $parentRecordLocalization[0];
4566
            $id = $parentRecord['uid'];
4567
            // Process overlay for current selected workspace
4568
            BackendUtility::workspaceOL($table, $parentRecord);
4569
        }
4570
4571
        $field = $command['field'];
4572
        $language = $command['language'];
4573
        $action = $command['action'];
4574
        $ids = $command['ids'];
4575
4576
        if (!$field || !($action === 'localize' || $action === 'synchronize') && empty($ids) || !isset($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
4577
            return;
4578
        }
4579
4580
        $config = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
4581
        $foreignTable = $config['foreign_table'];
4582
4583
        $transOrigPointer = (int)$parentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
4584
        $childTransOrigPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
4585
4586
        if (!$parentRecord || !is_array($parentRecord) || $language <= 0 || !$transOrigPointer) {
4587
            return;
4588
        }
4589
4590
        $inlineSubType = $this->getInlineFieldType($config);
4591
        if ($inlineSubType === false) {
4592
            return;
4593
        }
4594
4595
        $transOrigRecord = BackendUtility::getRecordWSOL($table, $transOrigPointer);
4596
4597
        $removeArray = [];
4598
        $mmTable = $inlineSubType === 'mm' && isset($config['MM']) && $config['MM'] ? $config['MM'] : '';
4599
        // Fetch children from original language parent:
4600
        /** @var RelationHandler $dbAnalysisOriginal */
4601
        $dbAnalysisOriginal = $this->createRelationHandlerInstance();
4602
        $dbAnalysisOriginal->start($transOrigRecord[$field], $foreignTable, $mmTable, $transOrigRecord['uid'], $table, $config);
4603
        $elementsOriginal = [];
4604
        foreach ($dbAnalysisOriginal->itemArray as $item) {
4605
            $elementsOriginal[$item['id']] = $item;
4606
        }
4607
        unset($dbAnalysisOriginal);
4608
        // Fetch children from current localized parent:
4609
        /** @var RelationHandler $dbAnalysisCurrent */
4610
        $dbAnalysisCurrent = $this->createRelationHandlerInstance();
4611
        $dbAnalysisCurrent->start($parentRecord[$field], $foreignTable, $mmTable, $id, $table, $config);
4612
        // Perform synchronization: Possibly removal of already localized records:
4613
        if ($action === 'synchronize') {
4614
            foreach ($dbAnalysisCurrent->itemArray as $index => $item) {
4615
                $childRecord = BackendUtility::getRecordWSOL($item['table'], $item['id']);
4616
                if (isset($childRecord[$childTransOrigPointerField]) && $childRecord[$childTransOrigPointerField] > 0) {
4617
                    $childTransOrigPointer = $childRecord[$childTransOrigPointerField];
4618
                    // If synchronization is requested, child record was translated once, but original record does not exist anymore, remove it:
4619
                    if (!isset($elementsOriginal[$childTransOrigPointer])) {
4620
                        unset($dbAnalysisCurrent->itemArray[$index]);
4621
                        $removeArray[$item['table']][$item['id']]['delete'] = 1;
4622
                    }
4623
                }
4624
            }
4625
        }
4626
        // Perform synchronization/localization: Possibly add unlocalized records for original language:
4627
        if ($action === 'localize' || $action === 'synchronize') {
4628
            foreach ($elementsOriginal as $originalId => $item) {
4629
                $item['id'] = $this->localize($item['table'], $item['id'], $language);
4630
                $item['id'] = $this->overlayAutoVersionId($item['table'], $item['id']);
4631
                $dbAnalysisCurrent->itemArray[] = $item;
4632
            }
4633
        } elseif (!empty($ids)) {
4634
            foreach ($ids as $childId) {
4635
                if (!MathUtility::canBeInterpretedAsInteger($childId) || !isset($elementsOriginal[$childId])) {
4636
                    continue;
4637
                }
4638
                $item = $elementsOriginal[$childId];
4639
                $item['id'] = $this->localize($item['table'], $item['id'], $language);
4640
                $item['id'] = $this->overlayAutoVersionId($item['table'], $item['id']);
4641
                $dbAnalysisCurrent->itemArray[] = $item;
4642
            }
4643
        }
4644
        // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
4645
        $value = implode(',', $dbAnalysisCurrent->getValueArray());
4646
        $this->registerDBList[$table][$id][$field] = $value;
4647
        // Remove child records (if synchronization requested it):
4648
        if (is_array($removeArray) && !empty($removeArray)) {
4649
            /** @var DataHandler $tce */
4650
            $tce = GeneralUtility::makeInstance(__CLASS__, $this->referenceIndexUpdater);
4651
            $tce->enableLogging = $this->enableLogging;
4652
            $tce->start([], $removeArray, $this->BE_USER);
4653
            $tce->process_cmdmap();
4654
            unset($tce);
4655
        }
4656
        $updateFields = [];
4657
        // Handle, reorder and store relations:
4658
        if ($inlineSubType === 'list') {
4659
            $updateFields = [$field => $value];
4660
        } elseif ($inlineSubType === 'field') {
4661
            $dbAnalysisCurrent->writeForeignField($config, $id);
4662
            $updateFields = [$field => $dbAnalysisCurrent->countItems(false)];
4663
        } elseif ($inlineSubType === 'mm') {
4664
            $dbAnalysisCurrent->writeMM($config['MM'], $id);
4665
            $updateFields = [$field => $dbAnalysisCurrent->countItems(false)];
4666
        }
4667
        // Update field referencing to child records of localized parent record:
4668
        if (!empty($updateFields)) {
4669
            $this->updateDB($table, $id, $updateFields);
4670
        }
4671
    }
4672
4673
    /*********************************************
4674
     *
4675
     * Cmd: Deleting
4676
     *
4677
     ********************************************/
4678
    /**
4679
     * Delete a single record
4680
     *
4681
     * @param string $table Table name
4682
     * @param int $id Record UID
4683
     * @internal should only be used from within DataHandler
4684
     */
4685
    public function deleteAction($table, $id)
4686
    {
4687
        $recordToDelete = BackendUtility::getRecord($table, $id);
4688
        // Record asked to be deleted was found:
4689
        if (is_array($recordToDelete)) {
4690
            $recordWasDeleted = false;
4691
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
4692
                $hookObj = GeneralUtility::makeInstance($className);
4693
                if (method_exists($hookObj, 'processCmdmap_deleteAction')) {
4694
                    $hookObj->processCmdmap_deleteAction($table, $id, $recordToDelete, $recordWasDeleted, $this);
4695
                }
4696
            }
4697
            // Delete the record if a hook hasn't deleted it yet
4698
            if (!$recordWasDeleted) {
0 ignored issues
show
introduced by
The condition $recordWasDeleted is always false.
Loading history...
4699
                $this->deleteEl($table, $id);
4700
            }
4701
        }
4702
    }
4703
4704
    /**
4705
     * Delete element from any table
4706
     *
4707
     * @param string $table Table name
4708
     * @param int $uid Record UID
4709
     * @param bool $noRecordCheck Flag: If $noRecordCheck is set, then the function does not check permission to delete record
4710
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4711
     * @param bool $deleteRecordsOnPage If false and if deleting pages, records on the page will not be deleted (edge case while swapping workspaces)
4712
     * @internal should only be used from within DataHandler
4713
     */
4714
    public function deleteEl($table, $uid, $noRecordCheck = false, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4715
    {
4716
        if ($table === 'pages') {
4717
            $this->deletePages($uid, $noRecordCheck, $forceHardDelete, $deleteRecordsOnPage);
4718
        } else {
4719
            $this->deleteVersionsForRecord($table, $uid, $forceHardDelete);
4720
            $this->deleteRecord($table, $uid, $noRecordCheck, $forceHardDelete);
4721
        }
4722
    }
4723
4724
    /**
4725
     * Delete versions for element from any table
4726
     *
4727
     * @param string $table Table name
4728
     * @param int $uid Record UID
4729
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4730
     * @internal should only be used from within DataHandler
4731
     */
4732
    public function deleteVersionsForRecord($table, $uid, $forceHardDelete)
4733
    {
4734
        $versions = BackendUtility::selectVersionsOfRecord($table, $uid, 'uid,pid,t3ver_wsid,t3ver_state', $this->BE_USER->workspace ?: null);
4735
        if (is_array($versions)) {
4736
            foreach ($versions as $verRec) {
4737
                if (!$verRec['_CURRENT_VERSION']) {
4738
                    if ($table === 'pages') {
4739
                        $this->deletePages($verRec['uid'], true, $forceHardDelete);
4740
                    } else {
4741
                        $this->deleteRecord($table, $verRec['uid'], true, $forceHardDelete);
4742
                    }
4743
4744
                    // Delete move-placeholder
4745
                    $versionState = VersionState::cast($verRec['t3ver_state']);
4746
                    if ($versionState->equals(VersionState::MOVE_POINTER)) {
4747
                        $versionMovePlaceholder = BackendUtility::getMovePlaceholder($table, $uid, 'uid', $verRec['t3ver_wsid']);
4748
                        if (!empty($versionMovePlaceholder)) {
4749
                            $this->deleteEl($table, $versionMovePlaceholder['uid'], true, $forceHardDelete);
4750
                        }
4751
                    }
4752
                }
4753
            }
4754
        }
4755
    }
4756
4757
    /**
4758
     * Undelete a single record
4759
     *
4760
     * @param string $table Table name
4761
     * @param int $uid Record UID
4762
     * @internal should only be used from within DataHandler
4763
     */
4764
    public function undeleteRecord($table, $uid)
4765
    {
4766
        if ($this->isRecordUndeletable($table, $uid)) {
4767
            $this->deleteRecord($table, $uid, true, false, true);
4768
        }
4769
    }
4770
4771
    /**
4772
     * Deleting/Undeleting a record
4773
     * This function may not be used to delete pages-records unless the underlying records are already deleted
4774
     * Deletes a record regardless of versioning state (live or offline, doesn't matter, the uid decides)
4775
     * If both $noRecordCheck and $forceHardDelete are set it could even delete a "deleted"-flagged record!
4776
     *
4777
     * @param string $table Table name
4778
     * @param int $uid Record UID
4779
     * @param bool $noRecordCheck Flag: If $noRecordCheck is set, then the function does not check permission to delete record
4780
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4781
     * @param bool $undeleteRecord If TRUE, the "deleted" flag is set to 0 again and thus, the item is undeleted.
4782
     * @internal should only be used from within DataHandler
4783
     */
4784
    public function deleteRecord($table, $uid, $noRecordCheck = false, $forceHardDelete = false, $undeleteRecord = false)
4785
    {
4786
        $currentUserWorkspace = (int)$this->BE_USER->workspace;
4787
        $uid = (int)$uid;
4788
        if (!$GLOBALS['TCA'][$table] || !$uid) {
4789
            $this->log($table, $uid, SystemLogDatabaseAction::DELETE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to delete record without delete-permissions. [' . $this->BE_USER->errorMsg . ']');
4790
            return;
4791
        }
4792
        // Skip processing already deleted records
4793
        if (!$forceHardDelete && !$undeleteRecord && $this->hasDeletedRecord($table, $uid)) {
4794
            return;
4795
        }
4796
4797
        // Checking if there is anything else disallowing deleting the record by checking if editing is allowed
4798
        $deletedRecord = $forceHardDelete || $undeleteRecord;
4799
        $fullLanguageAccessCheck = true;
4800
        if ($table === 'pages') {
4801
            // If this is a page translation, the full language access check should not be done
4802
            $defaultLanguagePageId = $this->getDefaultLanguagePageId($uid);
4803
            if ($defaultLanguagePageId !== $uid) {
4804
                $fullLanguageAccessCheck = false;
4805
            }
4806
        }
4807
        $hasEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, false, $deletedRecord, $fullLanguageAccessCheck);
4808
        if (!$hasEditAccess) {
4809
            $this->log($table, $uid, SystemLogDatabaseAction::DELETE, 0, SystemLogErrorClassification::USER_ERROR, 'Attempt to delete record without delete-permissions');
4810
            return;
4811
        }
4812
        if ($table === 'pages') {
4813
            $perms = Permission::PAGE_DELETE;
4814
        } elseif ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap)) {
4815
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
4816
            $perms = Permission::PAGE_EDIT;
4817
        } else {
4818
            $perms = Permission::CONTENT_EDIT;
4819
        }
4820
        if (!$noRecordCheck && !$this->doesRecordExist($table, $uid, $perms)) {
4821
            return;
4822
        }
4823
4824
        // Clear cache before deleting the record, else the correct page cannot be identified by clear_cache
4825
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
0 ignored issues
show
Bug introduced by
'' of type string is incompatible with the type integer expected by parameter $pid of TYPO3\CMS\Backend\Utilit...endUtility::getTSCpid(). ( Ignorable by Annotation )

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

4825
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, /** @scrutinizer ignore-type */ '');
Loading history...
4826
        $this->registerRecordIdForPageCacheClearing($table, $uid, $parentUid);
4827
        $deleteField = $GLOBALS['TCA'][$table]['ctrl']['delete'];
4828
        $databaseErrorMessage = '';
4829
        if ($deleteField && !$forceHardDelete) {
4830
            $updateFields = [
4831
                $deleteField => $undeleteRecord ? 0 : 1
4832
            ];
4833
            if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
4834
                $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
4835
            }
4836
            // before (un-)deleting this record, check for child records or references
4837
            $this->deleteRecord_procFields($table, $uid, $undeleteRecord);
4838
            try {
4839
                // Delete all l10n records as well, impossible during undelete because it might bring too many records back to life
4840
                if (!$undeleteRecord) {
4841
                    $this->deletedRecords[$table][] = (int)$uid;
4842
                    $this->deleteL10nOverlayRecords($table, $uid);
4843
                }
4844
                GeneralUtility::makeInstance(ConnectionPool::class)
4845
                    ->getConnectionForTable($table)
4846
                    ->update($table, $updateFields, ['uid' => (int)$uid]);
4847
            } catch (DBALException $e) {
4848
                $databaseErrorMessage = $e->getPrevious()->getMessage();
4849
            }
4850
        } else {
4851
            // Delete the hard way...:
4852
            try {
4853
                $this->hardDeleteSingleRecord($table, (int)$uid);
4854
                $this->deletedRecords[$table][] = (int)$uid;
4855
                $this->deleteL10nOverlayRecords($table, $uid);
4856
            } catch (DBALException $e) {
4857
                $databaseErrorMessage = $e->getPrevious()->getMessage();
4858
            }
4859
        }
4860
        if ($this->enableLogging) {
4861
            $state = $undeleteRecord ? SystemLogDatabaseAction::INSERT : SystemLogDatabaseAction::DELETE;
4862
            if ($databaseErrorMessage === '') {
4863
                if ($forceHardDelete) {
4864
                    $message = 'Record \'%s\' (%s) was deleted unrecoverable from page \'%s\' (%s)';
4865
                } else {
4866
                    $message = $state === 1 ? 'Record \'%s\' (%s) was restored on page \'%s\' (%s)' : 'Record \'%s\' (%s) was deleted from page \'%s\' (%s)';
4867
                }
4868
                $propArr = $this->getRecordProperties($table, $uid);
4869
                $pagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4870
4871
                $this->log($table, $uid, $state, 0, SystemLogErrorClassification::MESSAGE, $message, 0, [
4872
                    $propArr['header'],
4873
                    $table . ':' . $uid,
4874
                    $pagePropArr['header'],
4875
                    $propArr['pid']
4876
                ], $propArr['event_pid']);
4877
            } else {
4878
                $this->log($table, $uid, $state, 0, SystemLogErrorClassification::TODAYS_SPECIAL, $databaseErrorMessage);
4879
            }
4880
        }
4881
4882
        // Add history entry
4883
        if ($undeleteRecord) {
4884
            $this->getRecordHistoryStore()->undeleteRecord($table, $uid, $this->correlationId);
4885
        } else {
4886
            $this->getRecordHistoryStore()->deleteRecord($table, $uid, $this->correlationId);
4887
        }
4888
4889
        // Update reference index with table/uid on left side (recuid)
4890
        $this->updateRefIndex($table, $uid);
4891
        // Update reference index with table/uid on right side (ref_uid). Important if children of a relation are deleted / undeleted.
4892
        $this->referenceIndexUpdater->registerUpdateForReferencesToItem($table, $uid, $currentUserWorkspace);
4893
    }
4894
4895
    /**
4896
     * Used to delete page because it will check for branch below pages and disallowed tables on the page as well.
4897
     *
4898
     * @param int $uid Page id
4899
     * @param bool $force If TRUE, pages are not checked for permission.
4900
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4901
     * @param bool $deleteRecordsOnPage If false, records on the page will not be deleted (edge case while swapping workspaces)
4902
     * @internal should only be used from within DataHandler
4903
     */
4904
    public function deletePages($uid, $force = false, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4905
    {
4906
        $uid = (int)$uid;
4907
        if ($uid === 0) {
4908
            if ($this->enableLogging) {
4909
                $this->log('pages', $uid, SystemLogGenericAction::UNDEFINED, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'Deleting all pages starting from the root-page is disabled.', -1, [], 0);
4910
            }
4911
            return;
4912
        }
4913
        // Getting list of pages to delete:
4914
        if ($force) {
4915
            // Returns the branch WITHOUT permission checks (0 secures that), so it cannot return -1
4916
            $pageIdsInBranch = $this->doesBranchExist('', $uid, 0, true);
4917
            $res = GeneralUtility::intExplode(',', $pageIdsInBranch . $uid, true);
4918
        } else {
4919
            $res = $this->canDeletePage($uid);
4920
        }
4921
        // Perform deletion if not error:
4922
        if (is_array($res)) {
4923
            foreach ($res as $deleteId) {
4924
                $this->deleteSpecificPage($deleteId, $forceHardDelete, $deleteRecordsOnPage);
4925
            }
4926
        } else {
4927
            /** @var FlashMessage $flashMessage */
4928
            $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $res, '', FlashMessage::ERROR, true);
4929
            /** @var FlashMessageService $flashMessageService */
4930
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
4931
            $flashMessageService->getMessageQueueByIdentifier()->addMessage($flashMessage);
4932
            $this->newlog($res, SystemLogErrorClassification::USER_ERROR);
4933
        }
4934
    }
4935
4936
    /**
4937
     * Delete a page (or set deleted field to 1) and all records on it.
4938
     *
4939
     * @param int $uid Page id
4940
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4941
     * @param bool $deleteRecordsOnPage If false, records on the page will not be deleted (edge case while swapping workspaces)
4942
     * @internal
4943
     * @see deletePages()
4944
     */
4945
    public function deleteSpecificPage($uid, $forceHardDelete = false, bool $deleteRecordsOnPage = true)
4946
    {
4947
        $uid = (int)$uid;
4948
        if (!$uid) {
4949
            // Early void return on invalid uid
4950
            return;
4951
        }
4952
        $forceHardDelete = (bool)$forceHardDelete;
4953
4954
        // Delete either a default language page or a translated page
4955
        $pageIdInDefaultLanguage = $this->getDefaultLanguagePageId($uid);
4956
        $isPageTranslation = false;
4957
        $pageLanguageId = 0;
4958
        if ($pageIdInDefaultLanguage !== $uid) {
4959
            // For translated pages, translated records in other tables (eg. tt_content) for the
4960
            // to-delete translated page have their pid field set to the uid of the default language record,
4961
            // NOT the uid of the translated page record.
4962
            // If a translated page is deleted, only translations of records in other tables of this language
4963
            // should be deleted. The code checks if the to-delete page is a translated page and
4964
            // adapts the query for other tables to use the uid of the default language page as pid together
4965
            // with the language id of the translated page.
4966
            $isPageTranslation = true;
4967
            $pageLanguageId = $this->pageInfo($uid, $GLOBALS['TCA']['pages']['ctrl']['languageField']);
4968
        }
4969
4970
        if ($deleteRecordsOnPage) {
4971
            $tableNames = $this->compileAdminTables();
4972
            foreach ($tableNames as $table) {
4973
                if ($table === 'pages' || ($isPageTranslation && !BackendUtility::isTableLocalizable($table))) {
4974
                    // Skip pages table. And skip table if not translatable, but a translated page is deleted
4975
                    continue;
4976
                }
4977
4978
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
4979
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
4980
                $queryBuilder
4981
                    ->select('uid')
4982
                    ->from($table);
4983
4984
                if ($isPageTranslation) {
4985
                    // Only delete records in the specified language
4986
                    $queryBuilder->where(
4987
                        $queryBuilder->expr()->eq(
4988
                            'pid',
4989
                            $queryBuilder->createNamedParameter($pageIdInDefaultLanguage, \PDO::PARAM_INT)
4990
                        ),
4991
                        $queryBuilder->expr()->eq(
4992
                            $GLOBALS['TCA'][$table]['ctrl']['languageField'],
4993
                            $queryBuilder->createNamedParameter($pageLanguageId, \PDO::PARAM_INT)
4994
                        )
4995
                    );
4996
                } else {
4997
                    // Delete all records on this page
4998
                    $queryBuilder->where(
4999
                        $queryBuilder->expr()->eq(
5000
                            'pid',
5001
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5002
                        )
5003
                    );
5004
                }
5005
                $statement = $queryBuilder->execute();
5006
5007
                while ($row = $statement->fetch()) {
5008
                    // Handle a detail related to workspace placeholder records, delete any
5009
                    // further workspace overlays for the record in question, then delete the record.
5010
                    $this->copyMovedRecordToNewLocation($table, $row['uid']);
5011
                    $this->deleteVersionsForRecord($table, $row['uid'], $forceHardDelete);
5012
                    $this->deleteRecord($table, $row['uid'], true, $forceHardDelete);
5013
                }
5014
            }
5015
        }
5016
5017
        // Handle a detail related to workspace placeholder records, delete any
5018
        // further workspace overlays for the page in question, then delete the page.
5019
        $this->copyMovedRecordToNewLocation('pages', $uid);
5020
        $this->deleteVersionsForRecord('pages', $uid, $forceHardDelete);
5021
        $this->deleteRecord('pages', $uid, true, $forceHardDelete);
5022
    }
5023
5024
    /**
5025
     * Copies the move placeholder of a record to its new location (pid).
5026
     * This will create a "new" placeholder at the new location and
5027
     * a version for this new placeholder. The original move placeholder
5028
     * is then deleted because it is not needed anymore.
5029
     *
5030
     * This method is used to assure that moved records are not deleted
5031
     * when the origin page is deleted.
5032
     *
5033
     * @param string $table Record table
5034
     * @param int $uid Record uid
5035
     */
5036
    protected function copyMovedRecordToNewLocation($table, $uid)
5037
    {
5038
        if ($this->BE_USER->workspace > 0) {
5039
            $originalRecord = BackendUtility::getRecord($table, $uid);
5040
            $movePlaceholder = BackendUtility::getMovePlaceholder($table, $uid);
5041
            // Check whether target page to copied to is different to current page
5042
            // Cloning on the same page is superfluous and does not help at all
5043
            if (!empty($originalRecord) && !empty($movePlaceholder) && (int)$originalRecord['pid'] !== (int)$movePlaceholder['pid']) {
5044
                // If move placeholder exists, copy to new location
5045
                // This will create a New placeholder on the new location
5046
                // and a version for this new placeholder
5047
                $command = [
5048
                    $table => [
5049
                        $uid => [
5050
                            'copy' => '-' . $movePlaceholder['uid']
5051
                        ]
5052
                    ]
5053
                ];
5054
                /** @var DataHandler $dataHandler */
5055
                $dataHandler = GeneralUtility::makeInstance(__CLASS__, $this->referenceIndexUpdater);
5056
                $dataHandler->enableLogging = $this->enableLogging;
5057
                $dataHandler->neverHideAtCopy = true;
5058
                $dataHandler->start([], $command, $this->BE_USER);
5059
                $dataHandler->process_cmdmap();
5060
                unset($dataHandler);
5061
5062
                // Delete move placeholder
5063
                $this->deleteRecord($table, $movePlaceholder['uid'], true, true);
5064
            }
5065
        }
5066
    }
5067
5068
    /**
5069
     * Used to evaluate if a page can be deleted
5070
     *
5071
     * @param int $uid Page id
5072
     * @return int[]|string If array: List of page uids to traverse and delete (means OK), if string: error message.
5073
     * @internal should only be used from within DataHandler
5074
     */
5075
    public function canDeletePage($uid)
5076
    {
5077
        $uid = (int)$uid;
5078
        $isTranslatedPage = null;
5079
5080
        // If we may at all delete this page
5081
        // If this is a page translation, do the check against the perms_* of the default page
5082
        // Because it is currently only deleting the translation
5083
        $defaultLanguagePageId = $this->getDefaultLanguagePageId($uid);
5084
        if ($defaultLanguagePageId !== $uid) {
5085
            if ($this->doesRecordExist('pages', (int)$defaultLanguagePageId, Permission::PAGE_DELETE)) {
5086
                $isTranslatedPage = true;
5087
            } else {
5088
                return 'Attempt to delete page without permissions';
5089
            }
5090
        } elseif (!$this->doesRecordExist('pages', $uid, Permission::PAGE_DELETE)) {
5091
            return 'Attempt to delete page without permissions';
5092
        }
5093
5094
        $pageIdsInBranch = $this->doesBranchExist('', $uid, Permission::PAGE_DELETE, true);
5095
5096
        if ($this->deleteTree) {
5097
            if ($pageIdsInBranch === -1) {
5098
                return 'Attempt to delete pages in branch without permissions';
5099
            }
5100
5101
            $pagesInBranch = GeneralUtility::intExplode(',', $pageIdsInBranch . $uid, true);
5102
        } else {
5103
            if ($pageIdsInBranch === -1) {
5104
                return 'Attempt to delete page without permissions';
5105
            }
5106
            if ($pageIdsInBranch !== '') {
5107
                return 'Attempt to delete page which has subpages';
5108
            }
5109
5110
            $pagesInBranch = [$uid];
5111
        }
5112
5113
        if ($disallowedTables = $this->checkForRecordsFromDisallowedTables($pagesInBranch)) {
5114
            return 'Attempt to delete records from disallowed tables (' . implode(', ', $disallowedTables) . ')';
5115
        }
5116
5117
        foreach ($pagesInBranch as $pageInBranch) {
5118
            if (!$this->BE_USER->recordEditAccessInternals('pages', $pageInBranch, false, false, $isTranslatedPage ? false : true)) {
5119
                return 'Attempt to delete page which has prohibited localizations.';
5120
            }
5121
        }
5122
        return $pagesInBranch;
5123
    }
5124
5125
    /**
5126
     * Returns TRUE if record CANNOT be deleted, otherwise FALSE. Used to check before the versioning API allows a record to be marked for deletion.
5127
     *
5128
     * @param string $table Record Table
5129
     * @param int $id Record UID
5130
     * @return string Returns a string IF there is an error (error string explaining). FALSE means record can be deleted
5131
     * @internal should only be used from within DataHandler
5132
     */
5133
    public function cannotDeleteRecord($table, $id)
5134
    {
5135
        if ($table === 'pages') {
5136
            $res = $this->canDeletePage($id);
5137
            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...
5138
        }
5139
        if ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap)) {
5140
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
5141
            $perms = Permission::PAGE_EDIT;
5142
        } else {
5143
            $perms = Permission::CONTENT_EDIT;
5144
        }
5145
        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...
5146
    }
5147
5148
    /**
5149
     * Determines whether a record can be undeleted.
5150
     *
5151
     * @param string $table Table name of the record
5152
     * @param int $uid uid of the record
5153
     * @return bool Whether the record can be undeleted
5154
     * @internal should only be used from within DataHandler
5155
     */
5156
    public function isRecordUndeletable($table, $uid)
5157
    {
5158
        $result = false;
5159
        $record = BackendUtility::getRecord($table, $uid, 'pid', '', false);
5160
        if ($record['pid']) {
5161
            $page = BackendUtility::getRecord('pages', $record['pid'], 'deleted, title, uid', '', false);
5162
            // The page containing the record is not deleted, thus the record can be undeleted:
5163
            if (!$page['deleted']) {
5164
                $result = true;
5165
            } else {
5166
                $this->log($table, $uid, SystemLogDatabaseAction::DELETE, '', SystemLogErrorClassification::USER_ERROR, 'Record cannot be undeleted since the page containing it is deleted! Undelete page "' . $page['title'] . ' (UID: ' . $page['uid'] . ')" first');
0 ignored issues
show
Bug introduced by
'' of type string is incompatible with the type integer expected by parameter $recpid of TYPO3\CMS\Core\DataHandling\DataHandler::log(). ( Ignorable by Annotation )

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

5166
                $this->log($table, $uid, SystemLogDatabaseAction::DELETE, /** @scrutinizer ignore-type */ '', SystemLogErrorClassification::USER_ERROR, 'Record cannot be undeleted since the page containing it is deleted! Undelete page "' . $page['title'] . ' (UID: ' . $page['uid'] . ')" first');
Loading history...
5167
            }
5168
        } else {
5169
            // The page containing the record is on rootlevel, so there is no parent record to check, and the record can be undeleted:
5170
            $result = true;
5171
        }
5172
        return $result;
5173
    }
5174
5175
    /**
5176
     * Before a record is deleted, check if it has references such as inline type or MM references.
5177
     * If so, set these child records also to be deleted.
5178
     *
5179
     * @param string $table Record Table
5180
     * @param string $uid Record UID
5181
     * @param bool $undeleteRecord If a record should be undeleted (e.g. from history/undo)
5182
     * @see deleteRecord()
5183
     * @internal should only be used from within DataHandler
5184
     */
5185
    public function deleteRecord_procFields($table, $uid, $undeleteRecord = false)
5186
    {
5187
        $conf = $GLOBALS['TCA'][$table]['columns'];
5188
        $row = BackendUtility::getRecord($table, $uid, '*', '', false);
0 ignored issues
show
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Backend\Utilit...endUtility::getRecord(). ( Ignorable by Annotation )

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

5188
        $row = BackendUtility::getRecord($table, /** @scrutinizer ignore-type */ $uid, '*', '', false);
Loading history...
5189
        if (empty($row)) {
5190
            return;
5191
        }
5192
        foreach ($row as $field => $value) {
5193
            $this->deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf[$field]['config'], $undeleteRecord);
5194
        }
5195
    }
5196
5197
    /**
5198
     * Process fields of a record to be deleted and search for special handling, like
5199
     * inline type, MM records, etc.
5200
     *
5201
     * @param string $table Record Table
5202
     * @param string $uid Record UID
5203
     * @param string $field Record field
5204
     * @param string $value Record field value
5205
     * @param array $conf TCA configuration of current field
5206
     * @param bool $undeleteRecord If a record should be undeleted (e.g. from history/undo)
5207
     * @see deleteRecord()
5208
     * @internal should only be used from within DataHandler
5209
     */
5210
    public function deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf, $undeleteRecord = false)
5211
    {
5212
        if ($conf['type'] === 'inline') {
5213
            $foreign_table = $conf['foreign_table'];
5214
            if ($foreign_table) {
5215
                $inlineType = $this->getInlineFieldType($conf);
5216
                if ($inlineType === 'list' || $inlineType === 'field') {
5217
                    /** @var RelationHandler $dbAnalysis */
5218
                    $dbAnalysis = $this->createRelationHandlerInstance();
5219
                    $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
0 ignored issues
show
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $MMuid of TYPO3\CMS\Core\Database\RelationHandler::start(). ( Ignorable by Annotation )

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

5219
                    $dbAnalysis->start($value, $conf['foreign_table'], '', /** @scrutinizer ignore-type */ $uid, $table, $conf);
Loading history...
5220
                    $dbAnalysis->undeleteRecord = true;
5221
5222
                    $enableCascadingDelete = true;
5223
                    // non type save comparison is intended!
5224
                    if (isset($conf['behaviour']['enableCascadingDelete']) && $conf['behaviour']['enableCascadingDelete'] == false) {
5225
                        $enableCascadingDelete = false;
5226
                    }
5227
5228
                    // Walk through the items and remove them
5229
                    foreach ($dbAnalysis->itemArray as $v) {
5230
                        if (!$undeleteRecord) {
5231
                            if ($enableCascadingDelete) {
5232
                                $this->deleteAction($v['table'], $v['id']);
5233
                            }
5234
                        } else {
5235
                            $this->undeleteRecord($v['table'], $v['id']);
5236
                        }
5237
                    }
5238
                }
5239
            }
5240
        } elseif ($this->isReferenceField($conf)) {
5241
            $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5242
            $dbAnalysis = $this->createRelationHandlerInstance();
5243
            $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
5244
            foreach ($dbAnalysis->itemArray as $v) {
5245
                $this->updateRefIndex($v['table'], $v['id']);
5246
            }
5247
        }
5248
    }
5249
5250
    /**
5251
     * Find l10n-overlay records and perform the requested delete action for these records.
5252
     *
5253
     * @param string $table Record Table
5254
     * @param string $uid Record UID
5255
     * @internal should only be used from within DataHandler
5256
     */
5257
    public function deleteL10nOverlayRecords($table, $uid)
5258
    {
5259
        // Check whether table can be localized
5260
        if (!BackendUtility::isTableLocalizable($table)) {
5261
            return;
5262
        }
5263
5264
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5265
        $queryBuilder->getRestrictions()
5266
            ->removeAll()
5267
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
5268
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->BE_USER->workspace));
5269
5270
        $queryBuilder->select('*')
5271
            ->from($table)
5272
            ->where(
5273
                $queryBuilder->expr()->eq(
5274
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5275
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5276
                )
5277
            );
5278
5279
        $result = $queryBuilder->execute();
5280
        while ($record = $result->fetch()) {
5281
            // Ignore workspace delete placeholders. Those records have been marked for
5282
            // deletion before - deleting them again in a workspace would revert that state.
5283
            if ((int)$this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
5284
                BackendUtility::workspaceOL($table, $record, $this->BE_USER->workspace);
5285
                if (VersionState::cast($record['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)) {
5286
                    continue;
5287
                }
5288
            }
5289
            $this->deleteAction($table, (int)$record['t3ver_oid'] > 0 ? (int)$record['t3ver_oid'] : (int)$record['uid']);
5290
        }
5291
    }
5292
5293
    /*********************************************
5294
     *
5295
     * Cmd: Workspace discard & flush
5296
     *
5297
     ********************************************/
5298
5299
    /**
5300
     * Discard a versioned record from this workspace. This deletes records from the database - no soft delete.
5301
     * This main entry method is called recursive for sub pages, localizations, relations and records on a page.
5302
     * The method checks user access and gathers facts about this record to hand the deletion over to detail methods.
5303
     *
5304
     * The incoming $uid or $row can be anything: The workspace of current user is respected and only records
5305
     * of current user workspace are discarded. If giving a live record uid, the versioned overly will be fetched.
5306
     *
5307
     * @param string $table Database table name
5308
     * @param int|null $uid Uid of live or versioned record to be discarded, or null if $record is given
5309
     * @param array|null $record Record row that should be discarded. Used instead of $uid within recursion.
5310
     */
5311
    public function discard(string $table, ?int $uid, array $record = null): void
5312
    {
5313
        if ($uid === null && $record === null) {
5314
            throw new \RuntimeException('Either record $uid or $record row must be given', 1600373491);
5315
        }
5316
5317
        // Fetch record we are dealing with if not given
5318
        if ($record === null) {
5319
            $record = BackendUtility::getRecord($table, $uid);
5320
        }
5321
        if (!is_array($record)) {
5322
            return;
5323
        }
5324
        $uid = (int)$record['uid'];
5325
5326
        // Call hook and return if hook took care of the element
5327
        $recordWasDiscarded = false;
5328
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] ?? [] as $className) {
5329
            $hookObj = GeneralUtility::makeInstance($className);
5330
            if (method_exists($hookObj, 'processCmdmap_discardAction')) {
5331
                $hookObj->processCmdmap_discardAction($table, $uid, $record, $recordWasDiscarded);
5332
            }
5333
        }
5334
5335
        $userWorkspace = (int)$this->BE_USER->workspace;
5336
        if ($recordWasDiscarded
5337
            || $userWorkspace === 0
5338
            || !BackendUtility::isTableWorkspaceEnabled($table)
5339
            || $this->hasDeletedRecord($table, $uid)
5340
        ) {
5341
            return;
5342
        }
5343
5344
        // Gather versioned, live and placeholder record if there are any
5345
        $liveRecord = null;
5346
        $versionRecord = null;
5347
        $placeholderRecord = null;
5348
        if ((int)$record['t3ver_wsid'] === 0) {
5349
            $liveRecord = $record;
5350
            $record = BackendUtility::getWorkspaceVersionOfRecord($userWorkspace, $table, $uid);
5351
        }
5352
        if (!is_array($record)) {
5353
            return;
5354
        }
5355
        $recordState = VersionState::cast($record['t3ver_state']);
5356
        if ($recordState->equals(VersionState::NEW_PLACEHOLDER)) {
5357
            $placeholderRecord = $record;
5358
            $versionRecord = BackendUtility::getWorkspaceVersionOfRecord($userWorkspace, $table, $uid);
5359
            if (!is_array($versionRecord)) {
5360
                return;
5361
            }
5362
        } elseif ($recordState->equals(VersionState::NEW_PLACEHOLDER_VERSION)) {
5363
            $versionRecord = $record;
5364
            $placeholderRecord = BackendUtility::getLiveVersionOfRecord($table, $uid);
5365
            if (!is_array($placeholderRecord)) {
5366
                return;
5367
            }
5368
        } elseif ($recordState->equals(VersionState::MOVE_POINTER)) {
5369
            $versionRecord = $record;
5370
            $liveRecord = $liveRecord ?: BackendUtility::getLiveVersionOfRecord($table, $uid);
5371
            if (!is_array($liveRecord)) {
5372
                return;
5373
            }
5374
            $placeholderRecord = BackendUtility::getMovePlaceholder($table, $liveRecord['uid']);
5375
            if (!is_array($placeholderRecord)) {
5376
                return;
5377
            }
5378
        } else {
5379
            $versionRecord = $record;
5380
            $liveRecord = $liveRecord ?: BackendUtility::getLiveVersionOfRecord($table, $uid);
5381
            if (!is_array($liveRecord)) {
5382
                return;
5383
            }
5384
        }
5385
        // Do not use $record, $recordState and $uid below anymore, rely on $versionRecord, $liveRecord and $placeholderRecord
5386
5387
        // User access checks
5388
        if ($userWorkspace !== (int)$versionRecord['t3ver_wsid']) {
5389
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: Different workspace', SystemLogErrorClassification::USER_ERROR);
5390
            return;
5391
        }
5392
        if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $versionRecord['uid'])) {
5393
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: ' . $errorCode, SystemLogErrorClassification::USER_ERROR);
5394
            return;
5395
        }
5396
        if (!$this->checkRecordUpdateAccess($table, $versionRecord['uid'])) {
5397
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: User has no edit access', SystemLogErrorClassification::USER_ERROR);
5398
            return;
5399
        }
5400
        $fullLanguageAccessCheck = !($table === 'pages' && (int)$versionRecord[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] !== 0);
5401
        if (!$this->BE_USER->recordEditAccessInternals($table, $versionRecord, false, true, $fullLanguageAccessCheck)) {
5402
            $this->newlog('Attempt to discard workspace record ' . $table . ':' . $versionRecord['uid'] . ' failed: User has no delete access', SystemLogErrorClassification::USER_ERROR);
5403
            return;
5404
        }
5405
5406
        // Perform discard operations
5407
        $versionState = VersionState::cast($versionRecord['t3ver_state']);
5408
        if ($table === 'pages' && $versionState->equals(VersionState::NEW_PLACEHOLDER_VERSION)) {
5409
            // When discarding a new page page, there can be new sub pages and new records.
5410
            // Those need to be discarded, otherwise they'd end up as records without parent page.
5411
            $this->discardSubPagesAndRecordsOnPage($versionRecord);
5412
        }
5413
5414
        $this->discardLocalizationOverlayRecords($table, $versionRecord);
5415
        $this->discardRecordRelations($table, $versionRecord);
5416
        $this->hardDeleteSingleRecord($table, (int)$versionRecord['uid']);
5417
        $this->deletedRecords[$table][] = (int)$versionRecord['uid'];
5418
        $this->registerReferenceIndexRowsForDrop($table, (int)$versionRecord['uid'], $userWorkspace);
5419
        $this->getRecordHistoryStore()->deleteRecord($table, (int)$versionRecord['uid'], $this->correlationId);
5420
        $this->log(
5421
            $table,
5422
            (int)$versionRecord['uid'],
5423
            SystemLogDatabaseAction::DELETE,
5424
            0,
5425
            SystemLogErrorClassification::MESSAGE,
5426
            'Record ' . $table . ':' . $versionRecord['uid'] . ' was deleted unrecoverable from page ' . $versionRecord['pid'],
5427
            0,
5428
            [],
5429
            (int)$versionRecord['pid']
5430
        );
5431
5432
        if ($versionState->equals(VersionState::MOVE_POINTER)
5433
            || $versionState->equals(VersionState::NEW_PLACEHOLDER_VERSION)
5434
        ) {
5435
            // Drop placeholder records if any
5436
            $this->hardDeleteSingleRecord($table, (int)$placeholderRecord['uid']);
5437
            $this->deletedRecords[$table][] = (int)$placeholderRecord['uid'];
5438
        }
5439
    }
5440
5441
    /**
5442
     * Also discard any sub pages and records of a new parent page if this page is discarded.
5443
     * Discarding only in specific localization, if needed.
5444
     *
5445
     * @param array $page Page record row
5446
     */
5447
    protected function discardSubPagesAndRecordsOnPage(array $page): void
5448
    {
5449
        $isLocalizedPage = false;
5450
        $sysLanguageId = (int)$page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
5451
        if ($sysLanguageId > 0) {
5452
            // New or moved localized page.
5453
            // Discard records on this page localization, but no sub pages.
5454
            // Records of a translated page have the pid set to the default language page uid. Found in l10n_parent.
5455
            // @todo: Discard other page translations that inherit from this?! (l10n_source field)
5456
            $isLocalizedPage = true;
5457
            $pid = (int)$page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
5458
        } else {
5459
            // New or moved default language page.
5460
            // Discard any sub pages and all other records of this page, including any page localizations.
5461
            // The t3ver_state=-1 record is incoming here. Records on this page have their pid field set to the uid
5462
            // of the t3ver_state=1 record, which is in the t3ver_oid field of the incoming record.
5463
            $pid = (int)$page['t3ver_oid'];
5464
        }
5465
        $tables = $this->compileAdminTables();
5466
        foreach ($tables as $table) {
5467
            if (($isLocalizedPage && $table === 'pages')
5468
                || ($isLocalizedPage && !BackendUtility::isTableLocalizable($table))
5469
                || !BackendUtility::isTableWorkspaceEnabled($table)
5470
            ) {
5471
                continue;
5472
            }
5473
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5474
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5475
            $queryBuilder->select('*')
5476
                ->from($table)
5477
                ->where(
5478
                    $queryBuilder->expr()->eq(
5479
                        'pid',
5480
                        $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
5481
                    ),
5482
                    $queryBuilder->expr()->eq(
5483
                        't3ver_wsid',
5484
                        $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5485
                    )
5486
                );
5487
            if ($isLocalizedPage) {
5488
                // Add sys_language_uid = x restriction if discarding a localized page
5489
                $queryBuilder->andWhere(
5490
                    $queryBuilder->expr()->eq(
5491
                        $GLOBALS['TCA'][$table]['ctrl']['languageField'],
5492
                        $queryBuilder->createNamedParameter($sysLanguageId, \PDO::PARAM_INT)
5493
                    )
5494
                );
5495
            }
5496
            $statement = $queryBuilder->execute();
5497
            while ($row = $statement->fetch()) {
5498
                $this->discard($table, null, $row);
5499
            }
5500
        }
5501
    }
5502
5503
    /**
5504
     * Discard record relations like inline and MM of a record.
5505
     *
5506
     * @param string $table Table name of this record
5507
     * @param array $record The record row to handle
5508
     */
5509
    protected function discardRecordRelations(string $table, array $record): void
5510
    {
5511
        foreach ($record as $field => $value) {
5512
            $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'] ?? null;
5513
            if (!isset($fieldConfig['type'])) {
5514
                continue;
5515
            }
5516
            if ($fieldConfig['type'] === 'inline') {
5517
                $foreignTable = $fieldConfig['foreign_table'] ?? null;
5518
                if (!$foreignTable
5519
                     || (isset($fieldConfig['behaviour']['enableCascadingDelete'])
5520
                        && (bool)$fieldConfig['behaviour']['enableCascadingDelete'] === false)
5521
                ) {
5522
                    continue;
5523
                }
5524
                $inlineType = $this->getInlineFieldType($fieldConfig);
5525
                if ($inlineType === 'list' || $inlineType === 'field') {
5526
                    $dbAnalysis = $this->createRelationHandlerInstance();
5527
                    $dbAnalysis->start($value, $fieldConfig['foreign_table'], '', (int)$record['uid'], $table, $fieldConfig);
5528
                    $dbAnalysis->undeleteRecord = true;
5529
                    foreach ($dbAnalysis->itemArray as $relationRecord) {
5530
                        $this->discard($relationRecord['table'], (int)$relationRecord['id']);
5531
                    }
5532
                }
5533
            } elseif ($this->isReferenceField($fieldConfig)) {
5534
                $allowedTables = $fieldConfig['type'] === 'group' ? $fieldConfig['allowed'] : $fieldConfig['foreign_table'];
5535
                $dbAnalysis = $this->createRelationHandlerInstance();
5536
                $dbAnalysis->start($value, $allowedTables, $fieldConfig['MM'], (int)$record['uid'], $table, $fieldConfig);
5537
                foreach ($dbAnalysis->itemArray as $relationRecord) {
5538
                    // @todo: Something should happen with these relations here ...
5539
                    // @todo: Can't use dropReferenceIndexRowsForRecord() here, this would drop sys_refindex entries we want to keep
5540
                    $this->updateRefIndex($relationRecord['table'], (int)$relationRecord['id']);
5541
                }
5542
            }
5543
        }
5544
    }
5545
5546
    /**
5547
     * Find localization overlays of a record and discard them.
5548
     *
5549
     * @param string $table Table of this record
5550
     * @param array $record Record row
5551
     */
5552
    protected function discardLocalizationOverlayRecords(string $table, array $record): void
5553
    {
5554
        if (!BackendUtility::isTableLocalizable($table)) {
5555
            return;
5556
        }
5557
        $uid = (int)$record['uid'];
5558
        $versionState = VersionState::cast($record['t3ver_state']);
5559
        if ($versionState->equals(VersionState::NEW_PLACEHOLDER_VERSION)) {
5560
            // The t3ver_state=-1 record is incoming here. Localization overlays of this record have their uid field set
5561
            // to the uid of the t3ver_state=1 record, which is in the t3ver_oid field of the incoming record.
5562
            $uid = (int)$record['t3ver_oid'];
5563
        }
5564
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5565
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
5566
        $statement = $queryBuilder->select('*')
5567
            ->from($table)
5568
            ->where(
5569
                $queryBuilder->expr()->eq(
5570
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5571
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5572
                ),
5573
                $queryBuilder->expr()->eq(
5574
                    't3ver_wsid',
5575
                    $queryBuilder->createNamedParameter((int)$this->BE_USER->workspace, \PDO::PARAM_INT)
5576
                )
5577
            )
5578
            ->execute();
5579
        while ($record = $statement->fetch()) {
5580
            $this->discard($table, null, $record);
5581
        }
5582
    }
5583
5584
    /*********************************************
5585
     *
5586
     * Cmd: Versioning
5587
     *
5588
     ********************************************/
5589
    /**
5590
     * Creates a new version of a record
5591
     * (Requires support in the table)
5592
     *
5593
     * @param string $table Table name
5594
     * @param int $id Record uid to versionize
5595
     * @param string $label Version label
5596
     * @param bool $delete If TRUE, the version is created to delete the record.
5597
     * @return int|null Returns the id of the new version (if any)
5598
     * @see copyRecord()
5599
     * @internal should only be used from within DataHandler
5600
     */
5601
    public function versionizeRecord($table, $id, $label, $delete = false)
5602
    {
5603
        $id = (int)$id;
5604
        // Stop any actions if the record is marked to be deleted:
5605
        // (this can occur if IRRE elements are versionized and child elements are removed)
5606
        if ($this->isElementToBeDeleted($table, $id)) {
5607
            return null;
5608
        }
5609
        if (!BackendUtility::isTableWorkspaceEnabled($table) || $id <= 0) {
5610
            $this->newlog('Versioning is not supported for this table "' . $table . '" / ' . $id, SystemLogErrorClassification::USER_ERROR);
5611
            return null;
5612
        }
5613
5614
        // Fetch record with permission check
5615
        $row = $this->recordInfoWithPermissionCheck($table, $id, Permission::PAGE_SHOW);
5616
5617
        // This checks if the record can be selected which is all that a copy action requires.
5618
        if ($row === false) {
5619
            $this->newlog(
5620
                'The record does not exist or you don\'t have correct permissions to make a new version (copy) of this record "' . $table . ':' . $id . '"',
5621
                SystemLogErrorClassification::USER_ERROR
5622
            );
5623
            return null;
5624
        }
5625
5626
        // Record must be online record, otherwise we would create a version of a version
5627
        if (($row['t3ver_oid'] ?? 0) > 0) {
5628
            $this->newlog('Record "' . $table . ':' . $id . '" you wanted to versionize was already a version in archive (record has an online ID)!', SystemLogErrorClassification::USER_ERROR);
5629
            return null;
5630
        }
5631
5632
        // Record must not be placeholder for moving.
5633
        if (VersionState::cast($row['t3ver_state'])->equals(VersionState::MOVE_PLACEHOLDER)) {
5634
            $this->newlog('Record cannot be versioned because it is a placeholder for a moving operation', SystemLogErrorClassification::USER_ERROR);
5635
            return null;
5636
        }
5637
5638
        if ($delete && $this->cannotDeleteRecord($table, $id)) {
5639
            $this->newlog('Record cannot be deleted: ' . $this->cannotDeleteRecord($table, $id), SystemLogErrorClassification::USER_ERROR);
5640
            return null;
5641
        }
5642
5643
        // Set up the values to override when making a raw-copy:
5644
        $overrideArray = [
5645
            't3ver_oid' => $id,
5646
            't3ver_wsid' => $this->BE_USER->workspace,
5647
            't3ver_state' => (string)($delete ? new VersionState(VersionState::DELETE_PLACEHOLDER) : new VersionState(VersionState::DEFAULT_STATE)),
5648
            't3ver_stage' => 0,
5649
        ];
5650
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock']) {
5651
            $overrideArray[$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
5652
        }
5653
        // Checking if the record already has a version in the current workspace of the backend user
5654
        $versionRecord = ['uid' => null];
5655
        if ($this->BE_USER->workspace !== 0) {
5656
            // Look for version already in workspace:
5657
            $versionRecord = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid');
5658
        }
5659
        // Create new version of the record and return the new uid
5660
        if (empty($versionRecord['uid'])) {
5661
            // Create raw-copy and return result:
5662
            // The information of the label to be used for the workspace record
5663
            // as well as the information whether the record shall be removed
5664
            // must be forwarded (creating remove placeholders on a workspace are
5665
            // done by copying the record and override several fields).
5666
            $workspaceOptions = [
5667
                'delete' => $delete,
5668
                'label' => $label,
5669
            ];
5670
            return $this->copyRecord_raw($table, $id, (int)$row['pid'], $overrideArray, $workspaceOptions);
5671
        }
5672
        // Reuse the existing record and return its uid
5673
        // (prior to TYPO3 CMS 6.2, an error was thrown here, which
5674
        // did not make much sense since the information is available)
5675
        return $versionRecord['uid'];
5676
    }
5677
5678
    /**
5679
     * Swaps MM-relations for current/swap record, see version_swap()
5680
     *
5681
     * @param string $table Table for the two input records
5682
     * @param int $id Current record (about to go offline)
5683
     * @param int $swapWith Swap record (about to go online)
5684
     * @see version_swap()
5685
     * @internal should only be used from within DataHandler
5686
     */
5687
    public function version_remapMMForVersionSwap($table, $id, $swapWith)
5688
    {
5689
        // Actually, selecting the records fully is only need if flexforms are found inside... This could be optimized ...
5690
        $currentRec = BackendUtility::getRecord($table, $id);
5691
        $swapRec = BackendUtility::getRecord($table, $swapWith);
5692
        $this->version_remapMMForVersionSwap_reg = [];
5693
        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5694
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fConf) {
5695
            $conf = $fConf['config'];
5696
            if ($this->isReferenceField($conf)) {
5697
                $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5698
                $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
5699
                if ($conf['MM']) {
5700
                    /** @var RelationHandler $dbAnalysis */
5701
                    $dbAnalysis = $this->createRelationHandlerInstance();
5702
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $id, $table, $conf);
5703
                    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

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

5973
                    $liveRelations->writeMM($conf['MM'], $liveId, /** @scrutinizer ignore-type */ $prependName);
Loading history...
5974
                }
5975
            }
5976
        }
5977
        // If a change has been done, set the new value(s)
5978
        if ($set) {
5979
            if ($conf['MM']) {
5980
                $dbAnalysis->writeMM($conf['MM'], $MM_localUid, $prependName);
5981
            } else {
5982
                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

5982
                return $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName);
Loading history...
5983
            }
5984
        }
5985
        return null;
5986
    }
5987
5988
    /**
5989
     * Performs remapping of old UID values to NEW uid values for an inline field.
5990
     *
5991
     * @param array $conf TCA field config
5992
     * @param string $value Field value
5993
     * @param int $uid The uid of the ORIGINAL record
5994
     * @param string $table Table name
5995
     * @internal should only be used from within DataHandler
5996
     */
5997
    public function remapListedDBRecords_procInline($conf, $value, $uid, $table)
5998
    {
5999
        $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
6000
        if ($conf['foreign_table']) {
6001
            $inlineType = $this->getInlineFieldType($conf);
6002
            if ($inlineType === 'mm') {
6003
                $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
6004
            } elseif ($inlineType !== false) {
6005
                /** @var RelationHandler $dbAnalysis */
6006
                $dbAnalysis = $this->createRelationHandlerInstance();
6007
                $dbAnalysis->start($value, $conf['foreign_table'], '', 0, $table, $conf);
6008
6009
                $updatePidForRecords = [];
6010
                // Update values for specific versioned records
6011
                foreach ($dbAnalysis->itemArray as &$item) {
6012
                    $updatePidForRecords[$item['table']][] = $item['id'];
6013
                    $versionedId = $this->getAutoVersionId($item['table'], $item['id']);
6014
                    if ($versionedId !== null) {
6015
                        $updatePidForRecords[$item['table']][] = $versionedId;
6016
                        $item['id'] = $versionedId;
6017
                    }
6018
                }
6019
6020
                // Update child records if using pointer fields ('foreign_field'):
6021
                if ($inlineType === 'field') {
6022
                    $dbAnalysis->writeForeignField($conf, $uid, $theUidToUpdate);
6023
                }
6024
                $thePidToUpdate = null;
6025
                // If the current field is set on a page record, update the pid of related child records:
6026
                if ($table === 'pages') {
6027
                    $thePidToUpdate = $theUidToUpdate;
6028
                } elseif (isset($this->registerDBPids[$table][$uid])) {
6029
                    $thePidToUpdate = $this->registerDBPids[$table][$uid];
6030
                    $thePidToUpdate = $this->copyMappingArray_merged['pages'][$thePidToUpdate];
6031
                }
6032
6033
                // Update child records if change to pid is required
6034
                if ($thePidToUpdate && !empty($updatePidForRecords)) {
6035
                    // Ensure that only the default language page is used as PID
6036
                    $thePidToUpdate = $this->getDefaultLanguagePageId($thePidToUpdate);
6037
                    // @todo: this can probably go away
6038
                    // ensure, only live page ids are used as 'pid' values
6039
                    $liveId = BackendUtility::getLiveVersionIdOfRecord('pages', $theUidToUpdate);
6040
                    if ($liveId !== null) {
6041
                        $thePidToUpdate = $liveId;
6042
                    }
6043
                    $updateValues = ['pid' => $thePidToUpdate];
6044
                    foreach ($updatePidForRecords as $tableName => $uids) {
6045
                        if (empty($tableName) || empty($uids)) {
6046
                            continue;
6047
                        }
6048
                        $conn = GeneralUtility::makeInstance(ConnectionPool::class)
6049
                            ->getConnectionForTable($tableName);
6050
                        foreach ($uids as $updateUid) {
6051
                            $conn->update($tableName, $updateValues, ['uid' => $updateUid]);
6052
                        }
6053
                    }
6054
                }
6055
            }
6056
        }
6057
    }
6058
6059
    /**
6060
     * Processes the $this->remapStack at the end of copying, inserting, etc. actions.
6061
     * The remapStack takes care about the correct mapping of new and old uids in case of relational data.
6062
     * @internal should only be used from within DataHandler
6063
     */
6064
    public function processRemapStack()
6065
    {
6066
        // Processes the remap stack:
6067
        if (is_array($this->remapStack)) {
0 ignored issues
show
introduced by
The condition is_array($this->remapStack) is always true.
Loading history...
6068
            $remapFlexForms = [];
6069
            $hookPayload = [];
6070
6071
            $newValue = null;
6072
            foreach ($this->remapStack as $remapAction) {
6073
                // If no position index for the arguments was set, skip this remap action:
6074
                if (!is_array($remapAction['pos'])) {
6075
                    continue;
6076
                }
6077
                // Load values from the argument array in remapAction:
6078
                $field = $remapAction['field'];
6079
                $id = $remapAction['args'][$remapAction['pos']['id']];
6080
                $rawId = $id;
6081
                $table = $remapAction['args'][$remapAction['pos']['table']];
6082
                $valueArray = $remapAction['args'][$remapAction['pos']['valueArray']];
6083
                $tcaFieldConf = $remapAction['args'][$remapAction['pos']['tcaFieldConf']];
6084
                $additionalData = $remapAction['additionalData'];
6085
                // The record is new and has one or more new ids (in case of versioning/workspaces):
6086
                if (strpos($id, 'NEW') !== false) {
6087
                    // Replace NEW...-ID with real uid:
6088
                    $id = $this->substNEWwithIDs[$id];
6089
                    // If the new parent record is on a non-live workspace or versionized, it has another new id:
6090
                    if (isset($this->autoVersionIdMap[$table][$id])) {
6091
                        $id = $this->autoVersionIdMap[$table][$id];
6092
                    }
6093
                    $remapAction['args'][$remapAction['pos']['id']] = $id;
6094
                }
6095
                // Replace relations to NEW...-IDs in field value (uids of child records):
6096
                if (is_array($valueArray)) {
6097
                    foreach ($valueArray as $key => $value) {
6098
                        if (strpos($value, 'NEW') !== false) {
6099
                            if (strpos($value, '_') === false) {
6100
                                $affectedTable = $tcaFieldConf['foreign_table'];
6101
                                $prependTable = false;
6102
                            } else {
6103
                                $parts = explode('_', $value);
6104
                                $value = array_pop($parts);
6105
                                $affectedTable = implode('_', $parts);
6106
                                $prependTable = true;
6107
                            }
6108
                            $value = $this->substNEWwithIDs[$value];
6109
                            // The record is new, but was also auto-versionized and has another new id:
6110
                            if (isset($this->autoVersionIdMap[$affectedTable][$value])) {
6111
                                $value = $this->autoVersionIdMap[$affectedTable][$value];
6112
                            }
6113
                            if ($prependTable) {
6114
                                $value = $affectedTable . '_' . $value;
6115
                            }
6116
                            // Set a hint that this was a new child record:
6117
                            $this->newRelatedIDs[$affectedTable][] = $value;
6118
                            $valueArray[$key] = $value;
6119
                        }
6120
                    }
6121
                    $remapAction['args'][$remapAction['pos']['valueArray']] = $valueArray;
6122
                }
6123
                // Process the arguments with the defined function:
6124
                if (!empty($remapAction['func'])) {
6125
                    $newValue = call_user_func_array([$this, $remapAction['func']], $remapAction['args']);
6126
                }
6127
                // If array is returned, check for maxitems condition, if string is returned this was already done:
6128
                if (is_array($newValue)) {
6129
                    $newValue = implode(',', $this->checkValue_checkMax($tcaFieldConf, $newValue));
6130
                    // The reference casting is only required if
6131
                    // checkValue_group_select_processDBdata() returns an array
6132
                    $newValue = $this->castReferenceValue($newValue, $tcaFieldConf);
6133
                }
6134
                // Update in database (list of children (csv) or number of relations (foreign_field)):
6135
                if (!empty($field)) {
6136
                    $fieldArray = [$field => $newValue];
6137
                    if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
6138
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
6139
                    }
6140
                    $this->updateDB($table, $id, $fieldArray);
6141
                } elseif (!empty($additionalData['flexFormId']) && !empty($additionalData['flexFormPath'])) {
6142
                    // Collect data to update FlexForms
6143
                    $flexFormId = $additionalData['flexFormId'];
6144
                    $flexFormPath = $additionalData['flexFormPath'];
6145
6146
                    if (!isset($remapFlexForms[$flexFormId])) {
6147
                        $remapFlexForms[$flexFormId] = [];
6148
                    }
6149
6150
                    $remapFlexForms[$flexFormId][$flexFormPath] = $newValue;
6151
                }
6152
6153
                // Collect elements that shall trigger processDatamap_afterDatabaseOperations
6154
                if (isset($this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'])) {
6155
                    $hookArgs = $this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'];
6156
                    if (!isset($hookPayload[$table][$rawId])) {
6157
                        $hookPayload[$table][$rawId] = [
6158
                            'status' => $hookArgs['status'],
6159
                            'fieldArray' => $hookArgs['fieldArray'],
6160
                            'hookObjects' => $hookArgs['hookObjectsArr'],
6161
                        ];
6162
                    }
6163
                    $hookPayload[$table][$rawId]['fieldArray'][$field] = $newValue;
6164
                }
6165
            }
6166
6167
            if ($remapFlexForms) {
6168
                foreach ($remapFlexForms as $flexFormId => $modifications) {
6169
                    $this->updateFlexFormData($flexFormId, $modifications);
6170
                }
6171
            }
6172
6173
            foreach ($hookPayload as $tableName => $rawIdPayload) {
6174
                foreach ($rawIdPayload as $rawId => $payload) {
6175
                    foreach ($payload['hookObjects'] as $hookObject) {
6176
                        if (!method_exists($hookObject, 'processDatamap_afterDatabaseOperations')) {
6177
                            continue;
6178
                        }
6179
                        $hookObject->processDatamap_afterDatabaseOperations(
6180
                            $payload['status'],
6181
                            $tableName,
6182
                            $rawId,
6183
                            $payload['fieldArray'],
6184
                            $this
6185
                        );
6186
                    }
6187
                }
6188
            }
6189
        }
6190
        // Processes the remap stack actions:
6191
        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...
6192
            foreach ($this->remapStackActions as $action) {
6193
                if (isset($action['callback'], $action['arguments'])) {
6194
                    call_user_func_array($action['callback'], $action['arguments']);
6195
                }
6196
            }
6197
        }
6198
        // Reset:
6199
        $this->remapStack = [];
6200
        $this->remapStackRecords = [];
6201
        $this->remapStackActions = [];
6202
    }
6203
6204
    /**
6205
     * Updates FlexForm data.
6206
     *
6207
     * @param string $flexFormId e.g. <table>:<uid>:<field>
6208
     * @param array $modifications Modifications with paths and values (e.g. 'sDEF/lDEV/field/vDEF' => 'TYPO3')
6209
     */
6210
    protected function updateFlexFormData($flexFormId, array $modifications)
6211
    {
6212
        [$table, $uid, $field] = explode(':', $flexFormId, 3);
6213
6214
        if (!MathUtility::canBeInterpretedAsInteger($uid) && !empty($this->substNEWwithIDs[$uid])) {
6215
            $uid = $this->substNEWwithIDs[$uid];
6216
        }
6217
6218
        $record = $this->recordInfo($table, $uid, '*');
6219
6220
        if (!$table || !$uid || !$field || !is_array($record)) {
6221
            return;
6222
        }
6223
6224
        BackendUtility::workspaceOL($table, $record);
6225
6226
        // Get current data structure and value array:
6227
        $valueStructure = GeneralUtility::xml2array($record[$field]);
6228
6229
        // Do recursive processing of the XML data:
6230
        foreach ($modifications as $path => $value) {
6231
            $valueStructure['data'] = ArrayUtility::setValueByPath(
6232
                $valueStructure['data'],
6233
                $path,
6234
                $value
6235
            );
6236
        }
6237
6238
        if (is_array($valueStructure['data'])) {
6239
            // The return value should be compiled back into XML
6240
            $values = [
6241
                $field => $this->checkValue_flexArray2Xml($valueStructure, true),
6242
            ];
6243
6244
            $this->updateDB($table, $uid, $values);
6245
        }
6246
    }
6247
6248
    /**
6249
     * Triggers a remap action for a specific record.
6250
     *
6251
     * Some records are post-processed by the processRemapStack() method (e.g. IRRE children).
6252
     * This method determines whether an action/modification is executed directly to a record
6253
     * or is postponed to happen after remapping data.
6254
     *
6255
     * @param string $table Name of the table
6256
     * @param string $id Id of the record (can also be a "NEW..." string)
6257
     * @param array $callback The method to be called
6258
     * @param array $arguments The arguments to be submitted to the callback method
6259
     * @param bool $forceRemapStackActions Whether to force to use the stack
6260
     * @see processRemapStack
6261
     */
6262
    protected function triggerRemapAction($table, $id, array $callback, array $arguments, $forceRemapStackActions = false)
6263
    {
6264
        // Check whether the affected record is marked to be remapped:
6265
        if (!$forceRemapStackActions && !isset($this->remapStackRecords[$table][$id]) && !isset($this->remapStackChildIds[$id])) {
6266
            call_user_func_array($callback, $arguments);
6267
        } else {
6268
            $this->addRemapAction($table, $id, $callback, $arguments);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $id of TYPO3\CMS\Core\DataHandl...ndler::addRemapAction(). ( Ignorable by Annotation )

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

6268
            $this->addRemapAction($table, /** @scrutinizer ignore-type */ $id, $callback, $arguments);
Loading history...
6269
        }
6270
    }
6271
6272
    /**
6273
     * Adds an instruction to the remap action stack (used with IRRE).
6274
     *
6275
     * @param string $table The affected table
6276
     * @param int $id The affected ID
6277
     * @param array $callback The callback information (object and method)
6278
     * @param array $arguments The arguments to be used with the callback
6279
     * @internal should only be used from within DataHandler
6280
     */
6281
    public function addRemapAction($table, $id, array $callback, array $arguments)
6282
    {
6283
        $this->remapStackActions[] = [
6284
            'affects' => [
6285
                'table' => $table,
6286
                'id' => $id
6287
            ],
6288
            'callback' => $callback,
6289
            'arguments' => $arguments
6290
        ];
6291
    }
6292
6293
    /**
6294
     * If a parent record was versionized on a workspace in $this->process_datamap,
6295
     * it might be possible, that child records (e.g. on using IRRE) were affected.
6296
     * This function finds these relations and updates their uids in the $incomingFieldArray.
6297
     * The $incomingFieldArray is updated by reference!
6298
     *
6299
     * @param string $table Table name of the parent record
6300
     * @param int $id Uid of the parent record
6301
     * @param array $incomingFieldArray Reference to the incomingFieldArray of process_datamap
6302
     * @param array $registerDBList Reference to the $registerDBList array that was created/updated by versionizing calls to DataHandler in process_datamap.
6303
     * @internal should only be used from within DataHandler
6304
     */
6305
    public function getVersionizedIncomingFieldArray($table, $id, &$incomingFieldArray, &$registerDBList)
6306
    {
6307
        if (is_array($registerDBList[$table][$id])) {
6308
            foreach ($incomingFieldArray as $field => $value) {
6309
                $fieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
6310
                if ($registerDBList[$table][$id][$field] && ($foreignTable = $fieldConf['foreign_table'])) {
6311
                    $newValueArray = [];
6312
                    $origValueArray = is_array($value) ? $value : explode(',', $value);
6313
                    // Update the uids of the copied records, but also take care about new records:
6314
                    foreach ($origValueArray as $childId) {
6315
                        $newValueArray[] = $this->autoVersionIdMap[$foreignTable][$childId] ?: $childId;
6316
                    }
6317
                    // Set the changed value to the $incomingFieldArray
6318
                    $incomingFieldArray[$field] = implode(',', $newValueArray);
6319
                }
6320
            }
6321
            // Clean up the $registerDBList array:
6322
            unset($registerDBList[$table][$id]);
6323
            if (empty($registerDBList[$table])) {
6324
                unset($registerDBList[$table]);
6325
            }
6326
        }
6327
    }
6328
6329
    /**
6330
     * Simple helper method to hard delete one row from table ignoring delete TCA field
6331
     *
6332
     * @param string $table A row from this table should be deleted
6333
     * @param int $uid Uid of row to be deleted
6334
     */
6335
    protected function hardDeleteSingleRecord(string $table, int $uid): void
6336
    {
6337
        GeneralUtility::makeInstance(ConnectionPool::class)
6338
            ->getConnectionForTable($table)
6339
            ->delete($table, ['uid' => $uid], [\PDO::PARAM_INT]);
6340
    }
6341
6342
    /*****************************
6343
     *
6344
     * Access control / Checking functions
6345
     *
6346
     *****************************/
6347
    /**
6348
     * Checking group modify_table access list
6349
     *
6350
     * @param string $table Table name
6351
     * @return bool Returns TRUE if the user has general access to modify the $table
6352
     * @internal should only be used from within DataHandler
6353
     */
6354
    public function checkModifyAccessList($table)
6355
    {
6356
        $res = $this->admin || (!$this->tableAdminOnly($table) && isset($this->BE_USER->groupData['tables_modify']) && GeneralUtility::inList($this->BE_USER->groupData['tables_modify'], $table));
6357
        // Hook 'checkModifyAccessList': Post-processing of the state of access
6358
        foreach ($this->getCheckModifyAccessListHookObjects() as $hookObject) {
6359
            /** @var DataHandlerCheckModifyAccessListHookInterface $hookObject */
6360
            $hookObject->checkModifyAccessList($res, $table, $this);
6361
        }
6362
        return $res;
6363
    }
6364
6365
    /**
6366
     * Checking if a record with uid $id from $table is in the BE_USERS webmounts which is required for editing etc.
6367
     *
6368
     * @param string $table Table name
6369
     * @param int $id UID of record
6370
     * @return bool Returns TRUE if OK. Cached results.
6371
     * @internal should only be used from within DataHandler
6372
     */
6373
    public function isRecordInWebMount($table, $id)
6374
    {
6375
        if (!isset($this->isRecordInWebMount_Cache[$table . ':' . $id])) {
6376
            $recP = $this->getRecordProperties($table, $id);
6377
            $this->isRecordInWebMount_Cache[$table . ':' . $id] = $this->isInWebMount($recP['event_pid']);
6378
        }
6379
        return $this->isRecordInWebMount_Cache[$table . ':' . $id];
6380
    }
6381
6382
    /**
6383
     * Checks if the input page ID is in the BE_USER webmounts
6384
     *
6385
     * @param int $pid Page ID to check
6386
     * @return bool TRUE if OK. Cached results.
6387
     * @internal should only be used from within DataHandler
6388
     */
6389
    public function isInWebMount($pid)
6390
    {
6391
        if (!isset($this->isInWebMount_Cache[$pid])) {
6392
            $this->isInWebMount_Cache[$pid] = $this->BE_USER->isInWebMount($pid);
6393
        }
6394
        return $this->isInWebMount_Cache[$pid];
6395
    }
6396
6397
    /**
6398
     * Checks if user may update a record with uid=$id from $table
6399
     *
6400
     * @param string $table Record table
6401
     * @param int $id Record UID
6402
     * @param array|bool $data Record data
6403
     * @param array $hookObjectsArr Hook objects
6404
     * @return bool Returns TRUE if the user may update the record given by $table and $id
6405
     * @internal should only be used from within DataHandler
6406
     */
6407
    public function checkRecordUpdateAccess($table, $id, $data = false, $hookObjectsArr = null)
6408
    {
6409
        $res = null;
6410
        if (is_array($hookObjectsArr)) {
6411
            foreach ($hookObjectsArr as $hookObj) {
6412
                if (method_exists($hookObj, 'checkRecordUpdateAccess')) {
6413
                    $res = $hookObj->checkRecordUpdateAccess($table, $id, $data, $res, $this);
6414
                }
6415
            }
6416
            if (isset($res)) {
6417
                return (bool)$res;
6418
            }
6419
        }
6420
        $res = false;
6421
6422
        if ($GLOBALS['TCA'][$table] && (int)$id > 0) {
6423
            $cacheId = 'checkRecordUpdateAccess_' . $table . '_' . $id;
6424
6425
            // If information is cached, return it
6426
            $cachedValue = $this->runtimeCache->get($cacheId);
6427
            if (!empty($cachedValue)) {
6428
                return $cachedValue;
6429
            }
6430
6431
            if ($table === 'pages' || ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap))) {
6432
                // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
6433
                $perms = Permission::PAGE_EDIT;
6434
            } else {
6435
                $perms = Permission::CONTENT_EDIT;
6436
            }
6437
            if ($this->doesRecordExist($table, $id, $perms)) {
6438
                $res = 1;
6439
            }
6440
            // Cache the result
6441
            $this->runtimeCache->set($cacheId, $res);
6442
        }
6443
        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...
6444
    }
6445
6446
    /**
6447
     * Checks if user may insert a record from $insertTable on $pid
6448
     *
6449
     * @param string $insertTable Tablename to check
6450
     * @param int $pid Integer PID
6451
     * @param int $action For logging: Action number.
6452
     * @return bool Returns TRUE if the user may insert a record from table $insertTable on page $pid
6453
     * @internal should only be used from within DataHandler
6454
     */
6455
    public function checkRecordInsertAccess($insertTable, $pid, $action = SystemLogDatabaseAction::INSERT)
6456
    {
6457
        $pid = (int)$pid;
6458
        if ($pid < 0) {
6459
            return false;
6460
        }
6461
        // If information is cached, return it
6462
        if (isset($this->recInsertAccessCache[$insertTable][$pid])) {
6463
            return $this->recInsertAccessCache[$insertTable][$pid];
6464
        }
6465
6466
        $res = false;
6467
        if ($insertTable === 'pages') {
6468
            $perms = Permission::PAGE_NEW;
6469
        } elseif (($insertTable === 'sys_file_reference') && array_key_exists('pages', $this->datamap)) {
6470
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
6471
            $perms = Permission::PAGE_EDIT;
6472
        } else {
6473
            $perms = Permission::CONTENT_EDIT;
6474
        }
6475
        $pageExists = (bool)$this->doesRecordExist('pages', $pid, $perms);
6476
        // 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
6477
        if ($pageExists || $pid === 0 && ($this->admin || BackendUtility::isRootLevelRestrictionIgnored($insertTable))) {
6478
            // Check permissions
6479
            if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
6480
                $res = true;
6481
                // Cache the result
6482
                $this->recInsertAccessCache[$insertTable][$pid] = $res;
6483
            } elseif ($this->enableLogging) {
6484
                $propArr = $this->getRecordProperties('pages', $pid);
6485
                $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']);
6486
            }
6487
        } elseif ($this->enableLogging) {
6488
            $propArr = $this->getRecordProperties('pages', $pid);
6489
            $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']);
6490
        }
6491
        return $res;
6492
    }
6493
6494
    /**
6495
     * 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.
6496
     *
6497
     * @param int $page_uid Page id for which to check, including 0 (zero) if checking for page tree root.
6498
     * @param string $checkTable Table name to check
6499
     * @return bool TRUE if OK
6500
     * @internal should only be used from within DataHandler
6501
     */
6502
    public function isTableAllowedForThisPage($page_uid, $checkTable)
6503
    {
6504
        $page_uid = (int)$page_uid;
6505
        $rootLevelSetting = (int)$GLOBALS['TCA'][$checkTable]['ctrl']['rootLevel'];
6506
        // 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.
6507
        if ($checkTable !== 'pages' && $rootLevelSetting !== -1 && ($rootLevelSetting xor !$page_uid)) {
6508
            return false;
6509
        }
6510
        $allowed = false;
6511
        // Check root-level
6512
        if (!$page_uid) {
6513
            if ($this->admin || BackendUtility::isRootLevelRestrictionIgnored($checkTable)) {
6514
                $allowed = true;
6515
            }
6516
        } else {
6517
            // Check non-root-level
6518
            $doktype = $this->pageInfo($page_uid, 'doktype');
6519
            $allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
6520
            $allowedArray = GeneralUtility::trimExplode(',', $allowedTableList, true);
6521
            // If all tables or the table is listed as an allowed type, return TRUE
6522
            if (strpos($allowedTableList, '*') !== false || in_array($checkTable, $allowedArray, true)) {
6523
                $allowed = true;
6524
            }
6525
        }
6526
        return $allowed;
6527
    }
6528
6529
    /**
6530
     * Checks if record can be selected based on given permission criteria
6531
     *
6532
     * @param string $table Record table name
6533
     * @param int $id Record UID
6534
     * @param int $perms Permission restrictions to observe: integer that will be bitwise AND'ed.
6535
     * @return bool Returns TRUE if the record given by $table, $id and $perms can be selected
6536
     *
6537
     * @throws \RuntimeException
6538
     * @internal should only be used from within DataHandler
6539
     */
6540
    public function doesRecordExist($table, $id, int $perms)
6541
    {
6542
        return $this->recordInfoWithPermissionCheck($table, $id, $perms, 'uid, pid') !== false;
6543
    }
6544
6545
    /**
6546
     * Looks up a page based on permissions.
6547
     *
6548
     * @param int $id Page id
6549
     * @param int $perms Permission integer
6550
     * @param array $columns Columns to select
6551
     * @return bool|array
6552
     * @internal
6553
     * @see doesRecordExist()
6554
     */
6555
    protected function doesRecordExist_pageLookUp($id, $perms, $columns = ['uid'])
6556
    {
6557
        $permission = new Permission($perms);
6558
        $cacheId = md5('doesRecordExist_pageLookUp_' . $id . '_' . $perms . '_' . implode(
6559
            '_',
6560
            $columns
6561
        ) . '_' . (string)$this->admin);
6562
6563
        // If result is cached, return it
6564
        $cachedResult = $this->runtimeCache->get($cacheId);
6565
        if (!empty($cachedResult)) {
6566
            return $cachedResult;
6567
        }
6568
6569
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6570
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6571
        $queryBuilder
6572
            ->select(...$columns)
6573
            ->from('pages')
6574
            ->where($queryBuilder->expr()->eq(
6575
                'uid',
6576
                $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
6577
            ));
6578
        if (!$permission->nothingIsGranted() && !$this->admin) {
6579
            $queryBuilder->andWhere($this->BE_USER->getPagePermsClause($perms));
6580
        }
6581
        if (!$this->admin && $GLOBALS['TCA']['pages']['ctrl']['editlock'] &&
6582
            ($permission->editPagePermissionIsGranted() || $permission->deletePagePermissionIsGranted() || $permission->editContentPermissionIsGranted())
6583
        ) {
6584
            $queryBuilder->andWhere($queryBuilder->expr()->eq(
6585
                $GLOBALS['TCA']['pages']['ctrl']['editlock'],
6586
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
6587
            ));
6588
        }
6589
6590
        $row = $queryBuilder->execute()->fetch();
6591
        $this->runtimeCache->set($cacheId, $row);
6592
6593
        return $row;
6594
    }
6595
6596
    /**
6597
     * Checks if a whole branch of pages exists
6598
     *
6599
     * Tests the branch under $pid like doesRecordExist(), but it doesn't test the page with $pid as uid - use doesRecordExist() for this purpose.
6600
     * 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
6601
     *
6602
     * @param string $inList List of page uids, this is added to and returned in the end
6603
     * @param int $pid Page ID to select subpages from.
6604
     * @param int $perms Perms integer to check each page record for.
6605
     * @param bool $recurse Recursion flag: If set, it will go out through the branch.
6606
     * @return string|int List of page IDs in branch, if there are subpages, empty string if there are none or -1 if no permission
6607
     * @internal should only be used from within DataHandler
6608
     */
6609
    public function doesBranchExist($inList, $pid, $perms, $recurse)
6610
    {
6611
        $pid = (int)$pid;
6612
        $perms = (int)$perms;
6613
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6614
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6615
        $result = $queryBuilder
6616
            ->select('uid', 'perms_userid', 'perms_groupid', 'perms_user', 'perms_group', 'perms_everybody')
6617
            ->from('pages')
6618
            ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
6619
            ->orderBy('sorting')
6620
            ->execute();
6621
        while ($row = $result->fetch()) {
6622
            // IF admin, then it's OK
6623
            if ($this->admin || $this->BE_USER->doesUserHaveAccess($row, $perms)) {
6624
                $inList .= $row['uid'] . ',';
6625
                if ($recurse) {
6626
                    // Follow the subpages recursively...
6627
                    $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
6628
                    if ($inList === -1) {
6629
                        return -1;
6630
                    }
6631
                }
6632
            } else {
6633
                // No permissions
6634
                return -1;
6635
            }
6636
        }
6637
        return $inList;
6638
    }
6639
6640
    /**
6641
     * Checks if the $table is readOnly
6642
     *
6643
     * @param string $table Table name
6644
     * @return bool TRUE, if readonly
6645
     * @internal should only be used from within DataHandler
6646
     */
6647
    public function tableReadOnly($table)
6648
    {
6649
        // Returns TRUE if table is readonly
6650
        return (bool)$GLOBALS['TCA'][$table]['ctrl']['readOnly'];
6651
    }
6652
6653
    /**
6654
     * Checks if the $table is only editable by admin-users
6655
     *
6656
     * @param string $table Table name
6657
     * @return bool TRUE, if readonly
6658
     * @internal should only be used from within DataHandler
6659
     */
6660
    public function tableAdminOnly($table)
6661
    {
6662
        // Returns TRUE if table is admin-only
6663
        return !empty($GLOBALS['TCA'][$table]['ctrl']['adminOnly']);
6664
    }
6665
6666
    /**
6667
     * Checks if page $id is a uid in the rootline of page id $destinationId
6668
     * Used when moving a page
6669
     *
6670
     * @param int $destinationId Destination Page ID to test
6671
     * @param int $id Page ID to test for presence inside Destination
6672
     * @return bool Returns FALSE if ID is inside destination (including equal to)
6673
     * @internal should only be used from within DataHandler
6674
     */
6675
    public function destNotInsideSelf($destinationId, $id)
6676
    {
6677
        $loopCheck = 100;
6678
        $destinationId = (int)$destinationId;
6679
        $id = (int)$id;
6680
        if ($destinationId === $id) {
6681
            return false;
6682
        }
6683
        while ($destinationId !== 0 && $loopCheck > 0) {
6684
            $loopCheck--;
6685
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6686
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6687
            $result = $queryBuilder
6688
                ->select('pid', 'uid', 't3ver_oid', 't3ver_wsid')
6689
                ->from('pages')
6690
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($destinationId, \PDO::PARAM_INT)))
6691
                ->execute();
6692
            if ($row = $result->fetch()) {
6693
                BackendUtility::fixVersioningPid('pages', $row);
6694
                if ($row['pid'] == $id) {
6695
                    return false;
6696
                }
6697
                $destinationId = (int)$row['pid'];
6698
            } else {
6699
                return false;
6700
            }
6701
        }
6702
        return true;
6703
    }
6704
6705
    /**
6706
     * 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
6707
     * Will also generate this list for admin-users so they must be check for before calling the function
6708
     *
6709
     * @return array Array of [table]-[field] pairs to exclude from editing.
6710
     * @internal should only be used from within DataHandler
6711
     */
6712
    public function getExcludeListArray()
6713
    {
6714
        $list = [];
6715
        if (isset($this->BE_USER->groupData['non_exclude_fields'])) {
6716
            $nonExcludeFieldsArray = array_flip(GeneralUtility::trimExplode(',', $this->BE_USER->groupData['non_exclude_fields']));
6717
            foreach ($GLOBALS['TCA'] as $table => $tableConfiguration) {
6718
                if (isset($tableConfiguration['columns'])) {
6719
                    foreach ($tableConfiguration['columns'] as $field => $config) {
6720
                        $isExcludeField = ($config['exclude'] ?? false);
6721
                        $isOnlyVisibleForAdmins = ($GLOBALS['TCA'][$table]['columns'][$field]['displayCond'] ?? '') === 'HIDE_FOR_NON_ADMINS';
6722
                        $editorHasPermissionForThisField = isset($nonExcludeFieldsArray[$table . ':' . $field]);
6723
                        if ($isOnlyVisibleForAdmins || ($isExcludeField && !$editorHasPermissionForThisField)) {
6724
                            $list[] = $table . '-' . $field;
6725
                        }
6726
                    }
6727
                }
6728
            }
6729
        }
6730
6731
        return $list;
6732
    }
6733
6734
    /**
6735
     * Checks if there are records on a page from tables that are not allowed
6736
     *
6737
     * @param int $page_uid Page ID
6738
     * @param int $doktype Page doktype
6739
     * @return bool|array Returns a list of the tables that are 'present' on the page but not allowed with the page_uid/doktype
6740
     * @internal should only be used from within DataHandler
6741
     */
6742
    public function doesPageHaveUnallowedTables($page_uid, $doktype)
6743
    {
6744
        $page_uid = (int)$page_uid;
6745
        if (!$page_uid) {
6746
            // Not a number. Probably a new page
6747
            return false;
6748
        }
6749
        $allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
6750
        // If all tables are allowed, return early
6751
        if (strpos($allowedTableList, '*') !== false) {
6752
            return false;
6753
        }
6754
        $allowedArray = GeneralUtility::trimExplode(',', $allowedTableList, true);
6755
        $tableList = [];
6756
        $allTableNames = $this->compileAdminTables();
6757
        foreach ($allTableNames as $table) {
6758
            // If the table is not in the allowed list, check if there are records...
6759
            if (in_array($table, $allowedArray, true)) {
6760
                continue;
6761
            }
6762
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6763
            $queryBuilder->getRestrictions()->removeAll();
6764
            $count = $queryBuilder
6765
                ->count('uid')
6766
                ->from($table)
6767
                ->where($queryBuilder->expr()->eq(
6768
                    'pid',
6769
                    $queryBuilder->createNamedParameter($page_uid, \PDO::PARAM_INT)
6770
                ))
6771
                ->execute()
6772
                ->fetchColumn(0);
6773
            if ($count) {
6774
                $tableList[] = $table;
6775
            }
6776
        }
6777
        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...
6778
    }
6779
6780
    /*****************************
6781
     *
6782
     * Information lookup
6783
     *
6784
     *****************************/
6785
    /**
6786
     * Returns the value of the $field from page $id
6787
     * 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!
6788
     *
6789
     * @param int $id Page uid
6790
     * @param string $field Field name for which to return value
6791
     * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
6792
     * @internal should only be used from within DataHandler
6793
     */
6794
    public function pageInfo($id, $field)
6795
    {
6796
        if (!isset($this->pageCache[$id])) {
6797
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6798
            $queryBuilder->getRestrictions()->removeAll();
6799
            $row = $queryBuilder
6800
                ->select('*')
6801
                ->from('pages')
6802
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6803
                ->execute()
6804
                ->fetch();
6805
            if ($row) {
6806
                $this->pageCache[$id] = $row;
6807
            }
6808
        }
6809
        return $this->pageCache[$id][$field];
6810
    }
6811
6812
    /**
6813
     * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
6814
     * NOTICE: No check for deleted or access!
6815
     *
6816
     * @param string $table Table name
6817
     * @param int $id UID of the record from $table
6818
     * @param string $fieldList Field list for the SELECT query, eg. "*" or "uid,pid,...
6819
     * @return array|null Returns the selected record on success, otherwise NULL.
6820
     * @internal should only be used from within DataHandler
6821
     */
6822
    public function recordInfo($table, $id, $fieldList)
6823
    {
6824
        // Skip, if searching for NEW records or there's no TCA table definition
6825
        if ((int)$id === 0 || !isset($GLOBALS['TCA'][$table])) {
6826
            return null;
6827
        }
6828
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6829
        $queryBuilder->getRestrictions()->removeAll();
6830
        $result = $queryBuilder
6831
            ->select(...GeneralUtility::trimExplode(',', $fieldList))
6832
            ->from($table)
6833
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6834
            ->execute()
6835
            ->fetch();
6836
        return $result ?: null;
6837
    }
6838
6839
    /**
6840
     * Checks if record exists with and without permission check and returns that row
6841
     *
6842
     * @param string $table Record table name
6843
     * @param int $id Record UID
6844
     * @param int $perms Permission restrictions to observe: An integer that will be bitwise AND'ed.
6845
     * @param string $fieldList - fields - default is '*'
6846
     * @throws \RuntimeException
6847
     * @return array|bool Row if exists and accessible, false otherwise
6848
     */
6849
    protected function recordInfoWithPermissionCheck(string $table, int $id, int $perms, string $fieldList = '*')
6850
    {
6851
        if ($this->bypassAccessCheckForRecords) {
6852
            $columns = GeneralUtility::trimExplode(',', $fieldList, true);
6853
6854
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6855
            $queryBuilder->getRestrictions()->removeAll();
6856
6857
            $record = $queryBuilder->select(...$columns)
6858
                ->from($table)
6859
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6860
                ->execute()
6861
                ->fetch();
6862
6863
            return $record ?: false;
6864
        }
6865
        if (!$perms) {
6866
            throw new \RuntimeException('Internal ERROR: no permissions to check for non-admin user', 1270853920);
6867
        }
6868
        // For all tables: Check if record exists:
6869
        $isWebMountRestrictionIgnored = BackendUtility::isWebMountRestrictionIgnored($table);
6870
        if (is_array($GLOBALS['TCA'][$table]) && $id > 0 && ($this->admin || $isWebMountRestrictionIgnored || $this->isRecordInWebMount($table, $id))) {
6871
            $columns = GeneralUtility::trimExplode(',', $fieldList, true);
6872
            if ($table !== 'pages') {
6873
                // Find record without checking page
6874
                // @todo: This should probably check for editlock
6875
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6876
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6877
                $output = $queryBuilder
6878
                    ->select(...$columns)
6879
                    ->from($table)
6880
                    ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6881
                    ->execute()
6882
                    ->fetch();
6883
                BackendUtility::fixVersioningPid($table, $output, true);
6884
                // If record found, check page as well:
6885
                if (is_array($output)) {
6886
                    // Looking up the page for record:
6887
                    $pageRec = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
6888
                    // 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):
6889
                    $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
6890
                    if (is_array($pageRec) || !$output['pid'] && ($this->admin || $isRootLevelRestrictionIgnored)) {
6891
                        return $output;
6892
                    }
6893
                }
6894
                return false;
6895
            }
6896
            return $this->doesRecordExist_pageLookUp($id, $perms, $columns);
6897
        }
6898
        return false;
6899
    }
6900
6901
    /**
6902
     * Returns an array with record properties, like header and pid
6903
     * No check for deleted or access is done!
6904
     * For versionized records, pid is resolved to its live versions pid.
6905
     * Used for logging
6906
     *
6907
     * @param string $table Table name
6908
     * @param int $id Uid of record
6909
     * @param bool $noWSOL If set, no workspace overlay is performed
6910
     * @return array Properties of record
6911
     * @internal should only be used from within DataHandler
6912
     */
6913
    public function getRecordProperties($table, $id, $noWSOL = false)
6914
    {
6915
        $row = $table === 'pages' && !$id ? ['title' => '[root-level]', 'uid' => 0, 'pid' => 0] : $this->recordInfo($table, $id, '*');
6916
        if (!$noWSOL) {
6917
            BackendUtility::workspaceOL($table, $row);
6918
        }
6919
        return $this->getRecordPropertiesFromRow($table, $row);
6920
    }
6921
6922
    /**
6923
     * Returns an array with record properties, like header and pid, based on the row
6924
     *
6925
     * @param string $table Table name
6926
     * @param array $row Input row
6927
     * @return array|null Output array
6928
     * @internal should only be used from within DataHandler
6929
     */
6930
    public function getRecordPropertiesFromRow($table, $row)
6931
    {
6932
        if ($GLOBALS['TCA'][$table]) {
6933
            BackendUtility::fixVersioningPid($table, $row);
6934
            $liveUid = ($row['t3ver_oid'] ?? null) ? $row['t3ver_oid'] : $row['uid'];
6935
            return [
6936
                'header' => BackendUtility::getRecordTitle($table, $row),
6937
                'pid' => $row['pid'],
6938
                'event_pid' => $this->eventPid($table, (int)$liveUid, $row['pid']),
6939
                't3ver_state' => BackendUtility::isTableWorkspaceEnabled($table) ? $row['t3ver_state'] : '',
6940
                '_ORIG_pid' => $row['_ORIG_pid']
6941
            ];
6942
        }
6943
        return null;
6944
    }
6945
6946
    /**
6947
     * @param string $table
6948
     * @param int $uid
6949
     * @param int $pid
6950
     * @return int
6951
     * @internal should only be used from within DataHandler
6952
     */
6953
    public function eventPid($table, $uid, $pid)
6954
    {
6955
        return $table === 'pages' ? $uid : $pid;
6956
    }
6957
6958
    /*********************************************
6959
     *
6960
     * Storing data to Database Layer
6961
     *
6962
     ********************************************/
6963
    /**
6964
     * Update database record
6965
     * Does not check permissions but expects them to be verified on beforehand
6966
     *
6967
     * @param string $table Record table name
6968
     * @param int $id Record uid
6969
     * @param array $fieldArray Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
6970
     * @internal should only be used from within DataHandler
6971
     */
6972
    public function updateDB($table, $id, $fieldArray)
6973
    {
6974
        if (is_array($fieldArray) && is_array($GLOBALS['TCA'][$table]) && (int)$id) {
6975
            // Do NOT update the UID field, ever!
6976
            unset($fieldArray['uid']);
6977
            if (!empty($fieldArray)) {
6978
                $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
6979
6980
                $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
6981
6982
                $types = [];
6983
                $platform = $connection->getDatabasePlatform();
6984
                if ($platform instanceof SQLServerPlatform) {
6985
                    // mssql needs to set proper PARAM_LOB and others to update fields
6986
                    $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
6987
                    foreach ($fieldArray as $columnName => $columnValue) {
6988
                        $types[$columnName] = $tableDetails->getColumn($columnName)->getType()->getBindingType();
6989
                    }
6990
                }
6991
6992
                // Execute the UPDATE query:
6993
                $updateErrorMessage = '';
6994
                try {
6995
                    $connection->update($table, $fieldArray, ['uid' => (int)$id], $types);
6996
                } catch (DBALException $e) {
6997
                    $updateErrorMessage = $e->getPrevious()->getMessage();
6998
                }
6999
                // If succeeds, do...:
7000
                if ($updateErrorMessage === '') {
7001
                    // Update reference index:
7002
                    $this->updateRefIndex($table, $id);
7003
                    // Set History data
7004
                    $historyEntryId = 0;
7005
                    if (isset($this->historyRecords[$table . ':' . $id])) {
7006
                        $historyEntryId = $this->getRecordHistoryStore()->modifyRecord($table, $id, $this->historyRecords[$table . ':' . $id], $this->correlationId);
7007
                    }
7008
                    if ($this->enableLogging) {
7009
                        if ($this->checkStoredRecords) {
7010
                            $newRow = $this->checkStoredRecord($table, $id, $fieldArray, SystemLogDatabaseAction::UPDATE);
7011
                        } else {
7012
                            $newRow = $fieldArray;
7013
                            $newRow['uid'] = $id;
7014
                        }
7015
                        // Set log entry:
7016
                        $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
7017
                        $isOfflineVersion = (bool)($newRow['t3ver_oid'] ?? 0);
7018
                        $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']);
7019
                    }
7020
                    // Clear cache for relevant pages:
7021
                    $this->registerRecordIdForPageCacheClearing($table, $id);
7022
                    // Unset the pageCache for the id if table was page.
7023
                    if ($table === 'pages') {
7024
                        unset($this->pageCache[$id]);
7025
                    }
7026
                } else {
7027
                    $this->log($table, $id, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$updateErrorMessage, $table . ':' . $id]);
7028
                }
7029
            }
7030
        }
7031
    }
7032
7033
    /**
7034
     * Insert into database
7035
     * Does not check permissions but expects them to be verified on beforehand
7036
     *
7037
     * @param string $table Record table name
7038
     * @param string $id "NEW...." uid string
7039
     * @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!
7040
     * @param bool $newVersion Set to TRUE if new version is created.
7041
     * @param int $suggestedUid Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
7042
     * @param bool $dontSetNewIdIndex If TRUE, the ->substNEWwithIDs array is not updated. Only useful in very rare circumstances!
7043
     * @return int|null Returns ID on success.
7044
     * @internal should only be used from within DataHandler
7045
     */
7046
    public function insertDB($table, $id, $fieldArray, $newVersion = false, $suggestedUid = 0, $dontSetNewIdIndex = false)
7047
    {
7048
        if (is_array($fieldArray) && is_array($GLOBALS['TCA'][$table]) && isset($fieldArray['pid'])) {
7049
            // Do NOT insert the UID field, ever!
7050
            unset($fieldArray['uid']);
7051
            if (!empty($fieldArray)) {
7052
                // Check for "suggestedUid".
7053
                // This feature is used by the import functionality to force a new record to have a certain UID value.
7054
                // This is only recommended for use when the destination server is a passive mirror of another server.
7055
                // As a security measure this feature is available only for Admin Users (for now)
7056
                $suggestedUid = (int)$suggestedUid;
7057
                if ($this->BE_USER->isAdmin() && $suggestedUid && $this->suggestedInsertUids[$table . ':' . $suggestedUid]) {
7058
                    // When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
7059
                    if ($this->suggestedInsertUids[$table . ':' . $suggestedUid] === 'DELETE') {
7060
                        $this->hardDeleteSingleRecord($table, (int)$suggestedUid);
7061
                    }
7062
                    $fieldArray['uid'] = $suggestedUid;
7063
                }
7064
                $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
7065
                $typeArray = [];
7066
                if (!empty($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'])
7067
                    && array_key_exists($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'], $fieldArray)
7068
                ) {
7069
                    $typeArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = Connection::PARAM_LOB;
7070
                }
7071
                $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
7072
                $insertErrorMessage = '';
7073
                try {
7074
                    // Execute the INSERT query:
7075
                    $connection->insert(
7076
                        $table,
7077
                        $fieldArray,
7078
                        $typeArray
7079
                    );
7080
                } catch (DBALException $e) {
7081
                    $insertErrorMessage = $e->getPrevious()->getMessage();
7082
                }
7083
                // If succees, do...:
7084
                if ($insertErrorMessage === '') {
7085
                    // Set mapping for NEW... -> real uid:
7086
                    // the NEW_id now holds the 'NEW....' -id
7087
                    $NEW_id = $id;
7088
                    $id = $this->postProcessDatabaseInsert($connection, $table, $suggestedUid);
7089
7090
                    if (!$dontSetNewIdIndex) {
7091
                        $this->substNEWwithIDs[$NEW_id] = $id;
7092
                        $this->substNEWwithIDs_table[$NEW_id] = $table;
7093
                    }
7094
                    $newRow = [];
7095
                    if ($this->enableLogging) {
7096
                        // Checking the record is properly saved if configured
7097
                        if ($this->checkStoredRecords) {
7098
                            $newRow = $this->checkStoredRecord($table, $id, $fieldArray, SystemLogDatabaseAction::INSERT);
7099
                        } else {
7100
                            $newRow = $fieldArray;
7101
                            $newRow['uid'] = $id;
7102
                        }
7103
                    }
7104
                    // Update reference index:
7105
                    $this->updateRefIndex($table, $id);
7106
7107
                    // Store in history
7108
                    $this->getRecordHistoryStore()->addRecord($table, $id, $newRow, $this->correlationId);
0 ignored issues
show
Bug introduced by
It seems like $newRow can also be of type null; however, parameter $payload of TYPO3\CMS\Core\DataHandl...storyStore::addRecord() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

7108
                    $this->getRecordHistoryStore()->addRecord($table, $id, /** @scrutinizer ignore-type */ $newRow, $this->correlationId);
Loading history...
7109
7110
                    if ($newVersion) {
7111
                        if ($this->enableLogging) {
7112
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
7113
                            $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);
7114
                        }
7115
                    } else {
7116
                        if ($this->enableLogging) {
7117
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
7118
                            $page_propArr = $this->getRecordProperties('pages', $propArr['pid']);
7119
                            $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);
7120
                        }
7121
                        // Clear cache for relevant pages:
7122
                        $this->registerRecordIdForPageCacheClearing($table, $id);
7123
                    }
7124
                    return $id;
7125
                }
7126
                if ($this->enableLogging) {
7127
                    $this->log($table, $id, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$insertErrorMessage, $table . ':' . $id]);
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type integer expected by parameter $recuid of TYPO3\CMS\Core\DataHandling\DataHandler::log(). ( Ignorable by Annotation )

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

7127
                    $this->log($table, /** @scrutinizer ignore-type */ $id, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$insertErrorMessage, $table . ':' . $id]);
Loading history...
7128
                }
7129
            }
7130
        }
7131
        return null;
7132
    }
7133
7134
    /**
7135
     * Checking stored record to see if the written values are properly updated.
7136
     *
7137
     * @param string $table Record table name
7138
     * @param int $id Record uid
7139
     * @param array $fieldArray Array of field=>value pairs to insert/update
7140
     * @param string $action Action, for logging only.
7141
     * @return array|null Selected row
7142
     * @see insertDB()
7143
     * @see updateDB()
7144
     * @internal should only be used from within DataHandler
7145
     */
7146
    public function checkStoredRecord($table, $id, $fieldArray, $action)
7147
    {
7148
        $id = (int)$id;
7149
        if (is_array($GLOBALS['TCA'][$table]) && $id) {
7150
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7151
            $queryBuilder->getRestrictions()->removeAll();
7152
7153
            $row = $queryBuilder
7154
                ->select('*')
7155
                ->from($table)
7156
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
7157
                ->execute()
7158
                ->fetch();
7159
7160
            if (!empty($row)) {
7161
                // Traverse array of values that was inserted into the database and compare with the actually stored value:
7162
                $errors = [];
7163
                foreach ($fieldArray as $key => $value) {
7164
                    if (!$this->checkStoredRecords_loose || $value || $row[$key]) {
7165
                        if (is_float($row[$key])) {
7166
                            // if the database returns the value as double, compare it as double
7167
                            if ((double)$value !== (double)$row[$key]) {
7168
                                $errors[] = $key;
7169
                            }
7170
                        } else {
7171
                            $dbType = $GLOBALS['TCA'][$table]['columns'][$key]['config']['dbType'] ?? false;
7172
                            if ($dbType === 'datetime' || $dbType === 'time') {
7173
                                $row[$key] = $this->normalizeTimeFormat($table, $row[$key], $dbType);
7174
                            }
7175
                            if ((string)$value !== (string)$row[$key]) {
7176
                                // The is_numeric check catches cases where we want to store a float/double value
7177
                                // and database returns the field as a string with the least required amount of
7178
                                // significant digits, i.e. "0.00" being saved and "0" being read back.
7179
                                if (is_numeric($value) && is_numeric($row[$key])) {
7180
                                    if ((double)$value === (double)$row[$key]) {
7181
                                        continue;
7182
                                    }
7183
                                }
7184
                                $errors[] = $key;
7185
                            }
7186
                        }
7187
                    }
7188
                }
7189
                // Set log message if there were fields with unmatching values:
7190
                if (!empty($errors)) {
7191
                    $message = sprintf(
7192
                        '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.',
7193
                        $id,
7194
                        $table,
7195
                        implode(', ', $errors)
7196
                    );
7197
                    $this->log($table, $id, $action, 0, SystemLogErrorClassification::USER_ERROR, $message);
0 ignored issues
show
Bug introduced by
$action of type string is incompatible with the type integer expected by parameter $action of TYPO3\CMS\Core\DataHandling\DataHandler::log(). ( Ignorable by Annotation )

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

7197
                    $this->log($table, $id, /** @scrutinizer ignore-type */ $action, 0, SystemLogErrorClassification::USER_ERROR, $message);
Loading history...
7198
                }
7199
                // Return selected rows:
7200
                return $row;
7201
            }
7202
        }
7203
        return null;
7204
    }
7205
7206
    /**
7207
     * Setting sys_history record, based on content previously set in $this->historyRecords[$table . ':' . $id] (by compareFieldArrayWithCurrentAndUnset())
7208
     *
7209
     * This functionality is now moved into the RecordHistoryStore and can be used instead.
7210
     *
7211
     * @param string $table Table name
7212
     * @param int $id Record ID
7213
     * @param int $logId Log entry ID, important for linking between log and history views
7214
     * @internal should only be used from within DataHandler
7215
     */
7216
    public function setHistory($table, $id, $logId)
7217
    {
7218
        if (isset($this->historyRecords[$table . ':' . $id])) {
7219
            $this->getRecordHistoryStore()->modifyRecord(
7220
                $table,
7221
                $id,
7222
                $this->historyRecords[$table . ':' . $id],
7223
                $this->correlationId
7224
            );
7225
        }
7226
    }
7227
7228
    /**
7229
     * @return RecordHistoryStore
7230
     */
7231
    protected function getRecordHistoryStore(): RecordHistoryStore
7232
    {
7233
        return GeneralUtility::makeInstance(
7234
            RecordHistoryStore::class,
7235
            RecordHistoryStore::USER_BACKEND,
7236
            $this->BE_USER->user['uid'],
7237
            $this->BE_USER->user['ses_backuserid'] ?? null,
7238
            $GLOBALS['EXEC_TIME'],
7239
            $this->BE_USER->workspace
7240
        );
7241
    }
7242
7243
    /**
7244
     * Register a table/uid combination in current user workspace for reference updating.
7245
     * Should be called on almost any update to a record which could affect references inside the record.
7246
     *
7247
     * @param string $table Table name
7248
     * @param int $uid Record UID
7249
     * @param int $workspace Workspace the record lives in
7250
     * @internal should only be used from within DataHandler
7251
     */
7252
    public function updateRefIndex($table, $uid, int $workspace = null): void
7253
    {
7254
        if ($workspace === null) {
7255
            $workspace = (int)$this->BE_USER->workspace;
7256
        }
7257
        $this->referenceIndexUpdater->registerForUpdate((string)$table, (int)$uid, $workspace);
7258
    }
7259
7260
    /**
7261
     * Delete rows from sys_refindex a table / uid combination is involved in:
7262
     * Either on left side (tablename + recuid) OR right side (ref_table + ref_uid).
7263
     * Useful in scenarios like workspace-discard where parents or children are hard deleted: The
7264
     * expensive updateRefIndex() does not need to be called since we can just drop straight ahead.
7265
     *
7266
     * @param string $table Table name, used as tablename and ref_table
7267
     * @param int $uid Record uid, used as recuid and ref_uid
7268
     * @param int $workspace Workspace the record lives in
7269
     */
7270
    public function registerReferenceIndexRowsForDrop(string $table, int $uid, int $workspace): void
7271
    {
7272
        $this->referenceIndexUpdater->registerForDrop($table, $uid, $workspace);
7273
    }
7274
7275
    /*********************************************
7276
     *
7277
     * Misc functions
7278
     *
7279
     ********************************************/
7280
    /**
7281
     * Returning sorting number for tables with a "sortby" column
7282
     * Using when new records are created and existing records are moved around.
7283
     *
7284
     * The strategy is:
7285
     *  - if no record exists: set interval as sorting number
7286
     *  - if inserted before an element: put in the middle of the existing elements
7287
     *  - if inserted behind the last element: add interval to last sorting number
7288
     *  - if collision: move all subsequent records by 2 * interval, insert new record with collision + interval
7289
     *
7290
     * How to calculate the maximum possible inserts for the worst case of adding all records to the top,
7291
     * such that the sorting number stays within INT_MAX
7292
     *
7293
     * i = interval (currently 256)
7294
     * c = number of inserts until collision
7295
     * s = max sorting number to reach (INT_MAX - 32bit)
7296
     * n = number of records (~83 million)
7297
     *
7298
     * c = 2 * g
7299
     * g = log2(i) / 2 + 1
7300
     * n = g * s / i - g + 1
7301
     *
7302
     * The algorithm can be tuned by adjusting the interval value.
7303
     * Higher value means less collisions, but also less inserts are possible to stay within INT_MAX.
7304
     *
7305
     * @param string $table Table name
7306
     * @param int $uid Uid of record to find sorting number for. May be zero in case of new.
7307
     * @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)
7308
     * @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.
7309
     * @internal should only be used from within DataHandler
7310
     */
7311
    public function getSortNumber($table, $uid, $pid)
7312
    {
7313
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7314
        if (!$sortColumn) {
7315
            return null;
7316
        }
7317
7318
        $considerWorkspaces = BackendUtility::isTableWorkspaceEnabled($table);
7319
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
7320
        $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
7321
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7322
7323
        $queryBuilder
7324
            ->select($sortColumn, 'pid', 'uid')
7325
            ->from($table);
7326
7327
        // find and return the sorting value for the first record on that pid
7328
        if ($pid >= 0) {
7329
            // Fetches the first record (lowest sorting) under this pid
7330
            $queryBuilder
7331
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)));
7332
7333
            if ($considerWorkspaces) {
7334
                $queryBuilder->andWhere(
7335
                    $queryBuilder->expr()->eq('t3ver_oid', 0)
7336
                );
7337
            }
7338
            $row = $queryBuilder
7339
                ->orderBy($sortColumn, 'ASC')
7340
                ->addOrderBy('uid', 'ASC')
7341
                ->setMaxResults(1)
7342
                ->execute()
7343
                ->fetch();
7344
7345
            if (!empty($row)) {
7346
                // The top record was the record itself, so we return its current sorting value
7347
                if ($row['uid'] == $uid) {
7348
                    return $row[$sortColumn];
7349
                }
7350
                // If the record sorting value < 1 we must resort all the records under this pid
7351
                if ($row[$sortColumn] < 1) {
7352
                    $this->increaseSortingOfFollowingRecords($table, (int)$pid);
7353
                    // Lowest sorting value after full resorting is $sortIntervals
7354
                    return $this->sortIntervals;
7355
                }
7356
                // Sorting number between current top element and zero
7357
                return floor($row[$sortColumn] / 2);
7358
            }
7359
            // No records, so we choose the default value as sorting-number
7360
            return $this->sortIntervals;
7361
        }
7362
7363
        // Find and return first possible sorting value AFTER record with given uid ($pid)
7364
        // Fetches the record which is supposed to be the prev record
7365
        $row = $queryBuilder
7366
                ->where($queryBuilder->expr()->eq(
7367
                    'uid',
7368
                    $queryBuilder->createNamedParameter(abs($pid), \PDO::PARAM_INT)
7369
                ))
7370
                ->execute()
7371
                ->fetch();
7372
7373
        // There is a previous record
7374
        if (!empty($row)) {
7375
            // Look, if the record UID happens to be an offline record. If so, find its live version.
7376
            // Offline uids will be used when a page is versionized as "branch" so this is when we must correct
7377
            // - otherwise a pid of "-1" and a wrong sort-row number is returned which we don't want.
7378
            if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $row['uid'], $sortColumn . ',pid,uid')) {
7379
                $row = $lookForLiveVersion;
7380
            }
7381
            // Fetch move placeholder, since it might point to a new page in the current workspace.
7382
            // Only do that if we're not inserting a record after itself, otherwise we'd update the
7383
            // move placeholder that we're currently trying to move around with data of itself.
7384
            $movePlaceholder = BackendUtility::getMovePlaceholder($table, $row['uid'], 'uid,pid,' . $sortColumn);
7385
            if ($movePlaceholder && ((int)$movePlaceholder['uid'] !== (int)$uid)) {
7386
                $row = $movePlaceholder;
7387
            }
7388
            // If the record should be inserted after itself, keep the current sorting information:
7389
            if ((int)$row['uid'] === (int)$uid) {
7390
                $sortNumber = $row[$sortColumn];
7391
            } else {
7392
                $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
7393
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7394
7395
                $queryBuilder
7396
                        ->select($sortColumn, 'pid', 'uid')
7397
                        ->from($table)
7398
                        ->where(
7399
                            $queryBuilder->expr()->eq(
7400
                                'pid',
7401
                                $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
7402
                            ),
7403
                            $queryBuilder->expr()->gte(
7404
                                $sortColumn,
7405
                                $queryBuilder->createNamedParameter($row[$sortColumn], \PDO::PARAM_INT)
7406
                            )
7407
                        )
7408
                        ->orderBy($sortColumn, 'ASC')
7409
                        ->addOrderBy('uid', 'DESC')
7410
                        ->setMaxResults(2);
7411
7412
                if ($considerWorkspaces) {
7413
                    $queryBuilder->andWhere(
7414
                        $queryBuilder->expr()->eq('t3ver_oid', 0)
7415
                    );
7416
                }
7417
7418
                $subResults = $queryBuilder
7419
                    ->execute()
7420
                    ->fetchAll();
7421
                // Fetches the next record in order to calculate the in-between sortNumber
7422
                // There was a record afterwards
7423
                if (count($subResults) === 2) {
7424
                    // There was a record afterwards, fetch that
7425
                    $subrow = array_pop($subResults);
7426
                    // The sortNumber is found in between these values
7427
                    $sortNumber = $row[$sortColumn] + floor(($subrow[$sortColumn] - $row[$sortColumn]) / 2);
7428
                    // The sortNumber happened NOT to be between the two surrounding numbers, so we'll have to resort the list
7429
                    if ($sortNumber <= $row[$sortColumn] || $sortNumber >= $subrow[$sortColumn]) {
7430
                        $this->increaseSortingOfFollowingRecords($table, (int)$row['pid'], (int)$row[$sortColumn]);
7431
                        $sortNumber = $row[$sortColumn] + $this->sortIntervals;
7432
                    }
7433
                } else {
7434
                    // If after the last record in the list, we just add the sortInterval to the last sortvalue
7435
                    $sortNumber = $row[$sortColumn] + $this->sortIntervals;
7436
                }
7437
            }
7438
            return ['pid' => $row['pid'], 'sortNumber' => $sortNumber];
7439
        }
7440
        if ($this->enableLogging) {
7441
            $propArr = $this->getRecordProperties($table, $uid);
7442
            // OK, don't insert $propArr['event_pid'] here...
7443
            $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']);
7444
        }
7445
        // There MUST be a previous record or else this cannot work
7446
        return false;
7447
    }
7448
7449
    /**
7450
     * Increases sorting field value of all records with sorting higher than $sortingValue
7451
     *
7452
     * Used internally by getSortNumber() to "make space" in sorting values when inserting new record
7453
     *
7454
     * @param string $table Table name
7455
     * @param int $pid Page Uid in which to resort records
7456
     * @param int $sortingValue All sorting numbers larger than this number will be shifted
7457
     * @see getSortNumber()
7458
     */
7459
    protected function increaseSortingOfFollowingRecords(string $table, int $pid, int $sortingValue = null): void
7460
    {
7461
        $sortBy = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7462
        if ($sortBy) {
7463
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7464
7465
            $queryBuilder
7466
                ->update($table)
7467
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
7468
                ->set($sortBy, $queryBuilder->quoteIdentifier($sortBy) . ' + ' . $this->sortIntervals . ' + ' . $this->sortIntervals, false);
7469
            if ($sortingValue !== null) {
7470
                $queryBuilder->andWhere($queryBuilder->expr()->gt($sortBy, $sortingValue));
7471
            }
7472
            if (BackendUtility::isTableWorkspaceEnabled($table)) {
7473
                $queryBuilder
7474
                    ->andWhere(
7475
                        $queryBuilder->expr()->eq('t3ver_oid', 0)
7476
                    );
7477
            }
7478
7479
            $deleteColumn = $GLOBALS['TCA'][$table]['ctrl']['delete'] ?? '';
7480
            if ($deleteColumn) {
7481
                $queryBuilder->andWhere($queryBuilder->expr()->eq($deleteColumn, 0));
7482
            }
7483
7484
            $queryBuilder->execute();
7485
        }
7486
    }
7487
7488
    /**
7489
     * Returning uid of previous localized record, if any, for tables with a "sortby" column
7490
     * Used when new localized records are created so that localized records are sorted in the same order as the default language records
7491
     *
7492
     * For a given record (A) uid (record we're translating) it finds first default language record (from the same colpos)
7493
     * with sorting smaller than given record (B).
7494
     * Then it fetches a translated version of record B and returns it's uid.
7495
     *
7496
     * If there is no record B, or it has no translation in given language, the record A uid is returned.
7497
     * The localized record will be placed the after record which uid is returned.
7498
     *
7499
     * @param string $table Table name
7500
     * @param int $uid Uid of default language record
7501
     * @param int $pid Pid of default language record
7502
     * @param int $language Language of localization
7503
     * @return int uid of record after which the localized record should be inserted
7504
     */
7505
    protected function getPreviousLocalizedRecordUid($table, $uid, $pid, $language)
7506
    {
7507
        $previousLocalizedRecordUid = $uid;
7508
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7509
        if ($sortColumn) {
7510
            $select = [$sortColumn, 'pid', 'uid'];
7511
            // For content elements, we also need the colPos
7512
            if ($table === 'tt_content') {
7513
                $select[] = 'colPos';
7514
            }
7515
            // Get the sort value of the default language record
7516
            $row = BackendUtility::getRecord($table, $uid, implode(',', $select));
7517
            if (is_array($row)) {
7518
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7519
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7520
7521
                $queryBuilder
7522
                    ->select(...$select)
7523
                    ->from($table)
7524
                    ->where(
7525
                        $queryBuilder->expr()->eq(
7526
                            'pid',
7527
                            $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
7528
                        ),
7529
                        $queryBuilder->expr()->eq(
7530
                            $GLOBALS['TCA'][$table]['ctrl']['languageField'],
7531
                            $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
7532
                        ),
7533
                        $queryBuilder->expr()->lt(
7534
                            $sortColumn,
7535
                            $queryBuilder->createNamedParameter($row[$sortColumn], \PDO::PARAM_INT)
7536
                        )
7537
                    )
7538
                    ->orderBy($sortColumn, 'DESC')
7539
                    ->addOrderBy('uid', 'DESC')
7540
                    ->setMaxResults(1);
7541
                if ($table === 'tt_content') {
7542
                    $queryBuilder
7543
                        ->andWhere(
7544
                            $queryBuilder->expr()->eq(
7545
                                'colPos',
7546
                                $queryBuilder->createNamedParameter($row['colPos'], \PDO::PARAM_INT)
7547
                            )
7548
                        );
7549
                }
7550
                // If there is an element, find its localized record in specified localization language
7551
                if ($previousRow = $queryBuilder->execute()->fetch()) {
7552
                    $previousLocalizedRecord = BackendUtility::getRecordLocalization($table, $previousRow['uid'], $language);
7553
                    if (is_array($previousLocalizedRecord[0])) {
7554
                        $previousLocalizedRecordUid = $previousLocalizedRecord[0]['uid'];
7555
                    }
7556
                }
7557
            }
7558
        }
7559
        return $previousLocalizedRecordUid;
7560
    }
7561
7562
    /**
7563
     * 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.
7564
     * Used for new records and during copy operations for defaults
7565
     *
7566
     * @param string $table Table name for which to set default values.
7567
     * @return array Array with default values.
7568
     * @internal should only be used from within DataHandler
7569
     */
7570
    public function newFieldArray($table)
7571
    {
7572
        $fieldArray = [];
7573
        if (is_array($GLOBALS['TCA'][$table]['columns'])) {
7574
            foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $content) {
7575
                if (isset($this->defaultValues[$table][$field])) {
7576
                    $fieldArray[$field] = $this->defaultValues[$table][$field];
7577
                } elseif (isset($content['config']['default'])) {
7578
                    $fieldArray[$field] = $content['config']['default'];
7579
                }
7580
            }
7581
        }
7582
        return $fieldArray;
7583
    }
7584
7585
    /**
7586
     * 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.
7587
     *
7588
     * @param string $table Table name
7589
     * @param array $incomingFieldArray Incoming array (passed by reference)
7590
     * @internal should only be used from within DataHandler
7591
     */
7592
    public function addDefaultPermittedLanguageIfNotSet($table, &$incomingFieldArray)
7593
    {
7594
        // Checking languages:
7595
        if ($GLOBALS['TCA'][$table]['ctrl']['languageField']) {
7596
            if (!isset($incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
7597
                // Language field must be found in input row - otherwise it does not make sense.
7598
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
7599
                    ->getQueryBuilderForTable('sys_language');
7600
                $queryBuilder->getRestrictions()
7601
                    ->removeAll()
7602
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7603
                $queryBuilder
7604
                    ->select('uid')
7605
                    ->from('sys_language')
7606
                    ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)));
7607
                $rows = array_merge([['uid' => 0]], $queryBuilder->execute()->fetchAll(), [['uid' => -1]]);
7608
                foreach ($rows as $r) {
7609
                    if ($this->BE_USER->checkLanguageAccess($r['uid'])) {
7610
                        $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $r['uid'];
7611
                        break;
7612
                    }
7613
                }
7614
            }
7615
        }
7616
    }
7617
7618
    /**
7619
     * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
7620
     *
7621
     * @param string $table Table name
7622
     * @param array $data Data array with fields from table. These will be overlaid with values in $this->overrideValues[$table]
7623
     * @return array Data array, processed.
7624
     * @internal should only be used from within DataHandler
7625
     */
7626
    public function overrideFieldArray($table, $data)
7627
    {
7628
        if (is_array($this->overrideValues[$table])) {
7629
            $data = array_merge($data, $this->overrideValues[$table]);
7630
        }
7631
        return $data;
7632
    }
7633
7634
    /**
7635
     * Compares the incoming field array with the current record and unsets all fields which are the same.
7636
     * Used for existing records being updated
7637
     *
7638
     * @param string $table Record table name
7639
     * @param int $id Record uid
7640
     * @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!
7641
     * @return array Returns $fieldArray. If the returned array is empty, then the record should not be updated!
7642
     * @internal should only be used from within DataHandler
7643
     */
7644
    public function compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray)
7645
    {
7646
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
7647
        $queryBuilder = $connection->createQueryBuilder();
7648
        $queryBuilder->getRestrictions()->removeAll();
7649
        $currentRecord = $queryBuilder->select('*')
7650
            ->from($table)
7651
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
7652
            ->execute()
7653
            ->fetch();
7654
        // If the current record exists (which it should...), begin comparison:
7655
        if (is_array($currentRecord)) {
7656
            $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
7657
            $columnRecordTypes = [];
7658
            foreach ($currentRecord as $columnName => $_) {
7659
                $columnRecordTypes[$columnName] = '';
7660
                $type = $tableDetails->getColumn($columnName)->getType();
7661
                if ($type instanceof IntegerType) {
7662
                    $columnRecordTypes[$columnName] = 'int';
7663
                }
7664
            }
7665
            // Unset the fields which are similar:
7666
            foreach ($fieldArray as $col => $val) {
7667
                $fieldConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
7668
                $isNullField = (!empty($fieldConfiguration['eval']) && GeneralUtility::inList($fieldConfiguration['eval'], 'null'));
7669
7670
                // Unset fields if stored and submitted values are equal - except the current field holds MM relations.
7671
                // In general this avoids to store superfluous data which also will be visualized in the editing history.
7672
                if (!$fieldConfiguration['MM'] && $this->isSubmittedValueEqualToStoredValue($val, $currentRecord[$col], $columnRecordTypes[$col], $isNullField)) {
7673
                    unset($fieldArray[$col]);
7674
                } else {
7675
                    if (!isset($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col])) {
7676
                        $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $currentRecord[$col];
7677
                    } elseif ($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col]) {
7678
                        $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col];
7679
                    }
7680
                    if (!isset($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col])) {
7681
                        $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $fieldArray[$col];
7682
                    } elseif ($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col]) {
7683
                        $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col];
7684
                    }
7685
                }
7686
            }
7687
        } else {
7688
            // If the current record does not exist this is an error anyways and we just return an empty array here.
7689
            $fieldArray = [];
7690
        }
7691
        return $fieldArray;
7692
    }
7693
7694
    /**
7695
     * Determines whether submitted values and stored values are equal.
7696
     * This prevents from adding superfluous field changes which would be shown in the record history as well.
7697
     * For NULL fields (see accordant TCA definition 'eval' = 'null'), a special handling is required since
7698
     * (!strcmp(NULL, '')) would be a false-positive.
7699
     *
7700
     * @param mixed $submittedValue Value that has submitted (e.g. from a backend form)
7701
     * @param mixed $storedValue Value that is currently stored in the database
7702
     * @param string $storedType SQL type of the stored value column (see mysql_field_type(), e.g 'int', 'string',  ...)
7703
     * @param bool $allowNull Whether NULL values are allowed by accordant TCA definition ('eval' = 'null')
7704
     * @return bool Whether both values are considered to be equal
7705
     */
7706
    protected function isSubmittedValueEqualToStoredValue($submittedValue, $storedValue, $storedType, $allowNull = false)
7707
    {
7708
        // No NULL values are allowed, this is the regular behaviour.
7709
        // Thus, check whether strings are the same or whether integer values are empty ("0" or "").
7710
        if (!$allowNull) {
7711
            $result = (string)$submittedValue === (string)$storedValue || $storedType === 'int' && (int)$storedValue === (int)$submittedValue;
7712
        // Null values are allowed, but currently there's a real (not NULL) value.
7713
        // Thus, ensure no NULL value was submitted and fallback to the regular behaviour.
7714
        } elseif ($storedValue !== null) {
7715
            $result = (
7716
                $submittedValue !== null
7717
                && $this->isSubmittedValueEqualToStoredValue($submittedValue, $storedValue, $storedType, false)
7718
            );
7719
        // Null values are allowed, and currently there's a NULL value.
7720
        // Thus, check whether a NULL value was submitted.
7721
        } else {
7722
            $result = ($submittedValue === null);
7723
        }
7724
7725
        return $result;
7726
    }
7727
7728
    /**
7729
     * Converts a HTML entity (like &#123;) to the character '123'
7730
     *
7731
     * @param string $input Input string
7732
     * @return string Output string
7733
     * @internal should only be used from within DataHandler
7734
     */
7735
    public function convNumEntityToByteValue($input)
7736
    {
7737
        $token = md5(microtime());
7738
        $parts = explode($token, preg_replace('/(&#([0-9]+);)/', $token . '\\2' . $token, $input));
7739
        foreach ($parts as $k => $v) {
7740
            if ($k % 2) {
7741
                $v = (int)$v;
7742
                // Just to make sure that control bytes are not converted.
7743
                if ($v > 32) {
7744
                    $parts[$k] = chr($v);
7745
                }
7746
            }
7747
        }
7748
        return implode('', $parts);
7749
    }
7750
7751
    /**
7752
     * Disables the delete clause for fetching records.
7753
     * In general only undeleted records will be used. If the delete
7754
     * clause is disabled, also deleted records are taken into account.
7755
     */
7756
    public function disableDeleteClause()
7757
    {
7758
        $this->disableDeleteClause = true;
7759
    }
7760
7761
    /**
7762
     * Returns delete-clause for the $table
7763
     *
7764
     * @param string $table Table name
7765
     * @return string Delete clause
7766
     * @internal should only be used from within DataHandler
7767
     */
7768
    public function deleteClause($table)
7769
    {
7770
        // Returns the proper delete-clause if any for a table from TCA
7771
        if (!$this->disableDeleteClause && $GLOBALS['TCA'][$table]['ctrl']['delete']) {
7772
            return ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
7773
        }
7774
        return '';
7775
    }
7776
7777
    /**
7778
     * Add delete restriction if not disabled
7779
     *
7780
     * @param QueryRestrictionContainerInterface $restrictions
7781
     */
7782
    protected function addDeleteRestriction(QueryRestrictionContainerInterface $restrictions)
7783
    {
7784
        if (!$this->disableDeleteClause) {
7785
            $restrictions->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7786
        }
7787
    }
7788
7789
    /**
7790
     * Gets UID of parent record. If record is deleted it will be looked up in
7791
     * an array built before the record was deleted
7792
     *
7793
     * @param string $table Table where record lives/lived
7794
     * @param int $uid Record UID
7795
     * @return int[] Parent UIDs
7796
     */
7797
    protected function getOriginalParentOfRecord($table, $uid)
7798
    {
7799
        if (isset(self::$recordPidsForDeletedRecords[$table][$uid])) {
7800
            return self::$recordPidsForDeletedRecords[$table][$uid];
7801
        }
7802
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, '');
0 ignored issues
show
Bug introduced by
'' of type string is incompatible with the type integer expected by parameter $pid of TYPO3\CMS\Backend\Utilit...endUtility::getTSCpid(). ( Ignorable by Annotation )

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

7802
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, /** @scrutinizer ignore-type */ '');
Loading history...
7803
        return [$parentUid];
7804
    }
7805
7806
    /**
7807
     * Extract entries from TSconfig for a specific table. This will merge specific and default configuration together.
7808
     *
7809
     * @param string $table Table name
7810
     * @param array $TSconfig TSconfig for page
7811
     * @return array TSconfig merged
7812
     * @internal should only be used from within DataHandler
7813
     */
7814
    public function getTableEntries($table, $TSconfig)
7815
    {
7816
        $tA = is_array($TSconfig['table.'][$table . '.']) ? $TSconfig['table.'][$table . '.'] : [];
7817
        $dA = is_array($TSconfig['default.']) ? $TSconfig['default.'] : [];
7818
        ArrayUtility::mergeRecursiveWithOverrule($dA, $tA);
7819
        return $dA;
7820
    }
7821
7822
    /**
7823
     * Returns the pid of a record from $table with $uid
7824
     *
7825
     * @param string $table Table name
7826
     * @param int $uid Record uid
7827
     * @return int|false PID value (unless the record did not exist in which case FALSE is returned)
7828
     * @internal should only be used from within DataHandler
7829
     */
7830
    public function getPID($table, $uid)
7831
    {
7832
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7833
        $queryBuilder->getRestrictions()
7834
            ->removeAll();
7835
        $queryBuilder->select('pid')
7836
            ->from($table)
7837
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)));
7838
        if ($row = $queryBuilder->execute()->fetch()) {
7839
            return $row['pid'];
7840
        }
7841
        return false;
7842
    }
7843
7844
    /**
7845
     * Executing dbAnalysisStore
7846
     * This will save MM relations for new records but is executed after records are created because we need to know the ID of them
7847
     * @internal should only be used from within DataHandler
7848
     */
7849
    public function dbAnalysisStoreExec()
7850
    {
7851
        foreach ($this->dbAnalysisStore as $action) {
7852
            $id = BackendUtility::wsMapId($action[4], MathUtility::canBeInterpretedAsInteger($action[2]) ? $action[2] : $this->substNEWwithIDs[$action[2]]);
7853
            if ($id) {
7854
                $action[0]->writeMM($action[1], $id, $action[3]);
7855
            }
7856
        }
7857
    }
7858
7859
    /**
7860
     * Returns array, $CPtable, of pages under the $pid going down to $counter levels.
7861
     * Selecting ONLY pages which the user has read-access to!
7862
     *
7863
     * @param array $CPtable Accumulation of page uid=>pid pairs in branch of $pid
7864
     * @param int $pid Page ID for which to find subpages
7865
     * @param int $counter Number of levels to go down.
7866
     * @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!
7867
     * @return array Return array.
7868
     * @internal should only be used from within DataHandler
7869
     */
7870
    public function int_pageTreeInfo($CPtable, $pid, $counter, $rootID)
7871
    {
7872
        if ($counter) {
7873
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
7874
            $restrictions = $queryBuilder->getRestrictions()->removeAll();
7875
            $this->addDeleteRestriction($restrictions);
7876
            $queryBuilder
7877
                ->select('uid')
7878
                ->from('pages')
7879
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
7880
                ->orderBy('sorting', 'DESC');
7881
            if (!$this->admin) {
7882
                $queryBuilder->andWhere($this->BE_USER->getPagePermsClause(Permission::PAGE_SHOW));
7883
            }
7884
            if ((int)$this->BE_USER->workspace === 0) {
7885
                $queryBuilder->andWhere(
7886
                    $queryBuilder->expr()->eq('t3ver_wsid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
7887
                );
7888
            } else {
7889
                $queryBuilder->andWhere($queryBuilder->expr()->in(
7890
                    't3ver_wsid',
7891
                    $queryBuilder->createNamedParameter([0, $this->BE_USER->workspace], Connection::PARAM_INT_ARRAY)
7892
                ));
7893
            }
7894
            $result = $queryBuilder->execute();
7895
7896
            $pages = [];
7897
            while ($row = $result->fetch()) {
7898
                $pages[$row['uid']] = $row;
7899
            }
7900
7901
            // Resolve placeholders of workspace versions
7902
            if (!empty($pages) && (int)$this->BE_USER->workspace !== 0) {
7903
                $pages = array_reverse(
7904
                    $this->resolveVersionedRecords(
7905
                        'pages',
7906
                        'uid',
7907
                        'sorting',
7908
                        array_keys($pages)
7909
                    ),
7910
                    true
7911
                );
7912
            }
7913
7914
            foreach ($pages as $page) {
7915
                if ($page['uid'] != $rootID) {
7916
                    $CPtable[$page['uid']] = $pid;
7917
                    // If the uid is NOT the rootID of the copyaction and if we are supposed to walk further down
7918
                    if ($counter - 1) {
7919
                        $CPtable = $this->int_pageTreeInfo($CPtable, $page['uid'], $counter - 1, $rootID);
7920
                    }
7921
                }
7922
            }
7923
        }
7924
        return $CPtable;
7925
    }
7926
7927
    /**
7928
     * List of all tables (those administrators has access to = array_keys of $GLOBALS['TCA'])
7929
     *
7930
     * @return array Array of all TCA table names
7931
     * @internal should only be used from within DataHandler
7932
     */
7933
    public function compileAdminTables()
7934
    {
7935
        return array_keys($GLOBALS['TCA']);
7936
    }
7937
7938
    /**
7939
     * Checks if any uniqueInPid eval input fields are in the record and if so, they are re-written to be correct.
7940
     *
7941
     * @param string $table Table name
7942
     * @param int $uid Record UID
7943
     * @internal should only be used from within DataHandler
7944
     */
7945
    public function fixUniqueInPid($table, $uid)
7946
    {
7947
        if (empty($GLOBALS['TCA'][$table])) {
7948
            return;
7949
        }
7950
7951
        $curData = $this->recordInfo($table, $uid, '*');
7952
        $newData = [];
7953
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
7954
            if ($conf['config']['type'] === 'input' && (string)$curData[$field] !== '') {
7955
                $evalCodesArray = GeneralUtility::trimExplode(',', $conf['config']['eval'], true);
7956
                if (in_array('uniqueInPid', $evalCodesArray, true)) {
7957
                    $newV = $this->getUnique($table, $field, $curData[$field], $uid, $curData['pid']);
7958
                    if ((string)$newV !== (string)$curData[$field]) {
7959
                        $newData[$field] = $newV;
7960
                    }
7961
                }
7962
            }
7963
        }
7964
        // IF there are changed fields, then update the database
7965
        if (!empty($newData)) {
7966
            $this->updateDB($table, $uid, $newData);
7967
        }
7968
    }
7969
7970
    /**
7971
     * Checks if any uniqueInSite eval fields are in the record and if so, they are re-written to be correct.
7972
     *
7973
     * @param string $table Table name
7974
     * @param int $uid Record UID
7975
     * @return bool whether the record had to be fixed or not
7976
     */
7977
    protected function fixUniqueInSite(string $table, int $uid): bool
7978
    {
7979
        $curData = $this->recordInfo($table, $uid, '*');
7980
        $workspaceId = $this->BE_USER->workspace;
7981
        $newData = [];
7982
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
7983
            if ($conf['config']['type'] === 'slug' && (string)$curData[$field] !== '') {
7984
                $evalCodesArray = GeneralUtility::trimExplode(',', $conf['config']['eval'], true);
7985
                if (in_array('uniqueInSite', $evalCodesArray, true)) {
7986
                    $helper = GeneralUtility::makeInstance(SlugHelper::class, $table, $field, $conf['config'], $workspaceId);
7987
                    $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

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

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