Completed
Push — master ( ba0ea8...c1bb75 )
by
unknown
25:13 queued 10:52
created

workspacePublishAccess()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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

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

1936
            $dbMountpoints = array_merge($workspaceWebMounts, /** @scrutinizer ignore-type */ $webMountsOfUser);
Loading history...
1937
            $dbMountpoints = array_unique($dbMountpoints);
1938
            foreach ($dbMountpoints as $mpId) {
1939
                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...
1940
                    $filteredDbMountpoints[] = $mpId;
1941
                }
1942
            }
1943
            // Re-insert webmounts
1944
            $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
1945
        }
1946
    }
1947
1948
    /**
1949
     * Checking if a workspace is allowed for backend user
1950
     *
1951
     * @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)
1952
     * @param string $fields List of fields to select. Default fields are all
1953
     * @return array Output will also show how access was granted. Admin users will have a true output regardless of input.
1954
     * @internal should only be used from within TYPO3 Core
1955
     */
1956
    public function checkWorkspace($wsRec, $fields = '*')
1957
    {
1958
        $retVal = false;
1959
        // If not array, look up workspace record:
1960
        if (!is_array($wsRec)) {
1961
            switch ((string)$wsRec) {
1962
                case '0':
1963
                    $wsRec = ['uid' => $wsRec];
1964
                    break;
1965
                default:
1966
                    if (ExtensionManagementUtility::isLoaded('workspaces')) {
1967
                        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
1968
                        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
1969
                        $wsRec = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields))
1970
                            ->from('sys_workspace')
1971
                            ->where($queryBuilder->expr()->eq(
1972
                                'uid',
1973
                                $queryBuilder->createNamedParameter($wsRec, \PDO::PARAM_INT)
1974
                            ))
1975
                            ->orderBy('title')
1976
                            ->setMaxResults(1)
1977
                            ->execute()
1978
                            ->fetch(\PDO::FETCH_ASSOC);
1979
                    }
1980
            }
1981
        }
1982
        // If wsRec is set to an array, evaluate it:
1983
        if (is_array($wsRec)) {
1984
            if ($this->isAdmin()) {
1985
                return array_merge($wsRec, ['_ACCESS' => 'admin']);
1986
            }
1987
            switch ((string)$wsRec['uid']) {
1988
                    case '0':
1989
                        $retVal = (($this->groupData['workspace_perms'] ?? 0) & 1)
1990
                            ? array_merge($wsRec, ['_ACCESS' => 'online'])
1991
                            : false;
1992
                        break;
1993
                    default:
1994
                        // Checking if the guy is admin:
1995
                        if (GeneralUtility::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
1996
                            return array_merge($wsRec, ['_ACCESS' => 'owner']);
1997
                        }
1998
                        // Checking if he is owner through a user group of his:
1999
                        foreach ($this->userGroupsUID as $groupUid) {
2000
                            if (GeneralUtility::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
2001
                                return array_merge($wsRec, ['_ACCESS' => 'owner']);
2002
                            }
2003
                        }
2004
                        // Checking if he is member as user:
2005
                        if (GeneralUtility::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
2006
                            return array_merge($wsRec, ['_ACCESS' => 'member']);
2007
                        }
2008
                        // Checking if he is member through a user group of his:
2009
                        foreach ($this->userGroupsUID as $groupUid) {
2010
                            if (GeneralUtility::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
2011
                                return array_merge($wsRec, ['_ACCESS' => 'member']);
2012
                            }
2013
                        }
2014
                }
2015
        }
2016
        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...
2017
    }
2018
2019
    /**
2020
     * Uses checkWorkspace() to check if current workspace is available for user.
2021
     * This function caches the result and so can be called many times with no performance loss.
2022
     *
2023
     * @return array See checkWorkspace()
2024
     * @see checkWorkspace()
2025
     * @internal should only be used from within TYPO3 Core
2026
     */
2027
    public function checkWorkspaceCurrent()
2028
    {
2029
        if (!isset($this->checkWorkspaceCurrent_cache)) {
2030
            $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
2031
        }
2032
        return $this->checkWorkspaceCurrent_cache;
2033
    }
2034
2035
    /**
2036
     * Setting workspace ID
2037
     *
2038
     * @param int $workspaceId ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
2039
     * @internal should only be used from within TYPO3 Core
2040
     */
2041
    public function setWorkspace($workspaceId)
