Completed
Push — master ( a088ad...55fcd8 )
by
unknown
23:17 queued 05:43
created

BackendUserAuthentication::getRealUserId()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
namespace TYPO3\CMS\Core\Authentication;
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\Driver\Statement;
18
use Psr\Http\Message\ServerRequestInterface;
19
use TYPO3\CMS\Backend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
20
use TYPO3\CMS\Backend\Utility\BackendUtility;
21
use TYPO3\CMS\Core\Cache\CacheManager;
22
use TYPO3\CMS\Core\Core\Environment;
23
use TYPO3\CMS\Core\Database\Connection;
24
use TYPO3\CMS\Core\Database\ConnectionPool;
25
use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
26
use TYPO3\CMS\Core\Database\Query\QueryHelper;
27
use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
28
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
29
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
30
use TYPO3\CMS\Core\Database\Query\Restriction\RootLevelRestriction;
31
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
32
use TYPO3\CMS\Core\Mail\FluidEmail;
33
use TYPO3\CMS\Core\Mail\Mailer;
34
use TYPO3\CMS\Core\Resource\ResourceFactory;
35
use TYPO3\CMS\Core\Resource\ResourceStorage;
36
use TYPO3\CMS\Core\SysLog\Action as SystemLogGenericAction;
37
use TYPO3\CMS\Core\SysLog\Action\Login as SystemLogLoginAction;
38
use TYPO3\CMS\Core\SysLog\Error as SystemLogErrorClassification;
39
use TYPO3\CMS\Core\SysLog\Type as SystemLogType;
40
use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
41
use TYPO3\CMS\Core\Type\Bitmask\Permission;
42
use TYPO3\CMS\Core\Type\Exception\InvalidEnumerationValueException;
43
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
44
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
45
use TYPO3\CMS\Core\Utility\GeneralUtility;
46
use TYPO3\CMS\Install\Service\SessionService;
47
48
/**
49
 * TYPO3 backend user authentication
50
 * Contains most of the functions used for checking permissions, authenticating users,
51
 * setting up the user, and API for user from outside.
52
 * This class contains the configuration of the database fields used plus some
53
 * functions for the authentication process of backend users.
54
 */
55
class BackendUserAuthentication extends AbstractUserAuthentication
56
{
57
    public const ROLE_SYSTEMMAINTAINER = 'systemMaintainer';
58
59
    /**
60
     * Should be set to the usergroup-column (id-list) in the user-record
61
     * @var string
62
     */
63
    public $usergroup_column = 'usergroup';
64
65
    /**
66
     * The name of the group-table
67
     * @var string
68
     */
69
    public $usergroup_table = 'be_groups';
70
71
    /**
72
     * holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
73
     * @var array
74
     * @internal
75
     */
76
    public $groupData = [
77
        'filemounts' => []
78
    ];
79
80
    /**
81
     * This array will hold the groups that the user is a member of
82
     * @var array
83
     */
84
    public $userGroups = [];
85
86
    /**
87
     * This array holds the uid's of the groups in the listed order
88
     * @var array
89
     */
90
    public $userGroupsUID = [];
91
92
    /**
93
     * This is $this->userGroupsUID imploded to a comma list... Will correspond to the 'usergroup_cached_list'
94
     * @var string
95
     */
96
    public $groupList = '';
97
98
    /**
99
     * User workspace.
100
     * -99 is ERROR (none available)
101
     * 0 is online
102
     * >0 is custom workspaces
103
     * @var int
104
     */
105
    public $workspace = -99;
106
107
    /**
108
     * Custom workspace record if any
109
     * @var array
110
     */
111
    public $workspaceRec = [];
112
113
    /**
114
     * Used to accumulate data for the user-group.
115
     * DON NOT USE THIS EXTERNALLY!
116
     * Use $this->groupData instead
117
     * @var array
118
     * @internal
119
     */
120
    public $dataLists = [
121
        'webmount_list' => '',
122
        'filemount_list' => '',
123
        'file_permissions' => '',
124
        'modList' => '',
125
        'tables_select' => '',
126
        'tables_modify' => '',
127
        'pagetypes_select' => '',
128
        'non_exclude_fields' => '',
129
        'explicit_allowdeny' => '',
130
        'allowed_languages' => '',
131
        'workspace_perms' => '',
132
        'available_widgets' => '',
133
        'custom_options' => ''
134
    ];
135
136
    /**
137
     * List of group_id's in the order they are processed.
138
     * @var array
139
     */
140
    public $includeGroupArray = [];
141
142
    /**
143
     * @var array Parsed user TSconfig
144
     */
145
    protected $userTS = [];
146
147
    /**
148
     * @var bool True if the user TSconfig was parsed and needs to be cached.
149
     */
150
    protected $userTSUpdated = false;
151
152
    /**
153
     * Contains last error message
154
     * @var string
155
     */
156
    public $errorMsg = '';
157
158
    /**
159
     * Cache for checkWorkspaceCurrent()
160
     * @var array|null
161
     */
162
    protected $checkWorkspaceCurrent_cache;
163
164
    /**
165
     * @var \TYPO3\CMS\Core\Resource\ResourceStorage[]
166
     */
167
    protected $fileStorages;
168
169
    /**
170
     * @var array
171
     */
172
    protected $filePermissions;
173
174
    /**
175
     * Table in database with user data
176
     * @var string
177
     */
178
    public $user_table = 'be_users';
179
180
    /**
181
     * Column for login-name
182
     * @var string
183
     */
184
    public $username_column = 'username';
185
186
    /**
187
     * Column for password
188
     * @var string
189
     */
190
    public $userident_column = 'password';
191
192
    /**
193
     * Column for user-id
194
     * @var string
195
     */
196
    public $userid_column = 'uid';
197
198
    /**
199
     * @var string
200
     */
201
    public $lastLogin_column = 'lastlogin';
202
203
    /**
204
     * @var array
205
     */
206
    public $enablecolumns = [
207
        'rootLevel' => 1,
208
        'deleted' => 'deleted',
209
        'disabled' => 'disable',
210
        'starttime' => 'starttime',
211
        'endtime' => 'endtime'
212
    ];
213
214
    /**
215
     * Form field with login-name
216
     * @var string
217
     */
218
    public $formfield_uname = 'username';
219
220
    /**
221
     * Form field with password
222
     * @var string
223
     */
224
    public $formfield_uident = 'userident';
225
226
    /**
227
     * Form field with status: *'login', 'logout'
228
     * @var string
229
     */
230
    public $formfield_status = 'login_status';
231
232
    /**
233
     * Decides if the writelog() function is called at login and logout
234
     * @var bool
235
     */
236
    public $writeStdLog = true;
237
238
    /**
239
     * If the writelog() functions is called if a login-attempt has be tried without success
240
     * @var bool
241
     */
242
    public $writeAttemptLog = true;
243
244
    /**
245
     * Session timeout (on the server), defaults to 8 hours for backend user
246
     *
247
     * If >0: session-timeout in seconds.
248
     * If <=0: Instant logout after login.
249
     * The value must be at least 180 to avoid side effects.
250
     *
251
     * @var int
252
     */
253
    public $sessionTimeout = 28800;
254
255
    /**
256
     * @var int
257
     */
258
    public $firstMainGroup = 0;
259
260
    /**
261
     * User Config
262
     * @var array
263
     */
264
    public $uc;
265
266
    /**
267
     * User Config Default values:
268
     * The array may contain other fields for configuration.
269
     * For this, see "setup" extension and "TSconfig" document (User TSconfig, "setup.[xxx]....")
270
     * Reserved keys for other storage of session data:
271
     * moduleData
272
     * moduleSessionID
273
     * @var array
274
     */
275
    public $uc_default = [
276
        'interfaceSetup' => '',
277
        // serialized content that is used to store interface pane and menu positions. Set by the logout.php-script
278
        'moduleData' => [],
279
        // user-data for the modules
280
        'thumbnailsByDefault' => 1,
281
        'emailMeAtLogin' => 0,
282
        'startModule' => 'help_AboutAbout',
283
        'titleLen' => 50,
284
        'edit_RTE' => '1',
285
        'edit_docModuleUpload' => '1',
286
        'resizeTextareas' => 1,
287
        'resizeTextareas_MaxHeight' => 500,
288
        'resizeTextareas_Flexible' => 0
289
    ];
290
291
    /**
292
     * Login type, used for services.
293
     * @var string
294
     */
295
    public $loginType = 'BE';
296
297
    /**
298
     * Constructor
299
     */
300
    public function __construct()
301
    {
302
        $this->name = self::getCookieName();
303
        $this->warningEmail = $GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'];
304
        $this->sessionTimeout = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['sessionTimeout'];
305
        parent::__construct();
306
    }
307
308
    /**
309
     * Returns TRUE if user is admin
310
     * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
311
     *
312
     * @return bool
313
     */
314
    public function isAdmin()
315
    {
316
        return is_array($this->user) && ($this->user['admin'] & 1) == 1;
317
    }
318
319
    /**
320
     * Returns TRUE if the current user is a member of group $groupId
321
     * $groupId must be set. $this->groupList must contain groups
322
     * Will return TRUE also if the user is a member of a group through subgroups.
323
     *
324
     * @param int $groupId Group ID to look for in $this->groupList
325
     * @return bool
326
     */
327
    public function isMemberOfGroup($groupId)
328
    {
329
        $groupId = (int)$groupId;
330
        if ($this->groupList && $groupId) {
331
            return GeneralUtility::inList($this->groupList, $groupId);
332
        }
333
        return false;
334
    }
335
336
    /**
337
     * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
338
     *
339
     * Bits for permissions, see $perms variable:
340
     *
341
     * 1  - Show:             See/Copy page and the pagecontent.
342
     * 2  - Edit page:        Change/Move the page, eg. change title, startdate, hidden.
343
     * 4  - Delete page:      Delete the page and pagecontent.
344
     * 8  - New pages:        Create new pages under the page.
345
     * 16 - Edit pagecontent: Change/Add/Delete/Move pagecontent.
346
     *
347
     * @param array $row Is the pagerow for which the permissions is checked
348
     * @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.
349
     * @return bool
350
     */
351
    public function doesUserHaveAccess($row, $perms)
352
    {
353
        $userPerms = $this->calcPerms($row);
354
        return ($userPerms & $perms) == $perms;
355
    }
356
357
    /**
358
     * Checks if the page id or page record ($idOrRow) is found within the webmounts set up for the user.
359
     * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
360
     * The point is that this will add the security that a user can NEVER touch parts outside his mounted
361
     * pages in the page tree. This is otherwise possible if the raw page permissions allows for it.
362
     * So this security check just makes it easier to make safe user configurations.
363
     * If the user is admin OR if this feature is disabled
364
     * (fx. by setting TYPO3_CONF_VARS['BE']['lockBeUserToDBmounts']=0) then it returns "1" right away
365
     * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
366
     *
367
     * @param int|array $idOrRow Page ID or full page record to check
368
     * @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!)
369
     * @param bool|int $exitOnError If set, then the function will exit with an error message.
370
     * @throws \RuntimeException
371
     * @return int|null The page UID of a page in the rootline that matched a mount point
372
     */
373
    public function isInWebMount($idOrRow, $readPerms = '', $exitOnError = 0)
374
    {
375
        if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['lockBeUserToDBmounts'] || $this->isAdmin()) {
376
            return 1;
377
        }
378
        $checkRec = [];
379
        $fetchPageFromDatabase = true;
380
        if (is_array($idOrRow)) {
381
            if (empty($idOrRow['uid'])) {
382
                throw new \RuntimeException('The given page record is invalid. Missing uid.', 1578950324);
383
            }
384
            $checkRec = $idOrRow;
385
            $id = (int)$idOrRow['uid'];
386
            // ensure the required fields are present on the record
387
            if (isset($checkRec['t3ver_oid'], $checkRec[$GLOBALS['TCA']['pages']['ctrl']['languageField']], $checkRec[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']])) {
388
                $fetchPageFromDatabase = false;
389
            }
390
        } else {
391
            $id = (int)$idOrRow;
392
        }
393
        if ($fetchPageFromDatabase) {
394
            // Check if input id is an offline version page in which case we will map id to the online version:
395
            $checkRec = BackendUtility::getRecord(
396
                'pages',
397
                $id,
398
                't3ver_oid,'
399
                . $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'] . ','
400
                . $GLOBALS['TCA']['pages']['ctrl']['languageField']
401
            );
402
        }
403
        if ($checkRec['t3ver_oid'] > 0) {
404
            $id = (int)$checkRec['t3ver_oid'];
405
        }
406
        // if current rec is a translation then get uid from l10n_parent instead
407
        // because web mounts point to pages in default language and rootline returns uids of default languages
408
        if ((int)$checkRec[$GLOBALS['TCA']['pages']['ctrl']['languageField']] !== 0 && (int)$checkRec[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] !== 0) {
409
            $id = (int)$checkRec[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
410
        }
411
        if (!$readPerms) {
412
            $readPerms = $this->getPagePermsClause(Permission::PAGE_SHOW);
413
        }
414
        if ($id > 0) {
415
            $wM = $this->returnWebmounts();
416
            $rL = BackendUtility::BEgetRootLine($id, ' AND ' . $readPerms);
417
            foreach ($rL as $v) {
418
                if ($v['uid'] && in_array($v['uid'], $wM)) {
419
                    return $v['uid'];
420
                }
421
            }
422
        }
423
        if ($exitOnError) {
424
            throw new \RuntimeException('Access Error: This page is not within your DB-mounts', 1294586445);
425
        }
426
        return null;
427
    }
428
429
    /**
430
     * Checks access to a backend module with the $MCONF passed as first argument
431
     *
432
     * @param array $conf $MCONF array of a backend module!
433
     * @throws \RuntimeException
434
     * @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
435
     */
436
    public function modAccess($conf)
437
    {
438
        if (!BackendUtility::isModuleSetInTBE_MODULES($conf['name'])) {
439
            throw new \RuntimeException('Fatal Error: This module "' . $conf['name'] . '" is not enabled in TBE_MODULES', 1294586446);
440
        }
441
        // Workspaces check:
442
        if (
443
            !empty($conf['workspaces'])
444
            && ExtensionManagementUtility::isLoaded('workspaces')
445
            && ($this->workspace !== 0 || !GeneralUtility::inList($conf['workspaces'], 'online'))
446
            && ($this->workspace !== -1 || !GeneralUtility::inList($conf['workspaces'], 'offline'))
447
            && ($this->workspace <= 0 || !GeneralUtility::inList($conf['workspaces'], 'custom'))
448
        ) {
449
            throw new \RuntimeException('Workspace Error: This module "' . $conf['name'] . '" is not available under the current workspace', 1294586447);
450
        }
451
        // Returns false if conf[access] is set to system maintainers and the user is system maintainer
452
        if (strpos($conf['access'], self::ROLE_SYSTEMMAINTAINER) !== false && !$this->isSystemMaintainer()) {
453
            throw new \RuntimeException('This module "' . $conf['name'] . '" is only available as system maintainer', 1504804727);
454
        }
455
        // Returns TRUE if conf[access] is not set at all or if the user is admin
456
        if (!$conf['access'] || $this->isAdmin()) {
457
            return true;
458
        }
459
        // If $conf['access'] is set but not with 'admin' then we return TRUE, if the module is found in the modList
460
        $acs = false;
461
        if (strpos($conf['access'], 'admin') === false && $conf['name']) {
462
            $acs = $this->check('modules', $conf['name']);
463
        }
464
        if (!$acs) {
465
            throw new \RuntimeException('Access Error: You don\'t have access to this module.', 1294586448);
466
        }
467
        return $acs;
468
    }
469
470
    /**
471
     * Checks if the user is in the valid list of allowed system maintainers. if the list is not set,
472
     * then all admins are system maintainers. If the list is empty, no one is system maintainer (good for production
473
     * systems). If the currently logged in user is in "switch user" mode, this method will return false.
474
     *
475
     * @return bool
476
     */
477
    public function isSystemMaintainer(): bool
478
    {
479
        if ((int)$GLOBALS['BE_USER']->user['ses_backuserid'] !== 0) {
480
            return false;
481
        }
482
        if (Environment::getContext()->isDevelopment() && $this->isAdmin()) {
483
            return true;
484
        }
485
        $systemMaintainers = $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? [];
486
        $systemMaintainers = array_map('intval', $systemMaintainers);
487
        if (!empty($systemMaintainers)) {
488
            return in_array((int)$this->user['uid'], $systemMaintainers, true);
489
        }
490
        // No system maintainers set up yet, so any admin is allowed to access the modules
491
        // but explicitly no system maintainers allowed (empty string in TYPO3_CONF_VARS).
492
        // @todo: this needs to be adjusted once system maintainers can log into the install tool with their credentials
493
        if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'])
494
            && empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'])) {
495
            return false;
496
        }
497
        return $this->isAdmin();
498
    }
499
500
    /**
501
     * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
502
     * $perms is the "mask" used to select. Fx. if $perms is 1 then you'll get all pages that a user can actually see!
503
     * 2^0 = show (1)
504
     * 2^1 = edit (2)
505
     * 2^2 = delete (4)
506
     * 2^3 = new (8)
507
     * If the user is 'admin' " 1=1" is returned (no effect)
508
     * 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)
509
     * The 95% use of this function is "->getPagePermsClause(1)" which will
510
     * return WHERE clauses for *selecting* pages in backend listings - in other words this will check read permissions.
511
     *
512
     * @param int $perms Permission mask to use, see function description
513
     * @return string Part of where clause. Prefix " AND " to this.
514
     */
515
    public function getPagePermsClause($perms)
516
    {
517
        if (is_array($this->user)) {
518
            if ($this->isAdmin()) {
519
                return ' 1=1';
520
            }
521
            // Make sure it's integer.
522
            $perms = (int)$perms;
523
            $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
524
                ->getQueryBuilderForTable('pages')
525
                ->expr();
526
527
            // User
528
            $constraint = $expressionBuilder->orX(
529
                $expressionBuilder->comparison(
530
                    $expressionBuilder->bitAnd('pages.perms_everybody', $perms),
531
                    ExpressionBuilder::EQ,
532
                    $perms
533
                ),
534
                $expressionBuilder->andX(
535
                    $expressionBuilder->eq('pages.perms_userid', (int)$this->user['uid']),
536
                    $expressionBuilder->comparison(
537
                        $expressionBuilder->bitAnd('pages.perms_user', $perms),
538
                        ExpressionBuilder::EQ,
539
                        $perms
540
                    )
541
                )
542
            );
543
544
            // Group (if any is set)
545
            if ($this->groupList) {
546
                $constraint->add(
547
                    $expressionBuilder->andX(
548
                        $expressionBuilder->in(
549
                            'pages.perms_groupid',
550
                            GeneralUtility::intExplode(',', $this->groupList)
551
                        ),
552
                        $expressionBuilder->comparison(
553
                            $expressionBuilder->bitAnd('pages.perms_group', $perms),
554
                            ExpressionBuilder::EQ,
555
                            $perms
556
                        )
557
                    )
558
                );
559
            }
560
561
            $constraint = ' (' . (string)$constraint . ')';
562
563
            // ****************
564
            // getPagePermsClause-HOOK
565
            // ****************
566
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'] ?? [] as $_funcRef) {
567
                $_params = ['currentClause' => $constraint, 'perms' => $perms];
568
                $constraint = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
569
            }
570
            return $constraint;
571
        }
572
        return ' 1=0';
573
    }
574
575
    /**
576
     * Returns a combined binary representation of the current users permissions for the page-record, $row.
577
     * The perms for user, group and everybody is OR'ed together (provided that the page-owner is the user
578
     * and for the groups that the user is a member of the group.
579
     * If the user is admin, 31 is returned	(full permissions for all five flags)
580
     *
581
     * @param array $row Input page row with all perms_* fields available.
582
     * @return int Bitwise representation of the users permissions in relation to input page row, $row
583
     */
584
    public function calcPerms($row)
585
    {
586
        // Return 31 for admin users.
587
        if ($this->isAdmin()) {
588
            return Permission::ALL;
589
        }
590
        // Return 0 if page is not within the allowed web mount
591
        // Always do this for the default language page record
592
        if (!$this->isInWebMount($row[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] ?: $row)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->isInWebMount($row...ointerField']] ?: $row) of type integer|null is loosely compared to false; 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...
593
            return Permission::NOTHING;
594
        }
595
        $out = Permission::NOTHING;
596
        if (
597
            isset($row['perms_userid']) && isset($row['perms_user']) && isset($row['perms_groupid'])
598
            && isset($row['perms_group']) && isset($row['perms_everybody']) && isset($this->groupList)
599
        ) {
600
            if ($this->user['uid'] == $row['perms_userid']) {
601
                $out |= $row['perms_user'];
602
            }
603
            if ($this->isMemberOfGroup($row['perms_groupid'])) {
604
                $out |= $row['perms_group'];
605
            }
606
            $out |= $row['perms_everybody'];
607
        }
608
        // ****************
609
        // CALCPERMS hook
610
        // ****************
611
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'] ?? [] as $_funcRef) {
612
            $_params = [
613
                'row' => $row,
614
                'outputPermissions' => $out
615
            ];
616
            $out = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
617
        }
618
        return $out;
619
    }
620
621
    /**
622
     * Returns TRUE if the RTE (Rich Text Editor) is enabled for the user.
623
     *
624
     * @return bool
625
     */
626
    public function isRTE()
627
    {
628
        return (bool)$this->uc['edit_RTE'];
629
    }
630
631
    /**
632
     * Returns TRUE if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
633
     * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
634
     * If user is admin TRUE is also returned
635
     * Please see the document Inside TYPO3 for examples.
636
     *
637
     * @param string $type The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules", "available_widgets"
638
     * @param string $value String to search for in the groupData-list
639
     * @return bool TRUE if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
640
     */
641
    public function check($type, $value)
642
    {
643
        return isset($this->groupData[$type])
644
            && ($this->isAdmin() || GeneralUtility::inList($this->groupData[$type], $value));
645
    }
646
647
    /**
648
     * Checking the authMode of a select field with authMode set
649
     *
650
     * @param string $table Table name
651
     * @param string $field Field name (must be configured in TCA and of type "select" with authMode set!)
652
     * @param string $value Value to evaluation (single value, must not contain any of the chars ":,|")
653
     * @param string $authMode Auth mode keyword (explicitAllow, explicitDeny, individual)
654
     * @return bool Whether access is granted or not
655
     */
656
    public function checkAuthMode($table, $field, $value, $authMode)
657
    {
658
        // Admin users can do anything:
659
        if ($this->isAdmin()) {
660
            return true;
661
        }
662
        // Allow all blank values:
663
        if ((string)$value === '') {
664
            return true;
665
        }
666
        // Allow dividers:
667
        if ($value === '--div--') {
668
            return true;
669
        }
670
        // Certain characters are not allowed in the value
671
        if (preg_match('/[:|,]/', $value)) {
672
            return false;
673
        }
674
        // Initialize:
675
        $testValue = $table . ':' . $field . ':' . $value;
676
        $out = true;
677
        // Checking value:
678
        switch ((string)$authMode) {
679
            case 'explicitAllow':
680
                if (!GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':ALLOW')) {
681
                    $out = false;
682
                }
683
                break;
684
            case 'explicitDeny':
685
                if (GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
686
                    $out = false;
687
                }
688
                break;
689
            case 'individual':
690
                if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
691
                    $items = $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'];
692
                    if (is_array($items)) {
693
                        foreach ($items as $iCfg) {
694
                            if ((string)$iCfg[1] === (string)$value && $iCfg[4]) {
695
                                switch ((string)$iCfg[4]) {
696
                                    case 'EXPL_ALLOW':
697
                                        if (!GeneralUtility::inList(
698
                                            $this->groupData['explicit_allowdeny'],
699
                                            $testValue . ':ALLOW'
700
                                        )) {
701
                                            $out = false;
702
                                        }
703
                                        break;
704
                                    case 'EXPL_DENY':
705
                                        if (GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
706
                                            $out = false;
707
                                        }
708
                                        break;
709
                                }
710
                                break;
711
                            }
712
                        }
713
                    }
714
                }
715
                break;
716
        }
