Completed
Push — master ( 354375...a02530 )
by
unknown
39:01 queued 25:47
created

DataHandler::checkValue_checkMax()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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

1511
                    $propArr = $this->getRecordProperties($table, /** @scrutinizer ignore-type */ $id);
Loading history...
1512
                    $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

1512
                    $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...
1513
                }
1514
                return $res;
1515
            }
1516
            if ($status === 'update') {
1517
                // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1518
                $onlyAllowedTables = $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1519
                if ($onlyAllowedTables) {
1520
                    // use the real page id (default language)
1521
                    $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

1521
                    $recordId = $this->getDefaultLanguagePageId(/** @scrutinizer ignore-type */ $id);
Loading history...
1522
                    $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

1522
                    $theWrongTables = $this->doesPageHaveUnallowedTables($recordId, /** @scrutinizer ignore-type */ $value);
Loading history...
1523
                    if ($theWrongTables) {
1524
                        if ($this->enableLogging) {
1525
                            $propArr = $this->getRecordProperties($table, $id);
1526
                            $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']);
1527
                        }
1528
                        return $res;
1529
                    }
1530
                }
1531
            }
1532
        }
1533
1534
        $curValue = null;
1535
        if ((int)$id !== 0) {
1536
            // Get current value:
1537
            $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

1537
            $curValueRec = $this->recordInfo($table, /** @scrutinizer ignore-type */ $id, $field);
Loading history...
1538
            // isset() won't work here, since values can be NULL
1539
            if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1540
                $curValue = $curValueRec[$field];
1541
            }
1542
        }
1543
1544
        if ($table === 'be_users'
1545
            && ($field === 'admin' || $field === 'password')
1546
            && $status === 'update'
1547
        ) {
1548
            // Do not allow a non system maintainer admin to change admin flag and password of system maintainers
1549
            $systemMaintainers = array_map('intval', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? []);
1550
            // False if current user is not in system maintainer list or if switch to user mode is active
1551
            $isCurrentUserSystemMaintainer = $this->BE_USER->isSystemMaintainer();
1552
            $isTargetUserInSystemMaintainerList = in_array((int)$id, $systemMaintainers, true);
1553
            if ($field === 'admin') {
1554
                $isFieldChanged = (int)$curValueRec[$field] !== (int)$value;
1555
            } else {
1556
                $isFieldChanged = $curValueRec[$field] !== $value;
1557
            }
1558
            if (!$isCurrentUserSystemMaintainer && $isTargetUserInSystemMaintainerList && $isFieldChanged) {
1559
                $value = $curValueRec[$field];
1560
                $message = GeneralUtility::makeInstance(
1561
                    FlashMessage::class,
1562
                    $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.adminCanNotChangeSystemMaintainer'),
1563
                    '',
1564
                    FlashMessage::ERROR,
1565
                    true
1566
                );
1567
                $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1568
                $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
1569
            }
1570
        }
1571
1572
        // Getting config for the field
1573
        $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1574
1575
        // Create $recFID only for those types that need it
1576
        if ($tcaFieldConf['type'] === 'flex') {
1577
            $recFID = $table . ':' . $id . ':' . $field;
1578
        } else {
1579
            $recFID = null;
1580
        }
1581
1582
        // Perform processing:
1583
        $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

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

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

2777
                $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, /** @scrutinizer ignore-type */ $prep);
Loading history...
2778
                if ($oldRelations != $newRelations) {
2779
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2780
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2781
                } else {
2782
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2783
                    $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2784
                }
2785
            } else {
2786
                $this->dbAnalysisStore[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable];
2787
            }
2788
            $valueArray = $dbAnalysis->countItems();
2789
        } else {
2790
            $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

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

3207
        BackendUtility::workspaceOL($table, /** @scrutinizer ignore-type */ $row, -99, false);
Loading history...
3208
        $row = BackendUtility::purgeComputedPropertiesFromRecord($row);
3209
3210
        // Initializing:
3211
        $theNewID = StringUtility::getUniqueId('NEW');
3212
        $enableField = isset($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']) ? $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'] : '';
3213
        $headerField = $GLOBALS['TCA'][$table]['ctrl']['label'];
3214
        // Getting "copy-after" fields if applicable:
3215
        $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

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

3528
        $row = array_merge(/** @scrutinizer ignore-type */ $row, $overrideArray);
Loading history...
3529
        // Traverse ALL fields of the selected record:
3530
        foreach ($row as $field => $value) {
3531
            if (!in_array($field, $nonFields, true)) {
3532
                // Get TCA configuration for the field:
3533
                $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
3534
                if (is_array($conf)) {
3535
                    // Processing based on the TCA config field type (files, references, flexforms...)
3536
                    $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $pid, 0, $workspaceOptions);
3537
                }
3538
                // Add value to array.
3539
                $row[$field] = $value;
3540
            }
3541
        }
3542
        // Force versioning related fields:
3543
        $row['pid'] = $pid;
3544
        // Setting original UID:
3545
        if ($GLOBALS['TCA'][$table]['ctrl']['origUid']) {
3546
            $row[$GLOBALS['TCA'][$table]['ctrl']['origUid']] = $uid;
3547
        }
3548
        // Do the copy by internal function
3549
        $theNewSQLID = $this->insertNewCopyVersion($table, $row, $pid);
3550
        if ($theNewSQLID) {
3551
            $this->dbAnalysisStoreExec();
3552
            $this->dbAnalysisStore = [];
3553
            return $this->copyMappingArray[$table][$uid] = $theNewSQLID;
3554
        }
3555
        return null;
3556
    }
3557
3558
    /**
3559
     * Inserts a record in the database, passing TCA configuration values through checkValue() but otherwise does NOTHING and checks nothing regarding permissions.
3560
     * 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...
3561
     *
3562
     * @param string $table Table name
3563
     * @param array $fieldArray Field array to insert as a record
3564
     * @param int $realPid The value of PID field.  -1 is indication that we are creating a new version!
3565
     * @return int Returns the new ID of the record (if applicable)
3566
     */
3567
    public function insertNewCopyVersion($table, $fieldArray, $realPid)
3568
    {
3569
        $id = StringUtility::getUniqueId('NEW');
3570
        // $fieldArray is set as current record.
3571
        // 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...
3572
        $this->checkValue_currentRecord = $fieldArray;
3573
        // Makes sure that transformations aren't processed on the copy.
3574
        $backupDontProcessTransformations = $this->dontProcessTransformations;
3575
        $this->dontProcessTransformations = true;
3576
        // Traverse record and input-process each value:
3577
        foreach ($fieldArray as $field => $fieldValue) {
3578
            if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
3579
                // Evaluating the value.
3580
                $res = $this->checkValue($table, $field, $fieldValue, $id, 'new', $realPid, 0, $fieldArray);
3581
                if (isset($res['value'])) {
3582
                    $fieldArray[$field] = $res['value'];
3583
                }
3584
            }
3585
        }
3586
        // System fields being set:
3587
        if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
3588
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
3589
        }
3590
        if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
3591
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
3592
        }
3593
        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
3594
            $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
3595
        }
3596
        // Finally, insert record:
3597
        $this->insertDB($table, $id, $fieldArray, true);
3598
        // Resets dontProcessTransformations to the previous state.
3599
        $this->dontProcessTransformations = $backupDontProcessTransformations;
3600
        // Return new id:
3601
        return $this->substNEWwithIDs[$id];
3602
    }
3603
3604
    /**
3605
     * Processing/Preparing content for copyRecord() function
3606
     *
3607
     * @param string $table Table name
3608
     * @param int $uid Record uid
3609
     * @param string $field Field name being processed
3610
     * @param string $value Input value to be processed.
3611
     * @param array $row Record array
3612
     * @param array $conf TCA field configuration
3613
     * @param int $realDestPid Real page id (pid) the record is copied to
3614
     * @param int $language Language ID (from sys_language table) used in the duplicated record
3615
     * @param array $workspaceOptions Options to be forwarded if actions happen on a workspace currently
3616
     * @return array|string
3617
     * @internal
3618
     * @see copyRecord()
3619
     */
3620
    public function copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $realDestPid, $language = 0, array $workspaceOptions = [])
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::copyRecord_procBasedOnFieldType" is not in camel caps format
Loading history...
3621
    {
3622
        $inlineSubType = $this->getInlineFieldType($conf);
3623
        // Get the localization mode for the current (parent) record (keep|select):
3624
        // Register if there are references to take care of or MM is used on an inline field (no change to value):
3625
        if ($this->isReferenceField($conf) || $inlineSubType === 'mm') {
3626
            $value = $this->copyRecord_processManyToMany($table, $uid, $field, $value, $conf, $language);
3627
        } elseif ($inlineSubType !== false) {
3628
            $value = $this->copyRecord_processInline($table, $uid, $field, $value, $row, $conf, $realDestPid, $language, $workspaceOptions);
3629
        }
3630
        // 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())
3631
        if ($conf['type'] === 'flex') {
3632
            // Get current value array:
3633
            $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
3634
            $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
3635
                ['config' => $conf],
3636
                $table,
3637
                $field,
3638
                $row
3639
            );
3640
            $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
3641
            $currentValueArray = GeneralUtility::xml2array($value);
3642
            // Traversing the XML structure, processing files:
3643
            if (is_array($currentValueArray)) {
3644
                $currentValueArray['data'] = $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $uid, $field, $realDestPid], 'copyRecord_flexFormCallBack', $workspaceOptions);
3645
                // Setting value as an array! -> which means the input will be processed according to the 'flex' type when the new copy is created.
3646
                $value = $currentValueArray;
3647
            }
3648
        }
3649
        return $value;
3650
    }
3651
3652
    /**
3653
     * Processes the children of an MM relation field (select, group, inline) when the parent record is copied.
3654
     *
3655
     * @param string $table
3656
     * @param int $uid
3657
     * @param string $field
3658
     * @param mixed $value
3659
     * @param array $conf
3660
     * @param string $language
3661
     * @return mixed
3662
     */
3663
    protected function copyRecord_processManyToMany($table, $uid, $field, $value, $conf, $language)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::copyRecord_processManyToMany" is not in camel caps format
Loading history...
3664
    {
3665
        $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
3666
        $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
3667
        $mmTable = isset($conf['MM']) && $conf['MM'] ? $conf['MM'] : '';
3668
        $localizeForeignTable = isset($conf['foreign_table']) && BackendUtility::isTableLocalizable($conf['foreign_table']);
3669
        // Localize referenced records of select fields:
3670
        $localizingNonManyToManyFieldReferences = empty($mmTable) && $localizeForeignTable && isset($conf['localizeReferencesAtParentLocalization']) && $conf['localizeReferencesAtParentLocalization'];
3671
        /** @var RelationHandler $dbAnalysis */
3672
        $dbAnalysis = $this->createRelationHandlerInstance();
3673
        $dbAnalysis->start($value, $allowedTables, $mmTable, $uid, $table, $conf);
3674
        $purgeItems = false;
3675
        if ($language > 0 && $localizingNonManyToManyFieldReferences) {
3676
            foreach ($dbAnalysis->itemArray as $index => $item) {
3677
                // Since select fields can reference many records, check whether there's already a localization:
3678
                $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

3678
                $recordLocalization = BackendUtility::getRecordLocalization($item['table'], $item['id'], /** @scrutinizer ignore-type */ $language);
Loading history...
3679
                if ($recordLocalization) {
3680
                    $dbAnalysis->itemArray[$index]['id'] = $recordLocalization[0]['uid'];
3681
                } elseif ($this->isNestedElementCallRegistered($item['table'], $item['id'], 'localize-' . (string)$language) === false) {
3682
                    $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

3682
                    $dbAnalysis->itemArray[$index]['id'] = $this->localize($item['table'], $item['id'], /** @scrutinizer ignore-type */ $language);
Loading history...
3683
                }
3684
            }
3685
            $purgeItems = true;
3686
        }
3687
3688
        if ($purgeItems || $mmTable) {
3689
            $dbAnalysis->purgeItemArray();
3690
            $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

3690
            $value = implode(',', $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName));
Loading history...
3691
        }
3692
        // Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
3693
        if ($value) {
3694
            $this->registerDBList[$table][$uid][$field] = $value;
3695
        }
3696
3697
        return $value;
3698
    }
3699
3700
    /**
3701
     * Processes child records in an inline (IRRE) element when the parent record is copied.
3702
     *
3703
     * @param string $table
3704
     * @param int $uid
3705
     * @param string $field
3706
     * @param mixed $value
3707
     * @param array $row
3708
     * @param array $conf
3709
     * @param int $realDestPid
3710
     * @param string $language
3711
     * @param array $workspaceOptions
3712
     * @return string
3713
     */
3714
    protected function copyRecord_processInline(
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::copyRecord_processInline" is not in camel caps format
Loading history...
3715
        $table,
3716
        $uid,
3717
        $field,
3718
        $value,
3719
        $row,
3720
        $conf,
3721
        $realDestPid,
3722
        $language,
3723
        array $workspaceOptions
3724
    ) {
3725
        // Fetch the related child records using \TYPO3\CMS\Core\Database\RelationHandler
3726
        /** @var RelationHandler $dbAnalysis */
3727
        $dbAnalysis = $this->createRelationHandlerInstance();
3728
        $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
3729
        // Walk through the items, copy them and remember the new id:
3730
        foreach ($dbAnalysis->itemArray as $k => $v) {
3731
            $newId = null;
3732
            // If language is set and differs from original record, this isn't a copy action but a localization of our parent/ancestor:
3733
            if ($language > 0 && BackendUtility::isTableLocalizable($table) && $language != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
3734
                // Children should be localized when the parent gets localized the first time, just do it:
3735
                $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

3735
                $newId = $this->localize($v['table'], $v['id'], /** @scrutinizer ignore-type */ $language);
Loading history...
3736
            } else {
3737
                if (!MathUtility::canBeInterpretedAsInteger($realDestPid)) {
3738
                    $newId = $this->copyRecord($v['table'], $v['id'], -$v['id']);
3739
                // If the destination page id is a NEW string, keep it on the same page
3740
                } elseif ($this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($v['table'])) {
3741
                    // A filled $workspaceOptions indicated that this call
3742
                    // has it's origin in previous versionizeRecord() processing
3743
                    if (!empty($workspaceOptions)) {
3744
                        // Versions use live default id, thus the "new"
3745
                        // id is the original live default child record
3746
                        $newId = $v['id'];
3747
                        $this->versionizeRecord(
3748
                            $v['table'],
3749
                            $v['id'],
3750
                            $workspaceOptions['label'] ?? 'Auto-created for WS #' . $this->BE_USER->workspace,
3751
                            $workspaceOptions['delete'] ?? false
3752
                        );
3753
                    // Otherwise just use plain copyRecord() to create placeholders etc.
3754
                    } else {
3755
                        // If a record has been copied already during this request,
3756
                        // prevent superfluous duplication and use the existing copy
3757
                        if (isset($this->copyMappingArray[$v['table']][$v['id']])) {
3758
                            $newId = $this->copyMappingArray[$v['table']][$v['id']];
3759
                        } else {
3760
                            $newId = $this->copyRecord($v['table'], $v['id'], $realDestPid);
3761
                        }
3762
                    }
3763
                } else {
3764
                    // If a record has been copied already during this request,
3765
                    // prevent superfluous duplication and use the existing copy
3766
                    if (isset($this->copyMappingArray[$v['table']][$v['id']])) {
3767
                        $newId = $this->copyMappingArray[$v['table']][$v['id']];
3768
                    } else {
3769
                        $newId = $this->copyRecord_raw($v['table'], $v['id'], $realDestPid, [], $workspaceOptions);
3770
                    }
3771
                }
3772
            }
3773
            // If the current field is set on a page record, update the pid of related child records:
3774
            if ($table === 'pages') {
3775
                $this->registerDBPids[$v['table']][$v['id']] = $uid;
3776
            } elseif (isset($this->registerDBPids[$table][$uid])) {
3777
                $this->registerDBPids[$v['table']][$v['id']] = $this->registerDBPids[$table][$uid];
3778
            }
3779
            $dbAnalysis->itemArray[$k]['id'] = $newId;
3780
        }
3781
        // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
3782
        $value = implode(',', $dbAnalysis->getValueArray());
3783
        $this->registerDBList[$table][$uid][$field] = $value;
3784
3785
        return $value;
3786
    }
3787
3788
    /**
3789
     * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
3790
     *
3791
     * @param array $pParams Array of parameters in num-indexes: table, uid, field
3792
     * @param array $dsConf TCA field configuration (from Data Structure XML)
3793
     * @param string $dataValue The value of the flexForm field
3794
     * @param string $_1 Not used.
3795
     * @param string $_2 Not used.
3796
     * @param string $_3 Not used.
3797
     * @param array $workspaceOptions
3798
     * @return array Result array with key "value" containing the value of the processing.
3799
     * @see copyRecord()
3800
     * @see checkValue_flex_procInData_travDS()
3801
     */
3802
    public function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $_1, $_2, $_3, $workspaceOptions)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::copyRecord_flexFormCallBack" is not in camel caps format
Loading history...
3803
    {
3804
        // Extract parameters:
3805
        [$table, $uid, $field, $realDestPid] = $pParams;
3806
        // If references are set for this field, set flag so they can be corrected later (in ->remapListedDBRecords())
3807
        if (($this->isReferenceField($dsConf) || $this->getInlineFieldType($dsConf) !== false) && (string)$dataValue !== '') {
3808
            $dataValue = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $dataValue, [], $dsConf, $realDestPid, 0, $workspaceOptions);
3809
            $this->registerDBList[$table][$uid][$field] = 'FlexForm_reference';
3810
        }
3811
        // Return
3812
        return ['value' => $dataValue];
3813
    }
3814
3815
    /**
3816
     * Find l10n-overlay records and perform the requested copy action for these records.
3817
     *
3818
     * @param string $table Record Table
3819
     * @param string $uid UID of the record in the default language
3820
     * @param string $destPid Position to copy to
3821
     * @param bool $first
3822
     * @param array $overrideValues
3823
     * @param string $excludeFields
3824
     */
3825
    public function copyL10nOverlayRecords($table, $uid, $destPid, $first = false, $overrideValues = [], $excludeFields = '')
3826
    {
3827
        // There's no need to perform this for tables that are not localizable
3828
        if (!BackendUtility::isTableLocalizable($table)) {
3829
            return;
3830
        }
3831
3832
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3833
        $queryBuilder->getRestrictions()
3834
            ->removeAll()
3835
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
3836
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
3837
3838
        $queryBuilder->select('*')
3839
            ->from($table)
3840
            ->where(
3841
                $queryBuilder->expr()->eq(
3842
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
3843
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':pointer')
3844
                )
3845
            );
3846
3847
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
3848
            $queryBuilder->andWhere(
3849
                $queryBuilder->expr()->eq('t3ver_oid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
3850
            );
3851
        }
3852
        // If $destPid is < 0, get the pid of the record with uid equal to abs($destPid)
3853
        $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

3853
        $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

3853
        $tscPID = BackendUtility::getTSconfig_pidValue($table, $uid, /** @scrutinizer ignore-type */ $destPid);
Loading history...
3854
        // Get the localized records to be copied
3855
        $l10nRecords = $queryBuilder->execute()->fetchAll();
3856
        if (is_array($l10nRecords)) {
3857
            $localizedDestPids = [];
3858
            // If $destPid < 0, then it is the uid of the original language record we are inserting after
3859
            if ($destPid < 0) {
3860
                // Get the localized records of the record we are inserting after
3861
                $queryBuilder->setParameter('pointer', abs($destPid), \PDO::PARAM_INT);
3862
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
3863
                // Index the localized record uids by language
3864
                if (is_array($destL10nRecords)) {
3865
                    foreach ($destL10nRecords as $record) {
3866
                        $localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]] = -$record['uid'];
3867
                    }
3868
                }
3869
            }
3870
            $languageSourceMap = [
3871
                $uid => $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]
3872
            ];
3873
            // Copy the localized records after the corresponding localizations of the destination record
3874
            foreach ($l10nRecords as $record) {
3875
                $localizedDestPid = (int)$localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]];
3876
                if ($localizedDestPid < 0) {
3877
                    $newUid = $this->copyRecord($table, $record['uid'], $localizedDestPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
3878
                } else {
3879
                    $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

3879
                    $newUid = $this->copyRecord($table, $record['uid'], /** @scrutinizer ignore-type */ $destPid < 0 ? $tscPID : $destPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
Loading history...
3880
                }
3881
                $languageSourceMap[$record['uid']] = $newUid;
3882
            }
3883
            $this->copy_remapTranslationSourceField($table, $l10nRecords, $languageSourceMap);
3884
        }
3885
    }
3886
3887
    /**
3888
     * Remap languageSource field to uids of newly created records
3889
     *
3890
     * @param string $table Table name
3891
     * @param array $l10nRecords array of localized records from the page we're copying from (source records)
3892
     * @param array $languageSourceMap array mapping source records uids to newly copied uids
3893
     */
3894
    protected function copy_remapTranslationSourceField($table, $l10nRecords, $languageSourceMap)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::copy_remapTranslationSourceField" is not in camel caps format
Loading history...
3895
    {
3896
        if (empty($GLOBALS['TCA'][$table]['ctrl']['translationSource']) || empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])) {
3897
            return;
3898
        }
3899
        $translationSourceFieldName = $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
3900
        $translationParentFieldName = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
3901
3902
        //We can avoid running these update queries by sorting the $l10nRecords by languageSource dependency (in copyL10nOverlayRecords)
3903
        //and first copy records depending on default record (and map the field).
3904
        foreach ($l10nRecords as $record) {
3905
            $oldSourceUid = $record[$translationSourceFieldName];
3906
            if ($oldSourceUid <= 0 && $record[$translationParentFieldName] > 0) {
3907
                //BC fix - in connected mode 'translationSource' field should not be 0
3908
                $oldSourceUid = $record[$translationParentFieldName];
3909
            }
3910
            if ($oldSourceUid > 0) {
3911
                if (empty($languageSourceMap[$oldSourceUid])) {
3912
                    // we don't have mapping information available e.g when copyRecord returned null
3913
                    continue;
3914
                }
3915
                $newFieldValue = $languageSourceMap[$oldSourceUid];
3916
                $updateFields = [
3917
                    $translationSourceFieldName => $newFieldValue
3918
                ];
3919
                GeneralUtility::makeInstance(ConnectionPool::class)
3920
                    ->getConnectionForTable($table)
3921
                    ->update($table, $updateFields, ['uid' => (int)$languageSourceMap[$record['uid']]]);
3922
                if ($this->BE_USER->workspace > 0) {
3923
                    GeneralUtility::makeInstance(ConnectionPool::class)
3924
                        ->getConnectionForTable($table)
3925
                        ->update($table, $updateFields, ['t3ver_oid' => (int)$languageSourceMap[$record['uid']], 't3ver_wsid' => $this->BE_USER->workspace]);
3926
                }
3927
            }
3928
        }
3929
    }
3930
3931
    /*********************************************
3932
     *
3933
     * Cmd: Moving, Localizing
3934
     *
3935
     ********************************************/
3936
    /**
3937
     * Moving single records
3938
     *
3939
     * @param string $table Table name to move
3940
     * @param int $uid Record uid to move
3941
     * @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
3942
     */
3943
    public function moveRecord($table, $uid, $destPid)
3944
    {
3945
        if (!$GLOBALS['TCA'][$table]) {
3946
            return;
3947
        }
3948
3949
        // In case the record to be moved turns out to be an offline version,
3950
        // we have to find the live version and work on that one.
3951
        if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $uid, 'uid')) {
3952
            $uid = $lookForLiveVersion['uid'];
3953
        }
3954
        // Initialize:
3955
        $destPid = (int)$destPid;
3956
        // Get this before we change the pid (for logging)
3957
        $propArr = $this->getRecordProperties($table, $uid);
3958
        $moveRec = $this->getRecordProperties($table, $uid, true);
3959
        // This is the actual pid of the moving to destination
3960
        $resolvedPid = $this->resolvePid($table, $destPid);
3961
        // 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.
3962
        // If the record is a page, then there are two options: If the page is moved within itself,
3963
        // (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.
3964
        if ($table !== 'pages' || $resolvedPid == $moveRec['pid']) {
3965
            // Edit rights for the record...
3966
            $mayMoveAccess = $this->checkRecordUpdateAccess($table, $uid);
3967
        } else {
3968
            $mayMoveAccess = $this->doesRecordExist($table, $uid, Permission::PAGE_DELETE);
3969
        }
3970
        // Finding out, if the record may be moved TO another place. Here we check insert-rights (non-pages = edit, pages = new),
3971
        // unless the pages are moved on the same pid, then edit-rights are checked
3972
        if ($table !== 'pages' || $resolvedPid != $moveRec['pid']) {
3973
            // Insert rights for the record...
3974
            $mayInsertAccess = $this->checkRecordInsertAccess($table, $resolvedPid, SystemLogDatabaseAction::MOVE);
3975
        } else {
3976
            $mayInsertAccess = $this->checkRecordUpdateAccess($table, $uid);
3977
        }
3978
        // Checking if there is anything else disallowing moving the record by checking if editing is allowed
3979
        $fullLanguageCheckNeeded = $table !== 'pages';
3980
        $mayEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, false, false, $fullLanguageCheckNeeded);
3981
        // If moving is allowed, begin the processing:
3982
        if (!$mayEditAccess) {
3983
            $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']);
3984
            return;
3985
        }
3986
3987
        if (!$mayMoveAccess) {
3988
            $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']);
3989
            return;
3990
        }
3991
3992
        if (!$mayInsertAccess) {
3993
            $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']);
3994
            return;
3995
        }
3996
3997
        $recordWasMoved = false;
3998
        // Move the record via a hook, used e.g. for versioning
3999
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] ?? [] as $className) {
4000
            $hookObj = GeneralUtility::makeInstance($className);
4001
            if (method_exists($hookObj, 'moveRecord')) {
4002
                $hookObj->moveRecord($table, $uid, $destPid, $propArr, $moveRec, $resolvedPid, $recordWasMoved, $this);
4003
            }
4004
        }
4005
        // Move the record if a hook hasn't moved it yet
4006
        if (!$recordWasMoved) {
0 ignored issues
show
introduced by
The condition $recordWasMoved is always false.
Loading history...
4007
            $this->moveRecord_raw($table, $uid, $destPid);
4008
        }
4009
    }
4010
4011
    /**
4012
     * Moves a record without checking security of any sort.
4013
     * USE ONLY INTERNALLY
4014
     *
4015
     * @param string $table Table name to move
4016
     * @param int $uid Record uid to move
4017
     * @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
4018
     * @see moveRecord()
4019
     */
4020
    public function moveRecord_raw($table, $uid, $destPid)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::moveRecord_raw" is not in camel caps format
