Passed
Push — master ( b1e781...b0edb4 )
by
unknown
14:30
created

getDefaultUploadFolder()   F

Complexity

Conditions 16
Paths 300

Size

Total Lines 58
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 35
nc 300
nop 3
dl 0
loc 58
rs 3.4833
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

1006
    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...
1007
    {
1008
        // Always for Live workspace AND if live-edit is enabled
1009
        // and tables are completely without versioning it is ok as well.
1010
        if (
1011
            $this->workspace === 0
1012
            || $this->workspaceRec['live_edit'] && !BackendUtility::isTableWorkspaceEnabled($table)
1013
            || $GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']
1014
        ) {
1015
            // OK to create for this table.
1016
            return 2;
1017
        }
1018
        // If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
1019
        return false;
1020
    }
1021
1022
    /**
1023
     * Checks if a record is allowed to be edited in the current workspace.
1024
     * This is not bound to an actual record, but to the mere fact if the user is in a workspace
1025
     * and depending on the table settings.
1026
     *
1027
     * @param string $table
1028
     * @return bool
1029
     * @internal should only be used from within TYPO3 Core
1030
     */
1031
    public function workspaceAllowsLiveEditingInTable(string $table): bool
1032
    {
1033
        // In live workspace the record can be added/modified
1034
        if ($this->workspace === 0) {
1035
            return true;
1036
        }
1037
        // Workspace setting allows to "live edit" records of tables without versioning
1038
        if ($this->workspaceRec['live_edit'] && !BackendUtility::isTableWorkspaceEnabled($table)) {
1039
            return true;
1040
        }
1041
        // Always for Live workspace AND if live-edit is enabled
1042
        // and tables are completely without versioning it is ok as well.
1043
        if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']) {
1044
            return true;
1045
        }
1046
        // If the answer is FALSE it means the only valid way to create or edit records by creating records in the workspace
1047
        return false;
1048
    }
1049
1050
    /**
1051
     * Evaluates if a record from $table can be created in $pid
1052
     *
1053
     * Note: this method is not in use anymore and will likely be deprecated in future TYPO3 versions.
1054
     *
1055
     * @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!
1056
     * @param string $table Table name
1057
     * @return bool TRUE if OK.
1058
     * @internal should only be used from within TYPO3 Core
1059
     */
1060
    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

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

1309
            $this->setWebmounts($alternativeWebmountPoints, /** @scrutinizer ignore-type */ $appendAlternativeWebmountPoints);
Loading history...
1310
        }
1311
    }
1312
1313
    /**
1314
     * Returns TRUE or FALSE, depending if an alert popup (a javascript confirmation) should be shown
1315
     * call like $GLOBALS['BE_USER']->jsConfirmation($BITMASK).
1316
     *
1317
     * @param int $bitmask Bitmask, one of \TYPO3\CMS\Core\Type\Bitmask\JsConfirmation
1318
     * @return bool TRUE if the confirmation should be shown
1319
     * @see JsConfirmation
1320
     */
1321
    public function jsConfirmation($bitmask)
1322
    {
1323
        try {
1324
            $alertPopupsSetting = trim((string)($this->getTSConfig()['options.']['alertPopups'] ?? ''));
1325
            $alertPopup = JsConfirmation::cast($alertPopupsSetting === '' ? null : (int)$alertPopupsSetting);
1326
        } catch (InvalidEnumerationValueException $e) {
1327
            $alertPopup = new JsConfirmation();
1328
        }
1329
1330
        return JsConfirmation::cast($bitmask)->matches($alertPopup);
1331
    }
1332
1333
    /**
1334
     * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
1335
     * This method is called by ->backendCheckLogin() (from extending BackendUserAuthentication)
1336
     * if the backend user login has verified OK.
1337
     * Generally this is required initialization of a backend user.
1338
     *
1339
     * @internal
1340
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1341
     */
1342
    public function fetchGroupData()
1343
    {
1344
        if ($this->user['uid']) {
1345
            // Get lists for the be_user record and set them as default/primary values.
1346
            // Enabled Backend Modules
1347
            $this->dataLists['modList'] = $this->user['userMods'];
1348
            // Add available widgets
1349
            $this->dataLists['available_widgets'] = $this->user['available_widgets'];
1350
            // Add Allowed Languages
1351
            $this->dataLists['allowed_languages'] = $this->user['allowed_languages'];
1352
            // Set user value for workspace permissions.
1353
            $this->dataLists['workspace_perms'] = $this->user['workspace_perms'];
1354
            // Database mountpoints
1355
            $this->dataLists['webmount_list'] = $this->user['db_mountpoints'];
1356
            // File mountpoints
1357
            $this->dataLists['filemount_list'] = $this->user['file_mountpoints'];
1358
            // Fileoperation permissions
1359
            $this->dataLists['file_permissions'] = $this->user['file_permissions'];
1360
1361
            // BE_GROUPS:
1362
            // Get the groups...
1363
            if (!empty($this->user[$this->usergroup_column])) {
1364
                // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc.
1365
                // Refer to fetchGroups() function.
1366
                $this->fetchGroups($this->user[$this->usergroup_column]);
1367
            }
1368
            // Populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
1369
            $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
1370
            // Finally this is the list of group_uid's in the order they are parsed (including subgroups!)
1371
            // and without duplicates (duplicates are presented with their last entrance in the list,
1372
            // which thus reflects the order of the TypoScript in TSconfig)
1373
            $this->groupList = implode(',', $this->userGroupsUID);
1374
            $this->setCachedList($this->groupList);
1375
1376
            $this->prepareUserTsConfig();
1377
1378
            // Processing webmounts
1379
            // Admin's always have the root mounted
1380
            if ($this->isAdmin() && !($this->getTSConfig()['options.']['dontMountAdminMounts'] ?? false)) {
1381
                $this->dataLists['webmount_list'] = '0,' . $this->dataLists['webmount_list'];
1382
            }
1383
            // The lists are cleaned for duplicates
1384
            $this->groupData['webmounts'] = GeneralUtility::uniqueList($this->dataLists['webmount_list']);
1385
            $this->groupData['pagetypes_select'] = GeneralUtility::uniqueList($this->dataLists['pagetypes_select']);
1386
            $this->groupData['tables_select'] = GeneralUtility::uniqueList($this->dataLists['tables_modify'] . ',' . $this->dataLists['tables_select']);
1387
            $this->groupData['tables_modify'] = GeneralUtility::uniqueList($this->dataLists['tables_modify']);
1388
            $this->groupData['non_exclude_fields'] = GeneralUtility::uniqueList($this->dataLists['non_exclude_fields']);
1389
            $this->groupData['explicit_allowdeny'] = GeneralUtility::uniqueList($this->dataLists['explicit_allowdeny']);
1390
            $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($this->dataLists['allowed_languages']);
1391
            $this->groupData['custom_options'] = GeneralUtility::uniqueList($this->dataLists['custom_options']);
1392
            $this->groupData['modules'] = GeneralUtility::uniqueList($this->dataLists['modList']);
1393
            $this->groupData['available_widgets'] = GeneralUtility::uniqueList($this->dataLists['available_widgets']);
1394
            $this->groupData['file_permissions'] = GeneralUtility::uniqueList($this->dataLists['file_permissions']);
1395
            $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
1396
1397
            if (!empty(trim($this->groupData['webmounts']))) {
1398
                // Checking read access to web mounts if there are mounts points (not empty string, false or 0)
1399
                $webmounts = explode(',', $this->groupData['webmounts']);
1400
                // Selecting all web mounts with permission clause for reading
1401
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1402
                $queryBuilder->getRestrictions()
1403
                    ->removeAll()
1404
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1405
1406
                $MProws = $queryBuilder->select('uid')
1407
                    ->from('pages')
1408
                    // @todo DOCTRINE: check how to make getPagePermsClause() portable
1409
                    ->where(
1410
                        $this->getPagePermsClause(Permission::PAGE_SHOW),
1411
                        $queryBuilder->expr()->in(
1412
                            'uid',
1413
                            $queryBuilder->createNamedParameter(
1414
                                GeneralUtility::intExplode(',', $this->groupData['webmounts']),
1415
                                Connection::PARAM_INT_ARRAY
1416
                            )
1417
                        )
1418
                    )
1419
                    ->execute()
1420
                    ->fetchAll();
1421
                $MProws = array_column(($MProws ?: []), 'uid', 'uid');
1422
                foreach ($webmounts as $idx => $mountPointUid) {
1423
                    // If the mount ID is NOT found among selected pages, unset it:
1424
                    if ($mountPointUid > 0 && !isset($MProws[$mountPointUid])) {
1425
                        unset($webmounts[$idx]);
1426
                    }
1427
                }
1428
                // Implode mounts in the end.
1429
                $this->groupData['webmounts'] = implode(',', $webmounts);
1430
            }
1431
            // Setting up workspace situation (after webmounts are processed!):
1432
            $this->workspaceInit();
1433
        }
1434
    }
