Passed
Push — master ( 5782f4...90ca76 )
by
unknown
16:23
created

BackendUserAuthentication::checkLockToIP()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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

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

2052
            $dbMountpoints = array_merge($workspaceWebMounts, /** @scrutinizer ignore-type */ $webMountsOfUser);
Loading history...
2053
            $dbMountpoints = array_unique($dbMountpoints);
2054
            foreach ($dbMountpoints as $mpId) {
2055
                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...
2056
                    $filteredDbMountpoints[] = $mpId;
2057
                }
2058
            }
2059
            // Re-insert webmounts
2060
            $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
2061
        }
2062
    }
2063
2064
    /**
2065
     * Checking if a workspace is allowed for backend user
2066
     *
2067
     * @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)
2068
     * @param string $fields List of fields to select. Default fields are all
2069
     * @return array Output will also show how access was granted. Admin users will have a true output regardless of input.
2070
     * @internal should only be used from within TYPO3 Core
2071
     */
2072
    public function checkWorkspace($wsRec, $fields = '*')
2073
    {
2074
        $retVal = false;
2075
        // If not array, look up workspace record:
2076
        if (!is_array($wsRec)) {
2077
            switch ((string)$wsRec) {
2078
                case '0':
2079
                    $wsRec = ['uid' => $wsRec];
2080
                    break;
2081
                default:
2082
                    if (ExtensionManagementUtility::isLoaded('workspaces')) {
2083
                        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2084
                        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2085
                        $wsRec = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields))
2086
                            ->from('sys_workspace')
2087
                            ->where($queryBuilder->expr()->eq(
2088
                                'uid',
2089
                                $queryBuilder->createNamedParameter($wsRec, \PDO::PARAM_INT)
2090
                            ))
2091
                            ->orderBy('title')
2092
                            ->setMaxResults(1)
2093
                            ->execute()
2094
                            ->fetch(\PDO::FETCH_ASSOC);
2095
                    }
2096
            }
2097
        }
2098
        // If wsRec is set to an array, evaluate it:
2099
        if (is_array($wsRec)) {
2100
            if ($this->isAdmin()) {
2101
                return array_merge($wsRec, ['_ACCESS' => 'admin']);
2102
            }
2103
            switch ((string)$wsRec['uid']) {
2104
                    case '0':
2105
                        $retVal = (($this->groupData['workspace_perms'] ?? 0) & 1)
2106
                            ? array_merge($wsRec, ['_ACCESS' => 'online'])
2107
                            : false;
2108
                        break;
2109
                    default:
2110
                        // Checking if the guy is admin:
2111
                        if (GeneralUtility::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
2112
                            return array_merge($wsRec, ['_ACCESS' => 'owner']);
2113
                        }
2114
                        // Checking if he is owner through a user group of his:
2115
                        foreach ($this->userGroupsUID as $groupUid) {
2116
                            if (GeneralUtility::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
2117
                                return array_merge($wsRec, ['_ACCESS' => 'owner']);
2118
                            }
2119
                        }
2120
                        // Checking if he is member as user:
2121
                        if (GeneralUtility::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
2122
                            return array_merge($wsRec, ['_ACCESS' => 'member']);
2123
                        }
2124
                        // Checking if he is member through a user group of his:
2125
                        foreach ($this->userGroupsUID as $groupUid) {
2126
                            if (GeneralUtility::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
2127
                                return array_merge($wsRec, ['_ACCESS' => 'member']);
2128
                            }
2129
                        }
2130
                }
2131
        }
2132
        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...
2133
    }
2134
2135
    /**
2136
     * Uses checkWorkspace() to check if current workspace is available for user.
2137
     * This function caches the result and so can be called many times with no performance loss.
2138
     *
2139
     * @return array See checkWorkspace()
2140
     * @see checkWorkspace()
2141
     * @internal should only be used from within TYPO3 Core
2142
     */
2143
    public function checkWorkspaceCurrent()
2144
    {
2145
        if (!isset($this->checkWorkspaceCurrent_cache)) {
2146
            $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
2147
        }
2148
        return $this->checkWorkspaceCurrent_cache;
2149
    }
2150
2151
    /**
2152
     * Setting workspace ID
2153
     *
2154
     * @param int $workspaceId ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
2155
     * @internal should only be used from within TYPO3 Core
2156
     */
2157
    public function setWorkspace($workspaceId)