Loading history...
4021
    {
4022
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
4023
        $origDestPid = $destPid;
4024
        // This is the actual pid of the moving to destination
4025
        $resolvedPid = $this->resolvePid($table, $destPid);
4026
        // Checking if the pid is negative, but no sorting row is defined. In that case, find the correct pid. Basically this check make the error message 4-13 meaning less... But you can always remove this check if you prefer the error instead of a no-good action (which is to move the record to its own page...)
4027
        // $destPid>=0 because we must correct pid in case of versioning "page" types.
4028
        if (($destPid < 0 && !$sortColumn) || $destPid >= 0) {
4029
            $destPid = $resolvedPid;
4030
        }
4031
        // Get this before we change the pid (for logging)
4032
        $propArr = $this->getRecordProperties($table, $uid);
4033
        $moveRec = $this->getRecordProperties($table, $uid, true);
4034
        // Prepare user defined objects (if any) for hooks which extend this function:
4035
        $hookObjectsArr = [];
4036
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] ?? [] as $className) {
4037
            $hookObjectsArr[] = GeneralUtility::makeInstance($className);
4038
        }
4039
        // Timestamp field:
4040
        $updateFields = [];
4041
        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
4042
            $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
4043
        }
4044
4045
        // Check if this is a translation of a page, if so then it just needs to be kept "sorting" in sync
4046
        // Usually called from moveL10nOverlayRecords()
4047
        if ($table === 'pages') {
4048
            $defaultLanguagePageId = $this->getDefaultLanguagePageId((int)$uid);
4049
            if ($defaultLanguagePageId !== (int)$uid) {
4050
                $originalTranslationRecord = $this->recordInfo($table, $defaultLanguagePageId, 'pid,' . $sortColumn);
4051
                $updateFields[$sortColumn] = $originalTranslationRecord[$sortColumn];
4052
                // Ensure that the PID is always the same as the default language page
4053
                $destPid = $originalTranslationRecord['pid'];
4054
            }
4055
        }
4056
4057
        // Insert as first element on page (where uid = $destPid)
4058
        if ($destPid >= 0) {
4059
            if ($table !== 'pages' || $this->destNotInsideSelf($destPid, $uid)) {
4060
                // Clear cache before moving
4061
                [$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

4061
                [$parentUid] = BackendUtility::getTSCpid($table, $uid, /** @scrutinizer ignore-type */ '');
Loading history...
4062
                $this->registerRecordIdForPageCacheClearing($table, $uid, $parentUid);
4063
                // Setting PID
4064
                $updateFields['pid'] = $destPid;
4065
                // Table is sorted by 'sortby'
4066
                if ($sortColumn && !isset($updateFields[$sortColumn])) {
4067
                    $sortNumber = $this->getSortNumber($table, $uid, $destPid);
4068
                    $updateFields[$sortColumn] = $sortNumber;
4069
                }
4070
                // Check for child records that have also to be moved
4071
                $this->moveRecord_procFields($table, $uid, $destPid);
4072
                // Create query for update:
4073
                GeneralUtility::makeInstance(ConnectionPool::class)
4074
                    ->getConnectionForTable($table)
4075
                    ->update($table, $updateFields, ['uid' => (int)$uid]);
4076
                // Check for the localizations of that element
4077
                $this->moveL10nOverlayRecords($table, $uid, $destPid, $destPid);
4078
                // Call post processing hooks:
4079
                foreach ($hookObjectsArr as $hookObj) {
4080
                    if (method_exists($hookObj, 'moveRecord_firstElementPostProcess')) {
4081
                        $hookObj->moveRecord_firstElementPostProcess($table, $uid, $destPid, $moveRec, $updateFields, $this);
4082
                    }
4083
                }
4084
4085
                $this->getRecordHistoryStore()->moveRecord($table, $uid, ['oldPageId' => $propArr['pid'], 'newPageId' => $destPid, 'oldData' => $propArr, 'newData' => $updateFields], $this->correlationId);
4086
                if ($this->enableLogging) {
4087
                    // Logging...
4088
                    $oldpagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4089
                    if ($destPid != $propArr['pid']) {
4090
                        // Logged to old page
4091
                        $newPropArr = $this->getRecordProperties($table, $uid);
4092
                        $newpagePropArr = $this->getRecordProperties('pages', $destPid);
4093
                        $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']);
4094
                        // Logged to new page
4095
                        $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);
4096
                    } else {
4097
                        // Logged to new page
4098
                        $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);
4099
                    }
4100
                }
4101
                // Clear cache after moving
4102
                $this->registerRecordIdForPageCacheClearing($table, $uid);
4103
                $this->fixUniqueInPid($table, $uid);
4104
                $this->fixUniqueInSite($table, (int)$uid);
4105
                if ($table === 'pages') {
4106
                    $this->fixUniqueInSiteForSubpages((int)$uid);
4107
                }
4108
                // fixCopyAfterDuplFields
4109
                if ($origDestPid < 0) {
4110
                    $this->fixCopyAfterDuplFields($table, $uid, abs($origDestPid), 1);
0 ignored issues
show
Bug introduced by
It seems like abs($origDestPid) 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

4110
                    $this->fixCopyAfterDuplFields($table, $uid, /** @scrutinizer ignore-type */ abs($origDestPid), 1);
Loading history...
4111
                }
4112
            } elseif ($this->enableLogging) {
4113
                $destPropArr = $this->getRecordProperties('pages', $destPid);
4114
                $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']);
4115
            }
4116
        } elseif ($sortColumn) {
4117
            // Put after another record
4118
            // Table is being sorted
4119
            // Save the position to which the original record is requested to be moved
4120
            $originalRecordDestinationPid = $destPid;
4121
            $sortInfo = $this->getSortNumber($table, $uid, $destPid);
4122
            // Setting the destPid to the new pid of the record.
4123
            $destPid = $sortInfo['pid'];
4124
            // If not an array, there was an error (which is already logged)
4125
            if (is_array($sortInfo)) {
4126
                if ($table !== 'pages' || $this->destNotInsideSelf($destPid, $uid)) {
4127
                    // clear cache before moving
4128
                    $this->registerRecordIdForPageCacheClearing($table, $uid);
4129
                    // We now update the pid and sortnumber (if not set for page translations)
4130
                    $updateFields['pid'] = $destPid;
4131
                    if (!isset($updateFields[$sortColumn])) {
4132
                        $updateFields[$sortColumn] = $sortInfo['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, $originalRecordDestinationPid);
4142
                    // Call post processing hooks:
4143
                    foreach ($hookObjectsArr as $hookObj) {
4144
                        if (method_exists($hookObj, 'moveRecord_afterAnotherElementPostProcess')) {
4145
                            $hookObj->moveRecord_afterAnotherElementPostProcess($table, $uid, $destPid, $origDestPid, $moveRec, $updateFields, $this);
4146
                        }
4147
                    }
4148
                    $this->getRecordHistoryStore()->moveRecord($table, $uid, ['oldPageId' => $propArr['pid'], 'newPageId' => $destPid, 'oldData' => $propArr, 'newData' => $updateFields], $this->correlationId);
4149
                    if ($this->enableLogging) {
4150
                        // Logging...
4151
                        $oldpagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4152
                        if ($destPid != $propArr['pid']) {
4153
                            // Logged to old page
4154
                            $newPropArr = $this->getRecordProperties($table, $uid);
4155
                            $newpagePropArr = $this->getRecordProperties('pages', $destPid);
4156
                            $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']);
4157
                            // Logged to old page
4158
                            $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);
4159
                        } else {
4160
                            // Logged to old page
4161
                            $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);
4162
                        }
4163
                    }
4164
                    // Clear cache after moving
4165
                    $this->registerRecordIdForPageCacheClearing($table, $uid);
4166
                    $this->fixUniqueInPid($table, $uid);
4167
                    $this->fixUniqueInSite($table, (int)$uid);
4168
                    if ($table === 'pages') {
4169
                        $this->fixUniqueInSiteForSubpages((int)$uid);
4170
                    }
4171
                    // fixCopyAfterDuplFields
4172
                    if ($origDestPid < 0) {
4173
                        $this->fixCopyAfterDuplFields($table, $uid, abs($origDestPid), 1);
4174
                    }
4175
                } elseif ($this->enableLogging) {
4176
                    $destPropArr = $this->getRecordProperties('pages', $destPid);
4177
                    $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']);
4178
                }
4179
            } else {
4180
                $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']);
4181
            }
4182
        }
4183
    }
4184
4185
    /**
4186
     * Walk through all fields of the moved record and look for children of e.g. the inline type.
4187
     * If child records are found, they are also move to the new $destPid.
4188
     *
4189
     * @param string $table Record Table
4190
     * @param int $uid Record UID
4191
     * @param int $destPid Position to move to
4192
     */
4193
    public function moveRecord_procFields($table, $uid, $destPid)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::moveRecord_procFields" is not in camel caps format
Loading history...
4194
    {
4195
        $row = BackendUtility::getRecordWSOL($table, $uid);
4196
        if (is_array($row) && (int)$destPid !== (int)$row['pid']) {
4197
            $conf = $GLOBALS['TCA'][$table]['columns'];
4198
            foreach ($row as $field => $value) {
4199
                $this->moveRecord_procBasedOnFieldType($table, $uid, $destPid, $field, $value, $conf[$field]['config']);
4200
            }
4201
        }
4202
    }
4203
4204
    /**
4205
     * Move child records depending on the field type of the parent record.
4206
     *
4207
     * @param string $table Record Table
4208
     * @param string $uid Record UID
4209
     * @param string $destPid Position to move to
4210
     * @param string $field Record field
4211
     * @param string $value Record field value
4212
     * @param array $conf TCA configuration of current field
4213
     */
4214
    public function moveRecord_procBasedOnFieldType($table, $uid, $destPid, $field, $value, $conf)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::moveRecord_procBasedOnFieldType" is not in camel caps format
Loading history...
4215
    {
4216
        $dbAnalysis = null;
4217
        if ($conf['type'] === 'inline') {
4218
            $foreign_table = $conf['foreign_table'];
4219
            $moveChildrenWithParent = !isset($conf['behaviour']['disableMovingChildrenWithParent']) || !$conf['behaviour']['disableMovingChildrenWithParent'];
4220
            if ($foreign_table && $moveChildrenWithParent) {
4221
                $inlineType = $this->getInlineFieldType($conf);
4222
                if ($inlineType === 'list' || $inlineType === 'field') {
4223
                    if ($table === 'pages') {
4224
                        // If the inline elements are related to a page record,
4225
                        // make sure they reside at that page and not at its parent
4226
                        $destPid = $uid;
4227
                    }
4228
                    $dbAnalysis = $this->createRelationHandlerInstance();
4229
                    $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

4229
                    $dbAnalysis->start($value, $conf['foreign_table'], '', /** @scrutinizer ignore-type */ $uid, $table, $conf);
Loading history...
4230
                }
4231
            }
4232
        }
4233
        // Move the records
4234
        if (isset($dbAnalysis)) {
4235
            // Moving records to a positive destination will insert each
4236
            // record at the beginning, thus the order is reversed here:
4237
            foreach (array_reverse($dbAnalysis->itemArray) as $v) {
4238
                $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

4238
                $this->moveRecord($v['table'], $v['id'], /** @scrutinizer ignore-type */ $destPid);
Loading history...
4239
            }
4240
        }
4241
    }
4242
4243
    /**
4244
     * Find l10n-overlay records and perform the requested move action for these records.
4245
     *
4246
     * @param string $table Record Table
4247
     * @param string $uid Record UID
4248
     * @param string $destPid Position to move to
4249
     * @param string $originalRecordDestinationPid Position to move the original record to
4250
     */
4251
    public function moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid)
4252
    {
4253
        // There's no need to perform this for non-localizable tables
4254
        if (!BackendUtility::isTableLocalizable($table)) {
4255
            return;
4256
        }
4257
4258
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
4259
        $queryBuilder->getRestrictions()
4260
            ->removeAll()
4261
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
4262
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
4263
4264
        $queryBuilder->select('*')
4265
            ->from($table)
4266
            ->where(
4267
                $queryBuilder->expr()->eq(
4268
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
4269
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':pointer')
4270
                )
4271
            );
4272
4273
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
4274
            $queryBuilder->andWhere(
4275
                $queryBuilder->expr()->eq('t3ver_oid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
4276
            );
4277
        }
4278
4279
        $l10nRecords = $queryBuilder->execute()->fetchAll();
4280
        if (is_array($l10nRecords)) {
4281
            $localizedDestPids = [];
4282
            // If $$originalRecordDestinationPid < 0, then it is the uid of the original language record we are inserting after
4283
            if ($originalRecordDestinationPid < 0) {
4284
                // Get the localized records of the record we are inserting after
4285
                $queryBuilder->setParameter('pointer', abs($originalRecordDestinationPid), \PDO::PARAM_INT);
4286
                $destL10nRecords = $queryBuilder->execute()->fetchAll();
4287
                // Index the localized record uids by language
4288
                if (is_array($destL10nRecords)) {
4289
                    foreach ($destL10nRecords as $record) {
4290
                        $localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]] = -$record['uid'];
4291
                    }
4292
                }
4293
            }
4294
            // Move the localized records after the corresponding localizations of the destination record
4295
            foreach ($l10nRecords as $record) {
4296
                $localizedDestPid = (int)$localizedDestPids[$record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]];
4297
                if ($localizedDestPid < 0) {
4298
                    $this->moveRecord($table, $record['uid'], $localizedDestPid);
4299
                } else {
4300
                    $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

4300
                    $this->moveRecord($table, $record['uid'], /** @scrutinizer ignore-type */ $destPid);
Loading history...
4301
                }
4302
            }
4303
        }
4304
    }
4305
4306
    /**
4307
     * Localizes a record to another system language
4308
     *
4309
     * @param string $table Table name
4310
     * @param int $uid Record uid (to be localized)
4311
     * @param int $language Language ID (from sys_language table)
4312
     * @return int|bool The uid (int) of the new translated record or FALSE (bool) if something went wrong
4313
     */
4314
    public function localize($table, $uid, $language)
4315
    {
4316
        $newId = false;
4317
        $uid = (int)$uid;
4318
        if (!$GLOBALS['TCA'][$table] || !$uid || $this->isNestedElementCallRegistered($table, $uid, 'localize-' . (string)$language) !== false) {
4319
            return false;
4320
        }
4321
4322
        $this->registerNestedElementCall($table, $uid, 'localize-' . (string)$language);
4323
        if (!$GLOBALS['TCA'][$table]['ctrl']['languageField'] || !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
4324
            $this->newlog('Localization failed; "languageField" and "transOrigPointerField" must be defined for the table ' . $table, SystemLogErrorClassification::USER_ERROR);
4325
            return false;
4326
        }
4327
        $langRec = BackendUtility::getRecord('sys_language', (int)$language, 'uid,title');
4328
        if (!$langRec) {
4329
            $this->newlog('Sys language UID "' . $language . '" not found valid!', SystemLogErrorClassification::USER_ERROR);
4330
            return false;
4331
        }
4332
4333
        if (!$this->doesRecordExist($table, $uid, Permission::PAGE_SHOW)) {
4334
            $this->newlog('Attempt to localize record ' . $table . ':' . $uid . ' without permission.', SystemLogErrorClassification::USER_ERROR);
4335
            return false;
4336
        }
4337
4338
        // Getting workspace overlay if possible - this will localize versions in workspace if any
4339
        $row = BackendUtility::getRecordWSOL($table, $uid);
4340
        if (!is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
4341
            $this->newlog('Attempt to localize record ' . $table . ':' . $uid . ' that did not exist!', SystemLogErrorClassification::USER_ERROR);
4342
            return false;
4343
        }
4344
4345
        // Make sure that records which are translated from another language than the default language have a correct
4346
        // localization source set themselves, before translating them to another language.
4347
        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] !== 0
4348
            && $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
4349
            $localizationParentRecord = BackendUtility::getRecord(
4350
                $table,
4351
                $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]
4352
            );
4353
            if ((int)$localizationParentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] !== 0) {
4354
                $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);
4355
                return false;
4356
            }
4357
        }
4358
4359
        // Default language records must never have a localization parent as they are the origin of any translation.
4360
        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] !== 0
4361
            && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
4362
            $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);
4363
            return false;
4364
        }
4365
4366
        $recordLocalizations = BackendUtility::getRecordLocalization($table, $uid, $language, 'AND pid=' . (int)$row['pid']);
4367
4368
        if (!empty($recordLocalizations)) {
4369
            $this->newlog(sprintf(
4370
                'Localization failed: there already are localizations (%s) for language %d of the "%s" record %d!',
4371
                implode(', ', array_column($recordLocalizations, 'uid')),
4372
                $language,
4373
                $table,
4374
                $uid
4375
            ), 1);
4376
            return false;
4377
        }
4378
4379
        // Initialize:
4380
        $overrideValues = [];
4381
        // Set override values:
4382
        $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $langRec['uid'];
4383
        // If the translated record is a default language record, set it's uid as localization parent of the new record.
4384
        // If translating from any other language, no override is needed; we just can copy the localization parent of
4385
        // the original record (which is pointing to the correspondent default language record) to the new record.
4386
        // In copy / free mode the TransOrigPointer field is always set to 0, as no connection to the localization parent is wanted in that case.
4387
        // For pages, there is no "copy/free mode".
4388
        if (($this->useTransOrigPointerField || $table === 'pages') && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
4389
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $uid;
4390
        } elseif (!$this->useTransOrigPointerField) {
4391
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = 0;
4392
        }
4393
        if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
4394
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['translationSource']] = $uid;
4395
        }
4396
        // Copy the type (if defined in both tables) from the original record so that translation has same type as original record
4397
        if (isset($GLOBALS['TCA'][$table]['ctrl']['type'])) {
4398
            $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['type']] = $row[$GLOBALS['TCA'][$table]['ctrl']['type']];
4399
        }
4400
        // Set exclude Fields:
4401
        foreach ($GLOBALS['TCA'][$table]['columns'] as $fN => $fCfg) {
4402
            $translateToMsg = '';
4403
            // Check if we are just prefixing:
4404
            if ($fCfg['l10n_mode'] === 'prefixLangTitle') {
4405
                if (($fCfg['config']['type'] === 'text' || $fCfg['config']['type'] === 'input') && (string)$row[$fN] !== '') {
4406
                    [$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

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

4755
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, /** @scrutinizer ignore-type */ '');
Loading history...
4756
        $this->registerRecordIdForPageCacheClearing($table, $uid, $parentUid);
4757
        $deleteField = $GLOBALS['TCA'][$table]['ctrl']['delete'];
4758
        $databaseErrorMessage = '';
4759
        if ($deleteField && !$forceHardDelete) {
4760
            $updateFields = [
4761
                $deleteField => $undeleteRecord ? 0 : 1
4762
            ];
4763
            if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
4764
                $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
4765
            }
4766
            // before (un-)deleting this record, check for child records or references
4767
            $this->deleteRecord_procFields($table, $uid, $undeleteRecord);
4768
            try {
4769
                GeneralUtility::makeInstance(ConnectionPool::class)
4770
                    ->getConnectionForTable($table)
4771
                    ->update($table, $updateFields, ['uid' => (int)$uid]);
4772
                // Delete all l10n records as well, impossible during undelete because it might bring too many records back to life
4773
                if (!$undeleteRecord) {
4774
                    $this->deletedRecords[$table][] = (int)$uid;
4775
                    $this->deleteL10nOverlayRecords($table, $uid);
4776
                }
4777
            } catch (DBALException $e) {
4778
                $databaseErrorMessage = $e->getPrevious()->getMessage();
4779
            }
4780
        } else {
4781
            // Delete the hard way...:
4782
            try {
4783
                GeneralUtility::makeInstance(ConnectionPool::class)
4784
                    ->getConnectionForTable($table)
4785
                    ->delete($table, ['uid' => (int)$uid]);
4786
                $this->deletedRecords[$table][] = (int)$uid;
4787
                $this->deleteL10nOverlayRecords($table, $uid);
4788
            } catch (DBALException $e) {
4789
                $databaseErrorMessage = $e->getPrevious()->getMessage();
4790
            }
4791
        }
4792
        if ($this->enableLogging) {
4793
            $state = $undeleteRecord ? SystemLogDatabaseAction::INSERT : SystemLogDatabaseAction::DELETE;
4794
            if ($databaseErrorMessage === '') {
4795
                if ($forceHardDelete) {
4796
                    $message = 'Record \'%s\' (%s) was deleted unrecoverable from page \'%s\' (%s)';
4797
                } else {
4798
                    $message = $state === 1 ? 'Record \'%s\' (%s) was restored on page \'%s\' (%s)' : 'Record \'%s\' (%s) was deleted from page \'%s\' (%s)';
4799
                }
4800
                $propArr = $this->getRecordProperties($table, $uid);
4801
                $pagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
4802
4803
                $this->log($table, $uid, $state, 0, SystemLogErrorClassification::MESSAGE, $message, 0, [
4804
                    $propArr['header'],
4805
                    $table . ':' . $uid,
4806
                    $pagePropArr['header'],
4807
                    $propArr['pid']
4808
                ], $propArr['event_pid']);
4809
            } else {
4810
                $this->log($table, $uid, $state, 0, SystemLogErrorClassification::TODAYS_SPECIAL, $databaseErrorMessage);
4811
            }
4812
        }
4813
4814
        // Add history entry
4815
        if ($undeleteRecord) {
4816
            $this->getRecordHistoryStore()->undeleteRecord($table, $uid, $this->correlationId);
4817
        } else {
4818
            $this->getRecordHistoryStore()->deleteRecord($table, $uid, $this->correlationId);
4819
        }
4820
4821
        // Update reference index:
4822
        $this->updateRefIndex($table, $uid);
4823
4824
        // We track calls to update the reference index as to avoid calling it twice
4825
        // with the same arguments. This is done because reference indexing is quite
4826
        // costly and the update reference index stack usually contain duplicates.
4827
        // NB: also filled and checked in loop below. The initialisation prevents
4828
        // running the "root" record twice if it appears in the stack twice.
4829
        $updateReferenceIndexCalls = [[$table, $uid]];
4830
4831
        // If there are entries in the updateRefIndexStack
4832
        if (is_array($this->updateRefIndexStack[$table]) && is_array($this->updateRefIndexStack[$table][$uid])) {
4833
            while ($args = array_pop($this->updateRefIndexStack[$table][$uid])) {
4834
                if (!in_array($args, $updateReferenceIndexCalls, true)) {
4835
                    // $args[0]: table, $args[1]: uid
4836
                    $this->updateRefIndex($args[0], $args[1]);
4837
                    $updateReferenceIndexCalls[] = $args;
4838
                }
4839
            }
4840
            unset($this->updateRefIndexStack[$table][$uid]);
4841
        }
4842
    }
4843
4844
    /**
4845
     * Used to delete page because it will check for branch below pages and disallowed tables on the page as well.
4846
     *
4847
     * @param int $uid Page id
4848
     * @param bool $force If TRUE, pages are not checked for permission.
4849
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4850
     */
4851
    public function deletePages($uid, $force = false, $forceHardDelete = false)
4852
    {
4853
        $uid = (int)$uid;
4854
        if ($uid === 0) {
4855
            if ($this->enableLogging) {
4856
                $this->log('pages', $uid, SystemLogGenericAction::UNDEFINED, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'Deleting all pages starting from the root-page is disabled.', -1, [], 0);
4857
            }
4858
            return;
4859
        }
4860
        // Getting list of pages to delete:
4861
        if ($force) {
4862
            // Returns the branch WITHOUT permission checks (0 secures that), so it cannot return -1
4863
            $pageIdsInBranch = $this->doesBranchExist('', $uid, 0, true);
4864
            $res = GeneralUtility::intExplode(',', $pageIdsInBranch . $uid, true);
4865
        } else {
4866
            $res = $this->canDeletePage($uid);
4867
        }
4868
        // Perform deletion if not error:
4869
        if (is_array($res)) {
4870
            foreach ($res as $deleteId) {
4871
                $this->deleteSpecificPage($deleteId, $forceHardDelete);
4872
            }
4873
        } else {
4874
            /** @var FlashMessage $flashMessage */
4875
            $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $res, '', FlashMessage::ERROR, true);
4876
            /** @var FlashMessageService $flashMessageService */
4877
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
4878
            $flashMessageService->getMessageQueueByIdentifier()->addMessage($flashMessage);
4879
            $this->newlog($res, SystemLogErrorClassification::USER_ERROR);
4880
        }
4881
    }
4882
4883
    /**
4884
     * Delete a page and all records on it.
4885
     *
4886
     * @param int $uid Page id
4887
     * @param bool $forceHardDelete If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
4888
     * @internal
4889
     * @see deletePages()
4890
     */
4891
    public function deleteSpecificPage($uid, $forceHardDelete = false)
4892
    {
4893
        $uid = (int)$uid;
4894
        if ($uid) {
4895
            $tableNames = $this->compileAdminTables();
4896
            foreach ($tableNames as $table) {
4897
                if ($table !== 'pages') {
4898
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
4899
                        ->getQueryBuilderForTable($table);
4900
4901
                    $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
4902
4903
                    $statement = $queryBuilder
4904
                        ->select('uid')
4905
                        ->from($table)
4906
                        ->where($queryBuilder->expr()->eq(
4907
                            'pid',
4908
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
4909
                        ))
4910
                        ->execute();
4911
4912
                    while ($row = $statement->fetch()) {
4913
                        $this->copyMovedRecordToNewLocation($table, $row['uid']);
4914
                        $this->deleteVersionsForRecord($table, $row['uid'], $forceHardDelete);
4915
                        $this->deleteRecord($table, $row['uid'], true, $forceHardDelete);
4916
                    }
4917
                }
4918
            }
4919
            $this->copyMovedRecordToNewLocation('pages', $uid);
4920
            $this->deleteVersionsForRecord('pages', $uid, $forceHardDelete);
4921
            $this->deleteRecord('pages', $uid, true, $forceHardDelete);
4922
        }
4923
    }
4924
4925
    /**
4926
     * Copies the move placeholder of a record to its new location (pid).
4927
     * This will create a "new" placeholder at the new location and
4928
     * a version for this new placeholder. The original move placeholder
4929
     * is then deleted because it is not needed anymore.
4930
     *
4931
     * This method is used to assure that moved records are not deleted
4932
     * when the origin page is deleted.
4933
     *
4934
     * @param string $table Record table
4935
     * @param int $uid Record uid
4936
     */
4937
    protected function copyMovedRecordToNewLocation($table, $uid)