2042
    {
2043
        // Check workspace validity and if not found, revert to default workspace.
2044
        if (!$this->setTemporaryWorkspace($workspaceId)) {
2045
            $this->setDefaultWorkspace();
2046
        }
2047
        // Unset access cache:
2048
        $this->checkWorkspaceCurrent_cache = null;
2049
        // If ID is different from the stored one, change it:
2050
        if ((int)$this->workspace !== (int)$this->user['workspace_id']) {
2051
            $this->user['workspace_id'] = $this->workspace;
2052
            GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
2053
                'be_users',
2054
                ['workspace_id' => $this->user['workspace_id']],
2055
                ['uid' => (int)$this->user['uid']]
2056
            );
2057
            $this->writelog(SystemLogType::EXTENSION, SystemLogGenericAction::UNDEFINED, SystemLogErrorClassification::MESSAGE, 0, 'User changed workspace to "' . $this->workspace . '"', []);
2058
        }
2059
    }
2060
2061
    /**
2062
     * Sets a temporary workspace in the context of the current backend user.
2063
     *
2064
     * @param int $workspaceId
2065
     * @return bool
2066
     * @internal should only be used from within TYPO3 Core
2067
     */
2068
    public function setTemporaryWorkspace($workspaceId)
2069
    {
2070
        $result = false;
2071
        $workspaceRecord = $this->checkWorkspace($workspaceId);
2072
2073
        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...
2074
            $this->workspaceRec = $workspaceRecord;
2075
            $this->workspace = (int)$workspaceId;
2076
            $result = true;
2077
        }
2078
2079
        return $result;
2080
    }
2081
2082
    /**
2083
     * Sets the default workspace in the context of the current backend user.
2084
     * @internal should only be used from within TYPO3 Core
2085
     */
2086
    public function setDefaultWorkspace()
2087
    {
2088
        $this->workspace = (int)$this->getDefaultWorkspace();
2089
        $this->workspaceRec = $this->checkWorkspace($this->workspace);
2090
    }
2091
2092
    /**
2093
     * Return default workspace ID for user,
2094
     * if EXT:workspaces is not installed the user will be pushed to the
2095
     * Live workspace, if he has access to. If no workspace is available for the user, the workspace ID is set to "-99"
2096
     *
2097
     * @return int Default workspace id.
2098
     * @internal should only be used from within TYPO3 Core
2099
     */
2100
    public function getDefaultWorkspace()
2101
    {
2102
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
2103
            return 0;
2104
        }
2105
        // Online is default
2106
        if ($this->checkWorkspace(0)) {
2107
            return 0;
2108
        }
2109
        // Otherwise -99 is the fallback
2110
        $defaultWorkspace = -99;
2111
        // Traverse all workspaces
2112
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2113
        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2114
        $result = $queryBuilder->select('*')
2115
            ->from('sys_workspace')
2116
            ->orderBy('title')
2117
            ->execute();
2118
        while ($workspaceRecord = $result->fetch()) {
2119
            if ($this->checkWorkspace($workspaceRecord)) {
2120
                $defaultWorkspace = (int)$workspaceRecord['uid'];
2121
                break;
2122
            }
2123
        }
2124
        return $defaultWorkspace;
2125
    }
2126
2127
    /**
2128
     * Writes an entry in the logfile/table
2129
     * Documentation in "TYPO3 Core API"
2130
     *
2131
     * @param int $type Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
2132
     * @param int $action Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
2133
     * @param int $error Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2134
     * @param int $details_nr The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
2135
     * @param string $details Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
2136
     * @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
2137
     * @param string $tablename Table name. Special field used by tce_main.php.
2138
     * @param int|string $recuid Record UID. Special field used by tce_main.php.
2139
     * @param int|string $recpid Record PID. Special field used by tce_main.php. OBSOLETE
2140
     * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
2141
     * @param string $NEWid Special field used by tce_main.php. NEWid string of newly created records.
2142
     * @param int $userId Alternative Backend User ID (used for logging login actions where this is not yet known).
2143
     * @return int Log entry ID.
2144
     */
2145
    public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0)
2146
    {
2147
        if (!$userId && !empty($this->user['uid'])) {
2148
            $userId = $this->user['uid'];
2149
        }
2150
2151
        if ($backuserid = $this->getOriginalUserIdWhenInSwitchUserMode()) {
2152
            if (empty($data)) {
2153
                $data = [];
2154
            }
2155
            $data['originalUser'] = $backuserid;
2156
        }
2157
2158
        $fields = [
2159
            'userid' => (int)$userId,
2160
            'type' => (int)$type,
2161
            'action' => (int)$action,
2162
            'error' => (int)$error,
2163
            'details_nr' => (int)$details_nr,
2164
            'details' => $details,
2165
            'log_data' => serialize($data),
2166
            'tablename' => $tablename,
2167
            'recuid' => (int)$recuid,
2168
            'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2169
            'tstamp' => $GLOBALS['EXEC_TIME'] ?? time(),
2170
            'event_pid' => (int)$event_pid,
2171
            'NEWid' => $NEWid,
2172
            'workspace' => $this->workspace
2173
        ];
2174
2175
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('sys_log');
2176
        $connection->insert(
2177
            'sys_log',
2178
            $fields,
2179
            [
2180
                \PDO::PARAM_INT,
2181
                \PDO::PARAM_INT,
2182
                \PDO::PARAM_INT,
2183
                \PDO::PARAM_INT,
2184
                \PDO::PARAM_INT,
2185
                \PDO::PARAM_STR,
2186
                \PDO::PARAM_STR,
2187
                \PDO::PARAM_STR,
2188
                \PDO::PARAM_INT,
2189
                \PDO::PARAM_STR,
2190
                \PDO::PARAM_INT,
2191
                \PDO::PARAM_INT,
2192
                \PDO::PARAM_STR,
2193
                \PDO::PARAM_STR,
2194
            ]
2195
        );
2196
2197
        return (int)$connection->lastInsertId('sys_log');
2198
    }