1435
1436
    /**
1437
     * This method parses the UserTSconfig from the current user and all their groups.
1438
     * If the contents are the same, parsing is skipped. No matching is applied here currently.
1439
     */
1440
    protected function prepareUserTsConfig(): void
1441
    {
1442
        $collectedUserTSconfig = [
1443
            'default' => $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig']
1444
        ];
1445
        // Default TSconfig for admin-users
1446
        if ($this->isAdmin()) {
1447
            $collectedUserTSconfig[] = 'admPanel.enable.all = 1';
1448
        }
1449
        // Setting defaults for sys_note author / email
1450
        $collectedUserTSconfig[] = '
1451
TCAdefaults.sys_note.author = ' . $this->user['realName'] . '
1452
TCAdefaults.sys_note.email = ' . $this->user['email'];
1453
1454
        // Loop through all groups and add their 'TSconfig' fields
1455
        foreach ($this->includeGroupArray as $groupId) {
1456
            $collectedUserTSconfig['group_' . $groupId] = $this->userGroups[$groupId]['TSconfig'] ?? '';
1457
        }
1458
1459
        $collectedUserTSconfig[] = $this->user['TSconfig'];
1460
        // Check external files
1461
        $collectedUserTSconfig = TypoScriptParser::checkIncludeLines_array($collectedUserTSconfig);
1462
        // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
1463
        $userTS_text = implode("\n[GLOBAL]\n", $collectedUserTSconfig);
1464
        // Parsing the user TSconfig (or getting from cache)
1465
        $hash = md5('userTS:' . $userTS_text);
1466
        $cache = GeneralUtility::makeInstance(CacheManager::class)->getCache('hash');
1467
        if (!($this->userTS = $cache->get($hash))) {
1468
            $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
1469
            $conditionMatcher = GeneralUtility::makeInstance(ConditionMatcher::class);
1470
            $parseObj->parse($userTS_text, $conditionMatcher);
1471
            $this->userTS = $parseObj->setup;
1472
            $cache->set($hash, $this->userTS, ['UserTSconfig'], 0);
1473
            // Ensure to update UC later
1474
            $this->userTSUpdated = true;
1475
        }
1476
    }
1477
1478
    /**
1479
     * Fetches the group records, subgroups and fills internal arrays.
1480
     * Function is called recursively to fetch subgroups
1481
     *
1482
     * @param string $grList Commalist of be_groups uid numbers
1483
     * @param string $idList List of already processed be_groups-uids so the function will not fall into an eternal recursion.
1484
     * @internal
1485
     */
1486
    public function fetchGroups($grList, $idList = '')
1487
    {
1488
        // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
1489
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->usergroup_table);
1490
        $expressionBuilder = $queryBuilder->expr();
1491
        $constraints = $expressionBuilder->andX(
1492
            $expressionBuilder->eq(
1493
                'pid',
1494
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
1495
            ),
1496
            $expressionBuilder->in(
1497
                'uid',
1498
                $queryBuilder->createNamedParameter(
1499
                    GeneralUtility::intExplode(',', $grList),
1500
                    Connection::PARAM_INT_ARRAY
1501
                )
1502
            ),
1503
            $expressionBuilder->orX(
1504
                $expressionBuilder->eq('lockToDomain', $queryBuilder->quote('')),
1505
                $expressionBuilder->isNull('lockToDomain'),
1506
                $expressionBuilder->eq(
1507
                    'lockToDomain',
1508
                    $queryBuilder->createNamedParameter(GeneralUtility::getIndpEnv('HTTP_HOST'), \PDO::PARAM_STR)
1509
                )
1510
            )
1511
        );
1512
        // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
1513
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] ?? [] as $className) {
1514
            $hookObj = GeneralUtility::makeInstance($className);
1515
            if (method_exists($hookObj, 'fetchGroupQuery_processQuery')) {
1516
                $constraints = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, (string)$constraints);
1517
            }
1518
        }
1519
        $res = $queryBuilder->select('*')
1520
            ->from($this->usergroup_table)
1521
            ->where($constraints)
1522
            ->execute();
1523
        // The userGroups array is filled
1524
        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
1525
            $this->userGroups[$row['uid']] = $row;
1526
        }
1527
        // Traversing records in the correct order
1528
        foreach (explode(',', $grList) as $uid) {
1529
            // Get row:
1530
            $row = $this->userGroups[$uid];
1531
            // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
1532
            if (is_array($row) && !GeneralUtility::inList($idList, $uid)) {
1533
                // Include sub groups
1534
                if (trim($row['subgroup'])) {
1535
                    // Make integer list
1536
                    $theList = implode(',', GeneralUtility::intExplode(',', $row['subgroup']));
1537
                    // Call recursively, pass along list of already processed groups so they are not recursed again.
1538
                    $this->fetchGroups($theList, $idList . ',' . $uid);
1539
                }
1540
                // Add the group uid, current list to the internal arrays.
1541
                $this->includeGroupArray[] = $uid;
1542
                // Mount group database-mounts
1543
                if (($this->user['options'] & Permission::PAGE_SHOW) == 1) {
1544
                    $this->dataLists['webmount_list'] .= ',' . $row['db_mountpoints'];
1545
                }
1546
                // Mount group file-mounts
1547
                if (($this->user['options'] & Permission::PAGE_EDIT) == 2) {
1548
                    $this->dataLists['filemount_list'] .= ',' . $row['file_mountpoints'];
1549
                }
1550
                // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
1551
                $this->dataLists['modList'] .= ',' . $row['groupMods'];
1552
                $this->dataLists['available_widgets'] .= ',' . $row['availableWidgets'];
1553
                $this->dataLists['tables_select'] .= ',' . $row['tables_select'];
1554
                $this->dataLists['tables_modify'] .= ',' . $row['tables_modify'];
1555
                $this->dataLists['pagetypes_select'] .= ',' . $row['pagetypes_select'];
1556
                $this->dataLists['non_exclude_fields'] .= ',' . $row['non_exclude_fields'];
1557
                $this->dataLists['explicit_allowdeny'] .= ',' . $row['explicit_allowdeny'];
1558
                $this->dataLists['allowed_languages'] .= ',' . $row['allowed_languages'];
1559
                $this->dataLists['custom_options'] .= ',' . $row['custom_options'];
1560
                $this->dataLists['file_permissions'] .= ',' . $row['file_permissions'];
1561
                // Setting workspace permissions:
1562
                $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
1563
                // If this function is processing the users OWN group-list (not subgroups) AND
1564
                // if the ->firstMainGroup is not set, then the ->firstMainGroup will be set.
1565
                if ($idList === '' && !$this->firstMainGroup) {
1566
                    $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...
1567
                }
1568
            }
1569
        }
