BackendUserAuthentication.php 103 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
15

16
17
namespace TYPO3\CMS\Core\Authentication;

18
use TYPO3\CMS\Backend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
19
use TYPO3\CMS\Backend\Utility\BackendUtility;
20
use TYPO3\CMS\Core\Cache\CacheManager;
21
use TYPO3\CMS\Core\Core\Environment;
22
use TYPO3\CMS\Core\Database\Connection;
23
use TYPO3\CMS\Core\Database\ConnectionPool;
24
use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
25
use TYPO3\CMS\Core\Database\Query\QueryHelper;
26
27
28
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\RootLevelRestriction;
29
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
30
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
31
32
use TYPO3\CMS\Core\Http\ImmediateResponseException;
use TYPO3\CMS\Core\Http\RedirectResponse;
33
34
35
use TYPO3\CMS\Core\Resource\Exception;
use TYPO3\CMS\Core\Resource\Filter\FileNameFilter;
use TYPO3\CMS\Core\Resource\Folder;
36
use TYPO3\CMS\Core\Resource\ResourceFactory;
37
use TYPO3\CMS\Core\Resource\ResourceStorage;
38
use TYPO3\CMS\Core\Resource\StorageRepository;
39
40
use TYPO3\CMS\Core\SysLog\Action as SystemLogGenericAction;
use TYPO3\CMS\Core\SysLog\Error as SystemLogErrorClassification;
crell's avatar
crell committed
41
use TYPO3\CMS\Core\SysLog\Type;
42
use TYPO3\CMS\Core\SysLog\Type as SystemLogType;
43
use TYPO3\CMS\Core\Type\Bitmask\BackendGroupMountOption;
44
use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
45
use TYPO3\CMS\Core\Type\Bitmask\Permission;
46
use TYPO3\CMS\Core\Type\Exception\InvalidEnumerationValueException;
47
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
48
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
49
use TYPO3\CMS\Core\Utility\GeneralUtility;
50
use TYPO3\CMS\Core\Utility\StringUtility;
51
use TYPO3\CMS\Core\Versioning\VersionState;
52
use TYPO3\CMS\Install\Service\SessionService;
53

54
55
56
57
58
59
60
/**
 * TYPO3 backend user authentication
 * Contains most of the functions used for checking permissions, authenticating users,
 * setting up the user, and API for user from outside.
 * This class contains the configuration of the database fields used plus some
 * functions for the authentication process of backend users.
 */