4938
    {
4939
        if ($this->BE_USER->workspace > 0) {
4940
            $originalRecord = BackendUtility::getRecord($table, $uid);
4941
            $movePlaceholder = BackendUtility::getMovePlaceholder($table, $uid);
4942
            // Check whether target page to copied to is different to current page
4943
            // Cloning on the same page is superfluous and does not help at all
4944
            if (!empty($originalRecord) && !empty($movePlaceholder) && (int)$originalRecord['pid'] !== (int)$movePlaceholder['pid']) {
4945
                // If move placeholder exists, copy to new location
4946
                // This will create a New placeholder on the new location
4947
                // and a version for this new placeholder
4948
                $command = [
4949
                    $table => [
4950
                        $uid => [
4951
                            'copy' => '-' . $movePlaceholder['uid']
4952
                        ]
4953
                    ]
4954
                ];
4955
                /** @var DataHandler $dataHandler */
4956
                $dataHandler = GeneralUtility::makeInstance(__CLASS__);
4957
                $dataHandler->enableLogging = $this->enableLogging;
4958
                $dataHandler->neverHideAtCopy = true;
4959
                $dataHandler->start([], $command, $this->BE_USER);
4960
                $dataHandler->process_cmdmap();
4961
                unset($dataHandler);
4962
4963
                // Delete move placeholder
4964
                $this->deleteRecord($table, $movePlaceholder['uid'], true, true);
4965
            }
4966
        }
4967
    }
4968
4969
    /**
4970
     * Used to evaluate if a page can be deleted
4971
     *
4972
     * @param int $uid Page id
4973
     * @return int[]|string If array: List of page uids to traverse and delete (means OK), if string: error message.
4974
     */
4975
    public function canDeletePage($uid)
4976
    {
4977
        $uid = (int)$uid;
4978
        $isTranslatedPage = null;
4979
4980
        // If we may at all delete this page
4981
        // If this is a page translation, do the check against the perms_* of the default page
4982
        // Because it is currently only deleting the translation
4983
        $defaultLanguagePageId = $this->getDefaultLanguagePageId($uid);
4984
        if ($defaultLanguagePageId !== $uid) {
4985
            if ($this->doesRecordExist('pages', (int)$defaultLanguagePageId, Permission::PAGE_DELETE)) {
4986
                $isTranslatedPage = true;
4987
            } else {
4988
                return 'Attempt to delete page without permissions';
4989
            }
4990
        } elseif (!$this->doesRecordExist('pages', $uid, Permission::PAGE_DELETE)) {
4991
            return 'Attempt to delete page without permissions';
4992
        }
4993
4994
        $pageIdsInBranch = $this->doesBranchExist('', $uid, Permission::PAGE_DELETE, true);
4995
4996
        if ($this->deleteTree) {
4997
            if ($pageIdsInBranch === -1) {
4998
                return 'Attempt to delete pages in branch without permissions';
4999
            }
5000
5001
            $pagesInBranch = GeneralUtility::intExplode(',', $pageIdsInBranch . $uid, true);
5002
        } else {
5003
            if ($pageIdsInBranch === -1) {
5004
                return 'Attempt to delete page without permissions';
5005
            }
5006
            if ($pageIdsInBranch !== '') {
5007
                return 'Attempt to delete page which has subpages';
5008
            }
5009
5010
            $pagesInBranch = [$uid];
5011
        }
5012
5013
        if (!$this->checkForRecordsFromDisallowedTables($pagesInBranch)) {
5014
            return 'Attempt to delete records from disallowed tables';
5015
        }
5016
5017
        foreach ($pagesInBranch as $pageInBranch) {
5018
            if (!$this->BE_USER->recordEditAccessInternals('pages', $pageInBranch, false, false, $isTranslatedPage ? false : true)) {
5019
                return 'Attempt to delete page which has prohibited localizations.';
5020
            }
5021
        }
5022
        return $pagesInBranch;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $pagesInBranch returns an array which contains values of type string which are incompatible with the documented value type integer.
Loading history...
5023
    }
5024
5025
    /**
5026
     * Returns TRUE if record CANNOT be deleted, otherwise FALSE. Used to check before the versioning API allows a record to be marked for deletion.
5027
     *
5028
     * @param string $table Record Table
5029
     * @param int $id Record UID
5030
     * @return string Returns a string IF there is an error (error string explaining). FALSE means record can be deleted
5031
     */
5032
    public function cannotDeleteRecord($table, $id)
5033
    {
5034
        if ($table === 'pages') {
5035
            $res = $this->canDeletePage($id);
5036
            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...
5037
        }
5038
        return $this->doesRecordExist($table, $id, Permission::PAGE_DELETE) ? 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...
5039
    }
5040
5041
    /**
5042
     * Determines whether a record can be undeleted.
5043
     *
5044
     * @param string $table Table name of the record
5045
     * @param int $uid uid of the record
5046
     * @return bool Whether the record can be undeleted
5047
     */
5048
    public function isRecordUndeletable($table, $uid)
5049
    {
5050
        $result = false;
5051
        $record = BackendUtility::getRecord($table, $uid, 'pid', '', false);
5052
        if ($record['pid']) {
5053
            $page = BackendUtility::getRecord('pages', $record['pid'], 'deleted, title, uid', '', false);
5054
            // The page containing the record is not deleted, thus the record can be undeleted:
5055
            if (!$page['deleted']) {
5056
                $result = true;
5057
            } else {
5058
                $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

5058
                $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...
5059
            }
5060
        } else {
5061
            // The page containing the record is on rootlevel, so there is no parent record to check, and the record can be undeleted:
5062
            $result = true;
5063
        }
5064
        return $result;
5065
    }
5066
5067
    /**
5068
     * Before a record is deleted, check if it has references such as inline type or MM references.
5069
     * If so, set these child records also to be deleted.
5070
     *
5071
     * @param string $table Record Table
5072
     * @param string $uid Record UID
5073
     * @param bool $undeleteRecord If a record should be undeleted (e.g. from history/undo)
5074
     * @see deleteRecord()
5075
     */
5076
    public function deleteRecord_procFields($table, $uid, $undeleteRecord = false)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::deleteRecord_procFields" is not in camel caps format
Loading history...
5077
    {
5078
        $conf = $GLOBALS['TCA'][$table]['columns'];
5079
        $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

5079
        $row = BackendUtility::getRecord($table, /** @scrutinizer ignore-type */ $uid, '*', '', false);
Loading history...
5080
        if (empty($row)) {
5081
            return;
5082
        }
5083
        foreach ($row as $field => $value) {
5084
            $this->deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf[$field]['config'], $undeleteRecord);
5085
        }
5086
    }
5087
5088
    /**
5089
     * Process fields of a record to be deleted and search for special handling, like
5090
     * inline type, MM records, etc.
5091
     *
5092
     * @param string $table Record Table
5093
     * @param string $uid Record UID
5094
     * @param string $field Record field
5095
     * @param string $value Record field value
5096
     * @param array $conf TCA configuration of current field
5097
     * @param bool $undeleteRecord If a record should be undeleted (e.g. from history/undo)
5098
     * @see deleteRecord()
5099
     */
5100
    public function deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf, $undeleteRecord = false)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::deleteRecord_procBasedOnFieldType" is not in camel caps format
Loading history...
5101
    {
5102
        if ($conf['type'] === 'inline') {
5103
            $foreign_table = $conf['foreign_table'];
5104
            if ($foreign_table) {
5105
                $inlineType = $this->getInlineFieldType($conf);
5106
                if ($inlineType === 'list' || $inlineType === 'field') {
5107
                    /** @var RelationHandler $dbAnalysis */
5108
                    $dbAnalysis = $this->createRelationHandlerInstance();
5109
                    $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

5109
                    $dbAnalysis->start($value, $conf['foreign_table'], '', /** @scrutinizer ignore-type */ $uid, $table, $conf);
Loading history...
5110
                    $dbAnalysis->undeleteRecord = true;
5111
5112
                    $enableCascadingDelete = true;
5113
                    // non type save comparison is intended!
5114
                    if (isset($conf['behaviour']['enableCascadingDelete']) && $conf['behaviour']['enableCascadingDelete'] == false) {
5115
                        $enableCascadingDelete = false;
5116
                    }
5117
5118
                    // Walk through the items and remove them
5119
                    foreach ($dbAnalysis->itemArray as $v) {
5120
                        if (!$undeleteRecord) {
5121
                            if ($enableCascadingDelete) {
5122
                                $this->deleteAction($v['table'], $v['id']);
5123
                            }
5124
                        } else {
5125
                            $this->undeleteRecord($v['table'], $v['id']);
5126
                        }
5127
                    }
5128
                }
5129
            }
5130
        } elseif ($this->isReferenceField($conf)) {
5131
            $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5132
            $dbAnalysis = $this->createRelationHandlerInstance();
5133
            $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
5134
            foreach ($dbAnalysis->itemArray as $v) {
5135
                $this->updateRefIndexStack[$table][$uid][] = [$v['table'], $v['id']];
5136
            }
5137
        }
5138
    }
5139
5140
    /**
5141
     * Find l10n-overlay records and perform the requested delete action for these records.
5142
     *
5143
     * @param string $table Record Table
5144
     * @param string $uid Record UID
5145
     */
5146
    public function deleteL10nOverlayRecords($table, $uid)
5147
    {
5148
        // Check whether table can be localized
5149
        if (!BackendUtility::isTableLocalizable($table)) {
5150
            return;
5151
        }
5152
5153
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
5154
        $queryBuilder->getRestrictions()
5155
            ->removeAll()
5156
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
5157
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
5158
5159
        $queryBuilder->select('*')
5160
            ->from($table)
5161
            ->where(
5162
                $queryBuilder->expr()->eq(
5163
                    $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
5164
                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
5165
                )
5166
            );
5167
5168
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
5169
            $queryBuilder->andWhere(
5170
                $queryBuilder->expr()->eq('t3ver_oid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
5171
            );
5172
        }
5173
5174
        $result = $queryBuilder->execute();
5175
        while ($record = $result->fetch()) {
5176
            // Ignore workspace delete placeholders. Those records have been marked for
5177
            // deletion before - deleting them again in a workspace would revert that state.
5178
            if ($this->BE_USER->workspace > 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
5179
                BackendUtility::workspaceOL($table, $record);
5180
                if (VersionState::cast($record['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)) {
5181
                    continue;
5182
                }
5183
            }
5184
            $this->deleteAction($table, (int)$record['t3ver_oid'] > 0 ? (int)$record['t3ver_oid'] : (int)$record['uid']);
5185
        }
5186
    }
5187
5188
    /*********************************************
5189
     *
5190
     * Cmd: Versioning
5191
     *
5192
     ********************************************/
5193
    /**
5194
     * Creates a new version of a record
5195
     * (Requires support in the table)
5196
     *
5197
     * @param string $table Table name
5198
     * @param int $id Record uid to versionize
5199
     * @param string $label Version label
5200
     * @param bool $delete If TRUE, the version is created to delete the record.
5201
     * @return int|null Returns the id of the new version (if any)
5202
     * @see copyRecord()
5203
     */
5204
    public function versionizeRecord($table, $id, $label, $delete = false)
5205
    {
5206
        $id = (int)$id;
5207
        // Stop any actions if the record is marked to be deleted:
5208
        // (this can occur if IRRE elements are versionized and child elements are removed)
5209
        if ($this->isElementToBeDeleted($table, $id)) {
5210
            return null;
5211
        }
5212
        if (!BackendUtility::isTableWorkspaceEnabled($table) || $id <= 0) {
5213
            $this->newlog('Versioning is not supported for this table "' . $table . '" / ' . $id, SystemLogErrorClassification::USER_ERROR);
5214
            return null;
5215
        }
5216
5217
        // Fetch record with permission check
5218
        $row = $this->recordInfoWithPermissionCheck($table, $id, Permission::PAGE_SHOW);
5219
5220
        // This checks if the record can be selected which is all that a copy action requires.
5221
        if ($row === false) {
5222
            $this->newlog(
5223
                'The record does not exist or you don\'t have correct permissions to make a new version (copy) of this record "' . $table . ':' . $id . '"',
5224
                1
5225
            );
5226
            return null;
5227
        }
5228
5229
        // Record must be online record, otherwise we would create a version of a version
5230
        if ($row['t3ver_oid'] ?? 0 > 0) {
5231
            $this->newlog('Record "' . $table . ':' . $id . '" you wanted to versionize was already a version in archive (record has an online ID)!', SystemLogErrorClassification::USER_ERROR);
5232
            return null;
5233
        }
5234
5235
        // Record must not be placeholder for moving.
5236
        if (VersionState::cast($row['t3ver_state'])->equals(VersionState::MOVE_PLACEHOLDER)) {
5237
            $this->newlog('Record cannot be versioned because it is a placeholder for a moving operation', SystemLogErrorClassification::USER_ERROR);
5238
            return null;
5239
        }
5240
5241
        if ($delete && $this->cannotDeleteRecord($table, $id)) {
5242
            $this->newlog('Record cannot be deleted: ' . $this->cannotDeleteRecord($table, $id), SystemLogErrorClassification::USER_ERROR);
5243
            return null;
5244
        }
5245
5246
        // Set up the values to override when making a raw-copy:
5247
        $overrideArray = [
5248
            't3ver_oid' => $id,
5249
            't3ver_wsid' => $this->BE_USER->workspace,
5250
            't3ver_state' => (string)($delete ? new VersionState(VersionState::DELETE_PLACEHOLDER) : new VersionState(VersionState::DEFAULT_STATE)),
5251
            't3ver_count' => 0,
5252
            't3ver_stage' => 0,
5253
            't3ver_tstamp' => 0
5254
        ];
5255
        if ($GLOBALS['TCA'][$table]['ctrl']['editlock']) {
5256
            $overrideArray[$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
5257
        }
5258
        // Checking if the record already has a version in the current workspace of the backend user
5259
        $versionRecord = ['uid' => null];
5260
        if ($this->BE_USER->workspace !== 0) {
5261
            // Look for version already in workspace:
5262
            $versionRecord = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid');
5263
        }
5264
        // Create new version of the record and return the new uid
5265
        if (empty($versionRecord['uid'])) {
5266
            // Create raw-copy and return result:
5267
            // The information of the label to be used for the workspace record
5268
            // as well as the information whether the record shall be removed
5269
            // must be forwarded (creating remove placeholders on a workspace are
5270
            // done by copying the record and override several fields).
5271
            $workspaceOptions = [
5272
                'delete' => $delete,
5273
                'label' => $label,
5274
            ];
5275
            return $this->copyRecord_raw($table, $id, -1, $overrideArray, $workspaceOptions);
5276
        }
5277
        // Reuse the existing record and return its uid
5278
        // (prior to TYPO3 CMS 6.2, an error was thrown here, which
5279
        // did not make much sense since the information is available)
5280
        return $versionRecord['uid'];
5281
    }
5282
5283
    /**
5284
     * Swaps MM-relations for current/swap record, see version_swap()
5285
     *
5286
     * @param string $table Table for the two input records
5287
     * @param int $id Current record (about to go offline)
5288
     * @param int $swapWith Swap record (about to go online)
5289
     * @see version_swap()
5290
     */
5291
    public function version_remapMMForVersionSwap($table, $id, $swapWith)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::version_remapMMForVersionSwap" is not in camel caps format
Loading history...
5292
    {
5293
        // Actually, selecting the records fully is only need if flexforms are found inside... This could be optimized ...
5294
        $currentRec = BackendUtility::getRecord($table, $id);
5295
        $swapRec = BackendUtility::getRecord($table, $swapWith);
5296
        $this->version_remapMMForVersionSwap_reg = [];
5297
        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5298
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fConf) {
5299
            $conf = $fConf['config'];
5300
            if ($this->isReferenceField($conf)) {
5301
                $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5302
                $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
5303
                if ($conf['MM']) {
5304
                    /** @var RelationHandler $dbAnalysis */
5305
                    $dbAnalysis = $this->createRelationHandlerInstance();
5306
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $id, $table, $conf);
5307
                    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

5307
                    if (!empty($dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName))) {
Loading history...
5308
                        $this->version_remapMMForVersionSwap_reg[$id][$field] = [$dbAnalysis, $conf['MM'], $prependName];
5309
                    }
5310
                    /** @var RelationHandler $dbAnalysis */
5311
                    $dbAnalysis = $this->createRelationHandlerInstance();
5312
                    $dbAnalysis->start('', $allowedTables, $conf['MM'], $swapWith, $table, $conf);
5313
                    if (!empty($dbAnalysis->getValueArray($prependName))) {
5314
                        $this->version_remapMMForVersionSwap_reg[$swapWith][$field] = [$dbAnalysis, $conf['MM'], $prependName];
5315
                    }
5316
                }
5317
            } elseif ($conf['type'] === 'flex') {
5318
                // Current record
5319
                $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5320
                    $fConf,
5321
                    $table,
5322
                    $field,
5323
                    $currentRec
5324
                );
5325
                $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5326
                $currentValueArray = GeneralUtility::xml2array($currentRec[$field]);
5327
                if (is_array($currentValueArray)) {
5328
                    $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $id, $field], 'version_remapMMForVersionSwap_flexFormCallBack');
5329
                }
5330
                // Swap record
5331
                $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5332
                    $fConf,
5333
                    $table,
5334
                    $field,
5335
                    $swapRec
5336
                );
5337
                $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5338
                $currentValueArray = GeneralUtility::xml2array($swapRec[$field]);
5339
                if (is_array($currentValueArray)) {
5340
                    $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $swapWith, $field], 'version_remapMMForVersionSwap_flexFormCallBack');
5341
                }
5342
            }
5343
        }
5344
        // Execute:
5345
        $this->version_remapMMForVersionSwap_execSwap($table, $id, $swapWith);
5346
    }
5347
5348
    /**
5349
     * Callback function for traversing the FlexForm structure in relation to ...
5350
     *
5351
     * @param array $pParams Array of parameters in num-indexes: table, uid, field
5352
     * @param array $dsConf TCA field configuration (from Data Structure XML)
5353
     * @param string $dataValue The value of the flexForm field
5354
     * @param string $dataValue_ext1 Not used.
5355
     * @param string $dataValue_ext2 Not used.
5356
     * @param string $path Path in flexforms
5357
     * @see version_remapMMForVersionSwap()
5358
     * @see checkValue_flex_procInData_travDS()
5359
     */
5360
    public function version_remapMMForVersionSwap_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::version_remapMMForVersionSwap_flexFormCallBack" is not in camel caps format
Loading history...
5361
    {
5362
        // Extract parameters:
5363
        [$table, $uid, $field] = $pParams;
5364
        if ($this->isReferenceField($dsConf)) {
5365
            $allowedTables = $dsConf['type'] === 'group' ? $dsConf['allowed'] : $dsConf['foreign_table'];
5366
            $prependName = $dsConf['type'] === 'group' ? $dsConf['prepend_tname'] : '';
5367
            if ($dsConf['MM']) {
5368
                /** @var RelationHandler $dbAnalysis */
5369
                $dbAnalysis = $this->createRelationHandlerInstance();
5370
                $dbAnalysis->start('', $allowedTables, $dsConf['MM'], $uid, $table, $dsConf);
5371
                $this->version_remapMMForVersionSwap_reg[$uid][$field . '/' . $path] = [$dbAnalysis, $dsConf['MM'], $prependName];
5372
            }
5373
        }
5374
    }
5375
5376
    /**
5377
     * Performing the remapping operations found necessary in version_remapMMForVersionSwap()
5378
     * 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.
5379
     *
5380
     * @param string $table Table for the two input records
5381
     * @param int $id Current record (about to go offline)
5382
     * @param int $swapWith Swap record (about to go online)
5383
     * @see version_remapMMForVersionSwap()
5384
     */
5385
    public function version_remapMMForVersionSwap_execSwap($table, $id, $swapWith)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::version_remapMMForVersionSwap_execSwap" is not in camel caps format
Loading history...
5386
    {
5387
        if (is_array($this->version_remapMMForVersionSwap_reg[$id])) {
5388
            foreach ($this->version_remapMMForVersionSwap_reg[$id] as $field => $str) {
5389
                $str[0]->remapMM($str[1], $id, -$id, $str[2]);
5390
            }
5391
        }
5392
        if (is_array($this->version_remapMMForVersionSwap_reg[$swapWith])) {
5393
            foreach ($this->version_remapMMForVersionSwap_reg[$swapWith] as $field => $str) {
5394
                $str[0]->remapMM($str[1], $swapWith, $id, $str[2]);
5395
            }
5396
        }
5397
        if (is_array($this->version_remapMMForVersionSwap_reg[$id])) {
5398
            foreach ($this->version_remapMMForVersionSwap_reg[$id] as $field => $str) {
5399
                $str[0]->remapMM($str[1], -$id, $swapWith, $str[2]);
5400
            }
5401
        }
5402
    }
5403
5404
    /*********************************************
5405
     *
5406
     * Cmd: Helper functions
5407
     *
5408
     ********************************************/
5409
5410
    /**
5411
     * Returns an instance of DataHandler for handling local datamaps/cmdmaps
5412
     *
5413
     * @return DataHandler
5414
     */
5415
    protected function getLocalTCE()
5416
    {
5417
        $copyTCE = GeneralUtility::makeInstance(DataHandler::class);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
5418
        $copyTCE->copyTree = $this->copyTree;
5419
        $copyTCE->enableLogging = $this->enableLogging;
5420
        // Transformations should NOT be carried out during copy
5421
        $copyTCE->dontProcessTransformations = true;
5422
        // make sure the isImporting flag is transferred, so all hooks know if
5423
        // the current process is an import process
5424
        $copyTCE->isImporting = $this->isImporting;
5425
        $copyTCE->bypassAccessCheckForRecords = $this->bypassAccessCheckForRecords;
5426
        $copyTCE->bypassWorkspaceRestrictions = $this->bypassWorkspaceRestrictions;
5427
        return $copyTCE;
5428
    }
5429
5430
    /**
5431
     * Processes the fields with references as registered during the copy process. This includes all FlexForm fields which had references.
5432
     */
5433
    public function remapListedDBRecords()
5434
    {
5435
        if (!empty($this->registerDBList)) {
5436
            $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
5437
            foreach ($this->registerDBList as $table => $records) {
5438
                foreach ($records as $uid => $fields) {
5439
                    $newData = [];
5440
                    $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
5441
                    $theUidToUpdate_saveTo = BackendUtility::wsMapId($table, $theUidToUpdate);
5442
                    foreach ($fields as $fieldName => $value) {
5443
                        $conf = $GLOBALS['TCA'][$table]['columns'][$fieldName]['config'];
5444
                        switch ($conf['type']) {
5445
                            case 'group':
5446
                            case 'select':
5447
                                $vArray = $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
5448
                                if (is_array($vArray)) {
5449
                                    $newData[$fieldName] = implode(',', $vArray);
5450
                                }
5451
                                break;
5452
                            case 'flex':
5453
                                if ($value === 'FlexForm_reference') {
5454
                                    // This will fetch the new row for the element
5455
                                    $origRecordRow = $this->recordInfo($table, $theUidToUpdate, '*');
5456
                                    if (is_array($origRecordRow)) {
5457
                                        BackendUtility::workspaceOL($table, $origRecordRow);
5458
                                        // Get current data structure and value array:
5459
                                        $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
5460
                                            ['config' => $conf],
5461
                                            $table,
5462
                                            $fieldName,
5463
                                            $origRecordRow
5464
                                        );
5465
                                        $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
5466
                                        $currentValueArray = GeneralUtility::xml2array($origRecordRow[$fieldName]);
5467
                                        // Do recursive processing of the XML data:
5468
                                        $currentValueArray['data'] = $this->checkValue_flex_procInData($currentValueArray['data'], [], [], $dataStructureArray, [$table, $theUidToUpdate, $fieldName], 'remapListedDBRecords_flexFormCallBack');
5469
                                        // The return value should be compiled back into XML, ready to insert directly in the field (as we call updateDB() directly later):
5470
                                        if (is_array($currentValueArray['data'])) {
5471
                                            $newData[$fieldName] = $this->checkValue_flexArray2Xml($currentValueArray, true);
5472
                                        }
5473
                                    }
5474
                                }
5475
                                break;
5476
                            case 'inline':
5477
                                $this->remapListedDBRecords_procInline($conf, $value, $uid, $table);
5478
                                break;
5479
                            default:
5480
                                $this->logger->debug('Field type should not appear here: ' . $conf['type']);
5481
                        }
5482
                    }
5483
                    // If any fields were changed, those fields are updated!
5484
                    if (!empty($newData)) {
5485
                        $this->updateDB($table, $theUidToUpdate_saveTo, $newData);
5486
                    }
5487
                }
5488
            }
5489
        }
5490
    }
5491
5492
    /**
5493
     * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
5494
     *
5495
     * @param array $pParams Set of parameters in numeric array: table, uid, field
5496
     * @param array $dsConf TCA config for field (from Data Structure of course)
5497
     * @param string $dataValue Field value (from FlexForm XML)
5498
     * @param string $dataValue_ext1 Not used
5499
     * @param string $dataValue_ext2 Not used
5500
     * @return array Array where the "value" key carries the value.
5501
     * @see checkValue_flex_procInData_travDS()
5502
     * @see remapListedDBRecords()
5503
     */
5504
    public function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::remapListedDBRecords_flexFormCallBack" is not in camel caps format
Loading history...
5505
    {
5506
        // Extract parameters:
5507
        [$table, $uid, $field] = $pParams;
5508
        // If references are set for this field, set flag so they can be corrected later:
5509
        if ($this->isReferenceField($dsConf) && (string)$dataValue !== '') {
5510
            $vArray = $this->remapListedDBRecords_procDBRefs($dsConf, $dataValue, $uid, $table);
5511
            if (is_array($vArray)) {
5512
                $dataValue = implode(',', $vArray);
5513
            }
5514
        }
5515
        // Return
5516
        return ['value' => $dataValue];
5517
    }
5518
5519
    /**
5520
     * Performs remapping of old UID values to NEW uid values for a DB reference field.
5521
     *
5522
     * @param array $conf TCA field config
5523
     * @param string $value Field value
5524
     * @param int $MM_localUid UID of local record (for MM relations - might need to change if support for FlexForms should be done!)
5525
     * @param string $table Table name
5526
     * @return array|null Returns array of items ready to implode for field content.
5527
     * @see remapListedDBRecords()
5528
     */
5529
    public function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid, $table)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::remapListedDBRecords_procDBRefs" is not in camel caps format