2199
2200
    /**
2201
     * Getter for the cookie name
2202
     *
2203
     * @static
2204
     * @return string returns the configured cookie name
2205
     */
2206
    public static function getCookieName()
2207
    {
2208
        $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
2209
        if (empty($configuredCookieName)) {
2210
            $configuredCookieName = 'be_typo_user';
2211
        }
2212
        return $configuredCookieName;
2213
    }
2214
2215
    /**
2216
     * Check if user is logged in and if so, call ->fetchGroupData() to load group information and
2217
     * access lists of all kind, further check IP, set the ->uc array.
2218
     * If no user is logged in the default behaviour is to exit with an error message.
2219
     * This function is called right after ->start() in fx. the TYPO3 Bootstrap.
2220
     *
2221
     * @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.
2222
     * @throws \RuntimeException
2223
     */
2224
    public function backendCheckLogin($proceedIfNoUserIsLoggedIn = false)
2225
    {
2226
        if (empty($this->user['uid'])) {
2227
            if ($proceedIfNoUserIsLoggedIn === false) {
2228
                $url = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir;
2229
                throw new ImmediateResponseException(new RedirectResponse($url, 303), 1607271747);
2230
            }
2231
        } else {
2232
            // ...and if that's the case, call these functions
2233
            $this->fetchGroupData();
2234
            // The groups are fetched and ready for permission checking in this initialization.
2235
            // Tables.php must be read before this because stuff like the modules has impact in this
2236
            if ($this->isUserAllowedToLogin()) {
2237
                // Setting the UC array. It's needed with fetchGroupData first, due to default/overriding of values.
2238
                $this->backendSetUC();
2239
                if ($this->loginSessionStarted) {
2240
                    // Also, if there is a recovery link set, unset it now
2241
                    // this will be moved into its own Event at a later stage.
2242
                    // If a token was set previously, this is now unset, as it was now possible to log-in
2243
                    if ($this->user['password_reset_token'] ?? '') {
2244
                        GeneralUtility::makeInstance(ConnectionPool::class)
2245
                            ->getConnectionForTable($this->user_table)
2246
                            ->update($this->user_table, ['password_reset_token' => ''], ['uid' => $this->user['uid']]);
2247
                    }
2248
                    // Process hooks
2249
                    $hooks = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['backendUserLogin'];
2250
                    foreach ($hooks ?? [] as $_funcRef) {
2251
                        $_params = ['user' => $this->user];
2252
                        GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2253
                    }
2254
                }
2255
            } else {
2256
                throw new \RuntimeException('Login Error: TYPO3 is in maintenance mode at the moment. Only administrators are allowed access.', 1294585860);
2257
            }
2258
        }
2259
    }
2260
2261
    /**
2262
     * Initialize the internal ->uc array for the backend user
2263
     * Will make the overrides if necessary, and write the UC back to the be_users record if changes has happened
2264
     *
2265
     * @internal
2266
     */
2267
    public function backendSetUC()
2268
    {
2269
        // UC - user configuration is a serialized array inside the user object
2270
        // If there is a saved uc we implement that instead of the default one.
2271
        $this->unpack_uc();
2272
        // Setting defaults if uc is empty
2273
        $updated = false;
2274
        $originalUc = [];
2275
        if (is_array($this->uc) && isset($this->uc['ucSetByInstallTool'])) {
2276
            $originalUc = $this->uc;
2277
            unset($originalUc['ucSetByInstallTool'], $this->uc);
2278
        }
2279
        if (!is_array($this->uc)) {
2280
            $this->uc = array_merge(
2281
                $this->uc_default,
2282
                (array)$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUC'],
2283
                GeneralUtility::removeDotsFromTS((array)($this->getTSConfig()['setup.']['default.'] ?? [])),
2284
                $originalUc
2285
            );
2286
            $this->overrideUC();
2287
            $updated = true;
2288
        }
2289
        // If TSconfig is updated, update the defaultUC.
2290
        if ($this->userTSUpdated) {
2291
            $this->overrideUC();
2292
            $updated = true;
2293
        }
2294
        // Setting default lang from be_user record.
2295
        if (!isset($this->uc['lang'])) {
2296
            $this->uc['lang'] = $this->user['lang'];
2297
            $updated = true;
2298
        }
2299
        // Setting the time of the first login:
2300
        if (!isset($this->uc['firstLoginTimeStamp'])) {
2301
            $this->uc['firstLoginTimeStamp'] = $GLOBALS['EXEC_TIME'];
2302
            $updated = true;
2303
        }
2304
        // Saving if updated.
2305
        if ($updated) {
2306
            $this->writeUC();
2307
        }
2308
    }