717
        return $out;
718
    }
719
720
    /**
721
     * Checking if a language value (-1, 0 and >0 for sys_language records) is allowed to be edited by the user.
722
     *
723
     * @param int $langValue Language value to evaluate
724
     * @return bool Returns TRUE if the language value is allowed, otherwise FALSE.
725
     */
726
    public function checkLanguageAccess($langValue)
727
    {
728
        // The users language list must be non-blank - otherwise all languages are allowed.
729
        if (trim($this->groupData['allowed_languages']) !== '') {
730
            $langValue = (int)$langValue;
731
            // Language must either be explicitly allowed OR the lang Value be "-1" (all languages)
732
            if ($langValue != -1 && !$this->check('allowed_languages', $langValue)) {
733
                return false;
734
            }
735
        }
736
        return true;
737
    }
738
739
    /**
740
     * Check if user has access to all existing localizations for a certain record
741
     *
742
     * @param string $table The table
743
     * @param array $record The current record
744
     * @return bool
745
     */
746
    public function checkFullLanguagesAccess($table, $record)
747
    {
748
        if (!$this->checkLanguageAccess(0)) {
749
            return false;
750
        }
751
752
        if (BackendUtility::isTableLocalizable($table)) {
753
            $pointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
754
            $pointerValue = $record[$pointerField] > 0 ? $record[$pointerField] : $record['uid'];
755
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
756
            $queryBuilder->getRestrictions()
757
                ->removeAll()
758
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
759
                ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
760
            $recordLocalizations = $queryBuilder->select('*')
761
                ->from($table)
762
                ->where(
763
                    $queryBuilder->expr()->eq(
764
                        $pointerField,
765
                        $queryBuilder->createNamedParameter($pointerValue, \PDO::PARAM_INT)
766
                    )
767
                )
768
                ->execute()
769
                ->fetchAll();
770
771
            foreach ($recordLocalizations as $recordLocalization) {
772
                if (!$this->checkLanguageAccess($recordLocalization[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
773
                    return false;
774
                }
775
            }
776
        }
777
        return true;
778
    }
779
780
    /**
781
     * Checking if a user has editing access to a record from a $GLOBALS['TCA'] table.
782
     * The checks does not take page permissions and other "environmental" things into account.
783
     * It only deal with record internals; If any values in the record fields disallows it.
784
     * For instance languages settings, authMode selector boxes are evaluated (and maybe more in the future).
785
     * It will check for workspace dependent access.
786
     * The function takes an ID (int) or row (array) as second argument.
787
     *
788
     * @param string $table Table name
789
     * @param mixed $idOrRow If integer, then this is the ID of the record. If Array this just represents fields in the record.
790
     * @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.
791
     * @param bool $deletedRecord Set, if testing a deleted record array.
792
     * @param bool $checkFullLanguageAccess Set, whenever access to all translations of the record is required
793
     * @return bool TRUE if OK, otherwise FALSE
794
     */
795
    public function recordEditAccessInternals($table, $idOrRow, $newRecord = false, $deletedRecord = false, $checkFullLanguageAccess = false)
796
    {
797
        if (!isset($GLOBALS['TCA'][$table])) {
798
            return false;
799
        }
800
        // Always return TRUE for Admin users.
801
        if ($this->isAdmin()) {
802
            return true;
803
        }
804
        // Fetching the record if the $idOrRow variable was not an array on input:
805
        if (!is_array($idOrRow)) {
806
            if ($deletedRecord) {
807
                $idOrRow = BackendUtility::getRecord($table, $idOrRow, '*', '', false);
808
            } else {
809
                $idOrRow = BackendUtility::getRecord($table, $idOrRow);
810
            }
811
            if (!is_array($idOrRow)) {
812
                $this->errorMsg = 'ERROR: Record could not be fetched.';
813
                return false;
814
            }
815
        }
816
        // Checking languages:
817
        if ($table === 'pages' && $checkFullLanguageAccess && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
818
            return false;
819
        }
820
        if ($GLOBALS['TCA'][$table]['ctrl']['languageField']) {
821
            // Language field must be found in input row - otherwise it does not make sense.
822
            if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
823
                if (!$this->checkLanguageAccess($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
824
                    $this->errorMsg = 'ERROR: Language was not allowed.';
825
                    return false;
826
                }
827
                if (
828
                    $checkFullLanguageAccess && $idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']] == 0
829
                    && !$this->checkFullLanguagesAccess($table, $idOrRow)
830
                ) {
831
                    $this->errorMsg = 'ERROR: Related/affected language was not allowed.';
832
                    return false;
833
                }
834
            } else {
835
                $this->errorMsg = 'ERROR: The "languageField" field named "'
836
                    . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '" was not found in testing record!';
837
                return false;
838
            }
839
        }
840
        // Checking authMode fields:
841
        if (is_array($GLOBALS['TCA'][$table]['columns'])) {
842
            foreach ($GLOBALS['TCA'][$table]['columns'] as $fieldName => $fieldValue) {
843
                if (isset($idOrRow[$fieldName])) {
844
                    if (
845
                        $fieldValue['config']['type'] === 'select' && $fieldValue['config']['authMode']
846
                        && $fieldValue['config']['authMode_enforce'] === 'strict'
847
                    ) {
848
                        if (!$this->checkAuthMode($table, $fieldName, $idOrRow[$fieldName], $fieldValue['config']['authMode'])) {
849
                            $this->errorMsg = 'ERROR: authMode "' . $fieldValue['config']['authMode']
850
                                . '" failed for field "' . $fieldName . '" with value "'
851
                                . $idOrRow[$fieldName] . '" evaluated';
852
                            return false;
853
                        }
854
                    }
855
                }
856
            }
857
        }
858
        // Checking "editlock" feature (doesn't apply to new records)
859
        if (!$newRecord && $GLOBALS['TCA'][$table]['ctrl']['editlock']) {
860
            if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']])) {
861
                if ($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']]) {
862
                    $this->errorMsg = 'ERROR: Record was locked for editing. Only admin users can change this state.';
863
                    return false;
864
                }
865
            } else {
866
                $this->errorMsg = 'ERROR: The "editLock" field named "' . $GLOBALS['TCA'][$table]['ctrl']['editlock']
867
                    . '" was not found in testing record!';
868
                return false;
869
            }
870
        }
871
        // Checking record permissions
872
        // THIS is where we can include a check for "perms_" fields for other records than pages...
873
        // Process any hooks
874
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'] ?? [] as $funcRef) {
875
            $params = [
876
                'table' => $table,
877
                'idOrRow' => $idOrRow,
878
                'newRecord' => $newRecord
879
            ];
880
            if (!GeneralUtility::callUserFunction($funcRef, $params, $this)) {
881
                return false;
882
            }
883
        }
884
        // Finally, return TRUE if all is well.
885
        return true;
886
    }