Loading history...
5530
    {
5531
        // Initialize variables
5532
        // Will be set TRUE if an upgrade should be done...
5533
        $set = false;
5534
        // Allowed tables for references.
5535
        $allowedTables = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
5536
        // Table name to prepend the UID
5537
        $prependName = $conf['type'] === 'group' ? $conf['prepend_tname'] : '';
5538
        // Which tables that should possibly not be remapped
5539
        $dontRemapTables = GeneralUtility::trimExplode(',', $conf['dontRemapTablesOnCopy'], true);
5540
        // Convert value to list of references:
5541
        $dbAnalysis = $this->createRelationHandlerInstance();
5542
        $dbAnalysis->registerNonTableValues = $conf['type'] === 'select' && $conf['allowNonIdValues'];
5543
        $dbAnalysis->start($value, $allowedTables, $conf['MM'], $MM_localUid, $table, $conf);
5544
        // Traverse those references and map IDs:
5545
        foreach ($dbAnalysis->itemArray as $k => $v) {
5546
            $mapID = $this->copyMappingArray_merged[$v['table']][$v['id']];
5547
            if ($mapID && !in_array($v['table'], $dontRemapTables, true)) {
5548
                $dbAnalysis->itemArray[$k]['id'] = $mapID;
5549
                $set = true;
5550
            }
5551
        }
5552
        if (!empty($conf['MM'])) {
5553
            // Purge invalid items (live/version)
5554
            $dbAnalysis->purgeItemArray();
5555
            if ($dbAnalysis->isPurged()) {
5556
                $set = true;
5557
            }
5558
5559
            // If record has been versioned/copied in this process, handle invalid relations of the live record
5560
            $liveId = BackendUtility::getLiveVersionIdOfRecord($table, $MM_localUid);
5561
            $originalId = 0;
5562
            if (!empty($this->copyMappingArray_merged[$table])) {
5563
                $originalId = array_search($MM_localUid, $this->copyMappingArray_merged[$table]);
5564
            }
5565
            if (!empty($liveId) && !empty($originalId) && (int)$liveId === (int)$originalId) {
5566
                $liveRelations = $this->createRelationHandlerInstance();
5567
                $liveRelations->setWorkspaceId(0);
5568
                $liveRelations->start('', $allowedTables, $conf['MM'], $liveId, $table, $conf);
5569
                // Purge invalid relations in the live workspace ("0")
5570
                $liveRelations->purgeItemArray(0);
5571
                if ($liveRelations->isPurged()) {
5572
                    $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

5572
                    $liveRelations->writeMM($conf['MM'], $liveId, /** @scrutinizer ignore-type */ $prependName);
Loading history...
5573
                }
5574
            }
5575
        }
5576
        // If a change has been done, set the new value(s)
5577
        if ($set) {
5578
            if ($conf['MM']) {
5579
                $dbAnalysis->writeMM($conf['MM'], $MM_localUid, $prependName);
5580
            } else {
5581
                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

5581
                return $dbAnalysis->getValueArray(/** @scrutinizer ignore-type */ $prependName);
Loading history...
5582
            }
5583
        }
5584
        return null;
5585
    }
5586
5587
    /**
5588
     * Performs remapping of old UID values to NEW uid values for an inline field.
5589
     *
5590
     * @param array $conf TCA field config
5591
     * @param string $value Field value
5592
     * @param int $uid The uid of the ORIGINAL record
5593
     * @param string $table Table name
5594
     */
5595
    public function remapListedDBRecords_procInline($conf, $value, $uid, $table)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::remapListedDBRecords_procInline" is not in camel caps format
Loading history...
5596
    {
5597
        $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
5598
        if ($conf['foreign_table']) {
5599
            $inlineType = $this->getInlineFieldType($conf);
5600
            if ($inlineType === 'mm') {
5601
                $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
5602
            } elseif ($inlineType !== false) {
5603
                /** @var RelationHandler $dbAnalysis */
5604
                $dbAnalysis = $this->createRelationHandlerInstance();
5605
                $dbAnalysis->start($value, $conf['foreign_table'], '', 0, $table, $conf);
5606
5607
                // Keep original (live) item array and update values for specific versioned records
5608
                $originalItemArray = $dbAnalysis->itemArray;
5609
                foreach ($dbAnalysis->itemArray as &$item) {
5610
                    $versionedId = $this->getAutoVersionId($item['table'], $item['id']);
5611
                    if (!empty($versionedId)) {
5612
                        $item['id'] = $versionedId;
5613
                    }
5614
                }
5615
5616
                // Update child records if using pointer fields ('foreign_field'):
5617
                if ($inlineType === 'field') {
5618
                    $dbAnalysis->writeForeignField($conf, $uid, $theUidToUpdate);
5619
                }
5620
                $thePidToUpdate = null;
5621
                // If the current field is set on a page record, update the pid of related child records:
5622
                if ($table === 'pages') {
5623
                    $thePidToUpdate = $theUidToUpdate;
5624
                } elseif (isset($this->registerDBPids[$table][$uid])) {
5625
                    $thePidToUpdate = $this->registerDBPids[$table][$uid];
5626
                    $thePidToUpdate = $this->copyMappingArray_merged['pages'][$thePidToUpdate];
5627
                }
5628
5629
                // Update child records if change to pid is required (only if the current record is not on a workspace):
5630
                if ($thePidToUpdate) {
5631
                    // Ensure that only the default language page is used as PID
5632
                    $thePidToUpdate = $this->getDefaultLanguagePageId($thePidToUpdate);
5633
                    // ensure, only live page ids are used as 'pid' values
5634
                    $liveId = BackendUtility::getLiveVersionIdOfRecord('pages', $theUidToUpdate);
5635
                    if ($liveId !== null) {
0 ignored issues
show
introduced by
The condition $liveId !== null is always true.
Loading history...
5636
                        $thePidToUpdate = $liveId;
5637
                    }
5638
                    $updateValues = ['pid' => $thePidToUpdate];
5639
                    foreach ($originalItemArray as $v) {
5640
                        if ($v['id'] && $v['table'] && BackendUtility::getLiveVersionIdOfRecord($v['table'], $v['id']) === null) {
5641
                            GeneralUtility::makeInstance(ConnectionPool::class)
5642
                                ->getConnectionForTable($v['table'])
5643
                                ->update($v['table'], $updateValues, ['uid' => (int)$v['id']]);
5644
                        }
5645
                    }
5646
                }
5647
            }
5648
        }
5649
    }
5650
5651
    /**
5652
     * Processes the $this->remapStack at the end of copying, inserting, etc. actions.
5653
     * The remapStack takes care about the correct mapping of new and old uids in case of relational data.
5654
     */
5655
    public function processRemapStack()
5656
    {
5657
        // Processes the remap stack:
5658
        if (is_array($this->remapStack)) {
0 ignored issues
show
introduced by
The condition is_array($this->remapStack) is always true.
Loading history...
5659
            $remapFlexForms = [];
5660
            $hookPayload = [];
5661
5662
            $newValue = null;
5663
            foreach ($this->remapStack as $remapAction) {
5664
                // If no position index for the arguments was set, skip this remap action:
5665
                if (!is_array($remapAction['pos'])) {
5666
                    continue;
5667
                }
5668
                // Load values from the argument array in remapAction:
5669
                $field = $remapAction['field'];
5670
                $id = $remapAction['args'][$remapAction['pos']['id']];
5671
                $rawId = $id;
5672
                $table = $remapAction['args'][$remapAction['pos']['table']];
5673
                $valueArray = $remapAction['args'][$remapAction['pos']['valueArray']];
5674
                $tcaFieldConf = $remapAction['args'][$remapAction['pos']['tcaFieldConf']];
5675
                $additionalData = $remapAction['additionalData'];
5676
                // The record is new and has one or more new ids (in case of versioning/workspaces):
5677
                if (strpos($id, 'NEW') !== false) {
5678
                    // Replace NEW...-ID with real uid:
5679
                    $id = $this->substNEWwithIDs[$id];
5680
                    // If the new parent record is on a non-live workspace or versionized, it has another new id:
5681
                    if (isset($this->autoVersionIdMap[$table][$id])) {
5682
                        $id = $this->autoVersionIdMap[$table][$id];
5683
                    }
5684
                    $remapAction['args'][$remapAction['pos']['id']] = $id;
5685
                }
5686
                // Replace relations to NEW...-IDs in field value (uids of child records):
5687
                if (is_array($valueArray)) {
5688
                    foreach ($valueArray as $key => $value) {
5689
                        if (strpos($value, 'NEW') !== false) {
5690
                            if (strpos($value, '_') === false) {
5691
                                $affectedTable = $tcaFieldConf['foreign_table'];
5692
                                $prependTable = false;
5693
                            } else {
5694
                                $parts = explode('_', $value);
5695
                                $value = array_pop($parts);
5696
                                $affectedTable = implode('_', $parts);
5697
                                $prependTable = true;
5698
                            }
5699
                            $value = $this->substNEWwithIDs[$value];
5700
                            // The record is new, but was also auto-versionized and has another new id:
5701
                            if (isset($this->autoVersionIdMap[$affectedTable][$value])) {
5702
                                $value = $this->autoVersionIdMap[$affectedTable][$value];
5703
                            }
5704
                            if ($prependTable) {
5705
                                $value = $affectedTable . '_' . $value;
5706
                            }
5707
                            // Set a hint that this was a new child record:
5708
                            $this->newRelatedIDs[$affectedTable][] = $value;
5709
                            $valueArray[$key] = $value;
5710
                        }
5711
                    }
5712
                    $remapAction['args'][$remapAction['pos']['valueArray']] = $valueArray;
5713
                }
5714
                // Process the arguments with the defined function:
5715
                if (!empty($remapAction['func'])) {
5716
                    $newValue = call_user_func_array([$this, $remapAction['func']], $remapAction['args']);
5717
                }
5718
                // If array is returned, check for maxitems condition, if string is returned this was already done:
5719
                if (is_array($newValue)) {
5720
                    $newValue = implode(',', $this->checkValue_checkMax($tcaFieldConf, $newValue));
5721
                    // The reference casting is only required if
5722
                    // checkValue_group_select_processDBdata() returns an array
5723
                    $newValue = $this->castReferenceValue($newValue, $tcaFieldConf);
5724
                }
5725
                // Update in database (list of children (csv) or number of relations (foreign_field)):
5726
                if (!empty($field)) {
5727
                    $fieldArray = [$field => $newValue];
5728
                    if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
5729
                        $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
5730
                    }
5731
                    $this->updateDB($table, $id, $fieldArray);
5732
                } elseif (!empty($additionalData['flexFormId']) && !empty($additionalData['flexFormPath'])) {
5733
                    // Collect data to update FlexForms
5734
                    $flexFormId = $additionalData['flexFormId'];
5735
                    $flexFormPath = $additionalData['flexFormPath'];
5736
5737
                    if (!isset($remapFlexForms[$flexFormId])) {
5738
                        $remapFlexForms[$flexFormId] = [];
5739
                    }
5740
5741
                    $remapFlexForms[$flexFormId][$flexFormPath] = $newValue;
5742
                }
5743
5744
                // Collect elements that shall trigger processDatamap_afterDatabaseOperations
5745
                if (isset($this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'])) {
5746
                    $hookArgs = $this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'];
5747
                    if (!isset($hookPayload[$table][$rawId])) {
5748
                        $hookPayload[$table][$rawId] = [
5749
                            'status' => $hookArgs['status'],
5750
                            'fieldArray' => $hookArgs['fieldArray'],
5751
                            'hookObjects' => $hookArgs['hookObjectsArr'],
5752
                        ];
5753
                    }
5754
                    $hookPayload[$table][$rawId]['fieldArray'][$field] = $newValue;
5755
                }
5756
            }
5757
5758
            if ($remapFlexForms) {
5759
                foreach ($remapFlexForms as $flexFormId => $modifications) {
5760
                    $this->updateFlexFormData($flexFormId, $modifications);
5761
                }
5762
            }
5763
5764
            foreach ($hookPayload as $tableName => $rawIdPayload) {
5765
                foreach ($rawIdPayload as $rawId => $payload) {
5766
                    foreach ($payload['hookObjects'] as $hookObject) {
5767
                        if (!method_exists($hookObject, 'processDatamap_afterDatabaseOperations')) {
5768
                            continue;
5769
                        }
5770
                        $hookObject->processDatamap_afterDatabaseOperations(
5771
                            $payload['status'],
5772
                            $tableName,
5773
                            $rawId,
5774
                            $payload['fieldArray'],
5775
                            $this
5776
                        );
5777
                    }
5778
                }
5779
            }
5780
        }
5781
        // Processes the remap stack actions:
5782
        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...
5783
            foreach ($this->remapStackActions as $action) {
5784
                if (isset($action['callback'], $action['arguments'])) {
5785
                    call_user_func_array($action['callback'], $action['arguments']);
5786
                }
5787
            }
5788
        }
5789
        // Processes the reference index updates of the remap stack:
5790
        foreach ($this->remapStackRefIndex as $table => $idArray) {
5791
            foreach ($idArray as $id) {
5792
                $this->updateRefIndex($table, $id);
5793
                unset($this->remapStackRefIndex[$table][$id]);
5794
            }
5795
        }
5796
        // Reset:
5797
        $this->remapStack = [];
5798
        $this->remapStackRecords = [];
5799
        $this->remapStackActions = [];
5800
        $this->remapStackRefIndex = [];
5801
    }
5802
5803
    /**
5804
     * Updates FlexForm data.
5805
     *
5806
     * @param string $flexFormId e.g. <table>:<uid>:<field>
5807
     * @param array $modifications Modifications with paths and values (e.g. 'sDEF/lDEV/field/vDEF' => 'TYPO3')
5808
     */
5809
    protected function updateFlexFormData($flexFormId, array $modifications)
5810
    {
5811
        [$table, $uid, $field] = explode(':', $flexFormId, 3);
5812
5813
        if (!MathUtility::canBeInterpretedAsInteger($uid) && !empty($this->substNEWwithIDs[$uid])) {
5814
            $uid = $this->substNEWwithIDs[$uid];
5815
        }
5816
5817
        $record = $this->recordInfo($table, $uid, '*');
5818
5819
        if (!$table || !$uid || !$field || !is_array($record)) {
5820
            return;
5821
        }
5822
5823
        BackendUtility::workspaceOL($table, $record);
5824
5825
        // Get current data structure and value array:
5826
        $valueStructure = GeneralUtility::xml2array($record[$field]);
5827
5828
        // Do recursive processing of the XML data:
5829
        foreach ($modifications as $path => $value) {
5830
            $valueStructure['data'] = ArrayUtility::setValueByPath(
5831
                $valueStructure['data'],
5832
                $path,
5833
                $value
5834
            );
5835
        }
5836
5837
        if (is_array($valueStructure['data'])) {
5838
            // The return value should be compiled back into XML
5839
            $values = [
5840
                $field => $this->checkValue_flexArray2Xml($valueStructure, true),
5841
            ];
5842
5843
            $this->updateDB($table, $uid, $values);
5844
        }
5845
    }
5846
5847
    /**
5848
     * Triggers a remap action for a specific record.
5849
     *
5850
     * Some records are post-processed by the processRemapStack() method (e.g. IRRE children).
5851
     * This method determines whether an action/modification is executed directly to a record
5852
     * or is postponed to happen after remapping data.
5853
     *
5854
     * @param string $table Name of the table
5855
     * @param string $id Id of the record (can also be a "NEW..." string)
5856
     * @param array $callback The method to be called
5857
     * @param array $arguments The arguments to be submitted to the callback method
5858
     * @param bool $forceRemapStackActions Whether to force to use the stack
5859
     * @see processRemapStack
5860
     */
5861
    protected function triggerRemapAction($table, $id, array $callback, array $arguments, $forceRemapStackActions = false)
5862
    {
5863
        // Check whether the affected record is marked to be remapped:
5864
        if (!$forceRemapStackActions && !isset($this->remapStackRecords[$table][$id]) && !isset($this->remapStackChildIds[$id])) {
5865
            call_user_func_array($callback, $arguments);
5866
        } else {
5867
            $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

5867
            $this->addRemapAction($table, /** @scrutinizer ignore-type */ $id, $callback, $arguments);
Loading history...
5868
        }
5869
    }
5870
5871
    /**
5872
     * Adds an instruction to the remap action stack (used with IRRE).
5873
     *
5874
     * @param string $table The affected table
5875
     * @param int $id The affected ID
5876
     * @param array $callback The callback information (object and method)
5877
     * @param array $arguments The arguments to be used with the callback
5878
     */
5879
    public function addRemapAction($table, $id, array $callback, array $arguments)
5880
    {
5881
        $this->remapStackActions[] = [
5882
            'affects' => [
5883
                'table' => $table,
5884
                'id' => $id
5885
            ],
5886
            'callback' => $callback,
5887
            'arguments' => $arguments
5888
        ];
5889
    }
5890
5891
    /**
5892
     * Adds a table-id-pair to the reference index remapping stack.
5893
     *
5894
     * @param string $table
5895
     * @param int $id
5896
     */
5897
    public function addRemapStackRefIndex($table, $id)
5898
    {
5899
        $this->remapStackRefIndex[$table][$id] = $id;
5900
    }
5901
5902
    /**
5903
     * If a parent record was versionized on a workspace in $this->process_datamap,
5904
     * it might be possible, that child records (e.g. on using IRRE) were affected.
5905
     * This function finds these relations and updates their uids in the $incomingFieldArray.
5906
     * The $incomingFieldArray is updated by reference!
5907
     *
5908
     * @param string $table Table name of the parent record
5909
     * @param int $id Uid of the parent record
5910
     * @param array $incomingFieldArray Reference to the incomingFieldArray of process_datamap
5911
     * @param array $registerDBList Reference to the $registerDBList array that was created/updated by versionizing calls to DataHandler in process_datamap.
5912
     */
5913
    public function getVersionizedIncomingFieldArray($table, $id, &$incomingFieldArray, &$registerDBList)
5914
    {
5915
        if (is_array($registerDBList[$table][$id])) {
5916
            foreach ($incomingFieldArray as $field => $value) {
5917
                $fieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
5918
                if ($registerDBList[$table][$id][$field] && ($foreignTable = $fieldConf['foreign_table'])) {
5919
                    $newValueArray = [];
5920
                    $origValueArray = is_array($value) ? $value : explode(',', $value);
5921
                    // Update the uids of the copied records, but also take care about new records:
5922
                    foreach ($origValueArray as $childId) {
5923
                        $newValueArray[] = $this->autoVersionIdMap[$foreignTable][$childId] ?: $childId;
5924
                    }
5925
                    // Set the changed value to the $incomingFieldArray
5926
                    $incomingFieldArray[$field] = implode(',', $newValueArray);
5927
                }
5928
            }
5929
            // Clean up the $registerDBList array:
5930
            unset($registerDBList[$table][$id]);
5931
            if (empty($registerDBList[$table])) {
5932
                unset($registerDBList[$table]);
5933
            }
5934
        }
5935
    }
5936
5937
    /*****************************
5938
     *
5939
     * Access control / Checking functions
5940
     *
5941
     *****************************/
5942
    /**
5943
     * Checking group modify_table access list
5944
     *
5945
     * @param string $table Table name
5946
     * @return bool Returns TRUE if the user has general access to modify the $table
5947
     */
5948
    public function checkModifyAccessList($table)
5949
    {
5950
        $res = $this->admin || (!$this->tableAdminOnly($table) && isset($this->BE_USER->groupData['tables_modify']) && GeneralUtility::inList($this->BE_USER->groupData['tables_modify'], $table));
5951
        // Hook 'checkModifyAccessList': Post-processing of the state of access
5952
        foreach ($this->getCheckModifyAccessListHookObjects() as $hookObject) {
5953
            /** @var DataHandlerCheckModifyAccessListHookInterface $hookObject */
5954
            $hookObject->checkModifyAccessList($res, $table, $this);
5955
        }
5956
        return $res;
5957
    }
5958
5959
    /**
5960
     * Checking if a record with uid $id from $table is in the BE_USERS webmounts which is required for editing etc.
5961
     *
5962
     * @param string $table Table name
5963
     * @param int $id UID of record
5964
     * @return bool Returns TRUE if OK. Cached results.
5965
     */
5966
    public function isRecordInWebMount($table, $id)
5967
    {
5968
        if (!isset($this->isRecordInWebMount_Cache[$table . ':' . $id])) {
5969
            $recP = $this->getRecordProperties($table, $id);
5970
            $this->isRecordInWebMount_Cache[$table . ':' . $id] = $this->isInWebMount($recP['event_pid']);
5971
        }
5972
        return $this->isRecordInWebMount_Cache[$table . ':' . $id];
5973
    }
5974
5975
    /**
5976
     * Checks if the input page ID is in the BE_USER webmounts
5977
     *
5978
     * @param int $pid Page ID to check
5979
     * @return bool TRUE if OK. Cached results.
5980
     */
5981
    public function isInWebMount($pid)
5982
    {
5983
        if (!isset($this->isInWebMount_Cache[$pid])) {
5984
            $this->isInWebMount_Cache[$pid] = $this->BE_USER->isInWebMount($pid);
5985
        }
5986
        return $this->isInWebMount_Cache[$pid];
5987
    }
5988
5989
    /**
5990
     * Checks if user may update a record with uid=$id from $table
5991
     *
5992
     * @param string $table Record table
5993
     * @param int $id Record UID
5994
     * @param array|bool $data Record data
5995
     * @param array $hookObjectsArr Hook objects
5996
     * @return bool Returns TRUE if the user may update the record given by $table and $id
5997
     */
5998
    public function checkRecordUpdateAccess($table, $id, $data = false, $hookObjectsArr = null)
5999
    {
6000
        $res = null;
6001
        if (is_array($hookObjectsArr)) {
6002
            foreach ($hookObjectsArr as $hookObj) {
6003
                if (method_exists($hookObj, 'checkRecordUpdateAccess')) {
6004
                    $res = $hookObj->checkRecordUpdateAccess($table, $id, $data, $res, $this);
6005
                }
6006
            }
6007
            if (isset($res)) {
6008
                return (bool)$res;
6009
            }
6010
        }
6011
        $res = false;
6012
6013
        if ($GLOBALS['TCA'][$table] && (int)$id > 0) {
6014
            $cacheId = 'checkRecordUpdateAccess_' . $table . '_' . $id;
6015
6016
            // If information is cached, return it
6017
            $cachedValue = $this->runtimeCache->get($cacheId);
6018
            if (!empty($cachedValue)) {
6019
                return $cachedValue;
6020
            }
6021
6022
            if ($table === 'pages' || ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap))) {
6023
                // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
6024
                $perms = Permission::PAGE_EDIT;
6025
            } else {
6026
                $perms = Permission::CONTENT_EDIT;
6027
            }
6028
            if ($this->doesRecordExist($table, $id, $perms)) {
6029
                $res = 1;
6030
            }
6031
            // Cache the result
6032
            $this->runtimeCache->set($cacheId, $res);
6033
        }
6034
        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...
6035
    }
6036
6037
    /**
6038
     * Checks if user may insert a record from $insertTable on $pid
6039
     * Does not check for workspace, use BE_USER->workspaceAllowLiveRecordsInPID for this in addition to this function call.
6040
     *
6041
     * @param string $insertTable Tablename to check
6042
     * @param int $pid Integer PID
6043
     * @param int $action For logging: Action number.
6044
     * @return bool Returns TRUE if the user may insert a record from table $insertTable on page $pid
6045
     */
6046
    public function checkRecordInsertAccess($insertTable, $pid, $action = SystemLogDatabaseAction::INSERT)
6047
    {
6048
        $pid = (int)$pid;
6049
        if ($pid < 0) {
6050
            return false;
6051
        }
6052
        // If information is cached, return it
6053
        if (isset($this->recInsertAccessCache[$insertTable][$pid])) {
6054
            return $this->recInsertAccessCache[$insertTable][$pid];
6055
        }
6056
6057
        $res = false;
6058
        if ($insertTable === 'pages') {
6059
            $perms = Permission::PAGE_NEW;
6060
        } elseif (($insertTable === 'sys_file_reference') && array_key_exists('pages', $this->datamap)) {
6061
            // @todo: find a more generic way to handle content relations of a page (without needing content editing access to that page)
6062
            $perms = Permission::PAGE_EDIT;
6063
        } else {
6064
            $perms = Permission::CONTENT_EDIT;
6065
        }
6066
        $pageExists = (bool)$this->doesRecordExist('pages', $pid, $perms);
6067
        // 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
6068
        if ($pageExists || $pid === 0 && ($this->admin || BackendUtility::isRootLevelRestrictionIgnored($insertTable))) {
6069
            // Check permissions
6070
            if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
6071
                $res = true;
6072
                // Cache the result
6073
                $this->recInsertAccessCache[$insertTable][$pid] = $res;
6074
            } elseif ($this->enableLogging) {
6075
                $propArr = $this->getRecordProperties('pages', $pid);
6076
                $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']);
6077
            }
6078
        } elseif ($this->enableLogging) {
6079
            $propArr = $this->getRecordProperties('pages', $pid);
6080
            $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']);
6081
        }
6082
        return $res;
6083
    }
6084
6085
    /**
6086
     * 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.
6087
     *
6088
     * @param int $page_uid Page id for which to check, including 0 (zero) if checking for page tree root.
6089
     * @param string $checkTable Table name to check
6090
     * @return bool TRUE if OK
6091
     */
6092
    public function isTableAllowedForThisPage($page_uid, $checkTable)
6093
    {
6094
        $page_uid = (int)$page_uid;
6095
        $rootLevelSetting = (int)$GLOBALS['TCA'][$checkTable]['ctrl']['rootLevel'];
6096
        // 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.
6097
        if ($checkTable !== 'pages' && $rootLevelSetting !== -1 && ($rootLevelSetting xor !$page_uid)) {
6098
            return false;
6099
        }
6100
        $allowed = false;
6101
        // Check root-level
6102
        if (!$page_uid) {
6103
            if ($this->admin || BackendUtility::isRootLevelRestrictionIgnored($checkTable)) {
6104
                $allowed = true;
6105
            }
6106
        } else {
6107
            // Check non-root-level
6108
            $doktype = $this->pageInfo($page_uid, 'doktype');
6109
            $allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
6110
            $allowedArray = GeneralUtility::trimExplode(',', $allowedTableList, true);
6111
            // If all tables or the table is listed as an allowed type, return TRUE
6112
            if (strpos($allowedTableList, '*') !== false || in_array($checkTable, $allowedArray, true)) {
6113
                $allowed = true;
6114
            }
6115
        }
6116
        return $allowed;
6117
    }
6118
6119
    /**
6120
     * Checks if record can be selected based on given permission criteria
6121
     *
6122
     * @param string $table Record table name
6123
     * @param int $id Record UID
6124
     * @param int|string $perms Permission restrictions to observe: Either an integer that will be bitwise AND'ed or a string, which points to a key in the ->pMap array. Only integers are supported starting with TYPO3 v11.
6125
     * @return bool Returns TRUE if the record given by $table, $id and $perms can be selected
6126
     *
6127
     * @throws \RuntimeException
6128
     */
6129
    public function doesRecordExist($table, $id, $perms)
6130
    {
6131
        if (!MathUtility::canBeInterpretedAsInteger($perms)) {
6132
            trigger_error('Support for handing in permissions as string into "doesRecordExist" will be not be supported with TYPO3 v11 anymore. Use the Permission BitSet class instead.', E_USER_DEPRECATED);
6133
        }
6134
        return $this->recordInfoWithPermissionCheck($table, $id, $perms, 'uid, pid') !== false;
6135
    }
6136
6137
    /**
6138
     * Looks up a page based on permissions.
6139
     *
6140
     * @param int $id Page id
6141
     * @param int $perms Permission integer
6142
     * @param array $columns Columns to select
6143
     * @return bool|array
6144
     * @internal
6145
     * @see doesRecordExist()
6146
     */