2158
    {
2159
        // Check workspace validity and if not found, revert to default workspace.
2160
        if (!$this->setTemporaryWorkspace($workspaceId)) {
2161
            $this->setDefaultWorkspace();
2162
        }
2163
        // Unset access cache:
2164
        $this->checkWorkspaceCurrent_cache = null;
2165
        // If ID is different from the stored one, change it:
2166
        if ((int)$this->workspace !== (int)$this->user['workspace_id']) {
2167
            $this->user['workspace_id'] = $this->workspace;
2168
            GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
2169
                'be_users',
2170
                ['workspace_id' => $this->user['workspace_id']],
2171
                ['uid' => (int)$this->user['uid']]
2172
            );
2173
            $this->writelog(SystemLogType::EXTENSION, SystemLogGenericAction::UNDEFINED, SystemLogErrorClassification::MESSAGE, 0, 'User changed workspace to "' . $this->workspace . '"', []);
2174
        }
2175
    }
2176
2177
    /**
2178
     * Sets a temporary workspace in the context of the current backend user.
2179
     *
2180
     * @param int $workspaceId
2181
     * @return bool
2182
     * @internal should only be used from within TYPO3 Core
2183
     */
2184
    public function setTemporaryWorkspace($workspaceId)
2185
    {
2186
        $result = false;
2187
        $workspaceRecord = $this->checkWorkspace($workspaceId);
2188
2189
        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...
2190
            $this->workspaceRec = $workspaceRecord;
2191
            $this->workspace = (int)$workspaceId;
2192
            $result = true;
2193
        }
2194
2195
        return $result;
2196
    }
2197
2198
    /**
2199
     * Sets the default workspace in the context of the current backend user.
2200
     * @internal should only be used from within TYPO3 Core
2201
     */
2202
    public function setDefaultWorkspace()
2203
    {
2204
        $this->workspace = (int)$this->getDefaultWorkspace();
2205
        $this->workspaceRec = $this->checkWorkspace($this->workspace);
2206
    }
2207
2208
    /**
2209
     * Return default workspace ID for user,
2210
     * if EXT:workspaces is not installed the user will be pushed to the
2211
     * Live workspace, if he has access to. If no workspace is available for the user, the workspace ID is set to "-99"
2212
     *
2213
     * @return int Default workspace id.
2214
     * @internal should only be used from within TYPO3 Core
2215
     */
2216
    public function getDefaultWorkspace()
2217
    {
2218
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
2219
            return 0;
2220
        }
2221
        // Online is default
2222
        if ($this->checkWorkspace(0)) {
2223
            return 0;
2224
        }
2225
        // Otherwise -99 is the fallback
2226
        $defaultWorkspace = -99;
2227
        // Traverse all workspaces
2228
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2229
        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2230
        $result = $queryBuilder->select('*')
2231
            ->from('sys_workspace')
2232
            ->orderBy('title')
2233
            ->execute();
2234
        while ($workspaceRecord = $result->fetch()) {
2235
            if ($this->checkWorkspace($workspaceRecord)) {
2236
                $defaultWorkspace = (int)$workspaceRecord['uid'];
2237
                break;
2238
            }
2239
        }
2240
        return $defaultWorkspace;
2241
    }
2242
2243
    /**
2244
     * Writes an entry in the logfile/table
2245
     * Documentation in "TYPO3 Core API"
2246
     *
2247
     * @param int $type Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
2248
     * @param int $action Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
2249
     * @param int $error Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2250
     * @param int $details_nr The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
2251
     * @param string $details Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
2252
     * @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
2253
     * @param string $tablename Table name. Special field used by tce_main.php.
2254
     * @param int|string $recuid Record UID. Special field used by tce_main.php.
2255
     * @param int|string $recpid Record PID. Special field used by tce_main.php. OBSOLETE
2256
     * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
2257
     * @param string $NEWid Special field used by tce_main.php. NEWid string of newly created records.
2258
     * @param int $userId Alternative Backend User ID (used for logging login actions where this is not yet known).
2259
     * @return int Log entry ID.
2260
     */
2261
    public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0)