887
888
    /**
889
     * Returns TRUE if the BE_USER is allowed to *create* shortcuts in the backend modules
890
     *
891
     * @return bool
892
     */
893
    public function mayMakeShortcut()
894
    {
895
        return $this->getTSConfig()['options.']['enableBookmarks'] ?? false
896
            && !($this->getTSConfig()['options.']['mayNotCreateEditBookmarks'] ?? false);
897
    }
898
899
    /**
900
     * Checking if editing of an existing record is allowed in current workspace if that is offline.
901
     * Rules for editing in offline mode:
902
     * - record supports versioning and is an offline version from workspace and has the current stage
903
     * - or record (any) is in a branch where there is a page which is a version from the workspace
904
     *   and where the stage is not preventing records
905
     *
906
     * @param string $table Table of record
907
     * @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)
908
     * @return string String error code, telling the failure state. FALSE=All ok
909
     */
910
    public function workspaceCannotEditRecord($table, $recData)
911
    {
912
        // Only test if the user is in a workspace
913
        if ($this->workspace === 0) {
914
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
915
        }
916
        $tableSupportsVersioning = BackendUtility::isTableWorkspaceEnabled($table);
917
        if (!is_array($recData)) {
918
            $recData = BackendUtility::getRecord(
919
                $table,
920
                $recData,
921
                'pid' . ($tableSupportsVersioning ? ',t3ver_oid,t3ver_wsid,t3ver_stage' : '')
922
            );
923
        }
924
        if (is_array($recData)) {
925
            // We are testing a "version" (identified by having a t3ver_oid): it can be edited provided
926
            // that workspace matches and versioning is enabled for the table.
927
            if ($tableSupportsVersioning && (int)($recData['t3ver_oid'] ?? 0) > 0) {
928
                if ((int)$recData['t3ver_wsid'] !== $this->workspace) {
929
                    // So does workspace match?
930
                    return 'Workspace ID of record didn\'t match current workspace';
931
                }
932
                // So is the user allowed to "use" the edit stage within the workspace?
933
                return $this->workspaceCheckStageForCurrent(0)
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->workspaceC... not allow for editing' 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...
934
                        ? false
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "?"; newline found
Loading history...
935
                        : 'User\'s access level did not allow for editing';
0 ignored issues
show
Coding Style introduced by
Expected 1 space before ":"; newline found
Loading history...
936
            }
937
            // Check if we are testing a "live" record
938
            if ($this->workspaceAllowsLiveEditingInTable($table)) {
939
                // Live records are OK in the current workspace
940
                return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
941
            }
942
            // If not offline, output error
943
            return 'Online record was not in a workspace!';
944
        }
945
        return 'No record';
946
    }
947
948
    /**
949
     * Evaluates if a user is allowed to edit the offline version
950
     *
951
     * @param string $table Table of record
952
     * @param array|int $recData Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
953
     * @return string String error code, telling the failure state. FALSE=All ok
954
     * @see workspaceCannotEditRecord()
955
     * @internal this method will be moved to EXT:workspaces
956
     */
957
    public function workspaceCannotEditOfflineVersion($table, $recData)
958
    {
959
        if (!BackendUtility::isTableWorkspaceEnabled($table)) {
960
            return 'Table does not support versioning.';
961
        }
962
        if (!is_array($recData)) {
963
            $recData = BackendUtility::getRecord($table, $recData, 'uid,pid,t3ver_oid,t3ver_wsid,t3ver_stage');
964
        }
965
        if (is_array($recData)) {
966
            if ((int)$recData['t3ver_oid'] > 0) {
967
                return $this->workspaceCannotEditRecord($table, $recData);
968
            }
969
            return 'Not an offline version';
970
        }
971
        return 'No record';
972
    }
973
974
    /**
975
     * Check if "live" records from $table may be created or edited in this PID.
976
     * If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
977
     * If the answer is 1 or 2 it means it is OK to create a record, if -1 it means that it is OK in terms
978
     * of versioning because the element was within a versionized branch
979
     * but NOT ok in terms of the state the root point had!
980
     *
981
     * Note: this method is not in use anymore and will likely be deprecated in future TYPO3 versions.
982
     *
983
     * @param int $pid PID value to check for. OBSOLETE!
984
     * @param string $table Table name
985
     * @return mixed Returns FALSE if a live record cannot be created and must be versionized in order to do so. 2 means a) Workspace is "Live" or workspace allows "live edit" of records from non-versionized tables (and the $table is not versionizable). 1 and -1 means the pid is inside a versionized branch where -1 means that the branch-point did NOT allow a new record according to its state.
986
     */
987
    public function workspaceAllowLiveRecordsInPID($pid, $table)
0 ignored issues
show
Unused Code introduced by
The parameter $pid is not used and could be removed. ( Ignorable by Annotation )

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

987
    public function workspaceAllowLiveRecordsInPID(/** @scrutinizer ignore-unused */ $pid, $table)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
988
    {
989
        // Always for Live workspace AND if live-edit is enabled
990
        // and tables are completely without versioning it is ok as well.
991
        if (
992
            $this->workspace === 0
993
            || $this->workspaceRec['live_edit'] && !BackendUtility::isTableWorkspaceEnabled($table)
994
            || $GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']
995
        ) {
996
            // OK to create for this table.
997
            return 2;
998
        }
999
        // If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
1000
        return false;
1001
    }
1002
1003
    /**
1004
     * Checks if a record is allowed to be edited in the current workspace.
1005
     * This is not bound to an actual record, but to the mere fact if the user is in a workspace
1006
     * and depending on the table settings.
1007
     *
1008
     * @param string $table
1009
     * @return bool
1010
     */
1011
    public function workspaceAllowsLiveEditingInTable(string $table): bool
1012
    {
1013
        // In live workspace the record can be added/modified
1014
        if ($this->workspace === 0) {
1015
            return true;
1016
        }
1017
        // Workspace setting allows to "live edit" records of tables without versioning
1018
        if ($this->workspaceRec['live_edit'] && !BackendUtility::isTableWorkspaceEnabled($table)) {
1019
            return true;
1020
        }
1021
        // Always for Live workspace AND if live-edit is enabled
1022
        // and tables are completely without versioning it is ok as well.
1023
        if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']) {
1024
            return true;
1025
        }
1026
        // If the answer is FALSE it means the only valid way to create or edit records by creating records in the workspace
1027
        return false;
1028
    }
1029
1030
    /**
1031
     * Evaluates if a record from $table can be created in $pid
1032
     *
1033
     * Note: this method is not in use anymore and will likely be deprecated in future TYPO3 versions.
1034
     *
1035
     * @param int $pid Page id. This value must be the _ORIG_uid if available: So when you have pages versionized as "page" or "element" you must supply the id of the page version in the workspace!
1036
     * @param string $table Table name
1037
     * @return bool TRUE if OK.
1038
     */
1039
    public function workspaceCreateNewRecord($pid, $table)
0 ignored issues
show
Unused Code introduced by
The parameter $pid is not used and could be removed. ( Ignorable by Annotation )

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

1039
    public function workspaceCreateNewRecord(/** @scrutinizer ignore-unused */ $pid, $table)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1040
    {
1041
        // If LIVE records cannot be created due to workspace restrictions, prepare creation of placeholder-record
1042
        if (!$this->workspaceAllowsLiveEditingInTable($table) && !BackendUtility::isTableWorkspaceEnabled($table)) {
1043
            // So, if no live records were allowed, we have to create a new version of this record
1044
            return false;
1045
        }
1046
        return true;
1047
    }
1048
1049
    /**
1050
     * Evaluates if a record from $table can be created. If the table is not set up for versioning,
1051
     * and the "live edit" flag of the page is set, return false. In live workspace this is always true,
1052
     * as all records can be created in live workspace
1053
     *
1054
     * @param string $table Table name
1055
     * @return bool
1056
     */
1057
    public function workspaceCanCreateNewRecord(string $table): bool
1058
    {
1059
        // If LIVE records cannot be created due to workspace restrictions, prepare creation of placeholder-record
1060
        if (!$this->workspaceAllowsLiveEditingInTable($table) && !BackendUtility::isTableWorkspaceEnabled($table)) {
1061
            return false;
1062
        }
1063
        return true;
1064
    }
1065
1066
    /**
1067
     * Evaluates if auto creation of a version of a record is allowed.
1068
     * Auto-creation of version: In offline workspace, test if versioning is
1069
     * enabled and look for workspace version of input record.
1070
     * If there is no versionized record found we will create one and save to that.
1071
     *
1072
     * @param string $table Table of the record
1073
     * @param int $id UID of record
1074
     * @param int $recpid PID of record
1075
     * @return bool TRUE if ok.
1076
     */
1077
    public function workspaceAllowAutoCreation($table, $id, $recpid)
1078
    {
1079
        // No version can be created in live workspace
1080
        if ($this->workspace === 0) {
1081
            return false;
1082
        }
1083
        // No versioning support for this table, so no version can be created
1084
        if (!BackendUtility::isTableWorkspaceEnabled($table)) {
1085
            return false;
1086
        }
1087
        if ($recpid < 0) {
1088
            return false;
1089
        }
1090
        // There must be no existing version of this record in workspace
1091
        if (BackendUtility::getWorkspaceVersionOfRecord($this->workspace, $table, $id, 'uid')) {
1092
            return false;
1093
        }
1094
        return true;
1095
    }
1096
1097
    /**
1098
     * Checks if an element stage allows access for the user in the current workspace
1099
     * In live workspace (= 0) access is always granted for any stage.
1100
     * Admins are always allowed.
1101
     * An option for custom workspaces allows members to also edit when the stage is "Review"
1102
     *
1103
     * @param int $stage Stage id from an element: -1,0 = editing, 1 = reviewer, >1 = owner
1104
     * @return bool TRUE if user is allowed access
1105
     */
1106
    public function workspaceCheckStageForCurrent($stage)