6147
    protected function doesRecordExist_pageLookUp($id, $perms, $columns = ['uid'])
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::doesRecordExist_pageLookUp" is not in camel caps format
Loading history...
6148
    {
6149
        $cacheId = md5('doesRecordExist_pageLookUp_' . $id . '_' . $perms . '_' . implode(
6150
            '_',
6151
            $columns
6152
        ) . '_' . (string)$this->admin);
6153
6154
        // If result is cached, return it
6155
        $cachedResult = $this->runtimeCache->get($cacheId);
6156
        if (!empty($cachedResult)) {
6157
            return $cachedResult;
6158
        }
6159
6160
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6161
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6162
        $queryBuilder
6163
            ->select(...$columns)
6164
            ->from('pages')
6165
            ->where($queryBuilder->expr()->eq(
6166
                'uid',
6167
                $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
6168
            ));
6169
        if ($perms && !$this->admin) {
6170
            $queryBuilder->andWhere($this->BE_USER->getPagePermsClause($perms));
6171
        }
6172
        if (!$this->admin && $GLOBALS['TCA']['pages']['ctrl']['editlock'] &&
6173
            $perms & Permission::PAGE_EDIT + Permission::PAGE_DELETE + Permission::CONTENT_EDIT
6174
        ) {
6175
            $queryBuilder->andWhere($queryBuilder->expr()->eq(
6176
                $GLOBALS['TCA']['pages']['ctrl']['editlock'],
6177
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
6178
            ));
6179
        }
6180
6181
        $row = $queryBuilder->execute()->fetch();
6182
        $this->runtimeCache->set($cacheId, $row);
6183
6184
        return $row;
6185
    }
6186
6187
    /**
6188
     * Checks if a whole branch of pages exists
6189
     *
6190
     * Tests the branch under $pid like doesRecordExist(), but it doesn't test the page with $pid as uid - use doesRecordExist() for this purpose.
6191
     * 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
6192
     *
6193
     * @param string $inList List of page uids, this is added to and returned in the end
6194
     * @param int $pid Page ID to select subpages from.
6195
     * @param int $perms Perms integer to check each page record for.
6196
     * @param bool $recurse Recursion flag: If set, it will go out through the branch.
6197
     * @return string|int List of page IDs in branch, if there are subpages, empty string if there are none or -1 if no permission
6198
     */
6199
    public function doesBranchExist($inList, $pid, $perms, $recurse)
6200
    {
6201
        $pid = (int)$pid;
6202
        $perms = (int)$perms;
6203
        if ($pid >= 0) {
6204
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6205
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6206
            $result = $queryBuilder
6207
                ->select('uid', 'perms_userid', 'perms_groupid', 'perms_user', 'perms_group', 'perms_everybody')
6208
                ->from('pages')
6209
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
6210
                ->orderBy('sorting')
6211
                ->execute();
6212
            while ($row = $result->fetch()) {
6213
                // IF admin, then it's OK
6214
                if ($this->admin || $this->BE_USER->doesUserHaveAccess($row, $perms)) {
6215
                    $inList .= $row['uid'] . ',';
6216
                    if ($recurse) {
6217
                        // Follow the subpages recursively...
6218
                        $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
6219
                        if ($inList === -1) {
6220
                            return -1;
6221
                        }
6222
                    }
6223
                } else {
6224
                    // No permissions
6225
                    return -1;
6226
                }
6227
            }
6228
        }
6229
        return $inList;
6230
    }
6231
6232
    /**
6233
     * Checks if the $table is readOnly
6234
     *
6235
     * @param string $table Table name
6236
     * @return bool TRUE, if readonly
6237
     */
6238
    public function tableReadOnly($table)
6239
    {
6240
        // Returns TRUE if table is readonly
6241
        return (bool)$GLOBALS['TCA'][$table]['ctrl']['readOnly'];
6242
    }
6243
6244
    /**
6245
     * Checks if the $table is only editable by admin-users
6246
     *
6247
     * @param string $table Table name
6248
     * @return bool TRUE, if readonly
6249
     */
6250
    public function tableAdminOnly($table)
6251
    {
6252
        // Returns TRUE if table is admin-only
6253
        return !empty($GLOBALS['TCA'][$table]['ctrl']['adminOnly']);
6254
    }
6255
6256
    /**
6257
     * Checks if page $id is a uid in the rootline of page id $destinationId
6258
     * Used when moving a page
6259
     *
6260
     * @param int $destinationId Destination Page ID to test
6261
     * @param int $id Page ID to test for presence inside Destination
6262
     * @return bool Returns FALSE if ID is inside destination (including equal to)
6263
     */
6264
    public function destNotInsideSelf($destinationId, $id)
6265
    {
6266
        $loopCheck = 100;
6267
        $destinationId = (int)$destinationId;
6268
        $id = (int)$id;
6269
        if ($destinationId === $id) {
6270
            return false;
6271
        }
6272
        while ($destinationId !== 0 && $loopCheck > 0) {
6273
            $loopCheck--;
6274
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6275
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6276
            $result = $queryBuilder
6277
                ->select('pid', 'uid', 't3ver_oid', 't3ver_wsid')
6278
                ->from('pages')
6279
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($destinationId, \PDO::PARAM_INT)))
6280
                ->execute();
6281
            if ($row = $result->fetch()) {
6282
                BackendUtility::fixVersioningPid('pages', $row);
6283
                if ($row['pid'] == $id) {
6284
                    return false;
6285
                }
6286
                $destinationId = (int)$row['pid'];
6287
            } else {
6288
                return false;
6289
            }
6290
        }
6291
        return true;
6292
    }
6293
6294
    /**
6295
     * 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
6296
     * Will also generate this list for admin-users so they must be check for before calling the function
6297
     *
6298
     * @return array Array of [table]-[field] pairs to exclude from editing.
6299
     */
6300
    public function getExcludeListArray()
6301
    {
6302
        $list = [];
6303
        if (isset($this->BE_USER->groupData['non_exclude_fields'])) {
6304
            $nonExcludeFieldsArray = array_flip(GeneralUtility::trimExplode(',', $this->BE_USER->groupData['non_exclude_fields']));
6305
            foreach ($GLOBALS['TCA'] as $table => $tableConfiguration) {
6306
                if (isset($tableConfiguration['columns'])) {
6307
                    foreach ($tableConfiguration['columns'] as $field => $config) {
6308
                        if ($config['exclude'] && !isset($nonExcludeFieldsArray[$table . ':' . $field])) {
6309
                            $list[] = $table . '-' . $field;
6310
                        }
6311
                    }
6312
                }
6313
            }
6314
        }
6315
6316
        return $list;
6317
    }
6318
6319
    /**
6320
     * Checks if there are records on a page from tables that are not allowed
6321
     *
6322
     * @param int $page_uid Page ID
6323
     * @param int $doktype Page doktype
6324
     * @return bool|array Returns a list of the tables that are 'present' on the page but not allowed with the page_uid/doktype
6325
     */
6326
    public function doesPageHaveUnallowedTables($page_uid, $doktype)
6327
    {
6328
        $page_uid = (int)$page_uid;
6329
        if (!$page_uid) {
6330
            // Not a number. Probably a new page
6331
            return false;
6332
        }
6333
        $allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
6334
        // If all tables are allowed, return early
6335
        if (strpos($allowedTableList, '*') !== false) {
6336
            return false;
6337
        }
6338
        $allowedArray = GeneralUtility::trimExplode(',', $allowedTableList, true);
6339
        $tableList = [];
6340
        $allTableNames = $this->compileAdminTables();
6341
        foreach ($allTableNames as $table) {
6342
            // If the table is not in the allowed list, check if there are records...
6343
            if (in_array($table, $allowedArray, true)) {
6344
                continue;
6345
            }
6346
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6347
            $queryBuilder->getRestrictions()->removeAll();
6348
            $count = $queryBuilder
6349
                ->count('uid')
6350
                ->from($table)
6351
                ->where($queryBuilder->expr()->eq(
6352
                    'pid',
6353
                    $queryBuilder->createNamedParameter($page_uid, \PDO::PARAM_INT)
6354
                ))
6355
                ->execute()
6356
                ->fetchColumn(0);
6357
            if ($count) {
6358
                $tableList[] = $table;
6359
            }
6360
        }
6361
        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...
6362
    }
6363
6364
    /*****************************
6365
     *
6366
     * Information lookup
6367
     *
6368
     *****************************/
6369
    /**
6370
     * Returns the value of the $field from page $id
6371
     * 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!
6372
     *
6373
     * @param int $id Page uid
6374
     * @param string $field Field name for which to return value
6375
     * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
6376
     */
6377
    public function pageInfo($id, $field)
6378
    {
6379
        if (!isset($this->pageCache[$id])) {
6380
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
6381
            $queryBuilder->getRestrictions()->removeAll();
6382
            $row = $queryBuilder
6383
                ->select('*')
6384
                ->from('pages')
6385
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6386
                ->execute()
6387
                ->fetch();
6388
            if ($row) {
6389
                $this->pageCache[$id] = $row;
6390
            }
6391
        }
6392
        return $this->pageCache[$id][$field];
6393
    }
6394
6395
    /**
6396
     * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
6397
     * NOTICE: No check for deleted or access!
6398
     *
6399
     * @param string $table Table name
6400
     * @param int $id UID of the record from $table
6401
     * @param string $fieldList Field list for the SELECT query, eg. "*" or "uid,pid,...
6402
     * @return array|null Returns the selected record on success, otherwise NULL.
6403
     */
6404
    public function recordInfo($table, $id, $fieldList)
6405
    {
6406
        // Skip, if searching for NEW records or there's no TCA table definition
6407
        if ((int)$id === 0 || !isset($GLOBALS['TCA'][$table])) {
6408
            return null;
6409
        }
6410
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6411
        $queryBuilder->getRestrictions()->removeAll();
6412
        $result = $queryBuilder
6413
            ->select(...GeneralUtility::trimExplode(',', $fieldList))
6414
            ->from($table)
6415
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6416
            ->execute()
6417
            ->fetch();
6418
        return $result ?: null;
6419
    }
6420
6421
    /**
6422
     * Checks if record exists with and without permission check and returns that row
6423
     *
6424
     * @param string $table Record table name
6425
     * @param int $id Record UID
6426
     * @param int|string $perms Permission restrictions to observe: Either an integer that will be bitwise AND'ed or a string, which points to a key in the ->pMap array. With TYPO3 v11, only integers are allowed
6427
     * @param string $fieldList - fields - default is '*'
6428
     * @throws \RuntimeException
6429
     * @return array|bool Row if exists and accessible, false otherwise
6430
     */
6431
    protected function recordInfoWithPermissionCheck(string $table, int $id, $perms, string $fieldList = '*')
6432
    {
6433
        if ($this->bypassAccessCheckForRecords) {
6434
            $columns = GeneralUtility::trimExplode(',', $fieldList, true);
6435
6436
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6437
            $queryBuilder->getRestrictions()->removeAll();
6438
6439
            $record = $queryBuilder->select(...$columns)
6440
                ->from($table)
6441
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6442
                ->execute()
6443
                ->fetch();
6444
6445
            return $record ?: false;
6446
        }
6447
        // Processing the incoming $perms (from possible string to integer that can be AND'ed)
6448
        if (!MathUtility::canBeInterpretedAsInteger($perms)) {
6449
            trigger_error('Support for handing in permissions as string into "recordInfoWithPermissionCheck" will be not be supported with TYPO3 v11 anymore. Use the Permission BitSet class instead.', E_USER_DEPRECATED);
6450
            if ($table !== 'pages') {
6451
                switch ($perms) {
6452
                    case 'edit':
6453
                    case 'delete':
6454
                    case 'new':
6455
                        // This holds it all in case the record is not page!!
6456
                        if ($table === 'sys_file_reference' && array_key_exists('pages', $this->datamap)) {
6457
                            $perms = 'edit';
6458
                        } else {
6459
                            $perms = 'editcontent';
6460
                        }
6461
                        break;
6462
                }
6463
            }
6464
            $perms = (int)(Permission::getMap()[$perms] ?? 0);
6465
        } else {
6466
            $perms = (int)$perms;
6467
        }
6468
        if (!$perms) {
6469
            throw new \RuntimeException('Internal ERROR: no permissions to check for non-admin user', 1270853920);
6470
        }
6471
        // For all tables: Check if record exists:
6472
        $isWebMountRestrictionIgnored = BackendUtility::isWebMountRestrictionIgnored($table);
6473
        if (is_array($GLOBALS['TCA'][$table]) && $id > 0 && ($this->admin || $isWebMountRestrictionIgnored || $this->isRecordInWebMount($table, $id))) {
6474
            $columns = GeneralUtility::trimExplode(',', $fieldList, true);
6475
            if ($table !== 'pages') {
6476
                // Find record without checking page
6477
                // @todo: This should probably check for editlock
6478
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6479
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6480
                $output = $queryBuilder
6481
                    ->select(...$columns)
6482
                    ->from($table)
6483
                    ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6484
                    ->execute()
6485
                    ->fetch();
6486
                BackendUtility::fixVersioningPid($table, $output, true);
6487
                // If record found, check page as well:
6488
                if (is_array($output)) {
6489
                    // Looking up the page for record:
6490
                    $pageRec = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
6491
                    // 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):
6492
                    $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
6493
                    if (is_array($pageRec) || !$output['pid'] && ($this->admin || $isRootLevelRestrictionIgnored)) {
6494
                        return $output;
6495
                    }
6496
                }
6497
                return false;
6498
            }
6499
            return $this->doesRecordExist_pageLookUp($id, $perms, $columns);
6500
        }
6501
        return false;
6502
    }
6503
6504
    /**
6505
     * Returns an array with record properties, like header and pid
6506
     * No check for deleted or access is done!
6507
     * For versionized records, pid is resolved to its live versions pid.
6508
     * Used for logging
6509
     *
6510
     * @param string $table Table name
6511
     * @param int $id Uid of record
6512
     * @param bool $noWSOL If set, no workspace overlay is performed
6513
     * @return array Properties of record
6514
     */
6515
    public function getRecordProperties($table, $id, $noWSOL = false)
6516
    {
6517
        $row = $table === 'pages' && !$id ? ['title' => '[root-level]', 'uid' => 0, 'pid' => 0] : $this->recordInfo($table, $id, '*');
6518
        if (!$noWSOL) {
6519
            BackendUtility::workspaceOL($table, $row);
6520
        }
6521
        return $this->getRecordPropertiesFromRow($table, $row);
6522
    }
6523
6524
    /**
6525
     * Returns an array with record properties, like header and pid, based on the row
6526
     *
6527
     * @param string $table Table name
6528
     * @param array $row Input row
6529
     * @return array|null Output array
6530
     */
6531
    public function getRecordPropertiesFromRow($table, $row)
6532
    {
6533
        if ($GLOBALS['TCA'][$table]) {
6534
            BackendUtility::fixVersioningPid($table, $row);
6535
            $liveUid = ($row['t3ver_oid'] ?? null) ? $row['t3ver_oid'] : $row['uid'];
6536
            return [
6537
                'header' => BackendUtility::getRecordTitle($table, $row),
6538
                'pid' => $row['pid'],
6539
                'event_pid' => $this->eventPid($table, (int)$liveUid, $row['pid']),
6540
                't3ver_state' => BackendUtility::isTableWorkspaceEnabled($table) ? $row['t3ver_state'] : '',
6541
                '_ORIG_pid' => $row['_ORIG_pid']
6542
            ];
6543
        }
6544
        return null;
6545
    }
6546
6547
    /**
6548
     * @param string $table
6549
     * @param int $uid
6550
     * @param int $pid
6551
     * @return int
6552
     */
6553
    public function eventPid($table, $uid, $pid)
6554
    {
6555
        return $table === 'pages' ? $uid : $pid;
6556
    }
6557
6558
    /*********************************************
6559
     *
6560
     * Storing data to Database Layer
6561
     *
6562
     ********************************************/
6563
    /**
6564
     * Update database record
6565
     * Does not check permissions but expects them to be verified on beforehand
6566
     *
6567
     * @param string $table Record table name
6568
     * @param int $id Record uid
6569
     * @param array $fieldArray Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
6570
     */
6571
    public function updateDB($table, $id, $fieldArray)
6572
    {
6573
        if (is_array($fieldArray) && is_array($GLOBALS['TCA'][$table]) && (int)$id) {
6574
            // Do NOT update the UID field, ever!
6575
            unset($fieldArray['uid']);
6576
            if (!empty($fieldArray)) {
6577
                $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
6578
6579
                $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
6580
6581
                $types = [];
6582
                $platform = $connection->getDatabasePlatform();
6583
                if ($platform instanceof SQLServerPlatform) {
6584
                    // mssql needs to set proper PARAM_LOB and others to update fields
6585
                    $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
6586
                    foreach ($fieldArray as $columnName => $columnValue) {
6587
                        $types[$columnName] = $tableDetails->getColumn($columnName)->getType()->getBindingType();
6588
                    }
6589
                }
6590
6591
                // Execute the UPDATE query:
6592
                $updateErrorMessage = '';
6593
                try {
6594
                    $connection->update($table, $fieldArray, ['uid' => (int)$id], $types);
6595
                } catch (DBALException $e) {
6596
                    $updateErrorMessage = $e->getPrevious()->getMessage();
6597
                }
6598
                // If succeeds, do...:
6599
                if ($updateErrorMessage === '') {
6600
                    // Update reference index:
6601
                    $this->updateRefIndex($table, $id);
6602
                    // Set History data
6603
                    $historyEntryId = 0;
6604
                    if (isset($this->historyRecords[$table . ':' . $id])) {
6605
                        $historyEntryId = $this->getRecordHistoryStore()->modifyRecord($table, $id, $this->historyRecords[$table . ':' . $id], $this->correlationId);
6606
                    }
6607
                    if ($this->enableLogging) {
6608
                        if ($this->checkStoredRecords) {
6609
                            $newRow = $this->checkStoredRecord($table, $id, $fieldArray, SystemLogDatabaseAction::UPDATE);
6610
                        } else {
6611
                            $newRow = $fieldArray;
6612
                            $newRow['uid'] = $id;
6613
                        }
6614
                        // Set log entry:
6615
                        $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
6616
                        $isOfflineVersion = (bool)($newRow['t3ver_oid'] ?? 0);
6617
                        $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']);
6618
                    }
6619
                    // Clear cache for relevant pages:
6620
                    $this->registerRecordIdForPageCacheClearing($table, $id);
6621
                    // Unset the pageCache for the id if table was page.
6622
                    if ($table === 'pages') {
6623
                        unset($this->pageCache[$id]);
6624
                    }
6625
                } else {
6626
                    $this->log($table, $id, SystemLogDatabaseAction::UPDATE, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$updateErrorMessage, $table . ':' . $id]);
6627
                }
6628
            }
6629
        }
6630
    }
6631
6632
    /**
6633
     * Insert into database
6634
     * Does not check permissions but expects them to be verified on beforehand
6635
     *
6636
     * @param string $table Record table name
6637
     * @param string $id "NEW...." uid string
6638
     * @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!
6639
     * @param bool $newVersion Set to TRUE if new version is created.
6640
     * @param int $suggestedUid Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
6641
     * @param bool $dontSetNewIdIndex If TRUE, the ->substNEWwithIDs array is not updated. Only useful in very rare circumstances!
6642
     * @return int|null Returns ID on success.
6643
     */
6644
    public function insertDB($table, $id, $fieldArray, $newVersion = false, $suggestedUid = 0, $dontSetNewIdIndex = false)
6645
    {
6646
        if (is_array($fieldArray) && is_array($GLOBALS['TCA'][$table]) && isset($fieldArray['pid'])) {
6647
            // Do NOT insert the UID field, ever!
6648
            unset($fieldArray['uid']);
6649
            if (!empty($fieldArray)) {
6650
                // Check for "suggestedUid".
6651
                // This feature is used by the import functionality to force a new record to have a certain UID value.
6652
                // This is only recommended for use when the destination server is a passive mirror of another server.
6653
                // As a security measure this feature is available only for Admin Users (for now)
6654
                $suggestedUid = (int)$suggestedUid;
6655
                if ($this->BE_USER->isAdmin() && $suggestedUid && $this->suggestedInsertUids[$table . ':' . $suggestedUid]) {
6656
                    // When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
6657
                    if ($this->suggestedInsertUids[$table . ':' . $suggestedUid] === 'DELETE') {
6658
                        // DELETE:
6659
                        GeneralUtility::makeInstance(ConnectionPool::class)
6660
                            ->getConnectionForTable($table)
6661
                            ->delete($table, ['uid' => (int)$suggestedUid]);
6662
                    }
6663
                    $fieldArray['uid'] = $suggestedUid;
6664
                }
6665
                $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
6666
                $typeArray = [];
6667
                if (!empty($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'])
6668
                    && array_key_exists($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'], $fieldArray)
6669
                ) {
6670
                    $typeArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = Connection::PARAM_LOB;
6671
                }
6672
                $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
6673
                $insertErrorMessage = '';
6674
                try {
6675
                    // Execute the INSERT query:
6676
                    $connection->insert(
6677
                        $table,
6678
                        $fieldArray,
6679
                        $typeArray
6680
                    );
6681
                } catch (DBALException $e) {
6682
                    $insertErrorMessage = $e->getPrevious()->getMessage();
6683
                }
6684
                // If succees, do...:
6685
                if ($insertErrorMessage === '') {
6686
                    // Set mapping for NEW... -> real uid:
6687
                    // the NEW_id now holds the 'NEW....' -id
6688
                    $NEW_id = $id;
6689
                    $id = $this->postProcessDatabaseInsert($connection, $table, $suggestedUid);
6690
6691
                    if (!$dontSetNewIdIndex) {
6692
                        $this->substNEWwithIDs[$NEW_id] = $id;
6693
                        $this->substNEWwithIDs_table[$NEW_id] = $table;
6694
                    }
6695
                    $newRow = [];
6696
                    if ($this->enableLogging) {
6697
                        // Checking the record is properly saved if configured
6698
                        if ($this->checkStoredRecords) {
6699
                            $newRow = $this->checkStoredRecord($table, $id, $fieldArray, SystemLogDatabaseAction::INSERT);
6700
                        } else {
6701
                            $newRow = $fieldArray;
6702
                            $newRow['uid'] = $id;
6703
                        }
6704
                    }
6705
                    // Update reference index:
6706
                    $this->updateRefIndex($table, $id);
6707
6708
                    // Store in history
6709
                    $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

6709
                    $this->getRecordHistoryStore()->addRecord($table, $id, /** @scrutinizer ignore-type */ $newRow, $this->correlationId);
Loading history...
6710
6711
                    if ($newVersion) {
6712
                        if ($this->enableLogging) {
6713
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
6714
                            $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);
6715
                        }
6716
                    } else {
6717
                        if ($this->enableLogging) {
6718
                            $propArr = $this->getRecordPropertiesFromRow($table, $newRow);
6719
                            $page_propArr = $this->getRecordProperties('pages', $propArr['pid']);
6720
                            $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);
6721
                        }
6722
                        // Clear cache for relevant pages:
6723
                        $this->registerRecordIdForPageCacheClearing($table, $id);
6724
                    }
6725
                    return $id;
6726
                }
6727
                if ($this->enableLogging) {
6728
                    $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

6728
                    $this->log($table, /** @scrutinizer ignore-type */ $id, SystemLogDatabaseAction::INSERT, 0, SystemLogErrorClassification::SYSTEM_ERROR, 'SQL error: \'%s\' (%s)', 12, [$insertErrorMessage, $table . ':' . $id]);
Loading history...
6729
                }
6730
            }
6731
        }
6732
        return null;
6733
    }
6734
6735
    /**
6736
     * Checking stored record to see if the written values are properly updated.
6737
     *
6738
     * @param string $table Record table name
6739
     * @param int $id Record uid
6740
     * @param array $fieldArray Array of field=>value pairs to insert/update
6741
     * @param string $action Action, for logging only.
6742
     * @return array|null Selected row
6743
     * @see insertDB()
6744
     * @see updateDB()
6745
     */
6746
    public function checkStoredRecord($table, $id, $fieldArray, $action)
6747
    {
6748
        $id = (int)$id;
6749
        if (is_array($GLOBALS['TCA'][$table]) && $id) {
6750
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
6751
            $queryBuilder->getRestrictions()->removeAll();
6752
6753
            $row = $queryBuilder
6754
                ->select('*')
6755
                ->from($table)
6756
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
6757
                ->execute()
6758
                ->fetch();
6759
6760
            if (!empty($row)) {
6761
                // Traverse array of values that was inserted into the database and compare with the actually stored value:
6762
                $errors = [];
6763
                foreach ($fieldArray as $key => $value) {
6764
                    if (!$this->checkStoredRecords_loose || $value || $row[$key]) {
6765
                        if (is_float($row[$key])) {
6766
                            // if the database returns the value as double, compare it as double
6767
                            if ((double)$value !== (double)$row[$key]) {
6768
                                $errors[] = $key;
6769
                            }
6770
                        } else {
6771
                            $dbType = $GLOBALS['TCA'][$table]['columns'][$key]['config']['dbType'] ?? false;
6772
                            if ($dbType === 'datetime' || $dbType === 'time') {
6773
                                $row[$key] = $this->normalizeTimeFormat($table, $row[$key], $dbType);
6774
                            }
6775
                            if ((string)$value !== (string)$row[$key]) {
6776
                                // The is_numeric check catches cases where we want to store a float/double value
6777
                                // and database returns the field as a string with the least required amount of
6778
                                // significant digits, i.e. "0.00" being saved and "0" being read back.
6779
                                if (is_numeric($value) && is_numeric($row[$key])) {
6780
                                    if ((double)$value === (double)$row[$key]) {
6781
                                        continue;
6782
                                    }
6783
                                }
6784
                                $errors[] = $key;
6785
                            }
6786
                        }
6787
                    }
6788
                }
6789
                // Set log message if there were fields with unmatching values:
6790
                if (!empty($errors)) {
6791
                    $message = sprintf(
6792
                        '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.',
6793
                        $id,
6794
                        $table,
6795
                        implode(', ', $errors)
6796
                    );
6797
                    $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

6797
                    $this->log($table, $id, /** @scrutinizer ignore-type */ $action, 0, SystemLogErrorClassification::USER_ERROR, $message);
Loading history...
6798
                }
6799
                // Return selected rows:
6800
                return $row;
6801
            }
6802
        }
6803
        return null;
6804
    }
6805
6806
    /**
6807
     * Setting sys_history record, based on content previously set in $this->historyRecords[$table . ':' . $id] (by compareFieldArrayWithCurrentAndUnset())
6808
     *
6809
     * This functionality is now moved into the RecordHistoryStore and can be used instead.
6810
     *
6811
     * @param string $table Table name
6812
     * @param int $id Record ID
6813
     * @param int $logId Log entry ID, important for linking between log and history views
6814
     */
6815
    public function setHistory($table, $id, $logId)