1570
        // HOOK: fetchGroups_postProcessing
1571
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] ?? [] as $_funcRef) {
1572
            $_params = [];
1573
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1574
        }
1575
    }
1576
1577
    /**
1578
     * Updates the field be_users.usergroup_cached_list if the groupList of the user
1579
     * has changed/is different from the current list.
1580
     * The field "usergroup_cached_list" contains the list of groups which the user is a member of.
1581
     * After authentication (where these functions are called...) one can depend on this list being
1582
     * a representation of the exact groups/subgroups which the BE_USER has membership with.
1583
     *
1584
     * @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.
1585
     * @internal
1586
     */
1587
    public function setCachedList($cList)
1588
    {
1589
        if ((string)$cList != (string)$this->user['usergroup_cached_list']) {
1590
            GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
1591
                'be_users',
1592
                ['usergroup_cached_list' => $cList],
1593
                ['uid' => (int)$this->user['uid']]
1594
            );
1595
        }
1596
    }
1597
1598
    /**
1599
     * Sets up all file storages for a user.
1600
     * Needs to be called AFTER the groups have been loaded.
1601
     */
1602
    protected function initializeFileStorages()
1603
    {
1604
        $this->fileStorages = [];
1605
        /** @var \TYPO3\CMS\Core\Resource\StorageRepository $storageRepository */
1606
        $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
1607
        // Admin users have all file storages visible, without any filters
1608
        if ($this->isAdmin()) {
1609
            $storageObjects = $storageRepository->findAll();
1610
            foreach ($storageObjects as $storageObject) {
1611
                $this->fileStorages[$storageObject->getUid()] = $storageObject;
1612
            }
1613
        } else {
1614
            // Regular users only have storages that are defined in their filemounts
1615
            // Permissions and file mounts for the storage are added in StoragePermissionAspect
1616
            foreach ($this->getFileMountRecords() as $row) {
1617
                if (!array_key_exists((int)$row['base'], $this->fileStorages)) {
1618
                    $storageObject = $storageRepository->findByUid($row['base']);
1619
                    if ($storageObject) {
1620
                        $this->fileStorages[$storageObject->getUid()] = $storageObject;
1621
                    }
1622
                }
1623
            }
1624
        }
1625
1626
        // This has to be called always in order to set certain filters
1627
        $this->evaluateUserSpecificFileFilterSettings();
1628
    }
1629
1630
    /**
1631
     * Returns an array of category mount points. The category permissions from BE Groups
1632
     * are also taken into consideration and are merged into User permissions.
1633
     *
1634
     * @return array
1635
     */
1636
    public function getCategoryMountPoints()
1637
    {
1638
        $categoryMountPoints = '';
1639
1640
        // Category mounts of the groups
1641
        if (is_array($this->userGroups)) {
0 ignored issues
show
introduced by
The condition is_array($this->userGroups) is always true.
Loading history...
1642
            foreach ($this->userGroups as $group) {
1643
                if ($group['category_perms']) {
1644
                    $categoryMountPoints .= ',' . $group['category_perms'];
1645
                }
1646
            }
1647
        }
1648
1649
        // Category mounts of the user record
1650
        if ($this->user['category_perms']) {
1651
            $categoryMountPoints .= ',' . $this->user['category_perms'];
1652
        }
1653
1654
        // Make the ids unique
1655
        $categoryMountPoints = GeneralUtility::trimExplode(',', $categoryMountPoints);
1656
        $categoryMountPoints = array_filter($categoryMountPoints); // remove empty value
1657
        $categoryMountPoints = array_unique($categoryMountPoints); // remove unique value
1658
1659
        return $categoryMountPoints;
1660
    }
1661
1662
    /**
1663
     * Returns an array of file mount records, taking workspaces and user home and group home directories into account
1664
     * Needs to be called AFTER the groups have been loaded.
1665
     *
1666
     * @return array
1667
     * @internal
1668
     */
1669
    public function getFileMountRecords()
1670
    {
1671
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
1672
        $fileMountRecordCache = $runtimeCache->get('backendUserAuthenticationFileMountRecords') ?: [];
1673
1674
        if (!empty($fileMountRecordCache)) {
1675
            return $fileMountRecordCache;
1676
        }
1677
1678
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1679
1680
        // Processing file mounts (both from the user and the groups)
1681
        $fileMounts = array_unique(GeneralUtility::intExplode(',', $this->dataLists['filemount_list'], true));
1682
1683
        // Limit file mounts if set in workspace record
1684
        if ($this->workspace > 0 && !empty($this->workspaceRec['file_mountpoints'])) {
1685
            $workspaceFileMounts = GeneralUtility::intExplode(',', $this->workspaceRec['file_mountpoints'], true);
1686
            $fileMounts = array_intersect($fileMounts, $workspaceFileMounts);
1687
        }
1688
1689
        if (!empty($fileMounts)) {
1690
            $orderBy = $GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'] ?? 'sorting';
1691
1692
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_filemounts');
1693
            $queryBuilder->getRestrictions()
1694
                ->removeAll()
1695
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
1696
                ->add(GeneralUtility::makeInstance(HiddenRestriction::class))
1697
                ->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
1698
1699
            $queryBuilder->select('*')
1700
                ->from('sys_filemounts')
1701
                ->where(
1702
                    $queryBuilder->expr()->in('uid', $queryBuilder->createNamedParameter($fileMounts, Connection::PARAM_INT_ARRAY))
1703
                );
1704
1705
            foreach (QueryHelper::parseOrderBy($orderBy) as $fieldAndDirection) {
1706
                $queryBuilder->addOrderBy(...$fieldAndDirection);
1707
            }
1708
1709
            $fileMountRecords = $queryBuilder->execute()->fetchAll(\PDO::FETCH_ASSOC);
1710
            if ($fileMountRecords !== false) {
1711
                foreach ($fileMountRecords as $fileMount) {
1712
                    $fileMountRecordCache[$fileMount['base'] . $fileMount['path']] = $fileMount;
1713
                }
1714
            }
1715
        }
1716
1717
        // Read-only file mounts
1718
        $readOnlyMountPoints = \trim($this->getTSConfig()['options.']['folderTree.']['altElementBrowserMountPoints'] ?? '');
1719
        if ($readOnlyMountPoints) {
1720
            // We cannot use the API here but need to fetch the default storage record directly
1721
            // to not instantiate it (which directly applies mount points) before all mount points are resolved!
1722
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file_storage');
1723
            $defaultStorageRow = $queryBuilder->select('uid')
1724
                ->from('sys_file_storage')
1725
                ->where(
1726
                    $queryBuilder->expr()->eq('is_default', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT))
1727
                )
1728
                ->setMaxResults(1)
1729
                ->execute()
1730
                ->fetch(\PDO::FETCH_ASSOC);
1731
1732
            $readOnlyMountPointArray = GeneralUtility::trimExplode(',', $readOnlyMountPoints);
1733
            foreach ($readOnlyMountPointArray as $readOnlyMountPoint) {
1734
                $readOnlyMountPointConfiguration = GeneralUtility::trimExplode(':', $readOnlyMountPoint);
1735
                if (count($readOnlyMountPointConfiguration) === 2) {
1736
                    // A storage is passed in the configuration
1737
                    $storageUid = (int)$readOnlyMountPointConfiguration[0];
1738
                    $path = $readOnlyMountPointConfiguration[1];
1739
                } else {
1740
                    if (empty($defaultStorageRow)) {
1741
                        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);
1742
                    }
1743
                    // Backwards compatibility: If no storage is passed, we use the default storage
1744
                    $storageUid = $defaultStorageRow['uid'];
1745
                    $path = $readOnlyMountPointConfiguration[0];
1746
                }
1747
                $fileMountRecordCache[$storageUid . $path] = [
1748
                    'base' => $storageUid,
1749
                    'title' => $path,
1750
                    'path' => $path,
1751
                    'read_only' => true
1752
                ];
1753
            }