2309
2310
    /**
2311
     * Override: Call this function every time the uc is updated.
2312
     * That is 1) by reverting to default values, 2) in the setup-module, 3) userTS changes (userauthgroup)
2313
     *
2314
     * @internal
2315
     */
2316
    public function overrideUC()
2317
    {
2318
        $this->uc = array_merge((array)$this->uc, (array)($this->getTSConfig()['setup.']['override.'] ?? []));
2319
    }
2320
2321
    /**
2322
     * Clears the user[uc] and ->uc to blank strings. Then calls ->backendSetUC() to fill it again with reset contents
2323
     *
2324
     * @internal
2325
     */
2326
    public function resetUC()
2327
    {
2328
        $this->user['uc'] = '';
2329
        $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...
2330
        $this->backendSetUC();
2331
    }
2332
2333
    /**
2334
     * Determines whether a backend user is allowed to access the backend.
2335
     *
2336
     * The conditions are:
2337
     * + backend user is a regular user and adminOnly is not defined
2338
     * + backend user is an admin user
2339
     * + backend user is used in CLI context and adminOnly is explicitly set to "2" (see CommandLineUserAuthentication)
2340
     * + backend user is being controlled by an admin user
2341
     *
2342
     * @return bool Whether a backend user is allowed to access the backend
2343
     */
2344
    protected function isUserAllowedToLogin()
2345
    {
2346
        $isUserAllowedToLogin = false;
2347
        $adminOnlyMode = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'];
2348
        // Backend user is allowed if adminOnly is not set or user is an admin:
2349
        if (!$adminOnlyMode || $this->isAdmin()) {
2350
            $isUserAllowedToLogin = true;
2351
        } elseif ($backUserId = $this->getOriginalUserIdWhenInSwitchUserMode()) {
2352
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('be_users');
2353
            $isUserAllowedToLogin = (bool)$queryBuilder->count('uid')
2354
                ->from('be_users')
2355
                ->where(
2356
                    $queryBuilder->expr()->eq(
2357
                        'uid',
2358
                        $queryBuilder->createNamedParameter($backUserId, \PDO::PARAM_INT)
2359
                    ),
2360
                    $queryBuilder->expr()->eq('admin', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT))
2361
                )
2362
                ->execute()
2363
                ->fetchColumn(0);
2364
        }
2365
        return $isUserAllowedToLogin;
2366
    }
2367
2368
    /**
2369
     * Logs out the current user and clears the form protection tokens.
2370
     */
2371
    public function logoff()
2372
    {
2373
        if (isset($GLOBALS['BE_USER'])
2374
            && $GLOBALS['BE_USER'] instanceof self
2375
            && isset($GLOBALS['BE_USER']->user['uid'])
2376
        ) {
2377
            FormProtectionFactory::get()->clean();
2378
            // Release the locked records
2379
            $this->releaseLockedRecords((int)$GLOBALS['BE_USER']->user['uid']);
2380
2381
            if ($this->isSystemMaintainer()) {
2382
                // If user is system maintainer, destroy its possibly valid install tool session.
2383
                $session = new SessionService();
2384
                $session->destroySession();
2385
            }
2386
        }
2387
        parent::logoff();
2388
    }
2389
2390
    /**
2391
     * Remove any "locked records" added for editing for the given user (= current backend user)
2392
     * @param int $userId
2393
     */
2394
    protected function releaseLockedRecords(int $userId)
2395
    {
2396
        if ($userId > 0) {
2397
            GeneralUtility::makeInstance(ConnectionPool::class)
2398
                ->getConnectionForTable('sys_lockedrecords')
2399
                ->delete(
2400
                    'sys_lockedrecords',
2401
                    ['userid' => $userId]
2402
                );
2403
        }
2404
    }
2405
2406
    /**
2407
     * Returns the uid of the backend user to return to.
2408
     * This is set when the current session is a "switch-user" session.
2409
     *
2410
     * @return int|null The user id
2411
     * @internal should only be used from within TYPO3 Core
2412
     */
2413
    public function getOriginalUserIdWhenInSwitchUserMode(): ?int
2414
    {
2415
        $originalUserId = $this->getSessionData('backuserid');
2416
        return $originalUserId ? (int)$originalUserId : null;
2417
    }
2418
}
2419