61
class BackendUserAuthentication extends AbstractUserAuthentication
62
{
63
64
    public const ROLE_SYSTEMMAINTAINER = 'systemMaintainer';

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    /**
     * Should be set to the usergroup-column (id-list) in the user-record
     * @var string
     */
    public $usergroup_column = 'usergroup';

    /**
     * The name of the group-table
     * @var string
     */
    public $usergroup_table = 'be_groups';

    /**
     * holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
     * @var array
     * @internal
     */
82
    public $groupData = [
crell's avatar
crell committed
83
84
85
86
87
88
89
90
        'allowed_languages' => '',
        'tables_select' => '',
        'tables_modify' => '',
        'pagetypes_select' => '',
        'non_exclude_fields' => '',
        'explicit_allowdeny' => '',
        'custom_options' => '',
        'file_permissions' => '',
91
    ];
92
93
94
95
96

    /**
     * This array holds the uid's of the groups in the listed order
     * @var array
     */
97
    public $userGroupsUID = [];
98
99
100
101
102
103
104
105
106
107
108
109
110
111

    /**
     * User workspace.
     * -99 is ERROR (none available)
     * 0 is online
     * >0 is custom workspaces
     * @var int
     */
    public $workspace = -99;

    /**
     * Custom workspace record if any
     * @var array
     */
112
    public $workspaceRec = [];
113
114

    /**
115
     * @var array Parsed user TSconfig
116
     */
117
    protected $userTS = [];
118
119

    /**
120
     * @var bool True if the user TSconfig was parsed and needs to be cached.
121
     */
122
    protected $userTSUpdated = false;
123
124
125

    /**
     * Contains last error message
126
     * @internal should only be used from within TYPO3 Core
127
128
129
130
131
132
     * @var string
     */
    public $errorMsg = '';

    /**
     * Cache for checkWorkspaceCurrent()
133
     * @var array|null
134
     */
135
    protected $checkWorkspaceCurrent_cache;
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178

    /**
     * @var \TYPO3\CMS\Core\Resource\ResourceStorage[]
     */
    protected $fileStorages;

    /**
     * @var array
     */
    protected $filePermissions;

    /**
     * Table in database with user data
     * @var string
     */
    public $user_table = 'be_users';

    /**
     * Column for login-name
     * @var string
     */
    public $username_column = 'username';

    /**
     * Column for password
     * @var string
     */
    public $userident_column = 'password';

    /**
     * Column for user-id
     * @var string
     */
    public $userid_column = 'uid';

    /**
     * @var string
     */
    public $lastLogin_column = 'lastlogin';

    /**
     * @var array
     */
179
    public $enablecolumns = [
180
181
182
183
184
        'rootLevel' => 1,
        'deleted' => 'deleted',
        'disabled' => 'disable',
        'starttime' => 'starttime',
        'endtime' => 'endtime'
185
    ];
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

    /**
     * Form field with login-name
     * @var string
     */
    public $formfield_uname = 'username';

    /**
     * Form field with password
     * @var string
     */
    public $formfield_uident = 'userident';

    /**
     * Form field with status: *'login', 'logout'
     * @var string
     */
    public $formfield_status = 'login_status';

    /**
     * Decides if the writelog() function is called at login and logout
     * @var bool
     */
    public $writeStdLog = true;

    /**
     * If the writelog() functions is called if a login-attempt has be tried without success
     * @var bool
     */
    public $writeAttemptLog = true;

    /**
     * @var int
219
     * @internal should only be used from within TYPO3 Core
220
221
222
223
224
     */
    public $firstMainGroup = 0;

    /**
     * User Config
225
     * @var array|string
226
227
228
229
230
231
     */
    public $uc;

    /**
     * User Config Default values:
     * The array may contain other fields for configuration.
232
     * For this, see "setup" extension and "TSconfig" document (User TSconfig, "setup.[xxx]....")
233
234
235
236
     * Reserved keys for other storage of session data:
     * moduleData
     * moduleSessionID
     * @var array
237
     * @internal should only be used from within TYPO3 Core
238
     */
239
    public $uc_default = [
240
241
        'interfaceSetup' => '',
        // serialized content that is used to store interface pane and menu positions. Set by the logout.php-script
242
        'moduleData' => [],
243
244
245
246
247
248
        // user-data for the modules
        'emailMeAtLogin' => 0,
        'titleLen' => 50,
        'edit_RTE' => '1',
        'edit_docModuleUpload' => '1',
        'resizeTextareas_MaxHeight' => 500,
249
    ];
250

251
252
253
254
255
256
    /**
     * Login type, used for services.
     * @var string
     */
    public $loginType = 'BE';

257
258
259
260
261
262
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->name = self::getCookieName();
263
        parent::__construct();
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
    }

    /**
     * Returns TRUE if user is admin
     * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
     *
     * @return bool
     */
    public function isAdmin()
    {
        return is_array($this->user) && ($this->user['admin'] & 1) == 1;
    }

    /**
     * Returns TRUE if the current user is a member of group $groupId
279
     * $groupId must be set. $this->userGroupsUID must contain groups
280
281
     * Will return TRUE also if the user is a member of a group through subgroups.
     *
282
     * @param int $groupId Group ID to look for in $this->userGroupsUID
283
     * @return bool
284
     * @internal should only be used from within TYPO3 Core, use Context API for quicker access
285
286
287
288
     */
    public function isMemberOfGroup($groupId)
    {
        $groupId = (int)$groupId;
289
290
        if (!empty($this->userGroupsUID) && $groupId) {
            return in_array($groupId, $this->userGroupsUID, true);
291
292
293
294
295
296
297
298
299
        }
        return false;
    }

    /**
     * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
     *
     * Bits for permissions, see $perms variable:
     *
300
301
302
303
304
     * 1  - Show:             See/Copy page and the pagecontent.
     * 2  - Edit page:        Change/Move the page, eg. change title, startdate, hidden.
     * 4  - Delete page:      Delete the page and pagecontent.
     * 8  - New pages:        Create new pages under the page.
     * 16 - Edit pagecontent: Change/Add/Delete/Move pagecontent.
305
306
307
308
309
310
311
312
313
314
315
316
     *
     * @param array $row Is the pagerow for which the permissions is checked
     * @param int $perms Is the binary representation of the permission we are going to check. Every bit in this number represents a permission that must be set. See function explanation.
     * @return bool
     */
    public function doesUserHaveAccess($row, $perms)
    {
        $userPerms = $this->calcPerms($row);
        return ($userPerms & $perms) == $perms;
    }

    /**
317
     * Checks if the page id or page record ($idOrRow) is found within the webmounts set up for the user.
318
319
320
321
     * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
     * The point is that this will add the security that a user can NEVER touch parts outside his mounted
     * pages in the page tree. This is otherwise possible if the raw page permissions allows for it.
     * So this security check just makes it easier to make safe user configurations.
322
     * If the user is admin then it returns "1" right away
323
324
     * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
     *
325
     * @param int|array $idOrRow Page ID or full page record to check
326
327
328
     * @param string $readPerms Content of "->getPagePermsClause(1)" (read-permissions). If not set, they will be internally calculated (but if you have the correct value right away you can save that database lookup!)
     * @param bool|int $exitOnError If set, then the function will exit with an error message.
     * @throws \RuntimeException
329
     * @return int|null The page UID of a page in the rootline that matched a mount point
330
     */