1754
        }
1755
1756
        // Personal or Group filemounts are not accessible if file mount list is set in workspace record
1757
        if ($this->workspace <= 0 || empty($this->workspaceRec['file_mountpoints'])) {
1758
            // If userHomePath is set, we attempt to mount it
1759
            if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
1760
                [$userHomeStorageUid, $userHomeFilter] = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'], 2);
1761
                $userHomeStorageUid = (int)$userHomeStorageUid;
1762
                $userHomeFilter = '/' . ltrim($userHomeFilter, '/');
1763
                if ($userHomeStorageUid > 0) {
1764
                    // Try and mount with [uid]_[username]
1765
                    $path = $userHomeFilter . $this->user['uid'] . '_' . $this->user['username'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1766
                    $fileMountRecordCache[$userHomeStorageUid . $path] = [
1767
                        'base' => $userHomeStorageUid,
1768
                        'title' => $this->user['username'],
1769
                        'path' => $path,
1770
                        'read_only' => false,
1771
                        'user_mount' => true
1772
                    ];
1773
                    // Try and mount with only [uid]
1774
                    $path = $userHomeFilter . $this->user['uid'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1775
                    $fileMountRecordCache[$userHomeStorageUid . $path] = [
1776
                        'base' => $userHomeStorageUid,
1777
                        'title' => $this->user['username'],
1778
                        'path' => $path,
1779
                        'read_only' => false,
1780
                        'user_mount' => true
1781
                    ];
1782
                }
1783
            }
1784
1785
            // Mount group home-dirs
1786
            if ((is_array($this->user) && $this->user['options'] & Permission::PAGE_EDIT) == 2 && $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'] != '') {
1787
                // If groupHomePath is set, we attempt to mount it
1788
                [$groupHomeStorageUid, $groupHomeFilter] = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'], 2);
1789
                $groupHomeStorageUid = (int)$groupHomeStorageUid;
1790
                $groupHomeFilter = '/' . ltrim($groupHomeFilter, '/');
1791
                if ($groupHomeStorageUid > 0) {
1792
                    foreach ($this->userGroups as $groupData) {
1793
                        $path = $groupHomeFilter . $groupData['uid'];
1794
                        $fileMountRecordCache[$groupHomeStorageUid . $path] = [
1795
                            'base' => $groupHomeStorageUid,
1796
                            'title' => $groupData['title'],
1797
                            'path' => $path,
1798
                            'read_only' => false,
1799
                            'user_mount' => true
1800
                        ];
1801
                    }
1802
                }
1803
            }
1804
        }
1805
1806
        $runtimeCache->set('backendUserAuthenticationFileMountRecords', $fileMountRecordCache);
1807
        return $fileMountRecordCache;
1808
    }
1809
1810
    /**
1811
     * Returns an array with the filemounts for the user.
1812
     * Each filemount is represented with an array of a "name", "path" and "type".
1813
     * If no filemounts an empty array is returned.
1814
     *
1815
     * @return \TYPO3\CMS\Core\Resource\ResourceStorage[]
1816
     */
1817
    public function getFileStorages()
1818
    {
1819
        // Initializing file mounts after the groups are fetched
1820
        if ($this->fileStorages === null) {
1821
            $this->initializeFileStorages();
1822
        }
1823
        return $this->fileStorages;
1824
    }
1825
1826
    /**
1827
     * Adds filters based on what the user has set
1828
     * this should be done in this place, and called whenever needed,
1829
     * but only when needed
1830
     */
1831
    public function evaluateUserSpecificFileFilterSettings()
1832
    {
1833
        // Add the option for also displaying the non-hidden files
1834
        if ($this->uc['showHiddenFilesAndFolders']) {
1835
            FileNameFilter::setShowHiddenFilesAndFolders(true);
1836
        }
1837
    }
1838
1839
    /**
1840
     * Returns the information about file permissions.
1841
     * Previously, this was stored in the DB field fileoper_perms now it is file_permissions.
1842
     * Besides it can be handled via userTSconfig
1843
     *
1844
     * permissions.file.default {
1845
     * addFile = 1
1846
     * readFile = 1
1847
     * writeFile = 1
1848
     * copyFile = 1
1849
     * moveFile = 1
1850
     * renameFile = 1
1851
     * deleteFile = 1
1852
     *
1853
     * addFolder = 1
1854
     * readFolder = 1
1855
     * writeFolder = 1
1856
     * copyFolder = 1
1857
     * moveFolder = 1
1858
     * renameFolder = 1
1859
     * deleteFolder = 1
1860
     * recursivedeleteFolder = 1
1861
     * }
1862
     *
1863
     * # overwrite settings for a specific storageObject
1864
     * permissions.file.storage.StorageUid {
1865
     * readFile = 1
1866
     * recursivedeleteFolder = 0
1867
     * }
1868
     *
1869
     * Please note that these permissions only apply, if the storage has the
1870
     * capabilities (browseable, writable), and if the driver allows for writing etc
1871
     *
1872
     * @return array
1873
     */
1874
    public function getFilePermissions()
1875
    {
1876
        if (!isset($this->filePermissions)) {
1877
            $filePermissions = [
1878
                // File permissions
1879
                'addFile' => false,
1880
                'readFile' => false,
1881
                'writeFile' => false,
1882
                'copyFile' => false,
1883
                'moveFile' => false,
1884
                'renameFile' => false,
1885
                'deleteFile' => false,
1886
                // Folder permissions
1887
                'addFolder' => false,
1888
                'readFolder' => false,
1889
                'writeFolder' => false,
1890
                'copyFolder' => false,
1891
                'moveFolder' => false,
1892
                'renameFolder' => false,
1893
                'deleteFolder' => false,
1894
                'recursivedeleteFolder' => false
1895
            ];
1896
            if ($this->isAdmin()) {
1897
                $filePermissions = array_map('is_bool', $filePermissions);
1898
            } else {
1899
                $userGroupRecordPermissions = GeneralUtility::trimExplode(',', $this->groupData['file_permissions'] ?? '', true);
1900
                array_walk(
1901
                    $userGroupRecordPermissions,
1902
                    function ($permission) use (&$filePermissions) {
1903
                        $filePermissions[$permission] = true;
1904
                    }
1905
                );
1906
1907
                // Finally overlay any userTSconfig
1908
                $permissionsTsConfig = $this->getTSConfig()['permissions.']['file.']['default.'] ?? [];
1909
                if (!empty($permissionsTsConfig)) {
1910
                    array_walk(
1911
                        $permissionsTsConfig,
1912
                        function ($value, $permission) use (&$filePermissions) {
1913
                            $filePermissions[$permission] = (bool)$value;
1914
                        }
1915
                    );
1916
                }
1917
            }
1918
            $this->filePermissions = $filePermissions;
1919
        }
1920
        return $this->filePermissions;
1921
    }
1922
1923
    /**
1924
     * Gets the file permissions for a storage
1925
     * by merging any storage-specific permissions for a
1926
     * storage with the default settings.
1927
     * Admin users will always get the default settings.
1928
     *
1929
     * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storageObject
1930
     * @return array
1931
     */
1932
    public function getFilePermissionsForStorage(ResourceStorage $storageObject)