2262
    {
2263
        if (!$userId && !empty($this->user['uid'])) {
2264
            $userId = $this->user['uid'];
2265
        }
2266
2267
        if (!empty($this->user['ses_backuserid'])) {
2268
            if (empty($data)) {
2269
                $data = [];
2270
            }
2271
            $data['originalUser'] = $this->user['ses_backuserid'];
2272
        }
2273
2274
        $fields = [
2275
            'userid' => (int)$userId,
2276
            'type' => (int)$type,
2277
            'action' => (int)$action,
2278
            'error' => (int)$error,
2279
            'details_nr' => (int)$details_nr,
2280
            'details' => $details,
2281
            'log_data' => serialize($data),
2282
            'tablename' => $tablename,
2283
            'recuid' => (int)$recuid,
2284
            'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2285
            'tstamp' => $GLOBALS['EXEC_TIME'] ?? time(),
2286
            'event_pid' => (int)$event_pid,
2287
            'NEWid' => $NEWid,
2288
            'workspace' => $this->workspace
2289
        ];
2290
2291
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('sys_log');
2292
        $connection->insert(
2293
            'sys_log',
2294
            $fields,
2295
            [
2296
                \PDO::PARAM_INT,
2297
                \PDO::PARAM_INT,
2298
                \PDO::PARAM_INT,
2299
                \PDO::PARAM_INT,
2300
                \PDO::PARAM_INT,
2301
                \PDO::PARAM_STR,
2302
                \PDO::PARAM_STR,
2303
                \PDO::PARAM_STR,
2304
                \PDO::PARAM_INT,
2305
                \PDO::PARAM_STR,
2306
                \PDO::PARAM_INT,
2307
                \PDO::PARAM_INT,
2308
                \PDO::PARAM_STR,
2309
                \PDO::PARAM_STR,
2310
            ]
2311
        );
2312
2313
        return (int)$connection->lastInsertId('sys_log');
2314
    }
2315
2316
    /**
2317
     * Getter for the cookie name
2318
     *
2319
     * @static
2320
     * @return string returns the configured cookie name
2321
     */
2322
    public static function getCookieName()
2323
    {
2324
        $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
2325
        if (empty($configuredCookieName)) {
2326
            $configuredCookieName = 'be_typo_user';
2327
        }
2328
        return $configuredCookieName;
2329
    }
2330
2331
    /**
2332
     * Check if user is logged in and if so, call ->fetchGroupData() to load group information and
2333
     * access lists of all kind, further check IP, set the ->uc array.
2334
     * If no user is logged in the default behaviour is to exit with an error message.
2335
     * This function is called right after ->start() in fx. the TYPO3 Bootstrap.
2336
     *
2337
     * @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.
2338
     * @throws \RuntimeException
2339
     */
2340
    public function backendCheckLogin($proceedIfNoUserIsLoggedIn = false)
2341
    {
2342
        if (empty($this->user['uid'])) {
2343
            if ($proceedIfNoUserIsLoggedIn === false) {
2344
                $url = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir;
2345
                HttpUtility::redirect($url);
2346
            }
2347
        } else {
2348
            // ...and if that's the case, call these functions
2349
            $this->fetchGroupData();
2350
            // The groups are fetched and ready for permission checking in this initialization.
2351
            // Tables.php must be read before this because stuff like the modules has impact in this
2352
            if ($this->isUserAllowedToLogin()) {
2353
                // Setting the UC array. It's needed with fetchGroupData first, due to default/overriding of values.
2354
                $this->backendSetUC();
2355
                if ($this->loginSessionStarted) {
2356
                    // Also, if there is a recovery link set, unset it now
2357
                    // this will be moved into its own Event at a later stage.
2358
                    // If a token was set previously, this is now unset, as it was now possible to log-in
2359
                    if ($this->user['password_reset_token'] ?? '') {
2360
                        GeneralUtility::makeInstance(ConnectionPool::class)
2361
                            ->getConnectionForTable($this->user_table)
2362
                            ->update($this->user_table, ['password_reset_token' => ''], ['uid' => $this->user['uid']]);
2363
                    }
2364
                    // Process hooks
2365
                    $hooks = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['backendUserLogin'];
2366
                    foreach ($hooks ?? [] as $_funcRef) {
2367
                        $_params = ['user' => $this->user];
2368
                        GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2369
                    }
2370
                }
2371
            } else {
2372
                throw new \RuntimeException('Login Error: TYPO3 is in maintenance mode at the moment. Only administrators are allowed access.', 1294585860);
2373
            }
2374
        }
2375
    }
2376
2377
    /**
2378
     * Initialize the internal ->uc array for the backend user
2379
     * Will make the overrides if necessary, and write the UC back to the be_users record if changes has happened
2380
     *
2381
     * @internal
2382
     */
2383
    public function backendSetUC()