6816
    {
6817
        if (isset($this->historyRecords[$table . ':' . $id])) {
6818
            $this->getRecordHistoryStore()->modifyRecord(
6819
                $table,
6820
                $id,
6821
                $this->historyRecords[$table . ':' . $id],
6822
                $this->correlationId
6823
            );
6824
        }
6825
    }
6826
6827
    /**
6828
     * @return RecordHistoryStore
6829
     */
6830
    protected function getRecordHistoryStore(): RecordHistoryStore
6831
    {
6832
        return GeneralUtility::makeInstance(
6833
            RecordHistoryStore::class,
6834
            RecordHistoryStore::USER_BACKEND,
6835
            $this->BE_USER->user['uid'],
6836
            $this->BE_USER->user['ses_backuserid'] ?? null,
6837
            $GLOBALS['EXEC_TIME'],
6838
            $this->BE_USER->workspace
6839
        );
6840
    }
6841
6842
    /**
6843
     * Update Reference Index (sys_refindex) for a record
6844
     * Should be called any almost any update to a record which could affect references inside the record.
6845
     *
6846
     * @param string $table Table name
6847
     * @param int $id Record UID
6848
     */
6849
    public function updateRefIndex($table, $id)
6850
    {
6851
        /** @var ReferenceIndex $refIndexObj */
6852
        $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class);
6853
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
6854
            $refIndexObj->setWorkspaceId($this->BE_USER->workspace);
6855
        }
6856
        $refIndexObj->enableRuntimeCache();
6857
        $refIndexObj->updateRefIndexTable($table, $id);
6858
    }
6859
6860
    /*********************************************
6861
     *
6862
     * Misc functions
6863
     *
6864
     ********************************************/
6865
    /**
6866
     * Returning sorting number for tables with a "sortby" column
6867
     * Using when new records are created and existing records are moved around.
6868
     *
6869
     * The strategy is:
6870
     *  - if no record exists: set interval as sorting number
6871
     *  - if inserted before an element: put in the middle of the existing elements
6872
     *  - if inserted behind the last element: add interval to last sorting number
6873
     *  - if collision: move all subsequent records by 2 * interval, insert new record with collision + interval
6874
     *
6875
     * How to calculate the maximum possible inserts for the worst case of adding all records to the top,
6876
     * such that the sorting number stays within INT_MAX
6877
     *
6878
     * i = interval (currently 256)
6879
     * c = number of inserts until collision
6880
     * s = max sorting number to reach (INT_MAX - 32bit)
6881
     * n = number of records (~83 million)
6882
     *
6883
     * c = 2 * g
6884
     * g = log2(i) / 2 + 1
6885
     * n = g * s / i - g + 1
6886
     *
6887
     * The algorithm can be tuned by adjusting the interval value.
6888
     * Higher value means less collisions, but also less inserts are possible to stay within INT_MAX.
6889
     *
6890
     * @param string $table Table name
6891
     * @param int $uid Uid of record to find sorting number for. May be zero in case of new.
6892
     * @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)
6893
     * @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.
6894
     */
6895
    public function getSortNumber($table, $uid, $pid)
6896
    {
6897
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
6898
        if (!$sortColumn) {
6899
            return null;
6900
        }
6901
6902
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
6903
        $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
6904
        $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6905
        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->BE_USER->workspace));
6906
6907
        $queryBuilder
6908
            ->select($sortColumn, 'pid', 'uid')
6909
            ->from($table);
6910
6911
        // find and return the sorting value for the first record on that pid
6912
        if ($pid >= 0) {
6913
            // Fetches the first record (lowest sorting) under this pid
6914
            $row = $queryBuilder
6915
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
6916
                ->orderBy($sortColumn, 'ASC')
6917
                ->addOrderBy('uid', 'ASC')
6918
                ->setMaxResults(1)
6919
                ->execute()
6920
                ->fetch();
6921
6922
            if (!empty($row)) {
6923
                // The top record was the record itself, so we return its current sorting value
6924
                if ($row['uid'] == $uid) {
6925
                    return $row[$sortColumn];
6926
                }
6927
                // If the record sorting value < 1 we must resort all the records under this pid
6928
                if ($row[$sortColumn] < 1) {
6929
                    $this->increaseSortingOfFollowingRecords($table, (int)$pid);
6930
                    // Lowest sorting value after full resorting is $sortIntervals
6931
                    return $this->sortIntervals;
6932
                }
6933
                // Sorting number between current top element and zero
6934
                return floor($row[$sortColumn] / 2);
6935
            }
6936
            // No records, so we choose the default value as sorting-number
6937
            return $this->sortIntervals;
6938
        }
6939
6940
        // Find and return first possible sorting value AFTER record with given uid ($pid)
6941
        // Fetches the record which is supposed to be the prev record
6942
        $row = $queryBuilder
6943
                ->where($queryBuilder->expr()->eq(
6944
                    'uid',
6945
                    $queryBuilder->createNamedParameter(abs($pid), \PDO::PARAM_INT)
6946
                ))
6947
                ->execute()
6948
                ->fetch();
6949
6950
        // There is a previous record
6951
        if (!empty($row)) {
6952
            // Look, if the record UID happens to be an offline record. If so, find its live version.
6953
            // Offline uids will be used when a page is versionized as "branch" so this is when we must correct
6954
            // - otherwise a pid of "-1" and a wrong sort-row number is returned which we don't want.
6955
            if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $row['uid'], $sortColumn . ',pid,uid')) {
6956
                $row = $lookForLiveVersion;
6957
            }
6958
            // Fetch move placeholder, since it might point to a new page in the current workspace
6959
            if ($movePlaceholder = BackendUtility::getMovePlaceholder($table, $row['uid'], 'uid,pid,' . $sortColumn)) {
6960
                $row = $movePlaceholder;
6961
            }
6962
            // If the record should be inserted after itself, keep the current sorting information:
6963
            if ((int)$row['uid'] === (int)$uid) {
6964
                $sortNumber = $row[$sortColumn];
6965
            } else {
6966
                $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
6967
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
6968
                $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->BE_USER->workspace));
6969
6970
                $subResults = $queryBuilder
6971
                        ->select($sortColumn, 'pid', 'uid')
6972
                        ->from($table)
6973
                        ->where(
6974
                            $queryBuilder->expr()->eq(
6975
                                'pid',
6976
                                $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
6977
                            ),
6978
                            $queryBuilder->expr()->gte(
6979
                                $sortColumn,
6980
                                $queryBuilder->createNamedParameter($row[$sortColumn], \PDO::PARAM_INT)
6981
                            )
6982
                        )
6983
                        ->orderBy($sortColumn, 'ASC')
6984
                        ->addOrderBy('uid', 'DESC')
6985
                        ->setMaxResults(2)
6986
                        ->execute()
6987
                        ->fetchAll();
6988
                // Fetches the next record in order to calculate the in-between sortNumber
6989
                // There was a record afterwards
6990
                if (count($subResults) === 2) {
6991
                    // There was a record afterwards, fetch that
6992
                    $subrow = array_pop($subResults);
6993
                    // The sortNumber is found in between these values
6994
                    $sortNumber = $row[$sortColumn] + floor(($subrow[$sortColumn] - $row[$sortColumn]) / 2);
6995
                    // The sortNumber happened NOT to be between the two surrounding numbers, so we'll have to resort the list
6996
                    if ($sortNumber <= $row[$sortColumn] || $sortNumber >= $subrow[$sortColumn]) {
6997
                        $this->increaseSortingOfFollowingRecords($table, (int)$row['pid'], (int)$row[$sortColumn]);
6998
                        $sortNumber = $row[$sortColumn] + $this->sortIntervals;
6999
                    }
7000
                } else {
7001
                    // If after the last record in the list, we just add the sortInterval to the last sortvalue
7002
                    $sortNumber = $row[$sortColumn] + $this->sortIntervals;
7003
                }
7004
            }
7005
            return ['pid' => $row['pid'], 'sortNumber' => $sortNumber];
7006
        }
7007
        if ($this->enableLogging) {
7008
            $propArr = $this->getRecordProperties($table, $uid);
7009
            // OK, don't insert $propArr['event_pid'] here...
7010
            $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']);
7011
        }
7012
        // There MUST be a previous record or else this cannot work
7013
        return false;
7014
    }
7015
7016
    /**
7017
     * Increases sorting field value of all records with sorting higher than $sortingValue
7018
     *
7019
     * Used internally by getSortNumber() to "make space" in sorting values when inserting new record
7020
     *
7021
     * @param string $table Table name
7022
     * @param int $pid Page Uid in which to resort records
7023
     * @param int $sortingValue All sorting numbers larger than this number will be shifted
7024
     * @see getSortNumber()
7025
     */
7026
    protected function increaseSortingOfFollowingRecords(string $table, int $pid, int $sortingValue = null): void
7027
    {
7028
        $sortBy = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7029
        if ($sortBy) {
7030
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7031
7032
            $queryBuilder
7033
                ->update($table)
7034
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
7035
                ->set($sortBy, $queryBuilder->quoteIdentifier($sortBy) . ' + ' . $this->sortIntervals . ' + ' . $this->sortIntervals, false);
7036
            if ($sortingValue !== null) {
7037
                $queryBuilder->andWhere($queryBuilder->expr()->gt($sortBy, $sortingValue));
7038
            }
7039
7040
            $deleteColumn = $GLOBALS['TCA'][$table]['ctrl']['delete'] ?? '';
7041
            if ($deleteColumn) {
7042
                $queryBuilder->andWhere($queryBuilder->expr()->eq($deleteColumn, 0));
7043
            }
7044
7045
            $queryBuilder->execute();
7046
        }
7047
    }
7048
7049
    /**
7050
     * Returning uid of previous localized record, if any, for tables with a "sortby" column
7051
     * Used when new localized records are created so that localized records are sorted in the same order as the default language records
7052
     *
7053
     * For a given record (A) uid (record we're translating) it finds first default language record (from the same colpos)
7054
     * with sorting smaller than given record (B).
7055
     * Then it fetches a translated version of record B and returns it's uid.
7056
     *
7057
     * If there is no record B, or it has no translation in given language, the record A uid is returned.
7058
     * The localized record will be placed the after record which uid is returned.
7059
     *
7060
     * @param string $table Table name
7061
     * @param int $uid Uid of default language record
7062
     * @param int $pid Pid of default language record
7063
     * @param int $language Language of localization
7064
     * @return int uid of record after which the localized record should be inserted
7065
     */
7066
    protected function getPreviousLocalizedRecordUid($table, $uid, $pid, $language)
7067
    {
7068
        $previousLocalizedRecordUid = $uid;
7069
        $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
7070
        if ($sortColumn) {
7071
            $select = [$sortColumn, 'pid', 'uid'];
7072
            // For content elements, we also need the colPos
7073
            if ($table === 'tt_content') {
7074
                $select[] = 'colPos';
7075
            }
7076
            // Get the sort value of the default language record
7077
            $row = BackendUtility::getRecord($table, $uid, implode(',', $select));
7078
            if (is_array($row)) {
7079
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7080
                $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7081
7082
                $queryBuilder
7083
                    ->select(...$select)
7084
                    ->from($table)
7085
                    ->where(
7086
                        $queryBuilder->expr()->eq(
7087
                            'pid',
7088
                            $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
7089
                        ),
7090
                        $queryBuilder->expr()->eq(
7091
                            $GLOBALS['TCA'][$table]['ctrl']['languageField'],
7092
                            $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
7093
                        ),
7094
                        $queryBuilder->expr()->lt(
7095
                            $sortColumn,
7096
                            $queryBuilder->createNamedParameter($row[$sortColumn], \PDO::PARAM_INT)
7097
                        )
7098
                    )
7099
                    ->orderBy($sortColumn, 'DESC')
7100
                    ->addOrderBy('uid', 'DESC')
7101
                    ->setMaxResults(1);
7102
                if ($table === 'tt_content') {
7103
                    $queryBuilder
7104
                        ->andWhere(
7105
                            $queryBuilder->expr()->eq(
7106
                                'colPos',
7107
                                $queryBuilder->createNamedParameter($row['colPos'], \PDO::PARAM_INT)
7108
                            )
7109
                        );
7110
                }
7111
                // If there is an element, find its localized record in specified localization language
7112
                if ($previousRow = $queryBuilder->execute()->fetch()) {
7113
                    $previousLocalizedRecord = BackendUtility::getRecordLocalization($table, $previousRow['uid'], $language);
7114
                    if (is_array($previousLocalizedRecord[0])) {
7115
                        $previousLocalizedRecordUid = $previousLocalizedRecord[0]['uid'];
7116
                    }
7117
                }
7118
            }
7119
        }
7120
        return $previousLocalizedRecordUid;
7121
    }
7122
7123
    /**
7124
     * Setting up perms_* fields in $fieldArray based on TSconfig input
7125
     * Used for new pages
7126
     *
7127
     * @param array $fieldArray Field Array, returned with modifications
7128
     * @param array $TSConfig_p TSconfig properties
7129
     * @return array Modified Field Array
7130
     * @deprecated will be removed in TYPO3 v11.0 - Use PagePermissionAssembler instead.
7131
     */
7132
    public function setTSconfigPermissions($fieldArray, $TSConfig_p)
7133
    {
7134
        trigger_error('DataHandler->setTSconfigPermissions will be removed in TYPO3 v11.0. Use the PagePermissionAssembler API instead.', E_USER_DEPRECATED);
7135
        if ((string)$TSConfig_p['userid'] !== '') {
7136
            $fieldArray['perms_userid'] = (int)$TSConfig_p['userid'];
7137
        }
7138
        if ((string)$TSConfig_p['groupid'] !== '') {
7139
            $fieldArray['perms_groupid'] = (int)$TSConfig_p['groupid'];
7140
        }
7141
        if ((string)$TSConfig_p['user'] !== '') {
7142
            $fieldArray['perms_user'] = MathUtility::canBeInterpretedAsInteger($TSConfig_p['user']) ? $TSConfig_p['user'] : $this->assemblePermissions($TSConfig_p['user']);
7143
        }
7144
        if ((string)$TSConfig_p['group'] !== '') {
7145
            $fieldArray['perms_group'] = MathUtility::canBeInterpretedAsInteger($TSConfig_p['group']) ? $TSConfig_p['group'] : $this->assemblePermissions($TSConfig_p['group']);
7146
        }
7147
        if ((string)$TSConfig_p['everybody'] !== '') {
7148
            $fieldArray['perms_everybody'] = MathUtility::canBeInterpretedAsInteger($TSConfig_p['everybody']) ? $TSConfig_p['everybody'] : $this->assemblePermissions($TSConfig_p['everybody']);
7149
        }
7150
        return $fieldArray;
7151
    }
7152
7153
    /**
7154
     * 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.
7155
     * Used for new records and during copy operations for defaults
7156
     *
7157
     * @param string $table Table name for which to set default values.
7158
     * @return array Array with default values.
7159
     */
7160
    public function newFieldArray($table)
7161
    {
7162
        $fieldArray = [];
7163
        if (is_array($GLOBALS['TCA'][$table]['columns'])) {
7164
            foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $content) {
7165
                if (isset($this->defaultValues[$table][$field])) {
7166
                    $fieldArray[$field] = $this->defaultValues[$table][$field];
7167
                } elseif (isset($content['config']['default'])) {
7168
                    $fieldArray[$field] = $content['config']['default'];
7169
                }
7170
            }
7171
        }
7172
        return $fieldArray;
7173
    }
7174
7175
    /**
7176
     * 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.
7177
     *
7178
     * @param string $table Table name
7179
     * @param array $incomingFieldArray Incoming array (passed by reference)
7180
     */
7181
    public function addDefaultPermittedLanguageIfNotSet($table, &$incomingFieldArray)
7182
    {
7183
        // Checking languages:
7184
        if ($GLOBALS['TCA'][$table]['ctrl']['languageField']) {
7185
            if (!isset($incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
7186
                // Language field must be found in input row - otherwise it does not make sense.
7187
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
7188
                    ->getQueryBuilderForTable('sys_language');
7189
                $queryBuilder->getRestrictions()
7190
                    ->removeAll()
7191
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7192
                $queryBuilder
7193
                    ->select('uid')
7194
                    ->from('sys_language')
7195
                    ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)));
7196
                $rows = array_merge([['uid' => 0]], $queryBuilder->execute()->fetchAll(), [['uid' => -1]]);
7197
                foreach ($rows as $r) {
7198
                    if ($this->BE_USER->checkLanguageAccess($r['uid'])) {
7199
                        $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $r['uid'];
7200
                        break;
7201
                    }
7202
                }
7203
            }
7204
        }
7205
    }
7206
7207
    /**
7208
     * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
7209
     *
7210
     * @param string $table Table name
7211
     * @param array $data Data array with fields from table. These will be overlaid with values in $this->overrideValues[$table]
7212
     * @return array Data array, processed.
7213
     */
7214
    public function overrideFieldArray($table, $data)
7215
    {
7216
        if (is_array($this->overrideValues[$table])) {
7217
            $data = array_merge($data, $this->overrideValues[$table]);
7218
        }
7219
        return $data;
7220
    }
7221
7222
    /**
7223
     * Compares the incoming field array with the current record and unsets all fields which are the same.
7224
     * Used for existing records being updated
7225
     *
7226
     * @param string $table Record table name
7227
     * @param int $id Record uid
7228
     * @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!
7229
     * @return array Returns $fieldArray. If the returned array is empty, then the record should not be updated!
7230
     */
7231
    public function compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray)
7232
    {
7233
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
7234
        $queryBuilder = $connection->createQueryBuilder();
7235
        $queryBuilder->getRestrictions()->removeAll();
7236
        $currentRecord = $queryBuilder->select('*')
7237
            ->from($table)
7238
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)))
7239
            ->execute()
7240
            ->fetch();
7241
        // If the current record exists (which it should...), begin comparison:
7242
        if (is_array($currentRecord)) {
7243
            $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
7244
            $columnRecordTypes = [];
7245
            foreach ($currentRecord as $columnName => $_) {
7246
                $columnRecordTypes[$columnName] = '';
7247
                $type = $tableDetails->getColumn($columnName)->getType();
7248
                if ($type instanceof IntegerType) {
7249
                    $columnRecordTypes[$columnName] = 'int';
7250
                }
7251
            }
7252
            // Unset the fields which are similar:
7253
            foreach ($fieldArray as $col => $val) {
7254
                $fieldConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
7255
                $isNullField = (!empty($fieldConfiguration['eval']) && GeneralUtility::inList($fieldConfiguration['eval'], 'null'));
7256
7257
                // Unset fields if stored and submitted values are equal - except the current field holds MM relations.
7258
                // In general this avoids to store superfluous data which also will be visualized in the editing history.
7259
                if (!$fieldConfiguration['MM'] && $this->isSubmittedValueEqualToStoredValue($val, $currentRecord[$col], $columnRecordTypes[$col], $isNullField)) {
7260
                    unset($fieldArray[$col]);
7261
                } else {
7262
                    if (!isset($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col])) {
7263
                        $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $currentRecord[$col];
7264
                    } elseif ($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col]) {
7265
                        $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col];
7266
                    }
7267
                    if (!isset($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col])) {
7268
                        $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $fieldArray[$col];
7269
                    } elseif ($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col]) {
7270
                        $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col];
7271
                    }
7272
                }
7273
            }
7274
        } else {
7275
            // If the current record does not exist this is an error anyways and we just return an empty array here.
7276
            $fieldArray = [];
7277
        }
7278
        return $fieldArray;
7279
    }
7280
7281
    /**
7282
     * Determines whether submitted values and stored values are equal.
7283
     * This prevents from adding superfluous field changes which would be shown in the record history as well.
7284
     * For NULL fields (see accordant TCA definition 'eval' = 'null'), a special handling is required since
7285
     * (!strcmp(NULL, '')) would be a false-positive.
7286
     *
7287
     * @param mixed $submittedValue Value that has submitted (e.g. from a backend form)
7288
     * @param mixed $storedValue Value that is currently stored in the database
7289
     * @param string $storedType SQL type of the stored value column (see mysql_field_type(), e.g 'int', 'string',  ...)
7290
     * @param bool $allowNull Whether NULL values are allowed by accordant TCA definition ('eval' = 'null')
7291
     * @return bool Whether both values are considered to be equal
7292
     */
7293
    protected function isSubmittedValueEqualToStoredValue($submittedValue, $storedValue, $storedType, $allowNull = false)
7294
    {
7295
        // No NULL values are allowed, this is the regular behaviour.
7296
        // Thus, check whether strings are the same or whether integer values are empty ("0" or "").
7297
        if (!$allowNull) {
7298
            $result = (string)$submittedValue === (string)$storedValue || $storedType === 'int' && (int)$storedValue === (int)$submittedValue;
7299
        // Null values are allowed, but currently there's a real (not NULL) value.
7300
        // Thus, ensure no NULL value was submitted and fallback to the regular behaviour.
7301
        } elseif ($storedValue !== null) {
7302
            $result = (
7303
                $submittedValue !== null
7304
                && $this->isSubmittedValueEqualToStoredValue($submittedValue, $storedValue, $storedType, false)
7305
            );
7306
        // Null values are allowed, and currently there's a NULL value.
7307
        // Thus, check whether a NULL value was submitted.
7308
        } else {
7309
            $result = ($submittedValue === null);
7310
        }
7311
7312
        return $result;
7313
    }
7314
7315
    /**
7316
     * Calculates the bitvalue of the permissions given in a string, comma-separated
7317
     *
7318
     * @param string $string List of pMap strings
7319
     * @return int Integer mask
7320
     * @see setTSconfigPermissions()
7321
     * @see newFieldArray()
7322
     * @deprecated will be removed in TYPO3 v11.0 - Use PagePermissionAssembler instead.
7323
     */
7324
    public function assemblePermissions($string)
7325
    {
7326
        trigger_error('DataHandler->assemblePermissions will be removed in TYPO3 v11.0. Use the PagePermissionAssembler API instead.', E_USER_DEPRECATED);
7327
        $keyArr = GeneralUtility::trimExplode(',', $string, true);
7328
        $value = 0;
7329
        $permissionMap = Permission::getMap();
7330
        foreach ($keyArr as $key) {
7331
            if ($key && isset($permissionMap[$key])) {
7332
                $value |= $permissionMap[$key];
7333
            }
7334
        }
7335
        return $value;
7336
    }
7337
7338
    /**
7339
     * Converts a HTML entity (like &#123;) to the character '123'
7340
     *
7341
     * @param string $input Input string
7342
     * @return string Output string
7343
     */
7344
    public function convNumEntityToByteValue($input)
7345
    {
7346
        $token = md5(microtime());
7347
        $parts = explode($token, preg_replace('/(&#([0-9]+);)/', $token . '\\2' . $token, $input));
7348
        foreach ($parts as $k => $v) {
7349
            if ($k % 2) {
7350
                $v = (int)$v;
7351
                // Just to make sure that control bytes are not converted.
7352
                if ($v > 32) {
7353
                    $parts[$k] = chr($v);
7354
                }
7355
            }
7356
        }
7357
        return implode('', $parts);
7358
    }
7359
7360
    /**
7361
     * Disables the delete clause for fetching records.
7362
     * In general only undeleted records will be used. If the delete
7363
     * clause is disabled, also deleted records are taken into account.
7364
     */
7365
    public function disableDeleteClause()
7366
    {
7367
        $this->disableDeleteClause = true;
7368
    }
7369
7370
    /**
7371
     * Returns delete-clause for the $table
7372
     *
7373
     * @param string $table Table name
7374
     * @return string Delete clause
7375
     */
7376
    public function deleteClause($table)
7377
    {
7378
        // Returns the proper delete-clause if any for a table from TCA
7379
        if (!$this->disableDeleteClause && $GLOBALS['TCA'][$table]['ctrl']['delete']) {
7380
            return ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
7381
        }
7382
        return '';
7383
    }
7384
7385
    /**
7386
     * Add delete restriction if not disabled
7387
     *
7388
     * @param QueryRestrictionContainerInterface $restrictions
7389
     */
7390
    protected function addDeleteRestriction(QueryRestrictionContainerInterface $restrictions)
7391
    {
7392
        if (!$this->disableDeleteClause) {
7393
            $restrictions->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7394
        }
7395
    }
7396
7397
    /**
7398
     * Gets UID of parent record. If record is deleted it will be looked up in
7399
     * an array built before the record was deleted
7400
     *
7401
     * @param string $table Table where record lives/lived
7402
     * @param int $uid Record UID
7403
     * @return int[] Parent UIDs
7404
     */
7405
    protected function getOriginalParentOfRecord($table, $uid)
7406
    {
7407
        if (isset(self::$recordPidsForDeletedRecords[$table][$uid])) {
7408
            return self::$recordPidsForDeletedRecords[$table][$uid];
7409
        }
7410
        [$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

7410
        [$parentUid] = BackendUtility::getTSCpid($table, $uid, /** @scrutinizer ignore-type */ '');
Loading history...
7411
        return [$parentUid];
7412
    }
7413
7414
    /**
7415
     * Extract entries from TSconfig for a specific table. This will merge specific and default configuration together.
7416
     *
7417
     * @param string $table Table name
7418
     * @param array $TSconfig TSconfig for page
7419
     * @return array TSconfig merged
7420
     */
7421
    public function getTableEntries($table, $TSconfig)
7422
    {
7423
        $tA = is_array($TSconfig['table.'][$table . '.']) ? $TSconfig['table.'][$table . '.'] : [];
7424
        $dA = is_array($TSconfig['default.']) ? $TSconfig['default.'] : [];
7425
        ArrayUtility::mergeRecursiveWithOverrule($dA, $tA);
7426
        return $dA;
7427
    }
7428
7429
    /**
7430
     * Returns the pid of a record from $table with $uid
7431
     *
7432
     * @param string $table Table name
7433
     * @param int $uid Record uid
7434
     * @return int|false PID value (unless the record did not exist in which case FALSE is returned)
7435
     */
7436
    public function getPID($table, $uid)
7437
    {
7438
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7439
        $queryBuilder->getRestrictions()
7440
            ->removeAll();
7441
        $queryBuilder->select('pid')
7442
            ->from($table)
7443
            ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)));
7444
        if ($row = $queryBuilder->execute()->fetch()) {
7445
            return $row['pid'];
7446
        }
7447
        return false;
7448
    }
7449
7450
    /**
7451
     * Executing dbAnalysisStore
7452
     * This will save MM relations for new records but is executed after records are created because we need to know the ID of them
7453
     */
7454
    public function dbAnalysisStoreExec()
7455
    {
7456
        foreach ($this->dbAnalysisStore as $action) {
7457
            $id = BackendUtility::wsMapId($action[4], MathUtility::canBeInterpretedAsInteger($action[2]) ? $action[2] : $this->substNEWwithIDs[$action[2]]);
7458
            if ($id) {
7459
                $action[0]->writeMM($action[1], $id, $action[3]);
7460
            }
7461
        }
7462
    }