1933
    {
1934
        $finalUserPermissions = $this->getFilePermissions();
1935
        if (!$this->isAdmin()) {
1936
            $storageFilePermissions = $this->getTSConfig()['permissions.']['file.']['storage.'][$storageObject->getUid() . '.'] ?? [];
1937
            if (!empty($storageFilePermissions)) {
1938
                array_walk(
1939
                    $storageFilePermissions,
1940
                    function ($value, $permission) use (&$finalUserPermissions) {
1941
                        $finalUserPermissions[$permission] = (bool)$value;
1942
                    }
1943
                );
1944
            }
1945
        }
1946
        return $finalUserPermissions;
1947
    }
1948
1949
    /**
1950
     * Returns a \TYPO3\CMS\Core\Resource\Folder object that is used for uploading
1951
     * files by default.
1952
     * This is used for RTE and its magic images, as well as uploads
1953
     * in the TCEforms fields.
1954
     *
1955
     * The default upload folder for a user is the defaultFolder on the first
1956
     * filestorage/filemount that the user can access and to which files are allowed to be added
1957
     * however, you can set the users' upload folder like this:
1958
     *
1959
     * options.defaultUploadFolder = 3:myfolder/yourfolder/
1960
     *
1961
     * @param int $pid PageUid
1962
     * @param string $table Table name
1963
     * @param string $field Field name
1964
     * @return \TYPO3\CMS\Core\Resource\Folder|bool The default upload folder for this user
1965
     */
1966
    public function getDefaultUploadFolder($pid = null, $table = null, $field = null)
1967
    {
1968
        $uploadFolder = $this->getTSConfig()['options.']['defaultUploadFolder'] ?? '';
1969
        if ($uploadFolder) {
1970
            try {
1971
                $uploadFolder = GeneralUtility::makeInstance(ResourceFactory::class)->getFolderObjectFromCombinedIdentifier($uploadFolder);
1972
            } catch (Exception\FolderDoesNotExistException $e) {
1973
                $uploadFolder = null;
1974
            }
1975
        }
1976
        if (empty($uploadFolder)) {
1977
            foreach ($this->getFileStorages() as $storage) {
1978
                if ($storage->isDefault() && $storage->isWritable()) {
1979
                    try {
1980
                        $uploadFolder = $storage->getDefaultFolder();
1981
                        if ($uploadFolder->checkActionPermission('write')) {
1982
                            break;
1983
                        }
1984
                        $uploadFolder = null;
1985
                    } catch (Exception $folderAccessException) {
1986
                        // If the folder is not accessible (no permissions / does not exist) we skip this one.
1987
                    }
1988
                    break;
1989
                }
1990
            }
1991
            if (!$uploadFolder instanceof Folder) {
1992
                /** @var ResourceStorage $storage */
1993
                foreach ($this->getFileStorages() as $storage) {
1994
                    if ($storage->isWritable()) {
1995
                        try {
1996
                            $uploadFolder = $storage->getDefaultFolder();
1997
                            if ($uploadFolder->checkActionPermission('write')) {
1998
                                break;
1999
                            }
2000
                            $uploadFolder = null;
2001
                        } catch (Exception $folderAccessException) {
2002
                            // If the folder is not accessible (no permissions / does not exist) try the next one.
2003
                        }
2004
                    }
2005
                }
2006
            }
2007
        }
2008
2009
        // HOOK: getDefaultUploadFolder
2010
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getDefaultUploadFolder'] ?? [] as $_funcRef) {
2011
            $_params = [
2012
                'uploadFolder' => $uploadFolder,
2013
                'pid' => $pid,
2014
                'table' => $table,
2015
                'field' => $field,
2016
            ];
2017
            $uploadFolder = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2018
        }
2019
2020
        if ($uploadFolder instanceof Folder) {
2021
            return $uploadFolder;
2022
        }
2023
        return false;
2024
    }
2025
2026
    /**
2027
     * Returns a \TYPO3\CMS\Core\Resource\Folder object that could be used for uploading
2028
     * temporary files in user context. The folder _temp_ below the default upload folder
2029
     * of the user is used.
2030
     *
2031
     * @return \TYPO3\CMS\Core\Resource\Folder|null
2032
     * @see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::getDefaultUploadFolder()
2033
     */
2034
    public function getDefaultUploadTemporaryFolder()
2035
    {
2036
        $defaultTemporaryFolder = null;
2037
        $defaultFolder = $this->getDefaultUploadFolder();
2038
2039
        if ($defaultFolder !== false) {
2040
            $tempFolderName = '_temp_';
2041
            $createFolder = !$defaultFolder->hasFolder($tempFolderName);
2042
            if ($createFolder === true) {
2043
                try {
2044
                    $defaultTemporaryFolder = $defaultFolder->createFolder($tempFolderName);
2045
                } catch (Exception $folderAccessException) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2046
                }
2047
            } else {
2048
                $defaultTemporaryFolder = $defaultFolder->getSubfolder($tempFolderName);
2049
            }
2050
        }
2051
2052
        return $defaultTemporaryFolder;
2053
    }
2054
2055
    /**
2056
     * Initializing workspace.
2057
     * Called from within this function, see fetchGroupData()
2058
     *
2059
     * @see fetchGroupData()
2060
     * @internal should only be used from within TYPO3 Core
2061
     */
2062
    public function workspaceInit()
2063
    {
2064
        // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
2065
        $this->setWorkspace($this->user['workspace_id']);
2066
        // Limiting the DB mountpoints if there any selected in the workspace record
2067
        $this->initializeDbMountpointsInWorkspace();
2068
        $allowed_languages = $this->getTSConfig()['options.']['workspaces.']['allowed_languages.'][$this->workspace] ?? '';
2069
        if (!empty($allowed_languages)) {
2070
            $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($allowed_languages);
2071
        }
2072
    }
2073
2074
    /**
2075
     * Limiting the DB mountpoints if there any selected in the workspace record
2076
     */
2077
    protected function initializeDbMountpointsInWorkspace()
2078
    {
2079
        $dbMountpoints = trim($this->workspaceRec['db_mountpoints'] ?? '');
2080
        if ($this->workspace > 0 && $dbMountpoints != '') {
2081
            $filteredDbMountpoints = [];
2082
            // Notice: We cannot call $this->getPagePermsClause(1);
2083
            // as usual because the group-list is not available at this point.
2084
            // But bypassing is fine because all we want here is check if the
2085
            // workspace mounts are inside the current webmounts rootline.
2086
            // The actual permission checking on page level is done elsewhere
2087
            // as usual anyway before the page tree is rendered.
2088
            $readPerms = '1=1';
2089
            // Traverse mount points of the
2090
            $dbMountpoints = GeneralUtility::intExplode(',', $dbMountpoints);
2091
            foreach ($dbMountpoints as $mpId) {
2092
                if ($this->isInWebMount($mpId, $readPerms)) {
0 ignored issues
show
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...
2093
                    $filteredDbMountpoints[] = $mpId;
2094
                }
2095
            }
2096
            // Re-insert webmounts:
2097
            $filteredDbMountpoints = array_unique($filteredDbMountpoints);
2098
            $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
2099
        }
2100
    }
2101
2102
    /**
2103
     * Checking if a workspace is allowed for backend user
2104
     *
2105
     * @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)
2106
     * @param string $fields List of fields to select. Default fields are all
2107
     * @return array Output will also show how access was granted. Admin users will have a true output regardless of input.
2108
     * @internal should only be used from within TYPO3 Core
2109
     */
2110
    public function checkWorkspace($wsRec, $fields = '*')
2111
    {
2112
        $retVal = false;
2113
        // If not array, look up workspace record:
2114
        if (!is_array($wsRec)) {
2115
            switch ((string)$wsRec) {
2116
                case '0':
2117
                    $wsRec = ['uid' => $wsRec];
2118
                    break;
2119
                default:
2120
                    if (ExtensionManagementUtility::isLoaded('workspaces')) {
2121
                        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2122
                        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2123
                        $wsRec = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields))
2124
                            ->from('sys_workspace')
2125
                            ->where($queryBuilder->expr()->eq(
2126
                                'uid',
2127
                                $queryBuilder->createNamedParameter($wsRec, \PDO::PARAM_INT)
2128
                            ))
2129
                            ->orderBy('title')
2130
                            ->setMaxResults(1)
2131
                            ->execute()
2132
                            ->fetch(\PDO::FETCH_ASSOC);
2133
                    }
2134
            }