331
    public function isInWebMount($idOrRow, $readPerms = '', $exitOnError = 0)
332
    {
333
        if ($this->isAdmin()) {
334
335
            return 1;
        }
336
        $checkRec = [];
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
        $fetchPageFromDatabase = true;
        if (is_array($idOrRow)) {
            if (empty($idOrRow['uid'])) {
                throw new \RuntimeException('The given page record is invalid. Missing uid.', 1578950324);
            }
            $checkRec = $idOrRow;
            $id = (int)$idOrRow['uid'];
            // ensure the required fields are present on the record
            if (isset($checkRec['t3ver_oid'], $checkRec[$GLOBALS['TCA']['pages']['ctrl']['languageField']], $checkRec[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']])) {
                $fetchPageFromDatabase = false;
            }
        } else {
            $id = (int)$idOrRow;
        }
        if ($fetchPageFromDatabase) {
            // Check if input id is an offline version page in which case we will map id to the online version:
            $checkRec = BackendUtility::getRecord(
                'pages',
                $id,
                't3ver_oid,'
                . $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'] . ','
                . $GLOBALS['TCA']['pages']['ctrl']['languageField']
            );
        }
        if ($checkRec['t3ver_oid'] > 0) {
362
363
            $id = (int)$checkRec['t3ver_oid'];
        }
364
365
366
367
368
        // if current rec is a translation then get uid from l10n_parent instead
        // because web mounts point to pages in default language and rootline returns uids of default languages
        if ((int)$checkRec[$GLOBALS['TCA']['pages']['ctrl']['languageField']] !== 0 && (int)$checkRec[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] !== 0) {
            $id = (int)$checkRec[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
        }
369
        if (!$readPerms) {
370
            $readPerms = $this->getPagePermsClause(Permission::PAGE_SHOW);
371
372
373
        }
        if ($id > 0) {
            $wM = $this->returnWebmounts();
374
            $rL = BackendUtility::BEgetRootLine($id, ' AND ' . $readPerms, true);
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
            foreach ($rL as $v) {
                if ($v['uid'] && in_array($v['uid'], $wM)) {
                    return $v['uid'];
                }
            }
        }
        if ($exitOnError) {
            throw new \RuntimeException('Access Error: This page is not within your DB-mounts', 1294586445);
        }
        return null;
    }

    /**
     * Checks access to a backend module with the $MCONF passed as first argument
     *
     * @param array $conf $MCONF array of a backend module!
     * @throws \RuntimeException
     * @return bool Will return TRUE if $MCONF['access'] is not set at all, if the BE_USER is admin or if the module is enabled in the be_users/be_groups records of the user (specifically enabled). Will return FALSE if the module name is not even found in $TBE_MODULES
     */
394
    public function modAccess($conf)
395
396
    {
        if (!BackendUtility::isModuleSetInTBE_MODULES($conf['name'])) {
397
            throw new \RuntimeException('Fatal Error: This module "' . $conf['name'] . '" is not enabled in TBE_MODULES', 1294586446);
398
399
400
401
        }
        // Workspaces check:
        if (
            !empty($conf['workspaces'])
402
            && ExtensionManagementUtility::isLoaded('workspaces')
403
404
405
            && ($this->workspace !== 0 || !GeneralUtility::inList($conf['workspaces'], 'online'))
            && ($this->workspace <= 0 || !GeneralUtility::inList($conf['workspaces'], 'custom'))
        ) {
406
            throw new \RuntimeException('Workspace Error: This module "' . $conf['name'] . '" is not available under the current workspace', 1294586447);
407
        }
408
409
        // Returns false if conf[access] is set to system maintainers and the user is system maintainer
        if (strpos($conf['access'], self::ROLE_SYSTEMMAINTAINER) !== false && !$this->isSystemMaintainer()) {
410
            throw new \RuntimeException('This module "' . $conf['name'] . '" is only available as system maintainer', 1504804727);
411
        }
412
413
414
415
416
417
        // Returns TRUE if conf[access] is not set at all or if the user is admin
        if (!$conf['access'] || $this->isAdmin()) {
            return true;
        }
        // If $conf['access'] is set but not with 'admin' then we return TRUE, if the module is found in the modList
        $acs = false;
418
        if (strpos($conf['access'], 'admin') === false && $conf['name']) {
419
420
            $acs = $this->check('modules', $conf['name']);
        }
421
        if (!$acs) {
422
423
            throw new \RuntimeException('Access Error: You don\'t have access to this module.', 1294586448);
        }
424
        return $acs;
425
426
    }

427
    /**
428
     * Checks if the user is in the valid list of allowed system maintainers. if the list is not set,
429
     * then all admins are system maintainers. If the list is empty, no one is system maintainer (good for production
430
     * systems). If the currently logged in user is in "switch user" mode, this method will return false.
431
432
433
434
435
     *
     * @return bool
     */
    public function isSystemMaintainer(): bool
    {
436
437
438
439
        if (!$this->isAdmin()) {
            return false;
        }

440
        if ($GLOBALS['BE_USER']->getOriginalUserIdWhenInSwitchUserMode()) {
441
442
            return false;
        }
443
        if (Environment::getContext()->isDevelopment()) {
444
445
            return true;
        }
446
        $systemMaintainers = $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? [];
447
        $systemMaintainers = array_map('intval', $systemMaintainers);
448
        if (!empty($systemMaintainers)) {
449
            return in_array((int)$this->user['uid'], $systemMaintainers, true);
450
451
452
453
454
455
456
457
        }
        // No system maintainers set up yet, so any admin is allowed to access the modules
        // but explicitly no system maintainers allowed (empty string in TYPO3_CONF_VARS).
        // @todo: this needs to be adjusted once system maintainers can log into the install tool with their credentials
        if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'])
            && empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'])) {
            return false;
        }
458
        return true;
459
460
    }

461
462
463
464
465
466
467
468
469
470
471
472
473
474
    /**
     * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
     * $perms is the "mask" used to select. Fx. if $perms is 1 then you'll get all pages that a user can actually see!
     * 2^0 = show (1)
     * 2^1 = edit (2)
     * 2^2 = delete (4)
     * 2^3 = new (8)
     * If the user is 'admin' " 1=1" is returned (no effect)
     * If the user is not set at all (->user is not an array), then " 1=0" is returned (will cause no selection results at all)
     * The 95% use of this function is "->getPagePermsClause(1)" which will
     * return WHERE clauses for *selecting* pages in backend listings - in other words this will check read permissions.
     *
     * @param int $perms Permission mask to use, see function description
     * @return string Part of where clause. Prefix " AND " to this.
475
     * @internal should only be used from within TYPO3 Core, use PagePermissionDatabaseRestriction instead.
476
477
478
479
480
481
482
483
     */
    public function getPagePermsClause($perms)
    {
        if (is_array($this->user)) {
            if ($this->isAdmin()) {
                return ' 1=1';
            }
            // Make sure it's integer.
484
485
486
487
488
            $perms = (int)$perms;
            $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
                ->getQueryBuilderForTable('pages')
                ->expr();

489
            // User
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
            $constraint = $expressionBuilder->orX(
                $expressionBuilder->comparison(
                    $expressionBuilder->bitAnd('pages.perms_everybody', $perms),
                    ExpressionBuilder::EQ,
                    $perms
                ),
                $expressionBuilder->andX(
                    $expressionBuilder->eq('pages.perms_userid', (int)$this->user['uid']),
                    $expressionBuilder->comparison(
                        $expressionBuilder->bitAnd('pages.perms_user', $perms),
                        ExpressionBuilder::EQ,
                        $perms
                    )
                )
            );

            // Group (if any is set)
507
            if (!empty($this->userGroupsUID)) {
508
509
510
511
                $constraint->add(
                    $expressionBuilder->andX(
                        $expressionBuilder->in(
                            'pages.perms_groupid',
512
                            $this->userGroupsUID
513
514
515
516
517
518
519
520
                        ),
                        $expressionBuilder->comparison(
                            $expressionBuilder->bitAnd('pages.perms_group', $perms),
                            ExpressionBuilder::EQ,
                            $perms
                        )
                    )
                );
521
            }
522
523
524

            $constraint = ' (' . (string)$constraint . ')';

525
526
527
            // ****************
            // getPagePermsClause-HOOK
            // ****************
528
529
530
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'] ?? [] as $_funcRef) {
                $_params = ['currentClause' => $constraint, 'perms' => $perms];
                $constraint = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
531
            }
532
            return $constraint;
533
        }
534
        return ' 1=0';
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
    }

    /**
     * Returns a combined binary representation of the current users permissions for the page-record, $row.
     * The perms for user, group and everybody is OR'ed together (provided that the page-owner is the user
     * and for the groups that the user is a member of the group.
     * If the user is admin, 31 is returned	(full permissions for all five flags)
     *
     * @param array $row Input page row with all perms_* fields available.
     * @return int Bitwise representation of the users permissions in relation to input page row, $row
     */
    public function calcPerms($row)
    {
        // Return 31 for admin users.
        if ($this->isAdmin()) {
            return Permission::ALL;
        }
        // Return 0 if page is not within the allowed web mount
553
        if (!$this->isInWebMount($row)) {
554
555
556
557
558
            return Permission::NOTHING;
        }
        $out = Permission::NOTHING;
        if (
            isset($row['perms_userid']) && isset($row['perms_user']) && isset($row['perms_groupid'])
559
            && isset($row['perms_group']) && isset($row['perms_everybody']) && !empty($this->userGroupsUID)
560
561
562
563
564
565
566
567
568
569
570
571
        ) {
            if ($this->user['uid'] == $row['perms_userid']) {
                $out |= $row['perms_user'];
            }
            if ($this->isMemberOfGroup($row['perms_groupid'])) {
                $out |= $row['perms_group'];
            }
            $out |= $row['perms_everybody'];
        }
        // ****************
        // CALCPERMS hook
        // ****************
572
573
574
575
576
577
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'] ?? [] as $_funcRef) {
            $_params = [
                'row' => $row,
                'outputPermissions' => $out
            ];
            $out = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
578
579
580
581
582
583
584
585
        }
        return $out;
    }

    /**
     * Returns TRUE if the RTE (Rich Text Editor) is enabled for the user.
     *
     * @return bool
586
     * @internal should only be used from within TYPO3 Core
587
588
589
590
591
592
593
594
595
596
597
598
     */
    public function isRTE()
    {
        return (bool)$this->uc['edit_RTE'];
    }

    /**
     * Returns TRUE if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
     * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
     * If user is admin TRUE is also returned
     * Please see the document Inside TYPO3 for examples.
     *
599
     * @param string $type The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules", "available_widgets", "mfa_providers"
600
601
602
603
604
     * @param string $value String to search for in the groupData-list
     * @return bool TRUE if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
     */
    public function check($type, $value)
    {
605
606
        return isset($this->groupData[$type])
            && ($this->isAdmin() || GeneralUtility::inList($this->groupData[$type], $value));
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
    }

    /**
     * Checking the authMode of a select field with authMode set
     *
     * @param string $table Table name
     * @param string $field Field name (must be configured in TCA and of type "select" with authMode set!)
     * @param string $value Value to evaluation (single value, must not contain any of the chars ":,|")
     * @param string $authMode Auth mode keyword (explicitAllow, explicitDeny, individual)
     * @return bool Whether access is granted or not
     */
    public function checkAuthMode($table, $field, $value, $authMode)
    {
        // Admin users can do anything:
        if ($this->isAdmin()) {
            return true;
        }
        // Allow all blank values:
        if ((string)$value === '') {
            return true;
        }
628
629
630
631
        // Allow dividers:
        if ($value === '--div--') {
            return true;
        }
632
633
634
635
636
637
638
639
640
641
        // Certain characters are not allowed in the value
        if (preg_match('/[:|,]/', $value)) {
            return false;
        }
        // Initialize:
        $testValue = $table . ':' . $field . ':' . $value;
        $out = true;
        // Checking value:
        switch ((string)$authMode) {
            case 'explicitAllow':
642
                if (!GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':ALLOW')) {
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
                    $out = false;
                }
                break;
            case 'explicitDeny':
                if (GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
                    $out = false;
                }
                break;
            case 'individual':
                if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
                    $items = $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'];
                    if (is_array($items)) {
                        foreach ($items as $iCfg) {
                            if ((string)$iCfg[1] === (string)$value && $iCfg[4]) {
                                switch ((string)$iCfg[4]) {
                                    case 'EXPL_ALLOW':
659
660
661
662
                                        if (!GeneralUtility::inList(
                                            $this->groupData['explicit_allowdeny'],
                                            $testValue . ':ALLOW'
                                        )) {
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
                                            $out = false;
                                        }
                                        break;
                                    case 'EXPL_DENY':
                                        if (GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
                                            $out = false;
                                        }
                                        break;
                                }
                                break;
                            }
                        }
                    }
                }
                break;
        }
        return $out;
    }

    /**
     * Checking if a language value (-1, 0 and >0 for sys_language records) is allowed to be edited by the user.
     *
     * @param int $langValue Language value to evaluate
     * @return bool Returns TRUE if the language value is allowed, otherwise FALSE.
     */
    public function checkLanguageAccess($langValue)
    {
        // The users language list must be non-blank - otherwise all languages are allowed.
        if (trim($this->groupData['allowed_languages']) !== '') {
            $langValue = (int)$langValue;
            // Language must either be explicitly allowed OR the lang Value be "-1" (all languages)
694
            if ($langValue != -1 && !$this->check('allowed_languages', (string)$langValue)) {
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
                return false;
            }
        }
        return true;
    }

    /**
     * Check if user has access to all existing localizations for a certain record
     *
     * @param string $table The table
     * @param array $record The current record
     * @return bool
     */
    public function checkFullLanguagesAccess($table, $record)
    {
710
711
712
713
714
        if (!$this->checkLanguageAccess(0)) {
            return false;
        }

        if (BackendUtility::isTableLocalizable($table)) {
715
716
717
            $pointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
            $pointerValue = $record[$pointerField] > 0 ? $record[$pointerField] : $record['uid'];
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
718
719
720
            $queryBuilder->getRestrictions()
                ->removeAll()
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
721
                ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->workspace));