1107
    {
1108
        // Always allow for admins
1109
        if ($this->isAdmin()) {
1110
            return true;
1111
        }
1112
        // Always OK for live workspace
1113
        if ($this->workspace === 0 || !ExtensionManagementUtility::isLoaded('workspaces')) {
1114
            return true;
1115
        }
1116
        $stage = (int)$stage;
1117
        $stat = $this->checkWorkspaceCurrent();
1118
        $accessType = $stat['_ACCESS'];
1119
        // Workspace owners are always allowed for stage change
1120
        if ($accessType === 'owner') {
1121
            return true;
1122
        }
1123
1124
        // Check if custom staging is activated
1125
        $workspaceRec = BackendUtility::getRecord('sys_workspace', $stat['uid']);
1126
        if ($workspaceRec['custom_stages'] > 0 && $stage !== 0 && $stage !== -10) {
1127
            // Get custom stage record
1128
            $workspaceStageRec = BackendUtility::getRecord('sys_workspace_stage', $stage);
1129
            // Check if the user is responsible for the current stage
1130
            if (
1131
                $accessType === 'member'
1132
                && GeneralUtility::inList($workspaceStageRec['responsible_persons'], 'be_users_' . $this->user['uid'])
1133
            ) {
1134
                return true;
1135
            }
1136
            // Check if the user is in a group which is responsible for the current stage
1137
            foreach ($this->userGroupsUID as $groupUid) {
1138
                if (
1139
                    $accessType === 'member'
1140
                    && GeneralUtility::inList($workspaceStageRec['responsible_persons'], 'be_groups_' . $groupUid)
1141
                ) {
1142
                    return true;
1143
                }
1144
            }
1145
        } elseif ($stage === -10 || $stage === -20) {
1146
            // Nobody is allowed to do that except the owner (which was checked above)
1147
            return false;
1148
        } elseif (
1149
            $accessType === 'reviewer' && $stage <= 1
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($accessType === 'review...'member' && $stage <= 0, Probably Intended Meaning: $accessType === 'reviewe...member' && $stage <= 0)
Loading history...
1150
            || $accessType === 'member' && $stage <= 0
1151
        ) {
1152
            return true;
1153
        }
1154
        return false;
1155
    }
1156
1157
    /**
1158
     * Returns TRUE if the user has access to publish content from the workspace ID given.
1159
     * Admin-users are always granted access to do this
1160
     * If the workspace ID is 0 (live) all users have access also
1161
     * For custom workspaces it depends on whether the user is owner OR like with
1162
     * draft workspace if the user has access to Live workspace.
1163
     *
1164
     * @param int $wsid Workspace UID; 0,1+
1165
     * @return bool Returns TRUE if the user has access to publish content from the workspace ID given.
1166
     * @internal this method will be moved to EXT:workspaces
1167
     */
1168
    public function workspacePublishAccess($wsid)
1169
    {
1170
        if ($this->isAdmin()) {
1171
            return true;
1172
        }
1173
        $wsAccess = $this->checkWorkspace($wsid);
1174
        // If no access to workspace, of course you cannot publish!
1175
        if ($wsAccess === false) {
0 ignored issues
show
introduced by
The condition $wsAccess === false is always false.
Loading history...
1176
            return false;
1177
        }
1178
        if ((int)$wsAccess['uid'] === 0) {
1179
            // If access to Live workspace, no problem.
1180
            return true;
1181
        }
1182
        // Custom workspaces
1183
        // 1. Owners can always publish
1184
        if ($wsAccess['_ACCESS'] === 'owner') {
1185
            return true;
1186
        }
1187
        // 2. User has access to online workspace which is OK as well as long as publishing
1188
        // access is not limited by workspace option.
1189
        return $this->checkWorkspace(0) && !($wsAccess['publish_access'] & 2);
1190
    }
1191
1192
    /**
1193
     * Workspace swap-mode access?
1194
     *
1195
     * @return bool Returns TRUE if records can be swapped in the current workspace, otherwise FALSE
1196
     * @internal this method will be moved to EXT:workspaces
1197
     */
1198
    public function workspaceSwapAccess()
1199
    {
1200
        // Always possible in live workspace
1201
        if ($this->workspace === 0) {
1202
            return true;
1203
        }
1204
        // In custom workspaces, only possible if swap_modes flag is not "2" (explicitly disabling swapping)
1205
        if ((int)$this->workspaceRec['swap_modes'] !== 2) {
1206
            return true;
1207
        }
1208
        return false;
1209
    }
1210
1211
    /**
1212
     * Returns full parsed user TSconfig array, merged with TSconfig from groups.
1213
     *
1214
     * Example:
1215
     * [
1216
     *     'options.' => [
1217
     *         'fooEnabled' => '0',
1218
     *         'fooEnabled.' => [
1219
     *             'tt_content' => 1,
1220
     *         ],
1221
     *     ],
1222
     * ]
1223
     *
1224
     * @return array Parsed and merged user TSconfig array
1225
     */
1226
    public function getTSConfig()
1227
    {
1228
        return $this->userTS;
1229
    }
1230
1231
    /**
1232
     * Returns an array with the webmounts.
1233
     * If no webmounts, and empty array is returned.
1234
     * NOTICE: Deleted pages WILL NOT be filtered out! So if a mounted page has been deleted
1235
     *         it is STILL coming out as a webmount. This is not checked due to performance.
1236
     *
1237
     * @return array
1238
     */
1239
    public function returnWebmounts()
1240
    {
1241
        return (string)$this->groupData['webmounts'] != '' ? explode(',', $this->groupData['webmounts']) : [];
1242
    }
1243
1244
    /**
1245
     * Initializes the given mount points for the current Backend user.
1246
     *
1247
     * @param array $mountPointUids Page UIDs that should be used as web mountpoints
1248
     * @param bool $append If TRUE the given mount point will be appended. Otherwise the current mount points will be replaced.
1249
     */
1250
    public function setWebmounts(array $mountPointUids, $append = false)
1251
    {
1252
        if (empty($mountPointUids)) {
1253
            return;
1254
        }
1255
        if ($append) {
1256
            $currentWebMounts = GeneralUtility::intExplode(',', $this->groupData['webmounts']);
1257
            $mountPointUids = array_merge($currentWebMounts, $mountPointUids);
1258
        }
1259
        $this->groupData['webmounts'] = implode(',', array_unique($mountPointUids));
1260
    }
1261
1262
    /**
1263
     * Checks for alternative web mount points for the element browser.
1264
     *
1265
     * If there is a temporary mount point active in the page tree it will be used.
1266
     *
1267
     * If the User TSconfig options.pageTree.altElementBrowserMountPoints is not empty the pages configured
1268
     * there are used as web mounts If options.pageTree.altElementBrowserMountPoints.append is enabled,
1269
     * they are appended to the existing webmounts.
1270
     *
1271
     * @internal - do not use in your own extension
1272
     */
1273
    public function initializeWebmountsForElementBrowser()
1274
    {
1275
        $alternativeWebmountPoint = (int)$this->getSessionData('pageTree_temporaryMountPoint');
1276
        if ($alternativeWebmountPoint) {
1277
            $alternativeWebmountPoint = GeneralUtility::intExplode(',', $alternativeWebmountPoint);
1278
            $this->setWebmounts($alternativeWebmountPoint);
1279
            return;
1280
        }
1281
1282
        $alternativeWebmountPoints = trim($this->getTSConfig()['options.']['pageTree.']['altElementBrowserMountPoints'] ?? '');
1283
        $appendAlternativeWebmountPoints = $this->getTSConfig()['options.']['pageTree.']['altElementBrowserMountPoints.']['append'] ?? '';
1284
        if ($alternativeWebmountPoints) {
1285
            $alternativeWebmountPoints = GeneralUtility::intExplode(',', $alternativeWebmountPoints);
1286
            $this->setWebmounts($alternativeWebmountPoints, $appendAlternativeWebmountPoints);
0 ignored issues
show
Bug introduced by
It seems like $appendAlternativeWebmountPoints can also be of type string; however, parameter $append of TYPO3\CMS\Core\Authentic...ication::setWebmounts() 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

1286
            $this->setWebmounts($alternativeWebmountPoints, /** @scrutinizer ignore-type */ $appendAlternativeWebmountPoints);
Loading history...
1287
        }
1288
    }
1289
1290
    /**
1291
     * Returns TRUE or FALSE, depending if an alert popup (a javascript confirmation) should be shown
1292
     * call like $GLOBALS['BE_USER']->jsConfirmation($BITMASK).
1293
     *
1294
     * @param int $bitmask Bitmask, one of \TYPO3\CMS\Core\Type\Bitmask\JsConfirmation
1295
     * @return bool TRUE if the confirmation should be shown
1296
     * @see JsConfirmation
1297
     */
1298
    public function jsConfirmation($bitmask)
1299
    {
1300
        try {
1301
            $alertPopupsSetting = trim((string)($this->getTSConfig()['options.']['alertPopups'] ?? ''));
1302
            $alertPopup = JsConfirmation::cast($alertPopupsSetting === '' ? null : (int)$alertPopupsSetting);
1303
        } catch (InvalidEnumerationValueException $e) {
1304
            $alertPopup = new JsConfirmation();
1305
        }
1306
1307
        return JsConfirmation::cast($bitmask)->matches($alertPopup);
1308
    }
1309
1310
    /**
1311
     * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
1312
     * This method is called by ->backendCheckLogin() (from extending BackendUserAuthentication)
1313
     * if the backend user login has verified OK.
1314
     * Generally this is required initialization of a backend user.
1315
     *
1316
     * @internal
1317
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1318
     */
1319
    public function fetchGroupData()
1320
    {
1321
        if ($this->user['uid']) {
1322
            // Get lists for the be_user record and set them as default/primary values.
1323
            // Enabled Backend Modules
1324
            $this->dataLists['modList'] = $this->user['userMods'];
1325
            // Add available widgets
1326
            $this->dataLists['available_widgets'] = $this->user['available_widgets'];
1327
            // Add Allowed Languages
1328
            $this->dataLists['allowed_languages'] = $this->user['allowed_languages'];
1329
            // Set user value for workspace permissions.
1330
            $this->dataLists['workspace_perms'] = $this->user['workspace_perms'];
1331
            // Database mountpoints
1332
            $this->dataLists['webmount_list'] = $this->user['db_mountpoints'];
1333
            // File mountpoints
1334
            $this->dataLists['filemount_list'] = $this->user['file_mountpoints'];
1335
            // Fileoperation permissions
1336
            $this->dataLists['file_permissions'] = $this->user['file_permissions'];
1337
1338
            // BE_GROUPS:
1339
            // Get the groups...
1340
            if (!empty($this->user[$this->usergroup_column])) {
1341
                // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc.
1342
                // Refer to fetchGroups() function.
1343
                $this->fetchGroups($this->user[$this->usergroup_column]);
1344
            }
1345
            // Populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
1346
            $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
1347
            // Finally this is the list of group_uid's in the order they are parsed (including subgroups!)
1348
            // and without duplicates (duplicates are presented with their last entrance in the list,
1349
            // which thus reflects the order of the TypoScript in TSconfig)
1350
            $this->groupList = implode(',', $this->userGroupsUID);
1351
            $this->setCachedList($this->groupList);
1352
1353
            $this->prepareUserTsConfig();
1354
1355
            // Processing webmounts
1356
            // Admin's always have the root mounted
1357
            if ($this->isAdmin() && !($this->getTSConfig()['options.']['dontMountAdminMounts'] ?? false)) {
1358
                $this->dataLists['webmount_list'] = '0,' . $this->dataLists['webmount_list'];
1359
            }
1360
            // The lists are cleaned for duplicates
1361
            $this->groupData['webmounts'] = GeneralUtility::uniqueList($this->dataLists['webmount_list']);
1362
            $this->groupData['pagetypes_select'] = GeneralUtility::uniqueList($this->dataLists['pagetypes_select']);
1363
            $this->groupData['tables_select'] = GeneralUtility::uniqueList($this->dataLists['tables_modify'] . ',' . $this->dataLists['tables_select']);
1364
            $this->groupData['tables_modify'] = GeneralUtility::uniqueList($this->dataLists['tables_modify']);
1365
            $this->groupData['non_exclude_fields'] = GeneralUtility::uniqueList($this->dataLists['non_exclude_fields']);
1366
            $this->groupData['explicit_allowdeny'] = GeneralUtility::uniqueList($this->dataLists['explicit_allowdeny']);
1367
            $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($this->dataLists['allowed_languages']);
1368
            $this->groupData['custom_options'] = GeneralUtility::uniqueList($this->dataLists['custom_options']);
1369
            $this->groupData['modules'] = GeneralUtility::uniqueList($this->dataLists['modList']);
1370
            $this->groupData['available_widgets'] = GeneralUtility::uniqueList($this->dataLists['available_widgets']);
1371
            $this->groupData['file_permissions'] = GeneralUtility::uniqueList($this->dataLists['file_permissions']);
1372
            $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
1373
1374
            if (!empty(trim($this->groupData['webmounts']))) {
1375
                // Checking read access to web mounts if there are mounts points (not empty string, false or 0)
1376
                $webmounts = explode(',', $this->groupData['webmounts']);
1377
                // Selecting all web mounts with permission clause for reading
1378
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1379
                $queryBuilder->getRestrictions()
1380
                    ->removeAll()
1381
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1382
1383
                $MProws = $queryBuilder->select('uid')
1384
                    ->from('pages')
1385
                    // @todo DOCTRINE: check how to make getPagePermsClause() portable
1386
                    ->where(
1387
                        $this->getPagePermsClause(Permission::PAGE_SHOW),
1388
                        $queryBuilder->expr()->in(
1389
                            'uid',
1390
                            $queryBuilder->createNamedParameter(
1391
                                GeneralUtility::intExplode(',', $this->groupData['webmounts']),
1392
                                Connection::PARAM_INT_ARRAY
1393
                            )
1394
                        )
1395
                    )
1396
                    ->execute()
1397
                    ->fetchAll();
1398
                $MProws = array_column(($MProws ?: []), 'uid', 'uid');
1399
                foreach ($webmounts as $idx => $mountPointUid) {
1400
                    // If the mount ID is NOT found among selected pages, unset it:
1401
                    if ($mountPointUid > 0 && !isset($MProws[$mountPointUid])) {
1402
                        unset($webmounts[$idx]);
1403
                    }
1404
                }
1405
                // Implode mounts in the end.
1406
                $this->groupData['webmounts'] = implode(',', $webmounts);
1407
            }
1408
            // Setting up workspace situation (after webmounts are processed!):
1409
            $this->workspaceInit();
1410
        }
1411
    }
1412
1413
    /**
1414
     * This method parses the UserTSconfig from the current user and all their groups.
1415
     * If the contents are the same, parsing is skipped. No matching is applied here currently.
1416
     */
1417
    protected function prepareUserTsConfig(): void
1418
    {
1419
        $collectedUserTSconfig = [
1420
            'default' => $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig']
1421
        ];
1422
        // Default TSconfig for admin-users
1423
        if ($this->isAdmin()) {
1424
            $collectedUserTSconfig[] = 'admPanel.enable.all = 1';
1425
        }
1426
        // Setting defaults for sys_note author / email
1427
        $collectedUserTSconfig[] = '
1428
TCAdefaults.sys_note.author = ' . $this->user['realName'] . '
1429
TCAdefaults.sys_note.email = ' . $this->user['email'];
1430
1431
        // Loop through all groups and add their 'TSconfig' fields
1432
        foreach ($this->includeGroupArray as $groupId) {
1433
            $collectedUserTSconfig['group_' . $groupId] = $this->userGroups[$groupId]['TSconfig'] ?? '';
1434
        }
1435
1436
        $collectedUserTSconfig[] = $this->user['TSconfig'];
1437
        // Check external files
1438
        $collectedUserTSconfig = TypoScriptParser::checkIncludeLines_array($collectedUserTSconfig);
1439
        // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
1440
        $userTS_text = implode("\n[GLOBAL]\n", $collectedUserTSconfig);
1441
        // Parsing the user TSconfig (or getting from cache)
1442
        $hash = md5('userTS:' . $userTS_text);
1443
        $cache = GeneralUtility::makeInstance(CacheManager::class)->getCache('hash');
1444
        if (!($this->userTS = $cache->get($hash))) {
1445
            $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
1446
            $conditionMatcher = GeneralUtility::makeInstance(ConditionMatcher::class);
1447
            $parseObj->parse($userTS_text, $conditionMatcher);
1448
            $this->userTS = $parseObj->setup;
1449
            $cache->set($hash, $this->userTS, ['UserTSconfig'], 0);
1450
            // Ensure to update UC later
1451
            $this->userTSUpdated = true;
1452
        }
1453
    }
1454
1455
    /**
1456
     * Fetches the group records, subgroups and fills internal arrays.
1457
     * Function is called recursively to fetch subgroups
1458
     *
1459
     * @param string $grList Commalist of be_groups uid numbers
1460
     * @param string $idList List of already processed be_groups-uids so the function will not fall into an eternal recursion.
1461
     * @internal
1462
     */
1463
    public function fetchGroups($grList, $idList = '')
1464
    {
1465
        // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
1466
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->usergroup_table);
1467
        $expressionBuilder = $queryBuilder->expr();
1468
        $constraints = $expressionBuilder->andX(
1469
            $expressionBuilder->eq(
1470
                'pid',
1471
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
1472
            ),
1473
            $expressionBuilder->in(
1474
                'uid',
1475
                $queryBuilder->createNamedParameter(
1476
                    GeneralUtility::intExplode(',', $grList),
1477
                    Connection::PARAM_INT_ARRAY
1478
                )
1479
            ),
1480
            $expressionBuilder->orX(
1481
                $expressionBuilder->eq('lockToDomain', $queryBuilder->quote('')),
1482
                $expressionBuilder->isNull('lockToDomain'),
1483
                $expressionBuilder->eq(
1484
                    'lockToDomain',
1485
                    $queryBuilder->createNamedParameter(GeneralUtility::getIndpEnv('HTTP_HOST'), \PDO::PARAM_STR)
1486
                )
1487
            )
1488
        );
1489
        // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
1490
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] ?? [] as $className) {
1491
            $hookObj = GeneralUtility::makeInstance($className);
1492
            if (method_exists($hookObj, 'fetchGroupQuery_processQuery')) {
1493
                $constraints = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, (string)$constraints);
1494
            }