2135
        }
2136
        // If wsRec is set to an array, evaluate it:
2137
        if (is_array($wsRec)) {
2138
            if ($this->isAdmin()) {
2139
                return array_merge($wsRec, ['_ACCESS' => 'admin']);
2140
            }
2141
            switch ((string)$wsRec['uid']) {
2142
                    case '0':
2143
                        $retVal = $this->groupData['workspace_perms'] & Permission::PAGE_SHOW
2144
                            ? array_merge($wsRec, ['_ACCESS' => 'online'])
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "?"; newline found
Loading history...
2145
                            : false;
0 ignored issues
show
Coding Style introduced by
Expected 1 space before ":"; newline found
Loading history...
2146
                        break;
2147
                    default:
2148
                        // Checking if the guy is admin:
2149
                        if (GeneralUtility::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
2150
                            return array_merge($wsRec, ['_ACCESS' => 'owner']);
2151
                        }
2152
                        // Checking if he is owner through a user group of his:
2153
                        foreach ($this->userGroupsUID as $groupUid) {
2154
                            if (GeneralUtility::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
2155
                                return array_merge($wsRec, ['_ACCESS' => 'owner']);
2156
                            }
2157
                        }
2158
                        // Checking if he is member as user:
2159
                        if (GeneralUtility::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
2160
                            return array_merge($wsRec, ['_ACCESS' => 'member']);
2161
                        }
2162
                        // Checking if he is member through a user group of his:
2163
                        foreach ($this->userGroupsUID as $groupUid) {
2164
                            if (GeneralUtility::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
2165
                                return array_merge($wsRec, ['_ACCESS' => 'member']);
2166
                            }
2167
                        }
2168
                }
0 ignored issues
show
Coding Style introduced by
Closing brace indented incorrectly; expected 12 spaces, found 16
Loading history...
2169
        }
2170
        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...
2171
    }
2172
2173
    /**
2174
     * Uses checkWorkspace() to check if current workspace is available for user.
2175
     * This function caches the result and so can be called many times with no performance loss.
2176
     *
2177
     * @return array See checkWorkspace()
2178
     * @see checkWorkspace()
2179
     * @internal should only be used from within TYPO3 Core
2180
     */
2181
    public function checkWorkspaceCurrent()
2182
    {
2183
        if (!isset($this->checkWorkspaceCurrent_cache)) {
2184
            $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
2185
        }
2186
        return $this->checkWorkspaceCurrent_cache;
2187
    }
2188
2189
    /**
2190
     * Setting workspace ID
2191
     *
2192
     * @param int $workspaceId ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
2193
     * @internal should only be used from within TYPO3 Core
2194
     */
2195
    public function setWorkspace($workspaceId)
2196
    {
2197
        // Check workspace validity and if not found, revert to default workspace.
2198
        if (!$this->setTemporaryWorkspace($workspaceId)) {
2199
            $this->setDefaultWorkspace();
2200
        }
2201
        // Unset access cache:
2202
        $this->checkWorkspaceCurrent_cache = null;
2203
        // If ID is different from the stored one, change it:
2204
        if ((int)$this->workspace !== (int)$this->user['workspace_id']) {
2205
            $this->user['workspace_id'] = $this->workspace;
2206
            GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
2207
                'be_users',
2208
                ['workspace_id' => $this->user['workspace_id']],
2209
                ['uid' => (int)$this->user['uid']]
2210
            );
2211
            $this->writelog(SystemLogType::EXTENSION, SystemLogGenericAction::UNDEFINED, SystemLogErrorClassification::MESSAGE, 0, 'User changed workspace to "' . $this->workspace . '"', []);
2212
        }
2213
    }
2214
2215
    /**
2216
     * Sets a temporary workspace in the context of the current backend user.
2217
     *
2218
     * @param int $workspaceId
2219
     * @return bool
2220
     * @internal should only be used from within TYPO3 Core
2221
     */
2222
    public function setTemporaryWorkspace($workspaceId)
2223
    {
2224
        $result = false;
2225
        $workspaceRecord = $this->checkWorkspace($workspaceId);
2226
2227
        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...
2228
            $this->workspaceRec = $workspaceRecord;
2229
            $this->workspace = (int)$workspaceId;
2230
            $result = true;
2231
        }
2232
2233
        return $result;
2234
    }
2235
2236
    /**
2237
     * Sets the default workspace in the context of the current backend user.
2238
     * @internal should only be used from within TYPO3 Core
2239
     */
2240
    public function setDefaultWorkspace()
2241
    {
2242
        $this->workspace = (int)$this->getDefaultWorkspace();
2243
        $this->workspaceRec = $this->checkWorkspace($this->workspace);
2244
    }
2245
2246
    /**
2247
     * Return default workspace ID for user,
2248
     * if EXT:workspaces is not installed the user will be pushed to the
2249
     * Live workspace, if he has access to. If no workspace is available for the user, the workspace ID is set to "-99"
2250
     *
2251
     * @return int Default workspace id.
2252
     * @internal should only be used from within TYPO3 Core
2253
     */
2254
    public function getDefaultWorkspace()
2255
    {
2256
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
2257
            return 0;
2258
        }
2259
        // Online is default
2260
        if ($this->checkWorkspace(0)) {
2261
            return 0;
2262
        }
2263
        // Otherwise -99 is the fallback
2264
        $defaultWorkspace = -99;
2265
        // Traverse all workspaces
2266
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2267
        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2268
        $result = $queryBuilder->select('*')
2269
            ->from('sys_workspace')
2270
            ->orderBy('title')
2271
            ->execute();
2272
        while ($workspaceRecord = $result->fetch()) {
2273
            if ($this->checkWorkspace($workspaceRecord)) {
2274
                $defaultWorkspace = (int)$workspaceRecord['uid'];
2275
                break;
2276
            }
2277
        }
2278
        return $defaultWorkspace;
2279
    }
2280
2281
    /**
2282
     * Writes an entry in the logfile/table
2283
     * Documentation in "TYPO3 Core API"
2284
     *
2285
     * @param int $type Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
2286
     * @param int $action Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
2287
     * @param int $error Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2288
     * @param int $details_nr The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
2289
     * @param string $details Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
2290
     * @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
2291
     * @param string $tablename Table name. Special field used by tce_main.php.
2292
     * @param int|string $recuid Record UID. Special field used by tce_main.php.
2293
     * @param int|string $recpid Record PID. Special field used by tce_main.php. OBSOLETE
2294
     * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
2295
     * @param string $NEWid Special field used by tce_main.php. NEWid string of newly created records.
2296
     * @param int $userId Alternative Backend User ID (used for logging login actions where this is not yet known).
2297
     * @return int Log entry ID.
2298
     */
2299
    public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0)