722
            $recordLocalizations = $queryBuilder->select('*')
723
                ->from($table)
724
725
726
727
728
729
730
                ->where(
                    $queryBuilder->expr()->eq(
                        $pointerField,
                        $queryBuilder->createNamedParameter($pointerValue, \PDO::PARAM_INT)
                    )
                )
                ->execute()
731
                ->fetchAll();
732

733
734
735
736
            foreach ($recordLocalizations as $recordLocalization) {
                if (!$this->checkLanguageAccess($recordLocalization[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
                    return false;
                }
737
738
            }
        }
739
        return true;
740
741
742
743
744
745
746
747
748
749
750
    }

    /**
     * Checking if a user has editing access to a record from a $GLOBALS['TCA'] table.
     * The checks does not take page permissions and other "environmental" things into account.
     * It only deal with record internals; If any values in the record fields disallows it.
     * For instance languages settings, authMode selector boxes are evaluated (and maybe more in the future).
     * It will check for workspace dependent access.
     * The function takes an ID (int) or row (array) as second argument.
     *
     * @param string $table Table name
751
     * @param int|array $idOrRow If integer, then this is the ID of the record. If Array this just represents fields in the record.
752
753
754
755
     * @param bool $newRecord Set, if testing a new (non-existing) record array. Will disable certain checks that doesn't make much sense in that context.
     * @param bool $deletedRecord Set, if testing a deleted record array.
     * @param bool $checkFullLanguageAccess Set, whenever access to all translations of the record is required
     * @return bool TRUE if OK, otherwise FALSE
756
     * @internal should only be used from within TYPO3 Core
757
     */