7463
7464
    /**
7465
     * Returns array, $CPtable, of pages under the $pid going down to $counter levels.
7466
     * Selecting ONLY pages which the user has read-access to!
7467
     *
7468
     * @param array $CPtable Accumulation of page uid=>pid pairs in branch of $pid
7469
     * @param int $pid Page ID for which to find subpages
7470
     * @param int $counter Number of levels to go down.
7471
     * @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!
7472
     * @return array Return array.
7473
     */
7474
    public function int_pageTreeInfo($CPtable, $pid, $counter, $rootID)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::int_pageTreeInfo" is not in camel caps format
Loading history...
7475
    {
7476
        if ($counter) {
7477
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
7478
            $restrictions = $queryBuilder->getRestrictions()->removeAll();
7479
            $this->addDeleteRestriction($restrictions);
7480
            $queryBuilder
7481
                ->select('uid')
7482
                ->from('pages')
7483
                ->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)))
7484
                ->orderBy('sorting', 'DESC');
7485
            if (!$this->admin) {
7486
                $queryBuilder->andWhere($this->BE_USER->getPagePermsClause(Permission::PAGE_SHOW));
7487
            }
7488
            if ((int)$this->BE_USER->workspace === 0) {
7489
                $queryBuilder->andWhere(
7490
                    $queryBuilder->expr()->eq('t3ver_wsid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
7491
                );
7492
            } else {
7493
                $queryBuilder->andWhere($queryBuilder->expr()->in(
7494
                    't3ver_wsid',
7495
                    $queryBuilder->createNamedParameter([0, $this->BE_USER->workspace], Connection::PARAM_INT_ARRAY)
7496
                ));
7497
            }
7498
            $result = $queryBuilder->execute();
7499
7500
            $pages = [];
7501
            while ($row = $result->fetch()) {
7502
                $pages[$row['uid']] = $row;
7503
            }
7504
7505
            // Resolve placeholders of workspace versions
7506
            if (!empty($pages) && (int)$this->BE_USER->workspace !== 0) {
7507
                $pages = array_reverse(
7508
                    $this->resolveVersionedRecords(
7509
                        'pages',
7510
                        'uid',
7511
                        'sorting',
7512
                        array_keys($pages)
7513
                    ),
7514
                    true
7515
                );
7516
            }
7517
7518
            foreach ($pages as $page) {
7519
                if ($page['uid'] != $rootID) {
7520
                    $CPtable[$page['uid']] = $pid;
7521
                    // If the uid is NOT the rootID of the copyaction and if we are supposed to walk further down
7522
                    if ($counter - 1) {
7523
                        $CPtable = $this->int_pageTreeInfo($CPtable, $page['uid'], $counter - 1, $rootID);
7524
                    }
7525
                }
7526
            }
7527
        }
7528
        return $CPtable;
7529
    }
7530
7531
    /**
7532
     * List of all tables (those administrators has access to = array_keys of $GLOBALS['TCA'])
7533
     *
7534
     * @return array Array of all TCA table names
7535
     */
7536
    public function compileAdminTables()
7537
    {
7538
        return array_keys($GLOBALS['TCA']);
7539
    }
7540
7541
    /**
7542
     * Checks if any uniqueInPid eval input fields are in the record and if so, they are re-written to be correct.
7543
     *
7544
     * @param string $table Table name
7545
     * @param int $uid Record UID
7546
     */
7547
    public function fixUniqueInPid($table, $uid)
7548
    {
7549
        if (empty($GLOBALS['TCA'][$table])) {
7550
            return;
7551
        }
7552
7553
        $curData = $this->recordInfo($table, $uid, '*');
7554
        $newData = [];
7555
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
7556
            if ($conf['config']['type'] === 'input' && (string)$curData[$field] !== '') {
7557
                $evalCodesArray = GeneralUtility::trimExplode(',', $conf['config']['eval'], true);
7558
                if (in_array('uniqueInPid', $evalCodesArray, true)) {
7559
                    $newV = $this->getUnique($table, $field, $curData[$field], $uid, $curData['pid']);
7560
                    if ((string)$newV !== (string)$curData[$field]) {
7561
                        $newData[$field] = $newV;
7562
                    }
7563
                }
7564
            }
7565
        }
7566
        // IF there are changed fields, then update the database
7567
        if (!empty($newData)) {
7568
            $this->updateDB($table, $uid, $newData);
7569
        }
7570
    }
7571
7572
    /**
7573
     * Checks if any uniqueInSite eval fields are in the record and if so, they are re-written to be correct.
7574
     *
7575
     * @param string $table Table name
7576
     * @param int $uid Record UID
7577
     * @return bool whether the record had to be fixed or not
7578
     */
7579
    protected function fixUniqueInSite(string $table, int $uid): bool
7580
    {
7581
        $curData = $this->recordInfo($table, $uid, '*');
7582
        $workspaceId = $this->BE_USER->workspace;
7583
        $newData = [];
7584
        foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
7585
            if ($conf['config']['type'] === 'slug' && (string)$curData[$field] !== '') {
7586
                $evalCodesArray = GeneralUtility::trimExplode(',', $conf['config']['eval'], true);
7587
                if (in_array('uniqueInSite', $evalCodesArray, true)) {
7588
                    $helper = GeneralUtility::makeInstance(SlugHelper::class, $table, $field, $conf['config'], $workspaceId);
7589
                    $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

7589
                    $state = RecordStateFactory::forName($table)->fromArray(/** @scrutinizer ignore-type */ $curData);
Loading history...
7590
                    $newValue = $helper->buildSlugForUniqueInSite($curData[$field], $state);
7591
                    if ((string)$newValue !== (string)$curData[$field]) {
7592
                        $newData[$field] = $newValue;
7593
                    }
7594
                }
7595
            }
7596
        }
7597
        // IF there are changed fields, then update the database
7598
        if (!empty($newData)) {
7599
            $this->updateDB($table, $uid, $newData);
7600
            return true;
7601
        }
7602
        return false;
7603
    }
7604
7605
    /**
7606
     * Check if there are subpages that need an adoption as well
7607
     * @param int $pageId
7608
     */
7609
    protected function fixUniqueInSiteForSubpages(int $pageId)
7610
    {
7611
        // Get ALL subpages to update - read-permissions are respected
7612
        $subPages = $this->int_pageTreeInfo([], $pageId, 99, $pageId);
7613
        // Now fix uniqueInSite for subpages
7614
        foreach ($subPages as $thePageUid => $thePagePid) {
7615
            $recordWasModified = $this->fixUniqueInSite('pages', $thePageUid);
7616
            if ($recordWasModified) {
7617
                // @todo: Add logging and history - but how? we don't know the data that was in the system before
7618
            }
7619
        }
7620
    }
7621
7622
    /**
7623
     * When er record is copied you can specify fields from the previous record which should be copied into the new one
7624
     * 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)
7625
     *
7626
     * @param string $table Table name
7627
     * @param int $uid Record UID
7628
     * @param int $prevUid UID of previous record
7629
     * @param bool $update If set, updates the record
7630
     * @param array $newData Input array. If fields are already specified AND $update is not set, values are not set in output array.
7631
     * @return array Output array (For when the copying operation needs to get the information instead of updating the info)
7632
     */
7633
    public function fixCopyAfterDuplFields($table, $uid, $prevUid, $update, $newData = [])
7634
    {
7635
        if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['copyAfterDuplFields']) {
7636
            $prevData = $this->recordInfo($table, $prevUid, '*');
7637
            $theFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['copyAfterDuplFields'], true);
7638
            foreach ($theFields as $field) {
7639
                if ($GLOBALS['TCA'][$table]['columns'][$field] && ($update || !isset($newData[$field]))) {
7640
                    $newData[$field] = $prevData[$field];
7641
                }
7642
            }
7643
            if ($update && !empty($newData)) {
7644
                $this->updateDB($table, $uid, $newData);
7645
            }
7646
        }
7647
        return $newData;
7648
    }
7649
7650
    /**
7651
     * Casts a reference value. In case MM relations or foreign_field
7652
     * references are used. All other configurations, as well as
7653
     * foreign_table(!) could be stored as comma-separated-values
7654
     * as well. Since the system is not able to determine the default
7655
     * value automatically then, the TCA default value is used if
7656
     * it has been defined.
7657
     *
7658
     * @param int|string $value The value to be casted (e.g. '', '0', '1,2,3')
7659
     * @param array $configuration The TCA configuration of the accordant field
7660
     * @return int|string
7661
     */
7662
    protected function castReferenceValue($value, array $configuration)
7663
    {
7664
        if ((string)$value !== '') {
7665
            return $value;
7666
        }
7667
7668
        if (!empty($configuration['MM']) || !empty($configuration['foreign_field'])) {
7669
            return 0;
7670
        }
7671
7672
        if (array_key_exists('default', $configuration)) {
7673
            return $configuration['default'];
7674
        }
7675
7676
        return $value;
7677
    }
7678
7679
    /**
7680
     * Returns TRUE if the TCA/columns field type is a DB reference field
7681
     *
7682
     * @param array $conf Config array for TCA/columns field
7683
     * @return bool TRUE if DB reference field (group/db or select with foreign-table)
7684
     */
7685
    public function isReferenceField($conf)
7686
    {
7687
        return $conf['type'] === 'group' && $conf['internal_type'] === 'db' || $conf['type'] === 'select' && $conf['foreign_table'];
7688
    }
7689
7690
    /**
7691
     * Returns the subtype as a string of an inline field.
7692
     * If it's not an inline field at all, it returns FALSE.
7693
     *
7694
     * @param array $conf Config array for TCA/columns field
7695
     * @return string|bool string Inline subtype (field|mm|list), boolean: FALSE
7696
     */
7697
    public function getInlineFieldType($conf)
7698
    {
7699
        if ($conf['type'] !== 'inline' || !$conf['foreign_table']) {
7700
            return false;
7701
        }
7702
        if ($conf['foreign_field']) {
7703
            // The reference to the parent is stored in a pointer field in the child record
7704
            return 'field';
7705
        }
7706
        if ($conf['MM']) {
7707
            // Regular MM intermediate table is used to store data
7708
            return 'mm';
7709
        }
7710
        // An item list (separated by comma) is stored (like select type is doing)
7711
        return 'list';
7712
    }
7713
7714
    /**
7715
     * Get modified header for a copied record
7716
     *
7717
     * @param string $table Table name
7718
     * @param int $pid PID value in which other records to test might be
7719
     * @param string $field Field name to get header value for.
7720
     * @param string $value Current field value
7721
     * @param int $count Counter (number of recursions)
7722
     * @param string $prevTitle Previous title we checked for (in previous recursion)
7723
     * @return string The field value, possibly appended with a "copy label
7724
     */
7725
    public function getCopyHeader($table, $pid, $field, $value, $count, $prevTitle = '')
7726
    {
7727
        // Set title value to check for:
7728
        $checkTitle = $value;
7729
        if ($count > 0) {
7730
            $checkTitle = $value . rtrim(' ' . sprintf($this->prependLabel($table), $count));
7731
        }
7732
        // Do check:
7733
        if ($prevTitle != $checkTitle || $count < 100) {
7734
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7735
            $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
7736
            $rowCount = $queryBuilder
7737
                ->count('uid')
7738
                ->from($table)
7739
                ->where(
7740
                    $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)),
7741
                    $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($checkTitle, \PDO::PARAM_STR))
7742
                )
7743
                ->execute()
7744
                ->fetchColumn(0);
7745
            if ($rowCount) {
7746
                return $this->getCopyHeader($table, $pid, $field, $value, $count + 1, $checkTitle);
7747
            }
7748
        }
7749
        // Default is to just return the current input title if no other was returned before:
7750
        return $checkTitle;
7751
    }
7752
7753
    /**
7754
     * Return "copy" label for a table. Although the name is "prepend" it actually APPENDs the label (after ...)
7755
     *
7756
     * @param string $table Table name
7757
     * @return string Label to append, containing "%s" for the number
7758
     * @see getCopyHeader()
7759
     */
7760
    public function prependLabel($table)
7761
    {
7762
        return $this->getLanguageService()->sL($GLOBALS['TCA'][$table]['ctrl']['prependAtCopy']);
7763
    }
7764
7765
    /**
7766
     * Get the final pid based on $table and $pid ($destPid type... pos/neg)
7767
     *
7768
     * @param string $table Table name
7769
     * @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!
7770
     * @return int
7771
     */
7772
    public function resolvePid($table, $pid)
7773
    {
7774
        $pid = (int)$pid;
7775
        if ($pid < 0) {
7776
            $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7777
            $query->getRestrictions()
7778
                ->removeAll();
7779
            $row = $query
7780
                ->select('pid')
7781
                ->from($table)
7782
                ->where($query->expr()->eq('uid', $query->createNamedParameter(abs($pid), \PDO::PARAM_INT)))
7783
                ->execute()
7784
                ->fetch();
7785
            // Look, if the record UID happens to be an offline record. If so, find its live version.
7786
            if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, abs($pid), 'pid')) {
0 ignored issues
show
Bug introduced by
It seems like abs($pid) can also be of type double; however, parameter $uid of TYPO3\CMS\Backend\Utilit...etLiveVersionOfRecord() 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

7786
            if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, /** @scrutinizer ignore-type */ abs($pid), 'pid')) {
Loading history...
7787
                $row = $lookForLiveVersion;
7788
            }
7789
            $pid = (int)$row['pid'];
7790
        }
7791
        return $pid;
7792
    }
7793
7794
    /**
7795
     * Removes the prependAtCopy prefix on values
7796
     *
7797
     * @param string $table Table name
7798
     * @param string $value The value to fix
7799
     * @return string Clean name
7800
     */
7801
    public function clearPrefixFromValue($table, $value)
7802
    {
7803
        $regex = '/\s' . sprintf(preg_quote($this->prependLabel($table)), '[0-9]*') . '$/';
7804
        return @preg_replace($regex, '', $value);
7805
    }
7806
7807
    /**
7808
     * Check if there are records from tables on the pages to be deleted which the current user is not allowed to
7809
     *
7810
     * @param int[] $pageIds IDs of pages which should be checked
7811
     * @return bool Return TRUE, if permission granted
7812
     * @see canDeletePage()
7813
     */
7814
    protected function checkForRecordsFromDisallowedTables(array $pageIds)
7815
    {
7816
        if ($this->admin) {
7817
            return true;
7818
        }
7819
7820
        if (!empty($pageIds)) {
7821
            $tableNames = $this->compileAdminTables();
7822
            foreach ($tableNames as $table) {
7823
                $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
7824
                $query->getRestrictions()
7825
                    ->removeAll()
7826
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7827
                $count = $query->count('uid')
7828
                    ->from($table)
7829
                    ->where($query->expr()->in(
7830
                        'pid',
7831
                        $query->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
7832
                    ))
7833
                    ->execute()
7834
                    ->fetchColumn(0);
7835
                if ($count && ($this->tableReadOnly($table) || !$this->checkModifyAccessList($table))) {
7836
                    return false;
7837
                }
7838
            }
7839
        }
7840
        return true;
7841
    }
7842
7843
    /**
7844
     * Determine if a record was copied or if a record is the result of a copy action.
7845
     *
7846
     * @param string $table The tablename of the record
7847
     * @param int $uid The uid of the record
7848
     * @return bool Returns TRUE if the record is copied or is the result of a copy action
7849
     */
7850
    public function isRecordCopied($table, $uid)
7851
    {
7852
        // If the record was copied:
7853
        if (isset($this->copyMappingArray[$table][$uid])) {
7854
            return true;
7855
        }
7856
        if (isset($this->copyMappingArray[$table]) && in_array($uid, array_values($this->copyMappingArray[$table]))) {
7857
            return true;
7858
        }
7859
        return false;
7860
    }
7861
7862
    /******************************
7863
     *
7864
     * Clearing cache
7865
     *
7866
     ******************************/
7867
7868
    /**
7869
     * Clearing the cache based on a page being updated
7870
     * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
7871
     * Else just clear the cache for the parent page of the record.
7872
     *
7873
     * @param string $table Table name of record that was just updated.
7874
     * @param int $uid UID of updated / inserted record
7875
     * @param int $pid REAL PID of page of a deleted/moved record to get TSconfig in ClearCache.
7876
     * @internal This method is not meant to be called directly but only from the core itself or from hooks
7877
     */
7878
    public function registerRecordIdForPageCacheClearing($table, $uid, $pid = null)
7879
    {
7880
        if (!is_array(static::$recordsToClearCacheFor[$table])) {
7881
            static::$recordsToClearCacheFor[$table] = [];
7882
        }
7883
        static::$recordsToClearCacheFor[$table][] = (int)$uid;
7884
        if ($pid !== null) {
7885
            if (!is_array(static::$recordPidsForDeletedRecords[$table])) {
7886
                static::$recordPidsForDeletedRecords[$table] = [];
7887
            }
7888
            static::$recordPidsForDeletedRecords[$table][$uid][] = (int)$pid;
7889
        }
7890
    }
7891
7892
    /**
7893
     * Do the actual clear cache
7894
     */
7895
    protected function processClearCacheQueue()
7896
    {
7897
        $tagsToClear = [];
7898
        $clearCacheCommands = [];
7899
7900
        foreach (static::$recordsToClearCacheFor as $table => $uids) {
7901
            foreach (array_unique($uids) as $uid) {
7902
                if (!isset($GLOBALS['TCA'][$table]) || $uid <= 0) {
7903
                    return;
7904
                }
7905
                // For move commands we may get more then 1 parent.
7906
                $pageUids = $this->getOriginalParentOfRecord($table, $uid);
7907
                foreach ($pageUids as $originalParent) {
7908
                    [$tagsToClearFromPrepare, $clearCacheCommandsFromPrepare]
7909
                        = $this->prepareCacheFlush($table, $uid, $originalParent);
7910
                    $tagsToClear = array_merge($tagsToClear, $tagsToClearFromPrepare);
7911
                    $clearCacheCommands = array_merge($clearCacheCommands, $clearCacheCommandsFromPrepare);
7912
                }
7913
            }
7914
        }
7915
7916
        /** @var CacheManager $cacheManager */
7917
        $cacheManager = $this->getCacheManager();
7918
        $cacheManager->flushCachesInGroupByTags('pages', array_keys($tagsToClear));
7919
7920
        // Filter duplicate cache commands from cacheQueue
7921
        $clearCacheCommands = array_unique($clearCacheCommands);
7922
        // Execute collected clear cache commands from page TSConfig
7923
        foreach ($clearCacheCommands as $command) {
7924
            $this->clear_cacheCmd($command);
7925
        }
7926
7927
        // Reset the cache clearing array
7928
        static::$recordsToClearCacheFor = [];
7929
7930
        // Reset the original pid array
7931
        static::$recordPidsForDeletedRecords = [];
7932
    }
7933
7934
    /**
7935
     * Prepare the cache clearing
7936
     *
7937
     * @param string $table Table name of record that needs to be cleared
7938
     * @param int $uid UID of record for which the cache needs to be cleared
7939
     * @param int $pid Original pid of the page of the record which the cache needs to be cleared
7940
     * @return array Array with tagsToClear and clearCacheCommands
7941
     * @internal This function is internal only it may be changed/removed also in minor version numbers.
7942
     */
7943
    protected function prepareCacheFlush($table, $uid, $pid)
7944
    {
7945
        $tagsToClear = [];
7946
        $clearCacheCommands = [];
7947
        $pageUid = 0;
7948
        // Get Page TSconfig relevant:
7949
        $TSConfig = BackendUtility::getPagesTSconfig($pid)['TCEMAIN.'] ?? [];
7950
        if (empty($TSConfig['clearCache_disable'])) {
7951
            $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
7952
            // If table is "pages":
7953
            $pageIdsThatNeedCacheFlush = [];
7954
            if ($table === 'pages') {
7955
                // Find out if the record is a get the original page
7956
                $pageUid = $this->getDefaultLanguagePageId($uid);
7957
7958
                // Builds list of pages on the SAME level as this page (siblings)
7959
                $queryBuilder = $connectionPool->getQueryBuilderForTable('pages');
7960
                $queryBuilder->getRestrictions()
7961
                    ->removeAll()
7962
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7963
                $siblings = $queryBuilder
7964
                    ->select('A.pid AS pid', 'B.uid AS uid')
7965
                    ->from('pages', 'A')
7966
                    ->from('pages', 'B')
7967
                    ->where(
7968
                        $queryBuilder->expr()->eq('A.uid', $queryBuilder->createNamedParameter($pageUid, \PDO::PARAM_INT)),
7969
                        $queryBuilder->expr()->eq('B.pid', $queryBuilder->quoteIdentifier('A.pid')),
7970
                        $queryBuilder->expr()->gte('A.pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
7971
                    )
7972
                    ->execute();
7973
7974
                $parentPageId = 0;
7975
                while ($row_tmp = $siblings->fetch()) {
7976
                    $pageIdsThatNeedCacheFlush[] = (int)$row_tmp['uid'];
7977
                    $parentPageId = (int)$row_tmp['pid'];
7978
                    // Add children as well:
7979
                    if ($TSConfig['clearCache_pageSiblingChildren']) {
7980
                        $siblingChildrenQuery = $connectionPool->getQueryBuilderForTable('pages');
7981
                        $siblingChildrenQuery->getRestrictions()
7982
                            ->removeAll()
7983
                            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
7984
                        $siblingChildren = $siblingChildrenQuery
7985
                            ->select('uid')
7986
                            ->from('pages')
7987
                            ->where($siblingChildrenQuery->expr()->eq(
7988
                                'pid',
7989
                                $siblingChildrenQuery->createNamedParameter($row_tmp['uid'], \PDO::PARAM_INT)
7990
                            ))
7991
                            ->execute();
7992
                        while ($row_tmp2 = $siblingChildren->fetch()) {
7993
                            $pageIdsThatNeedCacheFlush[] = (int)$row_tmp2['uid'];
7994
                        }
7995
                    }
7996
                }
7997
                // Finally, add the parent page as well when clearing a specific page
7998
                if ($parentPageId > 0) {
7999
                    $pageIdsThatNeedCacheFlush[] = $parentPageId;
8000
                }
8001
                // Add grand-parent as well if configured
8002
                if ($TSConfig['clearCache_pageGrandParent']) {
8003
                    $parentQuery = $connectionPool->getQueryBuilderForTable('pages');
8004
                    $parentQuery->getRestrictions()
8005
                        ->removeAll()
8006
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8007
                    $row_tmp = $parentQuery
8008
                        ->select('pid')
8009
                        ->from('pages')
8010
                        ->where($parentQuery->expr()->eq(
8011
                            'uid',
8012
                            $parentQuery->createNamedParameter($parentPageId, \PDO::PARAM_INT)
8013
                        ))
8014
                        ->execute()
8015
                        ->fetch();
8016
                    if (!empty($row_tmp)) {
8017
                        $pageIdsThatNeedCacheFlush[] = (int)$row_tmp['pid'];
8018
                    }
8019
                }
8020
            } else {
8021
                // For other tables than "pages", delete cache for the records "parent page".
8022
                $pageIdsThatNeedCacheFlush[] = $pageUid = (int)$this->getPID($table, $uid);
8023
                // Add the parent page as well
8024
                if ($TSConfig['clearCache_pageGrandParent']) {
8025
                    $parentQuery = $connectionPool->getQueryBuilderForTable('pages');
8026
                    $parentQuery->getRestrictions()
8027
                        ->removeAll()
8028
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
8029
                    $parentPageRecord = $parentQuery
8030
                        ->select('pid')
8031
                        ->from('pages')
8032
                        ->where($parentQuery->expr()->eq(
8033
                            'uid',
8034
                            $parentQuery->createNamedParameter($pageUid, \PDO::PARAM_INT)
8035
                        ))
8036
                        ->execute()
8037
                        ->fetch();
8038
                    if (!empty($parentPageRecord)) {
8039
                        $pageIdsThatNeedCacheFlush[] = (int)$parentPageRecord['pid'];
8040
                    }
8041
                }
8042
            }
8043
            // Call pre-processing function for clearing of cache for page ids:
8044
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] ?? [] as $funcName) {
8045
                $_params = ['pageIdArray' => &$pageIdsThatNeedCacheFlush, 'table' => $table, 'uid' => $uid, 'functionID' => 'clear_cache()'];
8046
                // Returns the array of ids to clear, FALSE if nothing should be cleared! Never an empty array!
8047
                GeneralUtility::callUserFunction($funcName, $_params, $this);
8048
            }
8049
            // Delete cache for selected pages:
8050
            foreach ($pageIdsThatNeedCacheFlush as $pageId) {
8051
                // Workspaces always use "-1" as the page id which do not
8052
                // point to real pages and caches at all. Flushing caches for
8053
                // those records does not make sense and decreases performance
8054
                if ($pageId >= 0) {
8055
                    $tagsToClear['pageId_' . $pageId] = true;
8056
                }
8057
            }
8058
            // Queue delete cache for current table and record
8059
            $tagsToClear[$table] = true;
8060
            $tagsToClear[$table . '_' . $uid] = true;
8061
        }
8062
        // Clear cache for pages entered in TSconfig:
8063
        if (!empty($TSConfig['clearCacheCmd'])) {
8064
            $commands = GeneralUtility::trimExplode(',', $TSConfig['clearCacheCmd'], true);
8065
            $clearCacheCommands = array_unique($commands);
8066
        }
8067
        // Call post processing function for clear-cache:
8068
        $_params = ['table' => $table, 'uid' => $uid, 'uid_page' => $pageUid, 'TSConfig' => $TSConfig];
8069
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] ?? [] as $_funcRef) {
8070
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
8071
        }
8072
        return [
8073
            $tagsToClear,
8074
            $clearCacheCommands
8075
        ];
8076
    }
8077
8078
    /**
8079
     * Clears the cache based on the command $cacheCmd.
8080
     *
8081
     * $cacheCmd='pages'
8082
     * Clears cache for all pages and page-based caches inside the cache manager.
8083
     * Requires admin-flag to be set for BE_USER.
8084
     *
8085
     * $cacheCmd='all'
8086
     * Clears all cache_tables. This is necessary if templates are updated.
8087
     * Requires admin-flag to be set for BE_USER.
8088
     *
8089
     * The following cache_* are intentionally not cleared by 'all'
8090
     *
8091
     * - imagesizes:	Clearing this table would cause a lot of unneeded
8092
     * Imagemagick calls because the size information has
8093
     * to be fetched again after clearing.
8094
     * - all caches inside the cache manager that are inside the group "system"
8095
     * - they are only needed to build up the core system and templates,
8096
     *   use "temp_cached" or "system" to do that
8097
     *
8098
     * $cacheCmd=[integer]
8099
     * Clears cache for the page pointed to by $cacheCmd (an integer).
8100
     *
8101
     * $cacheCmd='cacheTag:[string]'
8102
     * Flush page and pagesection cache by given tag
8103
     *
8104
     * $cacheCmd='cacheId:[string]'
8105
     * Removes cache identifier from page and page section cache
8106
     *
8107
     * Can call a list of post processing functions as defined in
8108
     * $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc']
8109
     * (numeric array with values being the function references, called by
8110
     * GeneralUtility::callUserFunction()).
8111
     *
8112
     *
8113
     * @param string $cacheCmd The cache command, see above description
8114
     */