1495
        }
1496
        $res = $queryBuilder->select('*')
1497
            ->from($this->usergroup_table)
1498
            ->where($constraints)
1499
            ->execute();
1500
        // The userGroups array is filled
1501
        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
1502
            $this->userGroups[$row['uid']] = $row;
1503
        }
1504
        // Traversing records in the correct order
1505
        foreach (explode(',', $grList) as $uid) {
1506
            // Get row:
1507
            $row = $this->userGroups[$uid];
1508
            // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
1509
            if (is_array($row) && !GeneralUtility::inList($idList, $uid)) {
1510
                // Include sub groups
1511
                if (trim($row['subgroup'])) {
1512
                    // Make integer list
1513
                    $theList = implode(',', GeneralUtility::intExplode(',', $row['subgroup']));
1514
                    // Call recursively, pass along list of already processed groups so they are not recursed again.
1515
                    $this->fetchGroups($theList, $idList . ',' . $uid);
1516
                }
1517
                // Add the group uid, current list to the internal arrays.
1518
                $this->includeGroupArray[] = $uid;
1519
                // Mount group database-mounts
1520
                if (($this->user['options'] & Permission::PAGE_SHOW) == 1) {
1521
                    $this->dataLists['webmount_list'] .= ',' . $row['db_mountpoints'];
1522
                }
1523
                // Mount group file-mounts
1524
                if (($this->user['options'] & Permission::PAGE_EDIT) == 2) {
1525
                    $this->dataLists['filemount_list'] .= ',' . $row['file_mountpoints'];
1526
                }
1527
                // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
1528
                $this->dataLists['modList'] .= ',' . $row['groupMods'];
1529
                $this->dataLists['available_widgets'] .= ',' . $row['availableWidgets'];
1530
                $this->dataLists['tables_select'] .= ',' . $row['tables_select'];
1531
                $this->dataLists['tables_modify'] .= ',' . $row['tables_modify'];
1532
                $this->dataLists['pagetypes_select'] .= ',' . $row['pagetypes_select'];
1533
                $this->dataLists['non_exclude_fields'] .= ',' . $row['non_exclude_fields'];
1534
                $this->dataLists['explicit_allowdeny'] .= ',' . $row['explicit_allowdeny'];
1535
                $this->dataLists['allowed_languages'] .= ',' . $row['allowed_languages'];
1536
                $this->dataLists['custom_options'] .= ',' . $row['custom_options'];
1537
                $this->dataLists['file_permissions'] .= ',' . $row['file_permissions'];
1538
                // Setting workspace permissions:
1539
                $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
1540
                // If this function is processing the users OWN group-list (not subgroups) AND
1541
                // if the ->firstMainGroup is not set, then the ->firstMainGroup will be set.
1542
                if ($idList === '' && !$this->firstMainGroup) {
1543
                    $this->firstMainGroup = $uid;
0 ignored issues
show
Documentation Bug introduced by
The property $firstMainGroup was declared of type integer, but $uid is of type string. 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...
1544
                }
1545
            }
1546
        }
1547
        // HOOK: fetchGroups_postProcessing
1548
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] ?? [] as $_funcRef) {
1549
            $_params = [];
1550
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1551
        }
1552
    }
1553
1554
    /**
1555
     * Updates the field be_users.usergroup_cached_list if the groupList of the user
1556
     * has changed/is different from the current list.
1557
     * The field "usergroup_cached_list" contains the list of groups which the user is a member of.
1558
     * After authentication (where these functions are called...) one can depend on this list being
1559
     * a representation of the exact groups/subgroups which the BE_USER has membership with.
1560
     *
1561
     * @param string $cList The newly compiled group-list which must be compared with the current list in the user record and possibly stored if a difference is detected.
1562
     * @internal
1563
     */
1564
    public function setCachedList($cList)
1565
    {
1566
        if ((string)$cList != (string)$this->user['usergroup_cached_list']) {
1567
            GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
1568
                'be_users',
1569
                ['usergroup_cached_list' => $cList],
1570
                ['uid' => (int)$this->user['uid']]
1571
            );
1572
        }
1573
    }
1574
1575
    /**
1576
     * Sets up all file storages for a user.
1577
     * Needs to be called AFTER the groups have been loaded.
1578
     */
1579
    protected function initializeFileStorages()
1580
    {
1581
        $this->fileStorages = [];
1582
        /** @var \TYPO3\CMS\Core\Resource\StorageRepository $storageRepository */
1583
        $storageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
1584
        // Admin users have all file storages visible, without any filters
1585
        if ($this->isAdmin()) {
1586
            $storageObjects = $storageRepository->findAll();
1587
            foreach ($storageObjects as $storageObject) {
1588
                $this->fileStorages[$storageObject->getUid()] = $storageObject;
1589
            }
1590
        } else {
1591
            // Regular users only have storages that are defined in their filemounts
1592
            // Permissions and file mounts for the storage are added in StoragePermissionAspect
1593
            foreach ($this->getFileMountRecords() as $row) {
1594
                if (!array_key_exists((int)$row['base'], $this->fileStorages)) {
1595
                    $storageObject = $storageRepository->findByUid($row['base']);
1596
                    if ($storageObject) {
1597
                        $this->fileStorages[$storageObject->getUid()] = $storageObject;
1598
                    }
1599
                }
1600
            }
1601
        }
1602
1603
        // This has to be called always in order to set certain filters
1604
        $this->evaluateUserSpecificFileFilterSettings();
1605
    }
1606
1607
    /**
1608
     * Returns an array of category mount points. The category permissions from BE Groups
1609
     * are also taken into consideration and are merged into User permissions.
1610
     *
1611
     * @return array
1612
     */
1613
    public function getCategoryMountPoints()
1614
    {
1615
        $categoryMountPoints = '';
1616
1617
        // Category mounts of the groups
1618
        if (is_array($this->userGroups)) {
0 ignored issues
show
introduced by
The condition is_array($this->userGroups) is always true.
Loading history...
1619
            foreach ($this->userGroups as $group) {
1620
                if ($group['category_perms']) {
1621
                    $categoryMountPoints .= ',' . $group['category_perms'];
1622
                }
1623
            }
1624
        }
1625
1626
        // Category mounts of the user record
1627
        if ($this->user['category_perms']) {
1628
            $categoryMountPoints .= ',' . $this->user['category_perms'];
1629
        }
1630
1631
        // Make the ids unique
1632
        $categoryMountPoints = GeneralUtility::trimExplode(',', $categoryMountPoints);
1633
        $categoryMountPoints = array_filter($categoryMountPoints); // remove empty value
1634
        $categoryMountPoints = array_unique($categoryMountPoints); // remove unique value
1635
1636
        return $categoryMountPoints;
1637
    }
1638
1639
    /**
1640
     * Returns an array of file mount records, taking workspaces and user home and group home directories into account
1641
     * Needs to be called AFTER the groups have been loaded.
1642
     *
1643
     * @return array
1644
     * @internal
1645
     */
1646
    public function getFileMountRecords()
1647
    {
1648
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
1649
        $fileMountRecordCache = $runtimeCache->get('backendUserAuthenticationFileMountRecords') ?: [];
1650
1651
        if (!empty($fileMountRecordCache)) {
1652
            return $fileMountRecordCache;
1653
        }
1654
1655
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1656
1657
        // Processing file mounts (both from the user and the groups)
1658
        $fileMounts = array_unique(GeneralUtility::intExplode(',', $this->dataLists['filemount_list'], true));
1659
1660
        // Limit file mounts if set in workspace record
1661
        if ($this->workspace > 0 && !empty($this->workspaceRec['file_mountpoints'])) {
1662
            $workspaceFileMounts = GeneralUtility::intExplode(',', $this->workspaceRec['file_mountpoints'], true);
1663
            $fileMounts = array_intersect($fileMounts, $workspaceFileMounts);
1664
        }
1665
1666
        if (!empty($fileMounts)) {
1667
            $orderBy = $GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'] ?? 'sorting';
1668
1669
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_filemounts');
1670
            $queryBuilder->getRestrictions()
1671
                ->removeAll()
1672
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
1673
                ->add(GeneralUtility::makeInstance(HiddenRestriction::class))
1674
                ->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
1675
1676
            $queryBuilder->select('*')
1677
                ->from('sys_filemounts')
1678
                ->where(
1679
                    $queryBuilder->expr()->in('uid', $queryBuilder->createNamedParameter($fileMounts, Connection::PARAM_INT_ARRAY))
1680
                );
1681
1682
            foreach (QueryHelper::parseOrderBy($orderBy) as $fieldAndDirection) {
1683
                $queryBuilder->addOrderBy(...$fieldAndDirection);
1684
            }
1685
1686
            $fileMountRecords = $queryBuilder->execute()->fetchAll(\PDO::FETCH_ASSOC);
1687
            if ($fileMountRecords !== false) {
1688
                foreach ($fileMountRecords as $fileMount) {
1689
                    $fileMountRecordCache[$fileMount['base'] . $fileMount['path']] = $fileMount;
1690
                }
1691
            }
1692
        }
1693
1694
        // Read-only file mounts
1695
        $readOnlyMountPoints = \trim($this->getTSConfig()['options.']['folderTree.']['altElementBrowserMountPoints'] ?? '');
1696
        if ($readOnlyMountPoints) {
1697
            // We cannot use the API here but need to fetch the default storage record directly
1698
            // to not instantiate it (which directly applies mount points) before all mount points are resolved!
1699
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file_storage');
1700
            $defaultStorageRow = $queryBuilder->select('uid')
1701
                ->from('sys_file_storage')
1702
                ->where(
1703
                    $queryBuilder->expr()->eq('is_default', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT))
1704
                )
1705
                ->setMaxResults(1)
1706
                ->execute()
1707
                ->fetch(\PDO::FETCH_ASSOC);
1708
1709
            $readOnlyMountPointArray = GeneralUtility::trimExplode(',', $readOnlyMountPoints);
1710
            foreach ($readOnlyMountPointArray as $readOnlyMountPoint) {
1711
                $readOnlyMountPointConfiguration = GeneralUtility::trimExplode(':', $readOnlyMountPoint);
1712
                if (count($readOnlyMountPointConfiguration) === 2) {
1713
                    // A storage is passed in the configuration
1714
                    $storageUid = (int)$readOnlyMountPointConfiguration[0];
1715
                    $path = $readOnlyMountPointConfiguration[1];
1716
                } else {
1717
                    if (empty($defaultStorageRow)) {
1718
                        throw new \RuntimeException('Read only mount points have been defined in User TsConfig without specific storage, but a default storage could not be resolved.', 1404472382);
1719
                    }
1720
                    // Backwards compatibility: If no storage is passed, we use the default storage
1721
                    $storageUid = $defaultStorageRow['uid'];
1722
                    $path = $readOnlyMountPointConfiguration[0];
1723
                }
1724
                $fileMountRecordCache[$storageUid . $path] = [
1725
                    'base' => $storageUid,
1726
                    'title' => $path,
1727
                    'path' => $path,
1728
                    'read_only' => true
1729
                ];
1730
            }
1731
        }