758
    public function recordEditAccessInternals($table, $idOrRow, $newRecord = false, $deletedRecord = false, $checkFullLanguageAccess = false): bool
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    {
        if (!isset($GLOBALS['TCA'][$table])) {
            return false;
        }
        // Always return TRUE for Admin users.
        if ($this->isAdmin()) {
            return true;
        }
        // Fetching the record if the $idOrRow variable was not an array on input:
        if (!is_array($idOrRow)) {
            if ($deletedRecord) {
                $idOrRow = BackendUtility::getRecord($table, $idOrRow, '*', '', false);
            } else {
                $idOrRow = BackendUtility::getRecord($table, $idOrRow);
            }
            if (!is_array($idOrRow)) {
                $this->errorMsg = 'ERROR: Record could not be fetched.';
                return false;
            }
        }
        // Checking languages:
780
781
782
        if ($table === 'pages' && $checkFullLanguageAccess && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
            return false;
        }
783
        if ($GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? false) {
784
785
786
787
788
            // Language field must be found in input row - otherwise it does not make sense.
            if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
                if (!$this->checkLanguageAccess($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
                    $this->errorMsg = 'ERROR: Language was not allowed.';
                    return false;
789
790
                }
                if (
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
                    $checkFullLanguageAccess && $idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']] == 0
                    && !$this->checkFullLanguagesAccess($table, $idOrRow)
                ) {
                    $this->errorMsg = 'ERROR: Related/affected language was not allowed.';
                    return false;
                }
            } else {
                $this->errorMsg = 'ERROR: The "languageField" field named "'
                    . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '" was not found in testing record!';
                return false;
            }
        }
        // Checking authMode fields:
        if (is_array($GLOBALS['TCA'][$table]['columns'])) {
            foreach ($GLOBALS['TCA'][$table]['columns'] as $fieldName => $fieldValue) {
806
807
808
809
810
811
812
813
814
                if (isset($idOrRow[$fieldName])
                    && ($fieldValue['config']['type'] ?? '') === 'select'
                    && ($fieldValue['config']['authMode'] ?? false)
                    && ($fieldValue['config']['authMode_enforce'] ?? '') === 'strict'
                    && !$this->checkAuthMode($table, $fieldName, $idOrRow[$fieldName], $fieldValue['config']['authMode'])) {
                    $this->errorMsg = 'ERROR: authMode "' . $fieldValue['config']['authMode']
                            . '" failed for field "' . $fieldName . '" with value "'
                            . $idOrRow[$fieldName] . '" evaluated';
                    return false;
815
816
817
818
                }
            }
        }
        // Checking "editlock" feature (doesn't apply to new records)
819
        if (!$newRecord && ($GLOBALS['TCA'][$table]['ctrl']['editlock'] ?? false)) {
820
821
822
823
824
825
826
827
828
829
830
831
832
833
            if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']])) {
                if ($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']]) {
                    $this->errorMsg = 'ERROR: Record was locked for editing. Only admin users can change this state.';
                    return false;
                }
            } else {
                $this->errorMsg = 'ERROR: The "editLock" field named "' . $GLOBALS['TCA'][$table]['ctrl']['editlock']
                    . '" was not found in testing record!';
                return false;
            }
        }
        // Checking record permissions
        // THIS is where we can include a check for "perms_" fields for other records than pages...
        // Process any hooks