8115
    public function clear_cacheCmd($cacheCmd)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::clear_cacheCmd" is not in camel caps format
Loading history...
8116
    {
8117
        if (is_object($this->BE_USER)) {
8118
            $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]);
8119
        }
8120
        $userTsConfig = $this->BE_USER->getTSConfig();
8121
        switch (strtolower($cacheCmd)) {
8122
            case 'pages':
8123
                if ($this->admin || $userTsConfig['options.']['clearCache.']['pages'] ?? false) {
8124
                    $this->getCacheManager()->flushCachesInGroup('pages');
8125
                }
8126
                break;
8127
            case 'all':
8128
                // allow to clear all caches if the TS config option is enabled or the option is not explicitly
8129
                // disabled for admins (which could clear all caches by default). The latter option is useful
8130
                // for big production sites where it should be possible to restrict the cache clearing for some admins.
8131
                if ($userTsConfig['options.']['clearCache.']['all'] ?? false
8132
                    || ($this->admin && (bool)($userTsConfig['options.']['clearCache.']['all'] ?? true))
8133
                ) {
8134
                    $this->getCacheManager()->flushCaches();
8135
                    GeneralUtility::makeInstance(ConnectionPool::class)
8136
                        ->getConnectionForTable('cache_treelist')
8137
                        ->truncate('cache_treelist');
8138
8139
                    // Delete Opcode Cache
8140
                    GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive();
8141
                }
8142
                break;
8143
        }
8144
8145
        $tagsToFlush = [];
8146
        // Clear cache for a page ID!
8147
        if (MathUtility::canBeInterpretedAsInteger($cacheCmd)) {
8148
            $list_cache = [$cacheCmd];
8149
            // Call pre-processing function for clearing of cache for page ids:
8150
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] ?? [] as $funcName) {
8151
                $_params = ['pageIdArray' => &$list_cache, 'cacheCmd' => $cacheCmd, 'functionID' => 'clear_cacheCmd()'];
8152
                // Returns the array of ids to clear, FALSE if nothing should be cleared! Never an empty array!
8153
                GeneralUtility::callUserFunction($funcName, $_params, $this);
8154
            }
8155
            // Delete cache for selected pages:
8156
            if (is_array($list_cache)) {
0 ignored issues
show
introduced by
The condition is_array($list_cache) is always true.
Loading history...
8157
                foreach ($list_cache as $pageId) {
8158
                    $tagsToFlush[] = 'pageId_' . (int)$pageId;
8159
                }
8160
            }
8161
        }
8162
        // flush cache by tag
8163
        if (GeneralUtility::isFirstPartOfStr(strtolower($cacheCmd), 'cachetag:')) {
8164
            $cacheTag = substr($cacheCmd, 9);
8165
            $tagsToFlush[] = $cacheTag;
8166
        }
8167
        // process caching framework operations
8168
        if (!empty($tagsToFlush)) {
8169
            $this->getCacheManager()->flushCachesInGroupByTags('pages', $tagsToFlush);
8170
        }
8171
8172
        // Call post processing function for clear-cache:
8173
        $_params = ['cacheCmd' => strtolower($cacheCmd)];
8174
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] ?? [] as $_funcRef) {
8175
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
8176
        }
8177
    }
8178
8179
    /*****************************
8180
     *
8181
     * Logging
8182
     *
8183
     *****************************/
8184
    /**
8185
     * Logging actions from DataHandler
8186
     *
8187
     * @param string $table Table name the log entry is concerned with. Blank if NA
8188
     * @param int $recuid Record UID. Zero if NA
8189
     * @param int $action Action number: 0=No category, 1=new record, 2=update record, 3= delete record, 4= move record, 5= Check/evaluate
8190
     * @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
8191
     * @param int $error The severity: 0 = message, 1 = error, 2 = System Error, 3 = security notice (admin), 4 warning
8192
     * @param string $details Default error message in english
8193
     * @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
8194
     * @param array $data Array with special information that may go into $details by '%s' marks / sprintf() when the log is shown
8195
     * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
8196
     * @param string $NEWid NEW id for new records
8197
     * @return int Log entry UID (0 if no log entry was written or logging is disabled)
8198
     * @see \TYPO3\CMS\Core\SysLog\Action\Database for all available values of argument $action
8199
     * @see \TYPO3\CMS\Core\SysLog\Error for all available values of argument $error
8200
     */
8201
    public function log($table, $recuid, $action, $recpid, $error, $details, $details_nr = -1, $data = [], $event_pid = -1, $NEWid = '')
8202
    {
8203
        if (!$this->enableLogging) {
8204
            return 0;
8205
        }
8206
        // Type value for DataHandler
8207
        if (!$this->storeLogMessages) {
8208
            $details = '';
8209
        }
8210
        if ($error > 0) {
8211
            $detailMessage = $details;
8212
            if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
8213
                $detailMessage = vsprintf($details, $data);
8214
            }
8215
            $this->errorLog[] = '[' . SystemLogType::DB . '.' . $action . '.' . $details_nr . ']: ' . $detailMessage;
8216
        }
8217
        return $this->BE_USER->writelog(SystemLogType::DB, $action, $error, $details_nr, $details, $data, $table, $recuid, $recpid, $event_pid, $NEWid);
8218
    }
8219
8220
    /**
8221
     * Simple logging function meant to be used when logging messages is not yet fixed.
8222
     *
8223
     * @param string $message Message string
8224
     * @param int $error Error code, see log()
8225
     * @return int Log entry UID
8226
     * @see log()
8227
     */
8228
    public function newlog($message, $error = SystemLogErrorClassification::MESSAGE)
8229
    {
8230
        return $this->log('', 0, SystemLogGenericAction::UNDEFINED, 0, $error, $message, -1);
8231
    }
8232
8233
    /**
8234
     * Print log error messages from the operations of this script instance
8235
     */
8236
    public function printLogErrorMessages()
8237
    {
8238
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_log');
8239
        $queryBuilder->getRestrictions()->removeAll();
8240
        $result = $queryBuilder
8241
            ->select('*')
8242
            ->from('sys_log')
8243
            ->where(
8244
                $queryBuilder->expr()->eq('type', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT)),
8245
                $queryBuilder->expr()->lt('action', $queryBuilder->createNamedParameter(256, \PDO::PARAM_INT)),
8246
                $queryBuilder->expr()->eq(
8247
                    'userid',
8248
                    $queryBuilder->createNamedParameter($this->BE_USER->user['uid'], \PDO::PARAM_INT)
8249
                ),
8250
                $queryBuilder->expr()->eq(
8251
                    'tstamp',
8252
                    $queryBuilder->createNamedParameter($GLOBALS['EXEC_TIME'], \PDO::PARAM_INT)
8253
                ),
8254
                $queryBuilder->expr()->neq('error', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
8255
            )
8256
            ->execute();
8257
8258
        while ($row = $result->fetch()) {
8259
            $log_data = unserialize($row['log_data']);
8260
            $msg = $row['error'] . ': ' . sprintf($row['details'], $log_data[0], $log_data[1], $log_data[2], $log_data[3], $log_data[4]);
8261
            /** @var FlashMessage $flashMessage */
8262
            $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $msg, '', $row['error'] === 4 ? FlashMessage::WARNING : FlashMessage::ERROR, true);
8263
            /** @var FlashMessageService $flashMessageService */
8264
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
8265
            $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
8266
            $defaultFlashMessageQueue->enqueue($flashMessage);
8267
        }
8268
    }
8269
8270
    /*****************************
8271
     *
8272
     * Internal (do not use outside Core!)
8273
     *
8274
     *****************************/
8275
8276
    /**
8277
     * Find out if the record is a get the original page
8278
     *
8279
     * @param int $pageId the page UID (can be the default page record, or a page translation record ID)
8280
     * @return int the page UID of the default page record
8281
     */
8282
    protected function getDefaultLanguagePageId(int $pageId): int
8283
    {
8284
        $localizationParentFieldName = $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'];
8285
        $row = $this->recordInfo('pages', $pageId, $localizationParentFieldName);
8286
        $localizationParent = (int)$row[$localizationParentFieldName];
8287
        if ($localizationParent > 0) {
8288
            return $localizationParent;
8289
        }
8290
        return $pageId;
8291
    }
8292
8293
    /**
8294
     * Preprocesses field array based on field type. Some fields must be adjusted
8295
     * before going to database. This is done on the copy of the field array because
8296
     * original values are used in remap action later.
8297
     *
8298
     * @param string $table	Table name
8299
     * @param array $fieldArray	Field array to check
8300
     * @return array Updated field array
8301
     */
8302
    public function insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray)
0 ignored issues
show
Coding Style introduced by
Method name "DataHandler::insertUpdateDB_preprocessBasedOnFieldType" is not in camel caps format
Loading history...
8303
    {
8304
        $result = $fieldArray;
8305
        foreach ($fieldArray as $field => $value) {
8306
            if (!MathUtility::canBeInterpretedAsInteger($value)
8307
                && $GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'inline'
8308
                && $GLOBALS['TCA'][$table]['columns'][$field]['config']['foreign_field']) {
8309
                $result[$field] = count(GeneralUtility::trimExplode(',', $value, true));
8310
            }
8311
        }
8312
        return $result;
8313
    }
8314
8315
    /**
8316
     * Determines whether a particular record has been deleted
8317
     * using DataHandler::deleteRecord() in this instance.
8318
     *
8319
     * @param string $tableName
8320
     * @param string $uid
8321
     * @return bool
8322
     */
8323
    public function hasDeletedRecord($tableName, $uid)
8324
    {
8325
        return
8326
            !empty($this->deletedRecords[$tableName])
8327
            && in_array($uid, $this->deletedRecords[$tableName])
8328
        ;
0 ignored issues
show
Coding Style introduced by
Space found before semicolon; expected ");" but found ")
;"
Loading history...
8329
    }
8330
8331
    /**
8332
     * Gets the automatically versionized id of a record.
8333
     *
8334
     * @param string $table Name of the table
8335
     * @param int $id Uid of the record
8336
     * @return int
8337
     */
8338
    public function getAutoVersionId($table, $id)
8339
    {
8340
        $result = null;
8341
        if (isset($this->autoVersionIdMap[$table][$id])) {
8342
            $result = $this->autoVersionIdMap[$table][$id];
8343
        }
8344
        return $result;
8345
    }
8346
8347
    /**
8348
     * Overlays the automatically versionized id of a record.
8349
     *
8350
     * @param string $table Name of the table
8351
     * @param int $id Uid of the record
8352
     * @return int
8353
     */
8354
    protected function overlayAutoVersionId($table, $id)
8355
    {
8356
        $autoVersionId = $this->getAutoVersionId($table, $id);
8357
        if ($autoVersionId !== null) {
0 ignored issues
show
introduced by
The condition $autoVersionId !== null is always true.
Loading history...
8358
            $id = $autoVersionId;
8359
        }
8360
        return $id;
8361
    }
8362
8363
    /**
8364
     * Adds new values to the remapStackChildIds array.
8365
     *
8366
     * @param array $idValues uid values
8367
     */
8368
    protected function addNewValuesToRemapStackChildIds(array $idValues)
8369
    {
8370
        foreach ($idValues as $idValue) {
8371
            if (strpos($idValue, 'NEW') === 0) {
8372
                $this->remapStackChildIds[$idValue] = true;
8373
            }
8374
        }
8375
    }
8376
8377
    /**
8378
     * Resolves versioned records for the current workspace scope.
8379
     * Delete placeholders and move placeholders are substituted and removed.
8380
     *
8381
     * @param string $tableName Name of the table to be processed
8382
     * @param string $fieldNames List of the field names to be fetched
8383
     * @param string $sortingField Name of the sorting field to be used
8384
     * @param array $liveIds Flat array of (live) record ids
8385
     * @return array
8386
     */
8387
    protected function resolveVersionedRecords($tableName, $fieldNames, $sortingField, array $liveIds)
8388
    {
8389
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)
8390
            ->getConnectionForTable($tableName);
8391
        $sortingStatement = !empty($sortingField)
8392
            ? [$connection->quoteIdentifier($sortingField)]
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "?"; newline found
Loading history...
8393
            : null;
0 ignored issues
show
Coding Style introduced by
Expected 1 space before ":"; newline found
Loading history...
8394
        /** @var PlainDataResolver $resolver */
8395
        $resolver = GeneralUtility::makeInstance(
8396
            PlainDataResolver::class,
8397
            $tableName,
8398
            $liveIds,
8399
            $sortingStatement
8400
        );
8401
8402
        $resolver->setWorkspaceId($this->BE_USER->workspace);
8403
        $resolver->setKeepDeletePlaceholder(false);
8404
        $resolver->setKeepMovePlaceholder(false);
8405
        $resolver->setKeepLiveIds(true);
8406
        $recordIds = $resolver->get();
8407
8408
        $records = [];
8409
        foreach ($recordIds as $recordId) {
8410
            $records[$recordId] = BackendUtility::getRecord($tableName, $recordId, $fieldNames);
8411
        }
8412
8413
        return $records;
8414
    }
8415
8416
    /**
8417
     * Gets the outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler
8418
     * Since \TYPO3\CMS\Core\DataHandling\DataHandler can create nested objects of itself,
8419
     * this method helps to determine the first (= outer most) one.
8420
     *
8421
     * @return DataHandler
8422
     */
8423
    protected function getOuterMostInstance()
8424
    {
8425
        if (!isset($this->outerMostInstance)) {
8426
            $stack = array_reverse(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS));
8427
            foreach ($stack as $stackItem) {
8428
                if (isset($stackItem['object']) && $stackItem['object'] instanceof self) {
8429
                    $this->outerMostInstance = $stackItem['object'];
8430
                    break;
8431
                }
8432
            }
8433
        }
8434
        return $this->outerMostInstance;
8435
    }
8436
8437
    /**
8438
     * Determines whether the this object is the outer most instance of itself
8439
     * Since DataHandler can create nested objects of itself,
8440
     * this method helps to determine the first (= outer most) one.
8441
     *
8442
     * @return bool
8443
     */
8444
    public function isOuterMostInstance()
8445
    {
8446
        return $this->getOuterMostInstance() === $this;
8447
    }
8448
8449
    /**
8450
     * Gets an instance of the runtime cache.
8451
     *
8452
     * @return FrontendInterface
8453
     */
8454
    protected function getRuntimeCache()
8455
    {
8456
        return $this->getCacheManager()->getCache('runtime');
8457
    }
8458
8459
    /**
8460
     * Determines nested element calls.
8461
     *
8462
     * @param string $table Name of the table
8463
     * @param int $id Uid of the record
8464
     * @param string $identifier Name of the action to be checked
8465
     * @return bool
8466
     */
8467
    protected function isNestedElementCallRegistered($table, $id, $identifier)
8468
    {
8469
        $nestedElementCalls = (array)$this->runtimeCache->get($this->cachePrefixNestedElementCalls);
8470
        return isset($nestedElementCalls[$identifier][$table][$id]);
8471
    }
8472
8473
    /**
8474
     * Registers nested elements calls.
8475
     * This is used to track nested calls (e.g. for following m:n relations).
8476
     *
8477
     * @param string $table Name of the table
8478
     * @param int $id Uid of the record
8479
     * @param string $identifier Name of the action to be tracked
8480
     */
8481
    protected function registerNestedElementCall($table, $id, $identifier)
8482
    {
8483
        $nestedElementCalls = (array)$this->runtimeCache->get($this->cachePrefixNestedElementCalls);
8484
        $nestedElementCalls[$identifier][$table][$id] = true;
8485
        $this->runtimeCache->set($this->cachePrefixNestedElementCalls, $nestedElementCalls);
8486
    }
8487
8488
    /**
8489
     * Resets the nested element calls.
8490
     */
8491
    protected function resetNestedElementCalls()
8492
    {
8493
        $this->runtimeCache->remove($this->cachePrefixNestedElementCalls);
8494
    }
8495
8496
    /**
8497
     * Determines whether an element was registered to be deleted in the registry.
8498
     *
8499
     * @param string $table Name of the table
8500
     * @param int $id Uid of the record
8501
     * @return bool
8502
     * @see registerElementsToBeDeleted
8503
     * @see resetElementsToBeDeleted
8504
     * @see copyRecord_raw
8505
     * @see versionizeRecord
8506
     */
8507
    protected function isElementToBeDeleted($table, $id)
8508
    {
8509
        $elementsToBeDeleted = (array)$this->runtimeCache->get('core-datahandler-elementsToBeDeleted');
8510
        return isset($elementsToBeDeleted[$table][$id]);
8511
    }
8512
8513
    /**
8514
     * Registers elements to be deleted in the registry.
8515
     *
8516
     * @see process_datamap
8517
     */
8518
    protected function registerElementsToBeDeleted()
8519
    {
8520
        $elementsToBeDeleted = (array)$this->runtimeCache->get('core-datahandler-elementsToBeDeleted');
8521
        $this->runtimeCache->set('core-datahandler-elementsToBeDeleted', array_merge($elementsToBeDeleted, $this->getCommandMapElements('delete')));
8522
    }
8523
8524
    /**
8525
     * Resets the elements to be deleted in the registry.
8526
     *
8527
     * @see process_datamap
8528
     */
8529
    protected function resetElementsToBeDeleted()
8530
    {
8531
        $this->runtimeCache->remove('core-datahandler-elementsToBeDeleted');
8532
    }
8533
8534
    /**
8535
     * Unsets elements (e.g. of the data map) that shall be deleted.
8536
     * This avoids to modify records that will be deleted later on.
8537
     *
8538
     * @param array $elements Elements to be modified
8539
     * @return array
8540
     */
8541
    protected function unsetElementsToBeDeleted(array $elements)
8542
    {
8543
        $elements = ArrayUtility::arrayDiffAssocRecursive($elements, $this->getCommandMapElements('delete'));
8544
        foreach ($elements as $key => $value) {
8545
            if (empty($value)) {
8546
                unset($elements[$key]);
8547
            }
8548
        }
8549
        return $elements;
8550
    }
8551
8552
    /**
8553
     * Gets elements of the command map that match a particular command.
8554
     *
8555
     * @param string $needle The command to be matched
8556
     * @return array
8557
     */
8558
    protected function getCommandMapElements($needle)
8559
    {
8560
        $elements = [];
8561
        foreach ($this->cmdmap as $tableName => $idArray) {
8562
            foreach ($idArray as $id => $commandArray) {
8563
                foreach ($commandArray as $command => $value) {
8564
                    if ($value && $command == $needle) {
8565
                        $elements[$tableName][$id] = true;
8566
                    }
8567
                }
8568
            }
8569
        }
8570
        return $elements;
8571
    }
8572
8573
    /**
8574
     * Controls active elements and sets NULL values if not active.
8575
     * Datamap is modified accordant to submitted control values.
8576
     */
8577
    protected function controlActiveElements()
8578
    {
8579
        if (!empty($this->control['active'])) {
8580
            $this->setNullValues(
8581
                $this->control['active'],
8582
                $this->datamap
8583
            );
8584
        }
8585
    }
8586
8587
    /**
8588
     * Sets NULL values in haystack array.
8589
     * The general behaviour in the user interface is to enable/activate fields.
8590
     * Thus, this method uses NULL as value to be stored if a field is not active.
8591
     *
8592
     * @param array $active hierarchical array with active elements
8593
     * @param array $haystack hierarchical array with haystack to be modified
8594
     */
8595
    protected function setNullValues(array $active, array &$haystack)
8596
    {
8597
        foreach ($active as $key => $value) {
8598
            // Nested data is processes recursively
8599
            if (is_array($value)) {
8600
                $this->setNullValues(
8601
                    $value,
8602
                    $haystack[$key]
8603
                );
8604
            } elseif ($value == 0) {
8605
                // Field has not been activated in the user interface,
8606
                // thus a NULL value shall be stored in the database
8607
                $haystack[$key] = null;
8608
            }
8609
        }
8610
    }
8611
8612
    /**
8613
     * @param CorrelationId $correlationId
8614
     */
8615
    public function setCorrelationId(CorrelationId $correlationId): void
8616
    {
8617
        $this->correlationId = $correlationId;
8618
    }
8619
8620
    /**
8621
     * @return CorrelationId|null
8622
     */
8623
    public function getCorrelationId(): ?CorrelationId
8624
    {
8625
        return $this->correlationId;
8626
    }
8627
8628
    /**
8629
     * Entry point to post process a database insert. Currently bails early unless a UID has been forced
8630
     * and the database platform is not MySQL.
8631
     *
8632
     * @param \TYPO3\CMS\Core\Database\Connection $connection
8633
     * @param string $tableName
8634
     * @param int $suggestedUid
8635
     * @return int
8636
     */
8637
    protected function postProcessDatabaseInsert(Connection $connection, string $tableName, int $suggestedUid): int
8638
    {
8639
        if ($suggestedUid !== 0 && $connection->getDatabasePlatform() instanceof PostgreSqlPlatform) {
8640
            $this->postProcessPostgresqlInsert($connection, $tableName);
8641
            // The last inserted id on postgresql is actually the last value generated by the sequence.
8642
            // On a forced UID insert this might not be the actual value or the sequence might not even
8643
            // have generated a value yet.
8644
            // Return the actual ID we forced on insert as a surrogate.
8645
            return $suggestedUid;
8646
        }
8647
        if ($connection->getDatabasePlatform() instanceof SQLServerPlatform) {
8648
            return $this->postProcessSqlServerInsert($connection, $tableName);
8649
        }
8650
        $id = $connection->lastInsertId($tableName);
8651
        return (int)$id;
8652
    }
8653
8654
    /**
8655
     * Get the last insert ID from sql server
8656
     *
8657
     * - first checks whether doctrine might be able to fetch the ID from the
8658
     * sequence table
8659
     * - if that does not succeed it manually selects the current IDENTITY value
8660
     * from a table
8661
     * - returns 0 if both fail
8662
     *
8663
     * @param \TYPO3\CMS\Core\Database\Connection $connection
8664
     * @param string $tableName
8665
     * @return int
8666
     * @throws \Doctrine\DBAL\DBALException
8667
     */
8668
    protected function postProcessSqlServerInsert(Connection $connection, string $tableName): int
8669
    {
8670
        $id = $connection->lastInsertId($tableName);
8671
        if (!((int)$id > 0)) {
8672
            $table = $connection->quoteIdentifier($tableName);
8673
            $result = $connection->executeQuery('SELECT IDENT_CURRENT(\'' . $table . '\') AS id')->fetch();
8674
            if (isset($result['id']) && $result['id'] > 0) {
8675
                $id = $result['id'];
8676
            }
8677
        }
8678
        return (int)$id;
8679
    }
8680
8681
    /**
8682
     * PostgreSQL works with sequences for auto increment columns. A sequence is not updated when a value is
8683
     * written to such a column. To avoid clashes when the sequence returns an existing ID this helper will
8684
     * update the sequence to the current max value of the column.
8685
     *
8686
     * @param \TYPO3\CMS\Core\Database\Connection $connection
8687
     * @param string $tableName
8688
     */
8689
    protected function postProcessPostgresqlInsert(Connection $connection, string $tableName)
8690
    {
8691
        $queryBuilder = $connection->createQueryBuilder();
8692
        $queryBuilder->getRestrictions()->removeAll();
8693
        $row = $queryBuilder->select('PGT.schemaname', 'S.relname', 'C.attname', 'T.relname AS tablename')
8694
            ->from('pg_class', 'S')
8695
            ->from('pg_depend', 'D')
8696
            ->from('pg_class', 'T')
8697
            ->from('pg_attribute', 'C')
8698
            ->from('pg_tables', 'PGT')
8699
            ->where(
8700
                $queryBuilder->expr()->eq('S.relkind', $queryBuilder->quote('S')),
8701
                $queryBuilder->expr()->eq('S.oid', $queryBuilder->quoteIdentifier('D.objid')),
8702
                $queryBuilder->expr()->eq('D.refobjid', $queryBuilder->quoteIdentifier('T.oid')),
8703
                $queryBuilder->expr()->eq('D.refobjid', $queryBuilder->quoteIdentifier('C.attrelid')),
8704
                $queryBuilder->expr()->eq('D.refobjsubid', $queryBuilder->quoteIdentifier('C.attnum')),
8705
                $queryBuilder->expr()->eq('T.relname', $queryBuilder->quoteIdentifier('PGT.tablename')),
8706
                $queryBuilder->expr()->eq('PGT.tablename', $queryBuilder->quote($tableName))
8707
            )
8708
            ->setMaxResults(1)
8709
            ->execute()
8710
            ->fetch();
8711
8712
        if ($row !== false) {
8713
            $connection->exec(
8714
                sprintf(
8715
                    'SELECT SETVAL(%s, COALESCE(MAX(%s), 0)+1, FALSE) FROM %s',
8716
                    $connection->quote($row['schemaname'] . '.' . $row['relname']),
8717
                    $connection->quoteIdentifier($row['attname']),
8718
                    $connection->quoteIdentifier($row['schemaname'] . '.' . $row['tablename'])
8719
                )
8720
            );
8721
        }
8722
    }
8723
8724
    /**
8725
     * Return the cache entry identifier for field evals
8726
     *
8727
     * @param string $additionalIdentifier
8728
     * @return string
8729
     */
8730
    protected function getFieldEvalCacheIdentifier($additionalIdentifier)
8731
    {
8732
        return 'core-datahandler-eval-' . md5($additionalIdentifier);
8733
    }
8734
8735
    /**
8736
     * @return RelationHandler
8737
     */
8738
    protected function createRelationHandlerInstance()
8739
    {
8740
        $isWorkspacesLoaded = ExtensionManagementUtility::isLoaded('workspaces');
8741
        $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
8742
        $relationHandler->setWorkspaceId($this->BE_USER->workspace);
8743
        $relationHandler->setUseLiveReferenceIds($isWorkspacesLoaded);
8744
        $relationHandler->setUseLiveParentIds($isWorkspacesLoaded);
8745
        return $relationHandler;
8746
    }
8747
8748
    /**
8749
     * Create and returns an instance of the CacheManager
8750
     *
8751
     * @return CacheManager
8752
     */
8753
    protected function getCacheManager()
8754
    {
8755
        return GeneralUtility::makeInstance(CacheManager::class);
8756
    }
8757
8758
    /**
8759
     * Gets the resourceFactory
8760
     *
8761
     * @return ResourceFactory
8762
     */
8763
    protected function getResourceFactory()
8764
    {
8765
        return GeneralUtility::makeInstance(ResourceFactory::class);
8766
    }
8767
8768
    /**
8769
     * @return LanguageService
8770
     */
8771
    protected function getLanguageService()
8772
    {
8773
        return $GLOBALS['LANG'];
8774
    }
8775
8776
    public function getHistoryRecords(): array
8777
    {
8778
        return $this->historyRecords;
8779
    }
8780
}
8781