1732
1733
        // Personal or Group filemounts are not accessible if file mount list is set in workspace record
1734
        if ($this->workspace <= 0 || empty($this->workspaceRec['file_mountpoints'])) {
1735
            // If userHomePath is set, we attempt to mount it
1736
            if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
1737
                [$userHomeStorageUid, $userHomeFilter] = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'], 2);
1738
                $userHomeStorageUid = (int)$userHomeStorageUid;
1739
                $userHomeFilter = '/' . ltrim($userHomeFilter, '/');
1740
                if ($userHomeStorageUid > 0) {
1741
                    // Try and mount with [uid]_[username]
1742
                    $path = $userHomeFilter . $this->user['uid'] . '_' . $this->user['username'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1743
                    $fileMountRecordCache[$userHomeStorageUid . $path] = [
1744
                        'base' => $userHomeStorageUid,
1745
                        'title' => $this->user['username'],
1746
                        'path' => $path,
1747
                        'read_only' => false,
1748
                        'user_mount' => true
1749
                    ];
1750
                    // Try and mount with only [uid]
1751
                    $path = $userHomeFilter . $this->user['uid'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1752
                    $fileMountRecordCache[$userHomeStorageUid . $path] = [
1753
                        'base' => $userHomeStorageUid,
1754
                        'title' => $this->user['username'],
1755
                        'path' => $path,
1756
                        'read_only' => false,
1757
                        'user_mount' => true
1758
                    ];
1759
                }
1760
            }
1761
1762
            // Mount group home-dirs
1763
            if ((is_array($this->user) && $this->user['options'] & Permission::PAGE_EDIT) == 2 && $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'] != '') {
1764
                // If groupHomePath is set, we attempt to mount it
1765
                [$groupHomeStorageUid, $groupHomeFilter] = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'], 2);
1766
                $groupHomeStorageUid = (int)$groupHomeStorageUid;
1767
                $groupHomeFilter = '/' . ltrim($groupHomeFilter, '/');
1768
                if ($groupHomeStorageUid > 0) {
1769
                    foreach ($this->userGroups as $groupData) {
1770
                        $path = $groupHomeFilter . $groupData['uid'];
1771
                        $fileMountRecordCache[$groupHomeStorageUid . $path] = [
1772
                            'base' => $groupHomeStorageUid,
1773
                            'title' => $groupData['title'],
1774
                            'path' => $path,
1775
                            'read_only' => false,
1776
                            'user_mount' => true
1777
                        ];
1778
                    }
1779
                }
1780
            }
1781
        }
1782
1783
        $runtimeCache->set('backendUserAuthenticationFileMountRecords', $fileMountRecordCache);
1784
        return $fileMountRecordCache;
1785
    }
1786
1787
    /**
1788
     * Returns an array with the filemounts for the user.
1789
     * Each filemount is represented with an array of a "name", "path" and "type".
1790
     * If no filemounts an empty array is returned.
1791
     *
1792
     * @return \TYPO3\CMS\Core\Resource\ResourceStorage[]
1793
     */
1794
    public function getFileStorages()
1795
    {
1796
        // Initializing file mounts after the groups are fetched
1797
        if ($this->fileStorages === null) {
1798
            $this->initializeFileStorages();
1799
        }
1800
        return $this->fileStorages;
1801
    }
1802
1803
    /**
1804
     * Adds filters based on what the user has set
1805
     * this should be done in this place, and called whenever needed,
1806
     * but only when needed
1807
     */
1808
    public function evaluateUserSpecificFileFilterSettings()
1809
    {
1810
        // Add the option for also displaying the non-hidden files
1811
        if ($this->uc['showHiddenFilesAndFolders']) {
1812
            \TYPO3\CMS\Core\Resource\Filter\FileNameFilter::setShowHiddenFilesAndFolders(true);
1813
        }
1814
    }
1815
1816
    /**
1817
     * Returns the information about file permissions.
1818
     * Previously, this was stored in the DB field fileoper_perms now it is file_permissions.
1819
     * Besides it can be handled via userTSconfig
1820
     *
1821
     * permissions.file.default {
1822
     * addFile = 1
1823
     * readFile = 1
1824
     * writeFile = 1
1825
     * copyFile = 1
1826
     * moveFile = 1
1827
     * renameFile = 1
1828
     * deleteFile = 1
1829
     *
1830
     * addFolder = 1
1831
     * readFolder = 1
1832
     * writeFolder = 1
1833
     * copyFolder = 1
1834
     * moveFolder = 1
1835
     * renameFolder = 1
1836
     * deleteFolder = 1
1837
     * recursivedeleteFolder = 1
1838
     * }
1839
     *
1840
     * # overwrite settings for a specific storageObject
1841
     * permissions.file.storage.StorageUid {
1842
     * readFile = 1
1843
     * recursivedeleteFolder = 0
1844
     * }
1845
     *
1846
     * Please note that these permissions only apply, if the storage has the
1847
     * capabilities (browseable, writable), and if the driver allows for writing etc
1848
     *
1849
     * @return array
1850
     */
1851
    public function getFilePermissions()
1852
    {
1853
        if (!isset($this->filePermissions)) {
1854
            $filePermissions = [
1855
                // File permissions
1856
                'addFile' => false,
1857
                'readFile' => false,
1858
                'writeFile' => false,
1859
                'copyFile' => false,
1860
                'moveFile' => false,
1861
                'renameFile' => false,
1862
                'deleteFile' => false,
1863
                // Folder permissions
1864
                'addFolder' => false,
1865
                'readFolder' => false,
1866
                'writeFolder' => false,
1867
                'copyFolder' => false,
1868
                'moveFolder' => false,
1869
                'renameFolder' => false,
1870
                'deleteFolder' => false,
1871
                'recursivedeleteFolder' => false
1872
            ];
1873
            if ($this->isAdmin()) {
1874
                $filePermissions = array_map('is_bool', $filePermissions);
1875
            } else {
1876
                $userGroupRecordPermissions = GeneralUtility::trimExplode(',', $this->groupData['file_permissions'] ?? '', true);
1877
                array_walk(
1878
                    $userGroupRecordPermissions,
1879
                    function ($permission) use (&$filePermissions) {
1880
                        $filePermissions[$permission] = true;
1881
                    }
1882
                );
1883
1884
                // Finally overlay any userTSconfig
1885
                $permissionsTsConfig = $this->getTSConfig()['permissions.']['file.']['default.'] ?? [];
1886
                if (!empty($permissionsTsConfig)) {
1887
                    array_walk(
1888
                        $permissionsTsConfig,
1889
                        function ($value, $permission) use (&$filePermissions) {
1890
                            $filePermissions[$permission] = (bool)$value;
1891
                        }
1892
                    );
1893
                }
1894
            }
1895
            $this->filePermissions = $filePermissions;
1896
        }
1897
        return $this->filePermissions;
1898
    }
1899
1900
    /**
1901
     * Gets the file permissions for a storage
1902
     * by merging any storage-specific permissions for a
1903
     * storage with the default settings.
1904
     * Admin users will always get the default settings.
1905
     *
1906
     * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storageObject
1907
     * @return array
1908
     */
1909
    public function getFilePermissionsForStorage(\TYPO3\CMS\Core\Resource\ResourceStorage $storageObject)
1910
    {
1911
        $finalUserPermissions = $this->getFilePermissions();
1912
        if (!$this->isAdmin()) {
1913
            $storageFilePermissions = $this->getTSConfig()['permissions.']['file.']['storage.'][$storageObject->getUid() . '.'] ?? [];
1914
            if (!empty($storageFilePermissions)) {
1915
                array_walk(
1916
                    $storageFilePermissions,
1917
                    function ($value, $permission) use (&$finalUserPermissions) {
1918
                        $finalUserPermissions[$permission] = (bool)$value;
1919
                    }
1920
                );
1921
            }
1922
        }
1923
        return $finalUserPermissions;
1924
    }
1925
1926
    /**
1927
     * Returns a \TYPO3\CMS\Core\Resource\Folder object that is used for uploading
1928
     * files by default.
1929
     * This is used for RTE and its magic images, as well as uploads
1930
     * in the TCEforms fields.
1931
     *
1932
     * The default upload folder for a user is the defaultFolder on the first
1933
     * filestorage/filemount that the user can access and to which files are allowed to be added
1934
     * however, you can set the users' upload folder like this:
1935
     *
1936
     * options.defaultUploadFolder = 3:myfolder/yourfolder/
1937
     *
1938
     * @param int $pid PageUid
1939
     * @param string $table Table name
1940
     * @param string $field Field name
1941
     * @return \TYPO3\CMS\Core\Resource\Folder|bool The default upload folder for this user
1942
     */
1943
    public function getDefaultUploadFolder($pid = null, $table = null, $field = null)
1944
    {
1945
        $uploadFolder = $this->getTSConfig()['options.']['defaultUploadFolder'] ?? '';
1946
        if ($uploadFolder) {
1947
            $uploadFolder = GeneralUtility::makeInstance(ResourceFactory::class)->getFolderObjectFromCombinedIdentifier($uploadFolder);
1948
        } else {
1949
            foreach ($this->getFileStorages() as $storage) {
1950
                if ($storage->isDefault() && $storage->isWritable()) {
1951
                    try {
1952
                        $uploadFolder = $storage->getDefaultFolder();
1953
                        if ($uploadFolder->checkActionPermission('write')) {
1954
                            break;
1955
                        }
1956
                        $uploadFolder = null;
1957
                    } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
1958
                        // If the folder is not accessible (no permissions / does not exist) we skip this one.
1959
                    }
1960
                    break;
1961
                }
1962
            }
1963
            if (!$uploadFolder instanceof \TYPO3\CMS\Core\Resource\Folder) {
1964
                /** @var ResourceStorage $storage */
1965
                foreach ($this->getFileStorages() as $storage) {
1966
                    if ($storage->isWritable()) {
1967
                        try {
1968
                            $uploadFolder = $storage->getDefaultFolder();
1969
                            if ($uploadFolder->checkActionPermission('write')) {
1970
                                break;
1971
                            }
1972
                            $uploadFolder = null;
1973
                        } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
1974
                            // If the folder is not accessible (no permissions / does not exist) try the next one.
1975
                        }
1976
                    }
1977
                }
1978
            }
1979
        }
1980
1981
        // HOOK: getDefaultUploadFolder
1982
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getDefaultUploadFolder'] ?? [] as $_funcRef) {
1983
            $_params = [
1984
                'uploadFolder' => $uploadFolder,
1985
                'pid' => $pid,
1986
                'table' => $table,
1987
                'field' => $field,
1988
            ];
1989
            $uploadFolder = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1990
        }
1991
1992
        if ($uploadFolder instanceof \TYPO3\CMS\Core\Resource\Folder) {
1993
            return $uploadFolder;
1994
        }
1995
        return false;
1996
    }
1997
1998
    /**
1999
     * Returns a \TYPO3\CMS\Core\Resource\Folder object that could be used for uploading
2000
     * temporary files in user context. The folder _temp_ below the default upload folder
2001
     * of the user is used.
2002
     *
2003
     * @return \TYPO3\CMS\Core\Resource\Folder|null
2004
     * @see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::getDefaultUploadFolder()
2005
     */
2006
    public function getDefaultUploadTemporaryFolder()
2007
    {
2008
        $defaultTemporaryFolder = null;
2009
        $defaultFolder = $this->getDefaultUploadFolder();
2010
2011
        if ($defaultFolder !== false) {
2012
            $tempFolderName = '_temp_';
2013
            $createFolder = !$defaultFolder->hasFolder($tempFolderName);
2014
            if ($createFolder === true) {
2015
                try {
2016
                    $defaultTemporaryFolder = $defaultFolder->createFolder($tempFolderName);
2017
                } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2018
                }
2019
            } else {
2020
                $defaultTemporaryFolder = $defaultFolder->getSubfolder($tempFolderName);
2021
            }
2022
        }