834
835
836
837
838
839
840
841
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'] ?? [] as $funcRef) {
            $params = [
                'table' => $table,
                'idOrRow' => $idOrRow,
                'newRecord' => $newRecord
            ];
            if (!GeneralUtility::callUserFunction($funcRef, $params, $this)) {
                return false;
842
843
844
845
846
847
848
849
850
851
852
853
854
            }
        }
        // Finally, return TRUE if all is well.
        return true;
    }

    /**
     * Returns TRUE if the BE_USER is allowed to *create* shortcuts in the backend modules
     *
     * @return bool
     */
    public function mayMakeShortcut()
    {
855
        return ($this->getTSConfig()['options.']['enableBookmarks'] ?? false)
856
            && !($this->getTSConfig()['options.']['mayNotCreateEditBookmarks'] ?? false);
857
858
859
860
861
    }

    /**
     * Checking if editing of an existing record is allowed in current workspace if that is offline.
     * Rules for editing in offline mode:
862
     * - record supports versioning and is an offline version from workspace and has the current stage
863
864
865
866
     * - or record (any) is in a branch where there is a page which is a version from the workspace
     *   and where the stage is not preventing records
     *
     * @param string $table Table of record
867
     * @param array|int $recData Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_oid, t3ver_stage (if versioningWS is set)
868
     * @return string String error code, telling the failure state. FALSE=All ok
869
     * @internal should only be used from within TYPO3 Core
870
871
872
     */
    public function workspaceCannotEditRecord($table, $recData)
    {
873
874
875
876
877
878
879
880
881
        // Only test if the user is in a workspace
        if ($this->workspace === 0) {
            return false;
        }
        $tableSupportsVersioning = BackendUtility::isTableWorkspaceEnabled($table);
        if (!is_array($recData)) {
            $recData = BackendUtility::getRecord(
                $table,
                $recData,
882
                'pid' . ($tableSupportsVersioning ? ',t3ver_oid,t3ver_wsid,t3ver_state,t3ver_stage' : '')
883
884
885
886
887
            );
        }
        if (is_array($recData)) {
            // We are testing a "version" (identified by having a t3ver_oid): it can be edited provided
            // that workspace matches and versioning is enabled for the table.
888
889
890
891
892
893
            $versionState = new VersionState($recData['t3ver_state'] ?? 0);
            if ($tableSupportsVersioning
                && (
                    $versionState->equals(VersionState::NEW_PLACEHOLDER) || (int)(($recData['t3ver_oid'] ?? 0) > 0)
                )
            ) {
894
895
896
                if ((int)$recData['t3ver_wsid'] !== $this->workspace) {
                    // So does workspace match?
                    return 'Workspace ID of record didn\'t match current workspace';
897
                }
898
899
900
901
                // So is the user allowed to "use" the edit stage within the workspace?
                return $this->workspaceCheckStageForCurrent(0)
                        ? false
                        : 'User\'s access level did not allow for editing';
902
            }
903
904
905
906
907
908
909
            // Check if we are testing a "live" record
            if ($this->workspaceAllowsLiveEditingInTable($table)) {
                // Live records are OK in the current workspace
                return false;
            }
            // If not offline, output error
            return 'Online record was not in a workspace!';
910
        }
911
        return 'No record';
912
913
914
915
916
917
    }

    /**
     * Evaluates if a user is allowed to edit the offline version
     *
     * @param string $table Table of record
918
     * @param array|int $recData Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
919
920
     * @return string String error code, telling the failure state. FALSE=All ok
     * @see workspaceCannotEditRecord()
921
     * @internal this method will be moved to EXT:workspaces
922
923
924
     */
    public function workspaceCannotEditOfflineVersion($table, $recData)
    {
925
926
927
928
        if (!BackendUtility::isTableWorkspaceEnabled($table)) {
            return 'Table does not support versioning.';
        }
        if (!is_array($recData)) {
929
            $recData = BackendUtility::getRecord($table, $recData, 'uid,pid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_stage');
930
931
        }
        if (is_array($recData)) {
932
933
            $versionState = new VersionState($recData['t3ver_state']);
            if ($versionState->equals(VersionState::NEW_PLACEHOLDER) || (int)$recData['t3ver_oid'] > 0) {
934
                return $this->workspaceCannotEditRecord($table, $recData);
935
            }
936
            return 'Not an offline version';
937
        }
938
        return 'No record';
939
940
    }