2300
    {
2301
        if (!$userId && !empty($this->user['uid'])) {
2302
            $userId = $this->user['uid'];
2303
        }
2304
2305
        if (!empty($this->user['ses_backuserid'])) {
2306
            if (empty($data)) {
2307
                $data = [];
2308
            }
2309
            $data['originalUser'] = $this->user['ses_backuserid'];
2310
        }
2311
2312
        $fields = [
2313
            'userid' => (int)$userId,
2314
            'type' => (int)$type,
2315
            'action' => (int)$action,
2316
            'error' => (int)$error,
2317
            'details_nr' => (int)$details_nr,
2318
            'details' => $details,
2319
            'log_data' => serialize($data),
2320
            'tablename' => $tablename,
2321
            'recuid' => (int)$recuid,
2322
            'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2323
            'tstamp' => $GLOBALS['EXEC_TIME'] ?? time(),
2324
            'event_pid' => (int)$event_pid,
2325
            'NEWid' => $NEWid,
2326
            'workspace' => $this->workspace
2327
        ];
2328
2329
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('sys_log');
2330
        $connection->insert(
2331
            'sys_log',
2332
            $fields,
2333
            [
2334
                \PDO::PARAM_INT,
2335
                \PDO::PARAM_INT,
2336
                \PDO::PARAM_INT,
2337
                \PDO::PARAM_INT,
2338
                \PDO::PARAM_INT,
2339
                \PDO::PARAM_STR,
2340
                \PDO::PARAM_STR,
2341
                \PDO::PARAM_STR,
2342
                \PDO::PARAM_INT,
2343
                \PDO::PARAM_STR,
2344
                \PDO::PARAM_INT,
2345
                \PDO::PARAM_INT,
2346
                \PDO::PARAM_STR,
2347
                \PDO::PARAM_STR,
2348
            ]
2349
        );
2350
2351
        return (int)$connection->lastInsertId('sys_log');
2352
    }
2353
2354
    /**
2355
     * Sends a warning to $email if there has been a certain amount of failed logins during a period.
2356
     * If a login fails, this function is called. It will look up the sys_log to see if there
2357
     * have been more than $max failed logins the last $secondsBack seconds (default 3600).
2358
     * If so, an email with a warning is sent to $email.
2359
     *
2360
     * @param string $email Email address
2361
     * @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.
2362
     * @param int $max Max allowed failures before a warning mail is sent
2363
     * @internal
2364
     */
2365
    public function checkLogFailures($email, $secondsBack = 3600, $max = 3)
2366
    {
2367
        if (!GeneralUtility::validEmail($email)) {
2368
            return;
2369
        }
2370
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
2371
2372
        // Get last flag set in the log for sending
2373
        $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
2374
        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_log');
2375
        $queryBuilder->select('tstamp')
2376
            ->from('sys_log')
2377
            ->where(
2378
                $queryBuilder->expr()->eq(
2379
                    'type',
2380
                    $queryBuilder->createNamedParameter(SystemLogType::LOGIN, \PDO::PARAM_INT)
2381
                ),
2382
                $queryBuilder->expr()->eq(
2383
                    'action',
2384
                    $queryBuilder->createNamedParameter(SystemLogLoginAction::SEND_FAILURE_WARNING_EMAIL, \PDO::PARAM_INT)
2385
                ),
2386
                $queryBuilder->expr()->gt(
2387
                    'tstamp',
2388
                    $queryBuilder->createNamedParameter($theTimeBack, \PDO::PARAM_INT)
2389
                )
2390
            )
2391
            ->orderBy('tstamp', 'DESC')
2392
            ->setMaxResults(1);
2393
        if ($testRow = $queryBuilder->execute()->fetch(\PDO::FETCH_ASSOC)) {
2394
            $theTimeBack = $testRow['tstamp'];
2395
        }
2396
2397
        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_log');
2398
        $result = $queryBuilder->select('*')
2399
            ->from('sys_log')
2400
            ->where(
2401
                $queryBuilder->expr()->eq(
2402
                    'type',
2403
                    $queryBuilder->createNamedParameter(SystemLogType::LOGIN, \PDO::PARAM_INT)
2404
                ),
2405
                $queryBuilder->expr()->eq(
2406
                    'action',
2407
                    $queryBuilder->createNamedParameter(SystemLogLoginAction::ATTEMPT, \PDO::PARAM_INT)
2408
                ),
2409
                $queryBuilder->expr()->neq(
2410
                    'error',
2411
                    $queryBuilder->createNamedParameter(SystemLogErrorClassification::MESSAGE, \PDO::PARAM_INT)
2412
                ),
2413
                $queryBuilder->expr()->gt(
2414
                    'tstamp',
2415
                    $queryBuilder->createNamedParameter($theTimeBack, \PDO::PARAM_INT)
2416
                )
2417
            )
2418
            ->orderBy('tstamp')
2419
            ->execute();
2420
2421
        $rowCount = $queryBuilder
2422
            ->count('uid')
2423
            ->execute()
2424
            ->fetchColumn(0);
2425
        // Check for more than $max number of error failures with the last period.
2426
        if ($rowCount > $max) {
2427
            // OK, so there were more than the max allowed number of login failures - so we will send an email then.
2428
            $this->sendLoginAttemptEmail($result, $email);
2429
            // Login failure attempt written to log
2430
            $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]);
2431
        }
2432
    }
2433
2434
    /**
2435
     * Sends out an email if the number of attempts have exceeded a limit.
2436
     *
2437
     * @param Statement $result
2438
     * @param string $emailAddress
2439
     */
2440
    protected function sendLoginAttemptEmail(Statement $result, string $emailAddress): void
2441
    {
2442
        $emailData = [];
2443
        while ($row = $result->fetch(\PDO::FETCH_ASSOC)) {
2444
            $theData = unserialize($row['log_data'], ['allowed_classes' => false]);
2445
            $text = @sprintf($row['details'], (string)$theData[0], (string)$theData[1], (string)$theData[2]);
2446
            if ((int)$row['type'] === SystemLogType::LOGIN) {
2447
                $text = str_replace('###IP###', $row['IP'], $text);
2448
            }
2449
            $emailData[] = [
2450
                'row' => $row,
2451
                'text' => $text
2452
            ];
2453
        }
2454
        $email = GeneralUtility::makeInstance(FluidEmail::class)
2455
            ->to($emailAddress)
2456
            ->setTemplate('Security/LoginAttemptFailedWarning')
2457
            ->assign('lines', $emailData);
2458
        if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface) {
2459
            $email->setRequest($GLOBALS['TYPO3_REQUEST']);
2460
        }
2461
        GeneralUtility::makeInstance(Mailer::class)->send($email);
2462
    }
2463
2464
    /**
2465
     * Getter for the cookie name
2466
     *
2467
     * @static
2468
     * @return string returns the configured cookie name
2469
     */
2470
    public static function getCookieName()
2471
    {
2472
        $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
2473
        if (empty($configuredCookieName)) {
2474
            $configuredCookieName = 'be_typo_user';
2475
        }
2476
        return $configuredCookieName;
2477
    }
2478
2479
    /**
2480
     * If TYPO3_CONF_VARS['BE']['enabledBeUserIPLock'] is enabled and
2481
     * an IP-list is found in the User TSconfig objString "options.lockToIP",
2482
     * then make an IP comparison with REMOTE_ADDR and check if the IP address matches
2483
     *
2484
     * @return bool TRUE, if IP address validates OK (or no check is done at all because no restriction is set)
2485
     * @internal should only be used from within TYPO3 Core
2486
     */
2487
    public function checkLockToIP()
2488
    {
2489
        $isValid = true;
2490
        if ($GLOBALS['TYPO3_CONF_VARS']['BE']['enabledBeUserIPLock']) {
2491
            $IPList = trim($this->getTSConfig()['options.']['lockToIP'] ?? '');
2492
            if (!empty($IPList)) {
2493
                $isValid = GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $IPList);
2494
            }
2495
        }
2496
        return $isValid;
2497
    }
2498
2499
    /**
2500
     * Check if user is logged in and if so, call ->fetchGroupData() to load group information and
2501
     * access lists of all kind, further check IP, set the ->uc array.
2502
     * If no user is logged in the default behaviour is to exit with an error message.
2503
     * This function is called right after ->start() in fx. the TYPO3 Bootstrap.
2504
     *
2505
     * @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.
2506
     * @throws \RuntimeException
2507
     */