2384
    {
2385
        // UC - user configuration is a serialized array inside the user object
2386
        // If there is a saved uc we implement that instead of the default one.
2387
        $this->unpack_uc();
2388
        // Setting defaults if uc is empty
2389
        $updated = false;
2390
        $originalUc = [];
2391
        if (is_array($this->uc) && isset($this->uc['ucSetByInstallTool'])) {
2392
            $originalUc = $this->uc;
2393
            unset($originalUc['ucSetByInstallTool'], $this->uc);
2394
        }
2395
        if (!is_array($this->uc)) {
2396
            $this->uc = array_merge(
2397
                $this->uc_default,
2398
                (array)$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUC'],
2399
                GeneralUtility::removeDotsFromTS((array)($this->getTSConfig()['setup.']['default.'] ?? [])),
2400
                $originalUc
2401
            );
2402
            $this->overrideUC();
2403
            $updated = true;
2404
        }
2405
        // If TSconfig is updated, update the defaultUC.
2406
        if ($this->userTSUpdated) {
2407
            $this->overrideUC();
2408
            $updated = true;
2409
        }
2410
        // Setting default lang from be_user record.
2411
        if (!isset($this->uc['lang'])) {
2412
            $this->uc['lang'] = $this->user['lang'];
2413
            $updated = true;
2414
        }
2415
        // Setting the time of the first login:
2416
        if (!isset($this->uc['firstLoginTimeStamp'])) {
2417
            $this->uc['firstLoginTimeStamp'] = $GLOBALS['EXEC_TIME'];
2418
            $updated = true;
2419
        }
2420
        // Saving if updated.
2421
        if ($updated) {
2422
            $this->writeUC();
2423
        }
2424
    }
2425
2426
    /**
2427
     * Override: Call this function every time the uc is updated.
2428
     * That is 1) by reverting to default values, 2) in the setup-module, 3) userTS changes (userauthgroup)
2429
     *
2430
     * @internal
2431
     */
2432
    public function overrideUC()
2433
    {
2434
        $this->uc = array_merge((array)$this->uc, (array)($this->getTSConfig()['setup.']['override.'] ?? []));
2435
    }
2436
2437
    /**
2438
     * Clears the user[uc] and ->uc to blank strings. Then calls ->backendSetUC() to fill it again with reset contents
2439
     *
2440
     * @internal
2441
     */
2442
    public function resetUC()
2443
    {
2444
        $this->user['uc'] = '';
2445
        $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...
2446
        $this->backendSetUC();
2447
    }
2448
2449
    /**
2450
     * Determines whether a backend user is allowed to access the backend.
2451
     *
2452
     * The conditions are:
2453
     * + backend user is a regular user and adminOnly is not defined
2454
     * + backend user is an admin user
2455
     * + backend user is used in CLI context and adminOnly is explicitly set to "2" (see CommandLineUserAuthentication)
2456
     * + backend user is being controlled by an admin user
2457
     *
2458
     * @return bool Whether a backend user is allowed to access the backend
2459
     */
2460
    protected function isUserAllowedToLogin()
2461
    {
2462
        $isUserAllowedToLogin = false;
2463
        $adminOnlyMode = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'];
2464
        // Backend user is allowed if adminOnly is not set or user is an admin:
2465
        if (!$adminOnlyMode || $this->isAdmin()) {
2466
            $isUserAllowedToLogin = true;
2467
        } elseif ($this->user['ses_backuserid']) {
2468
            $backendUserId = (int)$this->user['ses_backuserid'];
2469
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('be_users');
2470
            $isUserAllowedToLogin = (bool)$queryBuilder->count('uid')
2471
                ->from('be_users')
2472
                ->where(
2473
                    $queryBuilder->expr()->eq(
2474
                        'uid',
2475
                        $queryBuilder->createNamedParameter($backendUserId, \PDO::PARAM_INT)
2476
                    ),
2477
                    $queryBuilder->expr()->eq('admin', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT))
2478
                )
2479
                ->execute()
2480
                ->fetchColumn(0);
2481
        }
2482
        return $isUserAllowedToLogin;
2483
    }
2484
2485
    /**
2486
     * Logs out the current user and clears the form protection tokens.
2487
     */
2488
    public function logoff()
2489
    {
2490
        if (isset($GLOBALS['BE_USER'])
2491
            && $GLOBALS['BE_USER'] instanceof self
2492
            && isset($GLOBALS['BE_USER']->user['uid'])
2493
        ) {
2494
            FormProtectionFactory::get()->clean();
2495
            // Release the locked records
2496
            $this->releaseLockedRecords((int)$GLOBALS['BE_USER']->user['uid']);
2497
2498
            if ($this->isSystemMaintainer()) {
2499
                // If user is system maintainer, destroy its possibly valid install tool session.
2500
                $session = new SessionService();
2501
                $session->destroySession();
2502
            }
2503
        }
2504
        parent::logoff();
2505
    }
2506
2507
    /**
2508
     * Remove any "locked records" added for editing for the given user (= current backend user)
2509
     * @param int $userId
2510
     */
2511
    protected function releaseLockedRecords(int $userId)
2512
    {
2513
        if ($userId > 0) {
2514
            GeneralUtility::makeInstance(ConnectionPool::class)
2515
                ->getConnectionForTable('sys_lockedrecords')
2516
                ->delete(
2517
                    'sys_lockedrecords',
2518
                    ['userid' => $userId]
2519
                );
2520
        }
2521
    }
2522
}
2523