941
942
943
944
945
946
947
    /**
     * Checks if a record is allowed to be edited in the current workspace.
     * This is not bound to an actual record, but to the mere fact if the user is in a workspace
     * and depending on the table settings.
     *
     * @param string $table
     * @return bool
948
     * @internal should only be used from within TYPO3 Core
949
950
951
952
953
954
955
956
     */
    public function workspaceAllowsLiveEditingInTable(string $table): bool
    {
        // In live workspace the record can be added/modified
        if ($this->workspace === 0) {
            return true;
        }
        // Workspace setting allows to "live edit" records of tables without versioning
957
958
959
        if (($this->workspaceRec['live_edit'] ?? false)
            && !BackendUtility::isTableWorkspaceEnabled($table)
        ) {
960
961
962
963
            return true;
        }
        // Always for Live workspace AND if live-edit is enabled
        // and tables are completely without versioning it is ok as well.
964
        if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit'] ?? false) {
965
966
967
968
969
970
971
972
973
974
975
976
977
            return true;
        }
        // If the answer is FALSE it means the only valid way to create or edit records by creating records in the workspace
        return false;
    }

    /**
     * Evaluates if a record from $table can be created. If the table is not set up for versioning,
     * and the "live edit" flag of the page is set, return false. In live workspace this is always true,
     * as all records can be created in live workspace
     *
     * @param string $table Table name
     * @return bool
978
     * @internal should only be used from within TYPO3 Core
979
980
981
982
983
     */
    public function workspaceCanCreateNewRecord(string $table): bool
    {
        // If LIVE records cannot be created due to workspace restrictions, prepare creation of placeholder-record
        if (!$this->workspaceAllowsLiveEditingInTable($table) && !BackendUtility::isTableWorkspaceEnabled($table)) {
984
985
986
987
988
989
990
            return false;
        }
        return true;
    }

    /**
     * Evaluates if auto creation of a version of a record is allowed.
991
992
993
     * Auto-creation of version: In offline workspace, test if versioning is
     * enabled and look for workspace version of input record.
     * If there is no versionized record found we will create one and save to that.
994
995
996
997
998
     *
     * @param string $table Table of the record
     * @param int $id UID of record
     * @param int $recpid PID of record
     * @return bool TRUE if ok.
999
     * @internal should only be used from within TYPO3 Core
1000
     */