2023
2024
        return $defaultTemporaryFolder;
2025
    }
2026
2027
    /**
2028
     * Initializing workspace.
2029
     * Called from within this function, see fetchGroupData()
2030
     *
2031
     * @see fetchGroupData()
2032
     */
2033
    public function workspaceInit()
2034
    {
2035
        // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
2036
        $this->setWorkspace($this->user['workspace_id']);
2037
        // Limiting the DB mountpoints if there any selected in the workspace record
2038
        $this->initializeDbMountpointsInWorkspace();
2039
        $allowed_languages = $this->getTSConfig()['options.']['workspaces.']['allowed_languages.'][$this->workspace] ?? '';
2040
        if (!empty($allowed_languages)) {
2041
            $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($allowed_languages);
2042
        }
2043
    }
2044
2045
    /**
2046
     * Limiting the DB mountpoints if there any selected in the workspace record
2047
     */
2048
    protected function initializeDbMountpointsInWorkspace()
2049
    {
2050
        $dbMountpoints = trim($this->workspaceRec['db_mountpoints'] ?? '');
2051
        if ($this->workspace > 0 && $dbMountpoints != '') {
2052
            $filteredDbMountpoints = [];
2053
            // Notice: We cannot call $this->getPagePermsClause(1);
2054
            // as usual because the group-list is not available at this point.
2055
            // But bypassing is fine because all we want here is check if the
2056
            // workspace mounts are inside the current webmounts rootline.
2057
            // The actual permission checking on page level is done elsewhere
2058
            // as usual anyway before the page tree is rendered.
2059
            $readPerms = '1=1';
2060
            // Traverse mount points of the
2061
            $dbMountpoints = GeneralUtility::intExplode(',', $dbMountpoints);
2062
            foreach ($dbMountpoints as $mpId) {
2063
                if ($this->isInWebMount($mpId, $readPerms)) {
0 ignored issues
show
Bug introduced by
$mpId of type string is incompatible with the type array|integer expected by parameter $idOrRow of TYPO3\CMS\Core\Authentic...ication::isInWebMount(). ( Ignorable by Annotation )

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

2063
                if ($this->isInWebMount(/** @scrutinizer ignore-type */ $mpId, $readPerms)) {
Loading history...
Bug Best Practice introduced by
The expression $this->isInWebMount($mpId, $readPerms) 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...
2064
                    $filteredDbMountpoints[] = $mpId;
2065
                }
2066
            }
2067
            // Re-insert webmounts:
2068
            $filteredDbMountpoints = array_unique($filteredDbMountpoints);
2069
            $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
2070
        }
2071
    }
2072
2073
    /**
2074
     * Checking if a workspace is allowed for backend user
2075
     *
2076
     * @param mixed $wsRec If integer, workspace record is looked up, if array it is seen as a Workspace record with at least uid, title, members and adminusers columns. Can be faked for workspaces uid 0 and -1 (online and offline)
2077
     * @param string $fields List of fields to select. Default fields are all
2078
     * @return array Output will also show how access was granted. Admin users will have a true output regardless of input.
2079
     */
2080
    public function checkWorkspace($wsRec, $fields = '*')
2081
    {
2082
        $retVal = false;
2083
        // If not array, look up workspace record:
2084
        if (!is_array($wsRec)) {
2085
            switch ((string)$wsRec) {
2086
                case '0':
2087
                    $wsRec = ['uid' => $wsRec];
2088
                    break;
2089
                default:
2090
                    if (ExtensionManagementUtility::isLoaded('workspaces')) {
2091
                        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2092
                        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2093
                        $wsRec = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields))
2094
                            ->from('sys_workspace')
2095
                            ->where($queryBuilder->expr()->eq(
2096
                                'uid',
2097
                                $queryBuilder->createNamedParameter($wsRec, \PDO::PARAM_INT)
2098
                            ))
2099
                            ->orderBy('title')
2100
                            ->setMaxResults(1)
2101
                            ->execute()
2102
                            ->fetch(\PDO::FETCH_ASSOC);
2103
                    }
2104
            }
2105
        }
2106
        // If wsRec is set to an array, evaluate it:
2107
        if (is_array($wsRec)) {
2108
            if ($this->isAdmin()) {
2109
                return array_merge($wsRec, ['_ACCESS' => 'admin']);
2110
            }
2111
            switch ((string)$wsRec['uid']) {
2112
                    case '0':
2113
                        $retVal = $this->groupData['workspace_perms'] & Permission::PAGE_SHOW
2114
                            ? array_merge($wsRec, ['_ACCESS' => 'online'])
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "?"; newline found
Loading history...
2115
                            : false;
0 ignored issues
show
Coding Style introduced by
Expected 1 space before ":"; newline found
Loading history...
2116
                        break;
2117
                    default:
2118
                        // Checking if the guy is admin:
2119
                        if (GeneralUtility::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
2120
                            return array_merge($wsRec, ['_ACCESS' => 'owner']);
2121
                        }
2122
                        // Checking if he is owner through a user group of his:
2123
                        foreach ($this->userGroupsUID as $groupUid) {
2124
                            if (GeneralUtility::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
2125
                                return array_merge($wsRec, ['_ACCESS' => 'owner']);
2126
                            }
2127
                        }
2128
                        // Checking if he is member as user:
2129
                        if (GeneralUtility::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
2130
                            return array_merge($wsRec, ['_ACCESS' => 'member']);
2131
                        }
2132
                        // Checking if he is member through a user group of his:
2133
                        foreach ($this->userGroupsUID as $groupUid) {
2134
                            if (GeneralUtility::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
2135
                                return array_merge($wsRec, ['_ACCESS' => 'member']);
2136
                            }
2137
                        }
2138
                }
0 ignored issues
show
Coding Style introduced by
Closing brace indented incorrectly; expected 12 spaces, found 16
Loading history...
2139
        }
2140
        return $retVal;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $retVal could also return false which is incompatible with the documented return type array. 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...
2141
    }
2142
2143
    /**
2144
     * Uses checkWorkspace() to check if current workspace is available for user.
2145
     * This function caches the result and so can be called many times with no performance loss.
2146
     *
2147
     * @return array See checkWorkspace()
2148
     * @see checkWorkspace()
2149
     */
2150
    public function checkWorkspaceCurrent()
2151
    {
2152
        if (!isset($this->checkWorkspaceCurrent_cache)) {
2153
            $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
2154
        }
2155
        return $this->checkWorkspaceCurrent_cache;
2156
    }
2157
2158
    /**
2159
     * Setting workspace ID
2160
     *
2161
     * @param int $workspaceId ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
2162
     */
2163
    public function setWorkspace($workspaceId)
2164
    {
2165
        // Check workspace validity and if not found, revert to default workspace.
2166
        if (!$this->setTemporaryWorkspace($workspaceId)) {
2167
            $this->setDefaultWorkspace();
2168
        }
2169
        // Unset access cache:
2170
        $this->checkWorkspaceCurrent_cache = null;
2171
        // If ID is different from the stored one, change it:
2172
        if ((int)$this->workspace !== (int)$this->user['workspace_id']) {
2173
            $this->user['workspace_id'] = $this->workspace;
2174
            GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
2175
                'be_users',
2176
                ['workspace_id' => $this->user['workspace_id']],
2177
                ['uid' => (int)$this->user['uid']]
2178
            );
2179
            $this->writelog(SystemLogType::EXTENSION, SystemLogGenericAction::UNDEFINED, SystemLogErrorClassification::MESSAGE, 0, 'User changed workspace to "' . $this->workspace . '"', []);
2180
        }
2181
    }
2182
2183
    /**
2184
     * Sets a temporary workspace in the context of the current backend user.
2185
     *
2186
     * @param int $workspaceId
2187
     * @return bool
2188
     */
2189
    public function setTemporaryWorkspace($workspaceId)
2190
    {
2191
        $result = false;
2192
        $workspaceRecord = $this->checkWorkspace($workspaceId);
2193
2194
        if ($workspaceRecord) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $workspaceRecord 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...
2195
            $this->workspaceRec = $workspaceRecord;
2196
            $this->workspace = (int)$workspaceId;
2197
            $result = true;
2198
        }
2199
2200
        return $result;
2201
    }
2202
2203
    /**
2204
     * Sets the default workspace in the context of the current backend user.
2205
     */
2206
    public function setDefaultWorkspace()
2207
    {
2208
        $this->workspace = (int)$this->getDefaultWorkspace();
2209
        $this->workspaceRec = $this->checkWorkspace($this->workspace);
2210
    }
2211
2212
    /**
2213
     * Return default workspace ID for user,
2214
     * if EXT:workspaces is not installed the user will be pushed to the
2215
     * Live workspace, if he has access to. If no workspace is available for the user, the workspace ID is set to "-99"
2216
     *
2217
     * @return int Default workspace id.
2218
     */
2219
    public function getDefaultWorkspace()
2220
    {
2221
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
2222
            return 0;
2223
        }
2224
        // Online is default
2225
        if ($this->checkWorkspace(0)) {
2226
            return 0;
2227
        }
2228
        // Otherwise -99 is the fallback
2229
        $defaultWorkspace = -99;
2230
        // Traverse all workspaces
2231
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2232
        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2233
        $result = $queryBuilder->select('*')
2234
            ->from('sys_workspace')
2235
            ->orderBy('title')
2236
            ->execute();
2237
        while ($workspaceRecord = $result->fetch()) {
2238
            if ($this->checkWorkspace($workspaceRecord)) {
2239
                $defaultWorkspace = (int)$workspaceRecord['uid'];
2240
                break;
2241
            }
2242
        }
2243
        return $defaultWorkspace;
2244
    }
2245
2246
    /**
2247
     * Writes an entry in the logfile/table
2248
     * Documentation in "TYPO3 Core API"
2249
     *
2250
     * @param int $type Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
2251
     * @param int $action Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
2252
     * @param int $error Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2253
     * @param int $details_nr The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
2254
     * @param string $details Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
2255
     * @param array $data Data that follows the log. Might be used to carry special information. If an array the first 5 entries (0-4) will be sprintf'ed with the details-text
2256
     * @param string $tablename Table name. Special field used by tce_main.php.
2257
     * @param int|string $recuid Record UID. Special field used by tce_main.php.
2258
     * @param int|string $recpid Record PID. Special field used by tce_main.php. OBSOLETE
2259
     * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
2260
     * @param string $NEWid Special field used by tce_main.php. NEWid string of newly created records.
2261
     * @param int $userId Alternative Backend User ID (used for logging login actions where this is not yet known).
2262
     * @return int Log entry ID.
2263
     */
2264
    public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0)
2265
    {
2266
        if (!$userId && !empty($this->user['uid'])) {
2267
            $userId = $this->user['uid'];
2268
        }
2269
2270
        if (!empty($this->user['ses_backuserid'])) {
2271
            if (empty($data)) {
2272
                $data = [];
2273
            }
2274
            $data['originalUser'] = $this->user['ses_backuserid'];
2275
        }
2276
2277
        $fields = [
2278
            'userid' => (int)$userId,
2279
            'type' => (int)$type,
2280
            'action' => (int)$action,
2281
            'error' => (int)$error,
2282
            'details_nr' => (int)$details_nr,
2283
            'details' => $details,
2284
            'log_data' => serialize($data),
2285
            'tablename' => $tablename,
2286
            'recuid' => (int)$recuid,
2287
            'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2288
            'tstamp' => $GLOBALS['EXEC_TIME'] ?? time(),
2289
            'event_pid' => (int)$event_pid,
2290
            'NEWid' => $NEWid,
2291
            'workspace' => $this->workspace
2292
        ];
2293
2294
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('sys_log');
2295
        $connection->insert(
2296
            'sys_log',
2297
            $fields,
2298
            [
2299
                \PDO::PARAM_INT,
2300
                \PDO::PARAM_INT,
2301
                \PDO::PARAM_INT,
2302
                \PDO::PARAM_INT,
2303
                \PDO::PARAM_INT,
2304
                \PDO::PARAM_STR,
2305
                \PDO::PARAM_STR,
2306
                \PDO::PARAM_STR,
2307
                \PDO::PARAM_INT,
2308
                \PDO::PARAM_STR,
2309
                \PDO::PARAM_INT,
2310
                \PDO::PARAM_INT,
2311
                \PDO::PARAM_STR,
2312
                \PDO::PARAM_STR,
2313
            ]
2314
        );
2315
2316
        return (int)$connection->lastInsertId('sys_log');
2317
    }
2318
2319
    /**
2320
     * Sends a warning to $email if there has been a certain amount of failed logins during a period.
2321
     * If a login fails, this function is called. It will look up the sys_log to see if there
2322
     * have been more than $max failed logins the last $secondsBack seconds (default 3600).
2323
     * If so, an email with a warning is sent to $email.
2324
     *
2325
     * @param string $email Email address
2326
     * @param int $secondsBack Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
2327
     * @param int $max Max allowed failures before a warning mail is sent
2328
     * @internal
2329
     */
2330
    public function checkLogFailures($email, $secondsBack = 3600, $max = 3)