2508
    public function backendCheckLogin($proceedIfNoUserIsLoggedIn = false)
2509
    {
2510
        if (empty($this->user['uid'])) {
2511
            if ($proceedIfNoUserIsLoggedIn === false) {
2512
                $url = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir;
2513
                HttpUtility::redirect($url);
2514
            }
2515
        } else {
2516
            // ...and if that's the case, call these functions
2517
            $this->fetchGroupData();
2518
            // The groups are fetched and ready for permission checking in this initialization.
2519
            // Tables.php must be read before this because stuff like the modules has impact in this
2520
            if ($this->checkLockToIP()) {
2521
                if ($this->isUserAllowedToLogin()) {
2522
                    // Setting the UC array. It's needed with fetchGroupData first, due to default/overriding of values.
2523
                    $this->backendSetUC();
2524
                    if ($this->loginSessionStarted) {
2525
                        // Also, if there is a recovery link set, unset it now
2526
                        // this will be moved into its own Event at a later stage.
2527
                        // If a token was set previously, this is now unset, as it was now possible to log-in
2528
                        if ($this->user['password_reset_token'] ?? '') {
2529
                            GeneralUtility::makeInstance(ConnectionPool::class)
2530
                                ->getConnectionForTable($this->user_table)
2531
                                ->update($this->user_table, ['password_reset_token' => ''], ['uid' => $this->user['uid']]);
2532
                        }
2533
                        // Process hooks
2534
                        $hooks = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['backendUserLogin'];
2535
                        foreach ($hooks ?? [] as $_funcRef) {
2536
                            $_params = ['user' => $this->user];
2537
                            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2538
                        }
2539
                    }
2540
                } else {
2541
                    throw new \RuntimeException('Login Error: TYPO3 is in maintenance mode at the moment. Only administrators are allowed access.', 1294585860);
2542
                }
2543
            } else {
2544
                throw new \RuntimeException('Login Error: IP locking prevented you from being authorized. Can\'t proceed, sorry.', 1294585861);
2545
            }
2546
        }
2547
    }
2548
2549
    /**
2550
     * Initialize the internal ->uc array for the backend user
2551
     * Will make the overrides if necessary, and write the UC back to the be_users record if changes has happened
2552
     *
2553
     * @internal
2554
     */
2555
    public function backendSetUC()
2556
    {
2557
        // UC - user configuration is a serialized array inside the user object
2558
        // If there is a saved uc we implement that instead of the default one.
2559
        $this->unpack_uc();
2560
        // Setting defaults if uc is empty
2561
        $updated = false;
2562
        $originalUc = [];
2563
        if (is_array($this->uc) && isset($this->uc['ucSetByInstallTool'])) {
2564
            $originalUc = $this->uc;
2565
            unset($originalUc['ucSetByInstallTool'], $this->uc);
2566
        }
2567
        if (!is_array($this->uc)) {
2568
            $this->uc = array_merge(
2569
                $this->uc_default,
2570
                (array)$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUC'],
2571
                GeneralUtility::removeDotsFromTS((array)($this->getTSConfig()['setup.']['default.'] ?? [])),
2572
                $originalUc
2573
            );
2574
            $this->overrideUC();
2575
            $updated = true;
2576
        }
2577
        // If TSconfig is updated, update the defaultUC.
2578
        if ($this->userTSUpdated) {
2579
            $this->overrideUC();
2580
            $updated = true;
2581
        }
2582
        // Setting default lang from be_user record.
2583
        if (!isset($this->uc['lang'])) {
2584
            $this->uc['lang'] = $this->user['lang'];
2585
            $updated = true;
2586
        }
2587
        // Setting the time of the first login:
2588
        if (!isset($this->uc['firstLoginTimeStamp'])) {
2589
            $this->uc['firstLoginTimeStamp'] = $GLOBALS['EXEC_TIME'];
2590
            $updated = true;
2591
        }
2592
        // Saving if updated.
2593
        if ($updated) {
2594
            $this->writeUC();
2595
        }
2596
    }
2597
2598
    /**
2599
     * Override: Call this function every time the uc is updated.
2600
     * That is 1) by reverting to default values, 2) in the setup-module, 3) userTS changes (userauthgroup)
2601
     *
2602
     * @internal
2603
     */
2604
    public function overrideUC()
2605
    {
2606
        $this->uc = array_merge((array)$this->uc, (array)($this->getTSConfig()['setup.']['override.'] ?? []));
2607
    }
2608
2609
    /**
2610
     * Clears the user[uc] and ->uc to blank strings. Then calls ->backendSetUC() to fill it again with reset contents
2611
     *
2612
     * @internal
2613
     */
2614
    public function resetUC()
2615
    {
2616
        $this->user['uc'] = '';
2617
        $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...
2618
        $this->backendSetUC();
2619
    }
2620
2621
    /**
2622
     * Determines whether a backend user is allowed to access the backend.
2623
     *
2624
     * The conditions are:
2625
     * + backend user is a regular user and adminOnly is not defined
2626
     * + backend user is an admin user
2627
     * + backend user is used in CLI context and adminOnly is explicitly set to "2" (see CommandLineUserAuthentication)
2628
     * + backend user is being controlled by an admin user
2629
     *
2630
     * @return bool Whether a backend user is allowed to access the backend
2631
     */
2632
    protected function isUserAllowedToLogin()
2633
    {
2634
        $isUserAllowedToLogin = false;
2635
        $adminOnlyMode = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'];
2636
        // Backend user is allowed if adminOnly is not set or user is an admin:
2637
        if (!$adminOnlyMode || $this->isAdmin()) {
2638
            $isUserAllowedToLogin = true;
2639
        } elseif ($this->user['ses_backuserid']) {
2640
            $backendUserId = (int)$this->user['ses_backuserid'];
2641
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('be_users');
2642
            $isUserAllowedToLogin = (bool)$queryBuilder->count('uid')
2643
                ->from('be_users')
2644
                ->where(
2645
                    $queryBuilder->expr()->eq(
2646
                        'uid',
2647
                        $queryBuilder->createNamedParameter($backendUserId, \PDO::PARAM_INT)
2648
                    ),
2649
                    $queryBuilder->expr()->eq('admin', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT))
2650
                )
2651
                ->execute()
2652
                ->fetchColumn(0);
2653
        }
2654
        return $isUserAllowedToLogin;
2655
    }
2656
2657
    /**
2658
     * Logs out the current user and clears the form protection tokens.
2659
     */
2660
    public function logoff()
2661
    {
2662
        if (isset($GLOBALS['BE_USER'])
2663
            && $GLOBALS['BE_USER'] instanceof self
2664
            && isset($GLOBALS['BE_USER']->user['uid'])
2665
        ) {
2666
            FormProtectionFactory::get()->clean();
2667
            // Release the locked records
2668
            $this->releaseLockedRecords((int)$GLOBALS['BE_USER']->user['uid']);
2669
2670
            if ($this->isSystemMaintainer()) {
2671
                // If user is system maintainer, destroy its possibly valid install tool session.
2672
                $session = new SessionService();
2673
                if ($session->hasSession()) {
2674
                    $session->destroySession();
2675
                }
2676
            }
2677
        }
2678
        parent::logoff();
2679
    }
2680
2681
    /**
2682
     * Remove any "locked records" added for editing for the given user (= current backend user)
2683
     * @param int $userId
2684
     */
2685
    protected function releaseLockedRecords(int $userId)
2686
    {
2687
        if ($userId > 0) {
2688
            GeneralUtility::makeInstance(ConnectionPool::class)
2689
                ->getConnectionForTable('sys_lockedrecords')
2690
                ->delete(
2691
                    'sys_lockedrecords',
2692
                    ['userid' => $userId]
2693
                );
2694
        }
2695
    }
2696
}
2697