2331
    {
2332
        if (!GeneralUtility::validEmail($email)) {
2333
            return;
2334
        }
2335
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
2336
2337
        // Get last flag set in the log for sending
2338
        $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
2339
        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_log');
2340
        $queryBuilder->select('tstamp')
2341
            ->from('sys_log')
2342
            ->where(
2343
                $queryBuilder->expr()->eq(
2344
                    'type',
2345
                    $queryBuilder->createNamedParameter(SystemLogType::LOGIN, \PDO::PARAM_INT)
2346
                ),
2347
                $queryBuilder->expr()->eq(
2348
                    'action',
2349
                    $queryBuilder->createNamedParameter(SystemLogLoginAction::SEND_FAILURE_WARNING_EMAIL, \PDO::PARAM_INT)
2350
                ),
2351
                $queryBuilder->expr()->gt(
2352
                    'tstamp',
2353
                    $queryBuilder->createNamedParameter($theTimeBack, \PDO::PARAM_INT)
2354
                )
2355
            )
2356
            ->orderBy('tstamp', 'DESC')
2357
            ->setMaxResults(1);
2358
        if ($testRow = $queryBuilder->execute()->fetch(\PDO::FETCH_ASSOC)) {
2359
            $theTimeBack = $testRow['tstamp'];
2360
        }
2361
2362
        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_log');
2363
        $result = $queryBuilder->select('*')
2364
            ->from('sys_log')
2365
            ->where(
2366
                $queryBuilder->expr()->eq(
2367
                    'type',
2368
                    $queryBuilder->createNamedParameter(SystemLogType::LOGIN, \PDO::PARAM_INT)
2369
                ),
2370
                $queryBuilder->expr()->eq(
2371
                    'action',
2372
                    $queryBuilder->createNamedParameter(SystemLogLoginAction::ATTEMPT, \PDO::PARAM_INT)
2373
                ),
2374
                $queryBuilder->expr()->neq(
2375
                    'error',
2376
                    $queryBuilder->createNamedParameter(SystemLogErrorClassification::MESSAGE, \PDO::PARAM_INT)
2377
                ),
2378
                $queryBuilder->expr()->gt(
2379
                    'tstamp',
2380
                    $queryBuilder->createNamedParameter($theTimeBack, \PDO::PARAM_INT)
2381
                )
2382
            )
2383
            ->orderBy('tstamp')
2384
            ->execute();
2385
2386
        $rowCount = $queryBuilder
2387
            ->count('uid')
2388
            ->execute()
2389
            ->fetchColumn(0);
2390
        // Check for more than $max number of error failures with the last period.
2391
        if ($rowCount > $max) {
2392
            // OK, so there were more than the max allowed number of login failures - so we will send an email then.
2393
            $this->sendLoginAttemptEmail($result, $email);
2394
            // Login failure attempt written to log
2395
            $this->writelog(SystemLogType::LOGIN, SystemLogLoginAction::SEND_FAILURE_WARNING_EMAIL, SystemLogErrorClassification::MESSAGE, 3, 'Failure warning (%s failures within %s seconds) sent by email to %s', [$rowCount, $secondsBack, $email]);
2396
        }
2397
    }
2398
2399
    /**
2400
     * Sends out an email if the number of attempts have exceeded a limit.
2401
     *
2402
     * @param Statement $result
2403
     * @param string $emailAddress
2404
     */
2405
    protected function sendLoginAttemptEmail(Statement $result, string $emailAddress): void
2406
    {
2407
        $emailData = [];
2408
        while ($row = $result->fetch(\PDO::FETCH_ASSOC)) {
2409
            $theData = unserialize($row['log_data'], ['allowed_classes' => false]);
2410
            $text = @sprintf($row['details'], (string)$theData[0], (string)$theData[1], (string)$theData[2]);
2411
            if ((int)$row['type'] === SystemLogType::LOGIN) {
2412
                $text = str_replace('###IP###', $row['IP'], $text);
2413
            }
2414
            $emailData[] = [
2415
                'row' => $row,
2416
                'text' => $text
2417
            ];
2418
        }
2419
        $email = GeneralUtility::makeInstance(FluidEmail::class)
2420
            ->to($emailAddress)
2421
            ->setTemplate('Security/LoginAttemptFailedWarning')
2422
            ->assign('lines', $emailData);
2423
        if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface) {
2424
            $email->setRequest($GLOBALS['TYPO3_REQUEST']);
2425
        }
2426
        GeneralUtility::makeInstance(Mailer::class)->send($email);
2427
    }
2428
2429
    /**
2430
     * Getter for the cookie name
2431
     *
2432
     * @static
2433
     * @return string returns the configured cookie name
2434
     */
2435
    public static function getCookieName()
2436
    {
2437
        $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
2438
        if (empty($configuredCookieName)) {
2439
            $configuredCookieName = 'be_typo_user';
2440
        }
2441
        return $configuredCookieName;
2442
    }
2443
2444
    /**
2445
     * If TYPO3_CONF_VARS['BE']['enabledBeUserIPLock'] is enabled and
2446
     * an IP-list is found in the User TSconfig objString "options.lockToIP",
2447
     * then make an IP comparison with REMOTE_ADDR and check if the IP address matches
2448
     *
2449
     * @return bool TRUE, if IP address validates OK (or no check is done at all because no restriction is set)
2450
     */
2451
    public function checkLockToIP()
2452
    {
2453
        $isValid = true;
2454
        if ($GLOBALS['TYPO3_CONF_VARS']['BE']['enabledBeUserIPLock']) {
2455
            $IPList = trim($this->getTSConfig()['options.']['lockToIP'] ?? '');
2456
            if (!empty($IPList)) {
2457
                $isValid = GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $IPList);
2458
            }
2459
        }
2460
        return $isValid;
2461
    }
2462
2463
    /**
2464
     * Check if user is logged in and if so, call ->fetchGroupData() to load group information and
2465
     * access lists of all kind, further check IP, set the ->uc array.
2466
     * If no user is logged in the default behaviour is to exit with an error message.
2467
     * This function is called right after ->start() in fx. the TYPO3 Bootstrap.
2468
     *
2469
     * @param bool $proceedIfNoUserIsLoggedIn if this option is set, then there won't be a redirect to the login screen of the Backend - used for areas in the backend which do not need user rights like the login page.
2470
     * @throws \RuntimeException
2471
     */
2472
    public function backendCheckLogin($proceedIfNoUserIsLoggedIn = false)
2473
    {
2474
        if (empty($this->user['uid'])) {
2475
            if ($proceedIfNoUserIsLoggedIn === false) {
2476
                $url = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir;
2477
                \TYPO3\CMS\Core\Utility\HttpUtility::redirect($url);
2478
            }
2479
        } else {
2480
            // ...and if that's the case, call these functions
2481
            $this->fetchGroupData();
2482
            // The groups are fetched and ready for permission checking in this initialization.
2483
            // Tables.php must be read before this because stuff like the modules has impact in this
2484
            if ($this->checkLockToIP()) {
2485
                if ($this->isUserAllowedToLogin()) {
2486
                    // Setting the UC array. It's needed with fetchGroupData first, due to default/overriding of values.
2487
                    $this->backendSetUC();
2488
                    if ($this->loginSessionStarted) {
2489
                        // Also, if there is a recovery link set, unset it now
2490
                        // this will be moved into its own Event at a later stage.
2491
                        // If a token was set previously, this is now unset, as it was now possible to log-in
2492
                        if ($this->user['password_reset_token'] ?? '') {
2493
                            GeneralUtility::makeInstance(ConnectionPool::class)
2494
                                ->getConnectionForTable($this->user_table)
2495
                                ->update($this->user_table, ['password_reset_token' => ''], ['uid' => $this->user['uid']]);
2496
                        }
2497
                        // Process hooks
2498
                        $hooks = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['backendUserLogin'];
2499
                        foreach ($hooks ?? [] as $_funcRef) {
2500
                            $_params = ['user' => $this->user];
2501
                            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2502
                        }
2503
                    }
2504
                } else {
2505
                    throw new \RuntimeException('Login Error: TYPO3 is in maintenance mode at the moment. Only administrators are allowed access.', 1294585860);
2506
                }
2507
            } else {
2508
                throw new \RuntimeException('Login Error: IP locking prevented you from being authorized. Can\'t proceed, sorry.', 1294585861);
2509
            }
2510
        }
2511
    }
2512
2513
    /**
2514
     * Initialize the internal ->uc array for the backend user
2515
     * Will make the overrides if necessary, and write the UC back to the be_users record if changes has happened
2516
     *
2517
     * @internal
2518
     */
2519
    public function backendSetUC()
2520
    {
2521
        // UC - user configuration is a serialized array inside the user object
2522
        // If there is a saved uc we implement that instead of the default one.
2523
        $this->unpack_uc();
2524
        // Setting defaults if uc is empty
2525
        $updated = false;
2526
        $originalUc = [];
2527
        if (is_array($this->uc) && isset($this->uc['ucSetByInstallTool'])) {
2528
            $originalUc = $this->uc;
2529
            unset($originalUc['ucSetByInstallTool'], $this->uc);
2530
        }
2531
        if (!is_array($this->uc)) {
2532
            $this->uc = array_merge(
2533
                $this->uc_default,
2534
                (array)$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUC'],
2535
                GeneralUtility::removeDotsFromTS((array)($this->getTSConfig()['setup.']['default.'] ?? [])),
2536
                $originalUc
2537
            );
2538
            $this->overrideUC();
2539
            $updated = true;
2540
        }
2541
        // If TSconfig is updated, update the defaultUC.
2542
        if ($this->userTSUpdated) {
2543
            $this->overrideUC();
2544
            $updated = true;
2545
        }
2546
        // Setting default lang from be_user record.
2547
        if (!isset($this->uc['lang'])) {
2548
            $this->uc['lang'] = $this->user['lang'];
2549
            $updated = true;
2550
        }
2551
        // Setting the time of the first login:
2552
        if (!isset($this->uc['firstLoginTimeStamp'])) {
2553
            $this->uc['firstLoginTimeStamp'] = $GLOBALS['EXEC_TIME'];
2554
            $updated = true;
2555
        }
2556
        // Saving if updated.
2557
        if ($updated) {
2558
            $this->writeUC();
2559
        }
2560
    }
2561
2562
    /**
2563
     * Override: Call this function every time the uc is updated.
2564
     * That is 1) by reverting to default values, 2) in the setup-module, 3) userTS changes (userauthgroup)
2565
     *
2566
     * @internal
2567
     */
2568
    public function overrideUC()
2569
    {
2570
        $this->uc = array_merge((array)$this->uc, (array)($this->getTSConfig()['setup.']['override.'] ?? []));
2571
    }
2572
2573
    /**
2574
     * Clears the user[uc] and ->uc to blank strings. Then calls ->backendSetUC() to fill it again with reset contents
2575
     *
2576
     * @internal
2577
     */
2578
    public function resetUC()
2579
    {
2580
        $this->user['uc'] = '';
2581
        $this->uc = '';
0 ignored issues
show
Documentation Bug introduced by
It seems like '' of type string is incompatible with the declared type array of property $uc.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
2582
        $this->backendSetUC();
2583
    }
2584
2585
    /**
2586
     * Determines whether a backend user is allowed to access the backend.
2587
     *
2588
     * The conditions are:
2589
     * + backend user is a regular user and adminOnly is not defined
2590
     * + backend user is an admin user
2591
     * + backend user is used in CLI context and adminOnly is explicitly set to "2" (see CommandLineUserAuthentication)
2592
     * + backend user is being controlled by an admin user
2593
     *
2594
     * @return bool Whether a backend user is allowed to access the backend
2595
     */
2596
    protected function isUserAllowedToLogin()
2597
    {
2598
        $isUserAllowedToLogin = false;
2599
        $adminOnlyMode = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'];
2600
        // Backend user is allowed if adminOnly is not set or user is an admin:
2601
        if (!$adminOnlyMode || $this->isAdmin()) {
2602
            $isUserAllowedToLogin = true;
2603
        } elseif ($this->user['ses_backuserid']) {
2604
            $backendUserId = (int)$this->user['ses_backuserid'];
2605
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('be_users');
2606
            $isUserAllowedToLogin = (bool)$queryBuilder->count('uid')
2607
                ->from('be_users')
2608
                ->where(
2609
                    $queryBuilder->expr()->eq(
2610
                        'uid',
2611
                        $queryBuilder->createNamedParameter($backendUserId, \PDO::PARAM_INT)
2612
                    ),
2613
                    $queryBuilder->expr()->eq('admin', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT))
2614
                )
2615
                ->execute()
2616
                ->fetchColumn(0);
2617
        }
2618
        return $isUserAllowedToLogin;
2619
    }
2620
2621
    /**
2622
     * Logs out the current user and clears the form protection tokens.
2623
     */
2624
    public function logoff()
2625
    {
2626
        if (isset($GLOBALS['BE_USER'])
2627
            && $GLOBALS['BE_USER'] instanceof self
2628
            && isset($GLOBALS['BE_USER']->user['uid'])
2629
        ) {
2630
            FormProtectionFactory::get()->clean();
2631
            // Release the locked records
2632
            $this->releaseLockedRecords((int)$GLOBALS['BE_USER']->user['uid']);
2633
2634
            if ($this->isSystemMaintainer()) {
2635
                // If user is system maintainer, destroy its possibly valid install tool session.
2636
                $session = new SessionService();
2637
                if ($session->hasSession()) {
2638
                    $session->destroySession();
2639
                }
2640
            }
2641
        }
2642
        parent::logoff();
2643
    }
2644
2645
    /**
2646
     * Remove any "locked records" added for editing for the given user (= current backend user)
2647
     * @param int $userId
2648
     */
2649
    protected function releaseLockedRecords(int $userId)
2650
    {
2651
        if ($userId > 0) {
2652
            GeneralUtility::makeInstance(ConnectionPool::class)
2653
                ->getConnectionForTable('sys_lockedrecords')
2654
                ->delete(
2655
                    'sys_lockedrecords',
2656
                    ['userid' => $userId]
2657
                );
2658
        }
2659
    }
2660
}
2661