[TASK] Protect user TSconfig properties in BackendUserAuthentication
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Authentication / BackendUserAuthentication.php
1 <?php
2 namespace TYPO3\CMS\Core\Authentication;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Cache\CacheManager;
19 use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait;
20 use TYPO3\CMS\Core\Database\Connection;
21 use TYPO3\CMS\Core\Database\ConnectionPool;
22 use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
23 use TYPO3\CMS\Core\Database\Query\QueryHelper;
24 use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
25 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
26 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
27 use TYPO3\CMS\Core\Database\Query\Restriction\RootLevelRestriction;
28 use TYPO3\CMS\Core\Resource\ResourceStorage;
29 use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
30 use TYPO3\CMS\Core\Type\Bitmask\Permission;
31 use TYPO3\CMS\Core\Type\Exception\InvalidEnumerationValueException;
32 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
33 use TYPO3\CMS\Core\Utility\GeneralUtility;
34
35 /**
36 * TYPO3 backend user authentication
37 * Contains most of the functions used for checking permissions, authenticating users,
38 * setting up the user, and API for user from outside.
39 * This class contains the configuration of the database fields used plus some
40 * functions for the authentication process of backend users.
41 */
42 class BackendUserAuthentication extends AbstractUserAuthentication
43 {
44 use PublicPropertyDeprecationTrait;
45
46 public const ROLE_SYSTEMMAINTAINER = 'systemMaintainer';
47
48 /**
49 * Properties which have been moved to protected status from public
50 *
51 * @var array
52 */
53 protected $deprecatedPublicProperties = [
54 'TSdataArray' => 'Using $TSdataArray of class BackendUserAuthentication from the outside is discouraged. This property is for class internal use only.',
55 'userTS' => 'Using $userTS of class BackendUserAuthentication from the outside is discouraged. Use getTSConfig() instead.',
56 'userTSUpdated' => 'Using $userTSUpdated of class BackendUserAuthentication from the outside is discouraged. This property is for class internal use only.',
57 'userTS_text' => 'Using $userTS_text of class BackendUserAuthentication from the outside is discouraged. This property is for class internal use only.',
58 'userTS_dontGetCached' => 'Using $userTS_dontGetCached of class BackendUserAuthentication is deprecated. The property will be removed in v10.',
59 ];
60
61 /**
62 * Should be set to the usergroup-column (id-list) in the user-record
63 * @var string
64 */
65 public $usergroup_column = 'usergroup';
66
67 /**
68 * The name of the group-table
69 * @var string
70 */
71 public $usergroup_table = 'be_groups';
72
73 /**
74 * holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
75 * @var array
76 * @internal
77 */
78 public $groupData = [
79 'filemounts' => []
80 ];
81
82 /**
83 * This array will hold the groups that the user is a member of
84 * @var array
85 */
86 public $userGroups = [];
87
88 /**
89 * This array holds the uid's of the groups in the listed order
90 * @var array
91 */
92 public $userGroupsUID = [];
93
94 /**
95 * This is $this->userGroupsUID imploded to a comma list... Will correspond to the 'usergroup_cached_list'
96 * @var string
97 */
98 public $groupList = '';
99
100 /**
101 * User workspace.
102 * -99 is ERROR (none available)
103 * 0 is online
104 * >0 is custom workspaces
105 * @var int
106 */
107 public $workspace = -99;
108
109 /**
110 * Custom workspace record if any
111 * @var array
112 */
113 public $workspaceRec = [];
114
115 /**
116 * Used to accumulate data for the user-group.
117 * DON NOT USE THIS EXTERNALLY!
118 * Use $this->groupData instead
119 * @var array
120 * @internal
121 */
122 public $dataLists = [
123 'webmount_list' => '',
124 'filemount_list' => '',
125 'file_permissions' => '',
126 'modList' => '',
127 'tables_select' => '',
128 'tables_modify' => '',
129 'pagetypes_select' => '',
130 'non_exclude_fields' => '',
131 'explicit_allowdeny' => '',
132 'allowed_languages' => '',
133 'workspace_perms' => '',
134 'custom_options' => ''
135 ];
136
137 /**
138 * List of group_id's in the order they are processed.
139 * @var array
140 */
141 public $includeGroupArray = [];
142
143 /**
144 * @var array Accumulated, unparsed TSconfig data array of the user
145 */
146 protected $TSdataArray = [];
147
148 /**
149 * @var string Accumulated, unparsed TSconfig data string of the user
150 */
151 protected $userTS_text = '';
152
153 /**
154 * @var array Parsed user TSconfig
155 */
156 protected $userTS = [];
157
158 /**
159 * @var bool True if the user TSconfig was parsed and needs to be cached.
160 */
161 protected $userTSUpdated = false;
162
163 /**
164 * @var bool @deprecated since v9, will be removed in v10. If true, parsed TSconfig will not be cached
165 */
166 protected $userTS_dontGetCached = false;
167
168 /**
169 * Contains last error message
170 * @var string
171 */
172 public $errorMsg = '';
173
174 /**
175 * Cache for checkWorkspaceCurrent()
176 * @var array|null
177 */
178 public $checkWorkspaceCurrent_cache = null;
179
180 /**
181 * @var \TYPO3\CMS\Core\Resource\ResourceStorage[]
182 */
183 protected $fileStorages;
184
185 /**
186 * @var array
187 */
188 protected $filePermissions;
189
190 /**
191 * Table in database with user data
192 * @var string
193 */
194 public $user_table = 'be_users';
195
196 /**
197 * Column for login-name
198 * @var string
199 */
200 public $username_column = 'username';
201
202 /**
203 * Column for password
204 * @var string
205 */
206 public $userident_column = 'password';
207
208 /**
209 * Column for user-id
210 * @var string
211 */
212 public $userid_column = 'uid';
213
214 /**
215 * @var string
216 */
217 public $lastLogin_column = 'lastlogin';
218
219 /**
220 * @var array
221 */
222 public $enablecolumns = [
223 'rootLevel' => 1,
224 'deleted' => 'deleted',
225 'disabled' => 'disable',
226 'starttime' => 'starttime',
227 'endtime' => 'endtime'
228 ];
229
230 /**
231 * Form field with login-name
232 * @var string
233 */
234 public $formfield_uname = 'username';
235
236 /**
237 * Form field with password
238 * @var string
239 */
240 public $formfield_uident = 'userident';
241
242 /**
243 * Form field with status: *'login', 'logout'
244 * @var string
245 */
246 public $formfield_status = 'login_status';
247
248 /**
249 * Decides if the writelog() function is called at login and logout
250 * @var bool
251 */
252 public $writeStdLog = true;
253
254 /**
255 * If the writelog() functions is called if a login-attempt has be tried without success
256 * @var bool
257 */
258 public $writeAttemptLog = true;
259
260 /**
261 * Session timeout (on the server), defaults to 8 hours for backend user
262 *
263 * If >0: session-timeout in seconds.
264 * If <=0: Instant logout after login.
265 * The value must be at least 180 to avoid side effects.
266 *
267 * @var int
268 */
269 public $sessionTimeout = 28800;
270
271 /**
272 * @var int
273 */
274 public $firstMainGroup = 0;
275
276 /**
277 * User Config
278 * @var array
279 */
280 public $uc;
281
282 /**
283 * User Config Default values:
284 * The array may contain other fields for configuration.
285 * For this, see "setup" extension and "TSConfig" document (User TSconfig, "setup.[xxx]....")
286 * Reserved keys for other storage of session data:
287 * moduleData
288 * moduleSessionID
289 * @var array
290 */
291 public $uc_default = [
292 'interfaceSetup' => '',
293 // serialized content that is used to store interface pane and menu positions. Set by the logout.php-script
294 'moduleData' => [],
295 // user-data for the modules
296 'thumbnailsByDefault' => 1,
297 'emailMeAtLogin' => 0,
298 'startModule' => 'help_AboutAbout',
299 'titleLen' => 50,
300 'edit_RTE' => '1',
301 'edit_docModuleUpload' => '1',
302 'resizeTextareas' => 1,
303 'resizeTextareas_MaxHeight' => 500,
304 'resizeTextareas_Flexible' => 0
305 ];
306
307 /**
308 * Constructor
309 */
310 public function __construct()
311 {
312 parent::__construct();
313 $this->name = self::getCookieName();
314 $this->loginType = 'BE';
315 $this->warningEmail = $GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'];
316 $this->lockIP = $GLOBALS['TYPO3_CONF_VARS']['BE']['lockIP'];
317 $this->sessionTimeout = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['sessionTimeout'];
318 }
319
320 /**
321 * Returns TRUE if user is admin
322 * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
323 *
324 * @return bool
325 */
326 public function isAdmin()
327 {
328 return is_array($this->user) && ($this->user['admin'] & 1) == 1;
329 }
330
331 /**
332 * Returns TRUE if the current user is a member of group $groupId
333 * $groupId must be set. $this->groupList must contain groups
334 * Will return TRUE also if the user is a member of a group through subgroups.
335 *
336 * @param int $groupId Group ID to look for in $this->groupList
337 * @return bool
338 */
339 public function isMemberOfGroup($groupId)
340 {
341 $groupId = (int)$groupId;
342 if ($this->groupList && $groupId) {
343 return GeneralUtility::inList($this->groupList, $groupId);
344 }
345 return false;
346 }
347
348 /**
349 * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
350 *
351 * Bits for permissions, see $perms variable:
352 *
353 * 1 - Show: See/Copy page and the pagecontent.
354 * 16- Edit pagecontent: Change/Add/Delete/Move pagecontent.
355 * 2- Edit page: Change/Move the page, eg. change title, startdate, hidden.
356 * 4- Delete page: Delete the page and pagecontent.
357 * 8- New pages: Create new pages under the page.
358 *
359 * @param array $row Is the pagerow for which the permissions is checked
360 * @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.
361 * @return bool
362 */
363 public function doesUserHaveAccess($row, $perms)
364 {
365 $userPerms = $this->calcPerms($row);
366 return ($userPerms & $perms) == $perms;
367 }
368
369 /**
370 * Checks if the page id, $id, is found within the webmounts set up for the user.
371 * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
372 * The point is that this will add the security that a user can NEVER touch parts outside his mounted
373 * pages in the page tree. This is otherwise possible if the raw page permissions allows for it.
374 * So this security check just makes it easier to make safe user configurations.
375 * If the user is admin OR if this feature is disabled
376 * (fx. by setting TYPO3_CONF_VARS['BE']['lockBeUserToDBmounts']=0) then it returns "1" right away
377 * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
378 *
379 * @param int $id Page ID to check
380 * @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!)
381 * @param bool|int $exitOnError If set, then the function will exit with an error message.
382 * @throws \RuntimeException
383 * @return int|null The page UID of a page in the rootline that matched a mount point
384 */
385 public function isInWebMount($id, $readPerms = '', $exitOnError = 0)
386 {
387 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['lockBeUserToDBmounts'] || $this->isAdmin()) {
388 return 1;
389 }
390 $id = (int)$id;
391 // Check if input id is an offline version page in which case we will map id to the online version:
392 $checkRec = BackendUtility::getRecord('pages', $id, 'pid,t3ver_oid');
393 if ($checkRec['pid'] == -1) {
394 $id = (int)$checkRec['t3ver_oid'];
395 }
396 if (!$readPerms) {
397 $readPerms = $this->getPagePermsClause(Permission::PAGE_SHOW);
398 }
399 if ($id > 0) {
400 $wM = $this->returnWebmounts();
401 $rL = BackendUtility::BEgetRootLine($id, ' AND ' . $readPerms);
402 foreach ($rL as $v) {
403 if ($v['uid'] && in_array($v['uid'], $wM)) {
404 return $v['uid'];
405 }
406 }
407 }
408 if ($exitOnError) {
409 throw new \RuntimeException('Access Error: This page is not within your DB-mounts', 1294586445);
410 }
411 return null;
412 }
413
414 /**
415 * Checks access to a backend module with the $MCONF passed as first argument
416 *
417 * @param array $conf $MCONF array of a backend module!
418 * @param bool $exitOnError If set, an array will issue an error message and exit.
419 * @throws \RuntimeException
420 * @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
421 */
422 public function modAccess($conf, $exitOnError)
423 {
424 if (!BackendUtility::isModuleSetInTBE_MODULES($conf['name'])) {
425 if ($exitOnError) {
426 throw new \RuntimeException('Fatal Error: This module "' . $conf['name'] . '" is not enabled in TBE_MODULES', 1294586446);
427 }
428 return false;
429 }
430 // Workspaces check:
431 if (
432 !empty($conf['workspaces'])
433 && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')
434 && ($this->workspace !== 0 || !GeneralUtility::inList($conf['workspaces'], 'online'))
435 && ($this->workspace !== -1 || !GeneralUtility::inList($conf['workspaces'], 'offline'))
436 && ($this->workspace <= 0 || !GeneralUtility::inList($conf['workspaces'], 'custom'))
437 ) {
438 if ($exitOnError) {
439 throw new \RuntimeException('Workspace Error: This module "' . $conf['name'] . '" is not available under the current workspace', 1294586447);
440 }
441 return false;
442 }
443 // Returns false if conf[access] is set to system maintainers and the user is system maintainer
444 if (strpos($conf['access'], self::ROLE_SYSTEMMAINTAINER) !== false && !$this->isSystemMaintainer()) {
445 if ($exitOnError) {
446 throw new \RuntimeException('This module "' . $conf['name'] . '" is only available as system maintainer', 1504804727);
447 }
448 return false;
449 }
450 // Returns TRUE if conf[access] is not set at all or if the user is admin
451 if (!$conf['access'] || $this->isAdmin()) {
452 return true;
453 }
454 // If $conf['access'] is set but not with 'admin' then we return TRUE, if the module is found in the modList
455 $acs = false;
456 if (!strstr($conf['access'], 'admin') && $conf['name']) {
457 $acs = $this->check('modules', $conf['name']);
458 }
459 if (!$acs && $exitOnError) {
460 throw new \RuntimeException('Access Error: You don\'t have access to this module.', 1294586448);
461 }
462 return $acs;
463 }
464
465 /**
466 * Checks if the user is in the valid list of allowed system maintainers. if the list is not set,
467 * then all admins are system maintainers. If the list is empty, no one is system maintainer (good for production
468 * systems). If the currently logged in user is in "switch user" mode, this method will return false.
469 *
470 * @return bool
471 */
472 public function isSystemMaintainer(): bool
473 {
474 if ((int)$GLOBALS['BE_USER']->user['ses_backuserid'] !== 0) {
475 return false;
476 }
477 if (GeneralUtility::getApplicationContext()->isDevelopment() && $this->isAdmin()) {
478 return true;
479 }
480 $systemMaintainers = $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? [];
481 $systemMaintainers = array_map('intval', $systemMaintainers);
482 if (!empty($systemMaintainers)) {
483 return in_array((int)$this->user['uid'], $systemMaintainers, true);
484 }
485 // No system maintainers set up yet, so any admin is allowed to access the modules
486 // but explicitly no system maintainers allowed (empty string in TYPO3_CONF_VARS).
487 // @todo: this needs to be adjusted once system maintainers can log into the install tool with their credentials
488 if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'])
489 && empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'])) {
490 return false;
491 }
492 return $this->isAdmin();
493 }
494
495 /**
496 * If a user has actually logged in and switched to a different user (admins can use the SU switch user method)
497 * the real UID is sometimes needed (when checking for permissions for example).
498 */
499 protected function getRealUserId(): int
500 {
501 return (int)($GLOBALS['BE_USER']->user['ses_backuserid'] ?: $this->user['uid']);
502 }
503
504 /**
505 * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
506 * $perms is the "mask" used to select. Fx. if $perms is 1 then you'll get all pages that a user can actually see!
507 * 2^0 = show (1)
508 * 2^1 = edit (2)
509 * 2^2 = delete (4)
510 * 2^3 = new (8)
511 * If the user is 'admin' " 1=1" is returned (no effect)
512 * 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)
513 * The 95% use of this function is "->getPagePermsClause(1)" which will
514 * return WHERE clauses for *selecting* pages in backend listings - in other words this will check read permissions.
515 *
516 * @param int $perms Permission mask to use, see function description
517 * @return string Part of where clause. Prefix " AND " to this.
518 */
519 public function getPagePermsClause($perms)
520 {
521 if (is_array($this->user)) {
522 if ($this->isAdmin()) {
523 return ' 1=1';
524 }
525 // Make sure it's integer.
526 $perms = (int)$perms;
527 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
528 ->getQueryBuilderForTable('pages')
529 ->expr();
530
531 // User
532 $constraint = $expressionBuilder->orX(
533 $expressionBuilder->comparison(
534 $expressionBuilder->bitAnd('pages.perms_everybody', $perms),
535 ExpressionBuilder::EQ,
536 $perms
537 ),
538 $expressionBuilder->andX(
539 $expressionBuilder->eq('pages.perms_userid', (int)$this->user['uid']),
540 $expressionBuilder->comparison(
541 $expressionBuilder->bitAnd('pages.perms_user', $perms),
542 ExpressionBuilder::EQ,
543 $perms
544 )
545 )
546 );
547
548 // Group (if any is set)
549 if ($this->groupList) {
550 $constraint->add(
551 $expressionBuilder->andX(
552 $expressionBuilder->in(
553 'pages.perms_groupid',
554 GeneralUtility::intExplode(',', $this->groupList)
555 ),
556 $expressionBuilder->comparison(
557 $expressionBuilder->bitAnd('pages.perms_group', $perms),
558 ExpressionBuilder::EQ,
559 $perms
560 )
561 )
562 );
563 }
564
565 $constraint = ' (' . (string)$constraint . ')';
566
567 // ****************
568 // getPagePermsClause-HOOK
569 // ****************
570 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'] ?? [] as $_funcRef) {
571 $_params = ['currentClause' => $constraint, 'perms' => $perms];
572 $constraint = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
573 }
574 return $constraint;
575 }
576 return ' 1=0';
577 }
578
579 /**
580 * Returns a combined binary representation of the current users permissions for the page-record, $row.
581 * The perms for user, group and everybody is OR'ed together (provided that the page-owner is the user
582 * and for the groups that the user is a member of the group.
583 * If the user is admin, 31 is returned (full permissions for all five flags)
584 *
585 * @param array $row Input page row with all perms_* fields available.
586 * @return int Bitwise representation of the users permissions in relation to input page row, $row
587 */
588 public function calcPerms($row)
589 {
590 // Return 31 for admin users.
591 if ($this->isAdmin()) {
592 return Permission::ALL;
593 }
594 // Return 0 if page is not within the allowed web mount
595 // Always do this for the default language page record
596 if (!$this->isInWebMount($row[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] ?: $row['uid'])) {
597 return Permission::NOTHING;
598 }
599 $out = Permission::NOTHING;
600 if (
601 isset($row['perms_userid']) && isset($row['perms_user']) && isset($row['perms_groupid'])
602 && isset($row['perms_group']) && isset($row['perms_everybody']) && isset($this->groupList)
603 ) {
604 if ($this->user['uid'] == $row['perms_userid']) {
605 $out |= $row['perms_user'];
606 }
607 if ($this->isMemberOfGroup($row['perms_groupid'])) {
608 $out |= $row['perms_group'];
609 }
610 $out |= $row['perms_everybody'];
611 }
612 // ****************
613 // CALCPERMS hook
614 // ****************
615 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'] ?? [] as $_funcRef) {
616 $_params = [
617 'row' => $row,
618 'outputPermissions' => $out
619 ];
620 $out = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
621 }
622 return $out;
623 }
624
625 /**
626 * Returns TRUE if the RTE (Rich Text Editor) is enabled for the user.
627 *
628 * @return bool
629 */
630 public function isRTE()
631 {
632 return (bool)$this->uc['edit_RTE'];
633 }
634
635 /**
636 * Returns TRUE if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
637 * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
638 * If user is admin TRUE is also returned
639 * Please see the document Inside TYPO3 for examples.
640 *
641 * @param string $type The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules
642 * @param string $value String to search for in the groupData-list
643 * @return bool TRUE if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
644 */
645 public function check($type, $value)
646 {
647 return isset($this->groupData[$type])
648 && ($this->isAdmin() || GeneralUtility::inList($this->groupData[$type], $value));
649 }
650
651 /**
652 * Checking the authMode of a select field with authMode set
653 *
654 * @param string $table Table name
655 * @param string $field Field name (must be configured in TCA and of type "select" with authMode set!)
656 * @param string $value Value to evaluation (single value, must not contain any of the chars ":,|")
657 * @param string $authMode Auth mode keyword (explicitAllow, explicitDeny, individual)
658 * @return bool Whether access is granted or not
659 */
660 public function checkAuthMode($table, $field, $value, $authMode)
661 {
662 // Admin users can do anything:
663 if ($this->isAdmin()) {
664 return true;
665 }
666 // Allow all blank values:
667 if ((string)$value === '') {
668 return true;
669 }
670 // Certain characters are not allowed in the value
671 if (preg_match('/[:|,]/', $value)) {
672 return false;
673 }
674 // Initialize:
675 $testValue = $table . ':' . $field . ':' . $value;
676 $out = true;
677 // Checking value:
678 switch ((string)$authMode) {
679 case 'explicitAllow':
680 if (!GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':ALLOW')) {
681 $out = false;
682 }
683 break;
684 case 'explicitDeny':
685 if (GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
686 $out = false;
687 }
688 break;
689 case 'individual':
690 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
691 $items = $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'];
692 if (is_array($items)) {
693 foreach ($items as $iCfg) {
694 if ((string)$iCfg[1] === (string)$value && $iCfg[4]) {
695 switch ((string)$iCfg[4]) {
696 case 'EXPL_ALLOW':
697 if (!GeneralUtility::inList(
698 $this->groupData['explicit_allowdeny'],
699 $testValue . ':ALLOW'
700 )) {
701 $out = false;
702 }
703 break;
704 case 'EXPL_DENY':
705 if (GeneralUtility::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
706 $out = false;
707 }
708 break;
709 }
710 break;
711 }
712 }
713 }
714 }
715 break;
716 }
717 return $out;
718 }
719
720 /**
721 * Checking if a language value (-1, 0 and >0 for sys_language records) is allowed to be edited by the user.
722 *
723 * @param int $langValue Language value to evaluate
724 * @return bool Returns TRUE if the language value is allowed, otherwise FALSE.
725 */
726 public function checkLanguageAccess($langValue)
727 {
728 // The users language list must be non-blank - otherwise all languages are allowed.
729 if (trim($this->groupData['allowed_languages']) !== '') {
730 $langValue = (int)$langValue;
731 // Language must either be explicitly allowed OR the lang Value be "-1" (all languages)
732 if ($langValue != -1 && !$this->check('allowed_languages', $langValue)) {
733 return false;
734 }
735 }
736 return true;
737 }
738
739 /**
740 * Check if user has access to all existing localizations for a certain record
741 *
742 * @param string $table The table
743 * @param array $record The current record
744 * @return bool
745 */
746 public function checkFullLanguagesAccess($table, $record)
747 {
748 $recordLocalizationAccess = $this->checkLanguageAccess(0);
749 if ($recordLocalizationAccess && BackendUtility::isTableLocalizable($table)) {
750 $pointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
751 $pointerValue = $record[$pointerField] > 0 ? $record[$pointerField] : $record['uid'];
752 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
753 $queryBuilder->getRestrictions()
754 ->removeAll()
755 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
756 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
757 $recordLocalization = $queryBuilder->select('*')
758 ->from($table)
759 ->where(
760 $queryBuilder->expr()->eq(
761 $pointerField,
762 $queryBuilder->createNamedParameter($pointerValue, \PDO::PARAM_INT)
763 )
764 )
765 ->setMaxResults(1)
766 ->execute()
767 ->fetch();
768
769 if (is_array($recordLocalization)) {
770 $languageAccess = $this->checkLanguageAccess(
771 $recordLocalization[$GLOBALS['TCA'][$table]['ctrl']['languageField']]
772 );
773 $recordLocalizationAccess = $recordLocalizationAccess && $languageAccess;
774 }
775 }
776 return $recordLocalizationAccess;
777 }
778
779 /**
780 * Checking if a user has editing access to a record from a $GLOBALS['TCA'] table.
781 * The checks does not take page permissions and other "environmental" things into account.
782 * It only deal with record internals; If any values in the record fields disallows it.
783 * For instance languages settings, authMode selector boxes are evaluated (and maybe more in the future).
784 * It will check for workspace dependent access.
785 * The function takes an ID (int) or row (array) as second argument.
786 *
787 * @param string $table Table name
788 * @param mixed $idOrRow If integer, then this is the ID of the record. If Array this just represents fields in the record.
789 * @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.
790 * @param bool $deletedRecord Set, if testing a deleted record array.
791 * @param bool $checkFullLanguageAccess Set, whenever access to all translations of the record is required
792 * @return bool TRUE if OK, otherwise FALSE
793 */
794 public function recordEditAccessInternals($table, $idOrRow, $newRecord = false, $deletedRecord = false, $checkFullLanguageAccess = false)
795 {
796 if (!isset($GLOBALS['TCA'][$table])) {
797 return false;
798 }
799 // Always return TRUE for Admin users.
800 if ($this->isAdmin()) {
801 return true;
802 }
803 // Fetching the record if the $idOrRow variable was not an array on input:
804 if (!is_array($idOrRow)) {
805 if ($deletedRecord) {
806 $idOrRow = BackendUtility::getRecord($table, $idOrRow, '*', '', false);
807 } else {
808 $idOrRow = BackendUtility::getRecord($table, $idOrRow);
809 }
810 if (!is_array($idOrRow)) {
811 $this->errorMsg = 'ERROR: Record could not be fetched.';
812 return false;
813 }
814 }
815 // Checking languages:
816 if ($table === 'pages' && $checkFullLanguageAccess && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
817 return false;
818 }
819 if ($GLOBALS['TCA'][$table]['ctrl']['languageField']) {
820 // Language field must be found in input row - otherwise it does not make sense.
821 if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
822 if (!$this->checkLanguageAccess($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
823 $this->errorMsg = 'ERROR: Language was not allowed.';
824 return false;
825 }
826 if (
827 $checkFullLanguageAccess && $idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']] == 0
828 && !$this->checkFullLanguagesAccess($table, $idOrRow)
829 ) {
830 $this->errorMsg = 'ERROR: Related/affected language was not allowed.';
831 return false;
832 }
833 } else {
834 $this->errorMsg = 'ERROR: The "languageField" field named "'
835 . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '" was not found in testing record!';
836 return false;
837 }
838 }
839 // Checking authMode fields:
840 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
841 foreach ($GLOBALS['TCA'][$table]['columns'] as $fieldName => $fieldValue) {
842 if (isset($idOrRow[$fieldName])) {
843 if (
844 $fieldValue['config']['type'] === 'select' && $fieldValue['config']['authMode']
845 && $fieldValue['config']['authMode_enforce'] === 'strict'
846 ) {
847 if (!$this->checkAuthMode($table, $fieldName, $idOrRow[$fieldName], $fieldValue['config']['authMode'])) {
848 $this->errorMsg = 'ERROR: authMode "' . $fieldValue['config']['authMode']
849 . '" failed for field "' . $fieldName . '" with value "'
850 . $idOrRow[$fieldName] . '" evaluated';
851 return false;
852 }
853 }
854 }
855 }
856 }
857 // Checking "editlock" feature (doesn't apply to new records)
858 if (!$newRecord && $GLOBALS['TCA'][$table]['ctrl']['editlock']) {
859 if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']])) {
860 if ($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']]) {
861 $this->errorMsg = 'ERROR: Record was locked for editing. Only admin users can change this state.';
862 return false;
863 }
864 } else {
865 $this->errorMsg = 'ERROR: The "editLock" field named "' . $GLOBALS['TCA'][$table]['ctrl']['editlock']
866 . '" was not found in testing record!';
867 return false;
868 }
869 }
870 // Checking record permissions
871 // THIS is where we can include a check for "perms_" fields for other records than pages...
872 // Process any hooks
873 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'] ?? [] as $funcRef) {
874 $params = [
875 'table' => $table,
876 'idOrRow' => $idOrRow,
877 'newRecord' => $newRecord
878 ];
879 if (!GeneralUtility::callUserFunction($funcRef, $params, $this)) {
880 return false;
881 }
882 }
883 // Finally, return TRUE if all is well.
884 return true;
885 }
886
887 /**
888 * Checks a type of permission against the compiled permission integer,
889 * $compiledPermissions, and in relation to table, $tableName
890 *
891 * @param int $compiledPermissions Could typically be the "compiled permissions" integer returned by ->calcPerms
892 * @param string $tableName Is the tablename to check: If "pages" table then edit,new,delete and editcontent permissions can be checked. Other tables will be checked for "editcontent" only (and $type will be ignored)
893 * @param string $actionType For $tableName='pages' this can be 'edit' (2), 'new' (8 or 16), 'delete' (4), 'editcontent' (16). For all other tables this is ignored. (16 is used)
894 * @return bool
895 * @access public (used by ClickMenuController)
896 */
897 public function isPSet($compiledPermissions, $tableName, $actionType = '')
898 {
899 if ($this->isAdmin()) {
900 $result = true;
901 } elseif ($tableName === 'pages') {
902 switch ($actionType) {
903 case 'edit':
904 $result = ($compiledPermissions & Permission::PAGE_EDIT) !== 0;
905 break;
906 case 'new':
907 // Create new page OR page content
908 $result = ($compiledPermissions & Permission::PAGE_NEW + Permission::CONTENT_EDIT) !== 0;
909 break;
910 case 'delete':
911 $result = ($compiledPermissions & Permission::PAGE_DELETE) !== 0;
912 break;
913 case 'editcontent':
914 $result = ($compiledPermissions & Permission::CONTENT_EDIT) !== 0;
915 break;
916 default:
917 $result = false;
918 }
919 } else {
920 $result = ($compiledPermissions & Permission::CONTENT_EDIT) !== 0;
921 }
922 return $result;
923 }
924
925 /**
926 * Returns TRUE if the BE_USER is allowed to *create* shortcuts in the backend modules
927 *
928 * @return bool
929 */
930 public function mayMakeShortcut()
931 {
932 return $this->getTSConfigVal('options.enableBookmarks')
933 && !$this->getTSConfigVal('options.mayNotCreateEditBookmarks');
934 }
935
936 /**
937 * Checking if editing of an existing record is allowed in current workspace if that is offline.
938 * Rules for editing in offline mode:
939 * - record supports versioning and is an offline version from workspace and has the corrent stage
940 * - or record (any) is in a branch where there is a page which is a version from the workspace
941 * and where the stage is not preventing records
942 *
943 * @param string $table Table of record
944 * @param array|int $recData Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
945 * @return string String error code, telling the failure state. FALSE=All ok
946 */
947 public function workspaceCannotEditRecord($table, $recData)
948 {
949 // Only test offline spaces:
950 if ($this->workspace !== 0) {
951 if (!is_array($recData)) {
952 $recData = BackendUtility::getRecord(
953 $table,
954 $recData,
955 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : '')
956 );
957 }
958 if (is_array($recData)) {
959 // We are testing a "version" (identified by a pid of -1): it can be edited provided
960 // that workspace matches and versioning is enabled for the table.
961 if ((int)$recData['pid'] === -1) {
962 // No versioning, basic error, inconsistency even! Such records should not have a pid of -1!
963 if (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
964 return 'Versioning disabled for table';
965 }
966 if ((int)$recData['t3ver_wsid'] !== $this->workspace) {
967 // So does workspace match?
968 return 'Workspace ID of record didn\'t match current workspace';
969 }
970 // So is the user allowed to "use" the edit stage within the workspace?
971 return $this->workspaceCheckStageForCurrent(0)
972 ? false
973 : 'User\'s access level did not allow for editing';
974 }
975 // We are testing a "live" record:
976 // For "Live" records, check that PID for table allows editing
977 if ($res = $this->workspaceAllowLiveRecordsInPID($recData['pid'], $table)) {
978 // Live records are OK in this branch, but what about the stage of branch point, if any:
979 // OK
980 return $res > 0
981 ? false
982 : 'Stage for versioning root point and users access level did not allow for editing';
983 }
984 // If not offline and not in versionized branch, output error:
985 return 'Online record was not in versionized branch!';
986 }
987 return 'No record';
988 }
989 // OK because workspace is 0
990 return false;
991 }
992
993 /**
994 * Evaluates if a user is allowed to edit the offline version
995 *
996 * @param string $table Table of record
997 * @param array|int $recData Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
998 * @return string String error code, telling the failure state. FALSE=All ok
999 * @see workspaceCannotEditRecord()
1000 */
1001 public function workspaceCannotEditOfflineVersion($table, $recData)
1002 {
1003 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1004 if (!is_array($recData)) {
1005 $recData = BackendUtility::getRecord($table, $recData, 'uid,pid,t3ver_wsid,t3ver_stage');
1006 }
1007 if (is_array($recData)) {
1008 if ((int)$recData['pid'] === -1) {
1009 return $this->workspaceCannotEditRecord($table, $recData);
1010 }
1011 return 'Not an offline version';
1012 }
1013 return 'No record';
1014 }
1015 return 'Table does not support versioning.';
1016 }
1017
1018 /**
1019 * Check if "live" records from $table may be created or edited in this PID.
1020 * If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
1021 * If the answer is 1 or 2 it means it is OK to create a record, if -1 it means that it is OK in terms
1022 * of versioning because the element was within a versionized branch
1023 * but NOT ok in terms of the state the root point had!
1024 *
1025 * @param int $pid PID value to check for. OBSOLETE!
1026 * @param string $table Table name
1027 * @return mixed Returns FALSE if a live record cannot be created and must be versionized in order to do so. 2 means a) Workspace is "Live" or workspace allows "live edit" of records from non-versionized tables (and the $table is not versionizable). 1 and -1 means the pid is inside a versionized branch where -1 means that the branch-point did NOT allow a new record according to its state.
1028 */
1029 public function workspaceAllowLiveRecordsInPID($pid, $table)
1030 {
1031 // Always for Live workspace AND if live-edit is enabled
1032 // and tables are completely without versioning it is ok as well.
1033 if (
1034 $this->workspace === 0
1035 || $this->workspaceRec['live_edit'] && !$GLOBALS['TCA'][$table]['ctrl']['versioningWS']
1036 || $GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']
1037 ) {
1038 // OK to create for this table.
1039 return 2;
1040 }
1041 // If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
1042 return false;
1043 }
1044
1045 /**
1046 * Evaluates if a record from $table can be created in $pid
1047 *
1048 * @param int $pid Page id. This value must be the _ORIG_uid if available: So when you have pages versionized as "page" or "element" you must supply the id of the page version in the workspace!
1049 * @param string $table Table name
1050 * @return bool TRUE if OK.
1051 */
1052 public function workspaceCreateNewRecord($pid, $table)
1053 {
1054 if ($res = $this->workspaceAllowLiveRecordsInPID($pid, $table)) {
1055 // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
1056 if ($res < 0) {
1057 // Stage for versioning root point and users access level did not allow for editing
1058 return false;
1059 }
1060 } elseif (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1061 // So, if no live records were allowed, we have to create a new version of this record:
1062 return false;
1063 }
1064 return true;
1065 }
1066
1067 /**
1068 * Evaluates if auto creation of a version of a record is allowed.
1069 *
1070 * @param string $table Table of the record
1071 * @param int $id UID of record
1072 * @param int $recpid PID of record
1073 * @return bool TRUE if ok.
1074 */
1075 public function workspaceAllowAutoCreation($table, $id, $recpid)
1076 {
1077 // Auto-creation of version: In offline workspace, test if versioning is
1078 // enabled and look for workspace version of input record.
1079 // If there is no versionized record found we will create one and save to that.
1080 if (
1081 $this->workspace !== 0
1082 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $recpid >= 0
1083 && !BackendUtility::getWorkspaceVersionOfRecord($this->workspace, $table, $id, 'uid')
1084 ) {
1085 // There must be no existing version of this record in workspace.
1086 return true;
1087 }
1088 return false;
1089 }
1090
1091 /**
1092 * Checks if an element stage allows access for the user in the current workspace
1093 * In live workspace (= 0) access is always granted for any stage.
1094 * Admins are always allowed.
1095 * An option for custom workspaces allows members to also edit when the stage is "Review"
1096 *
1097 * @param int $stage Stage id from an element: -1,0 = editing, 1 = reviewer, >1 = owner
1098 * @return bool TRUE if user is allowed access
1099 */
1100 public function workspaceCheckStageForCurrent($stage)
1101 {
1102 // Always allow for admins
1103 if ($this->isAdmin()) {
1104 return true;
1105 }
1106 if ($this->workspace !== 0 && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
1107 $stage = (int)$stage;
1108 $stat = $this->checkWorkspaceCurrent();
1109 // Check if custom staging is activated
1110 $workspaceRec = BackendUtility::getRecord('sys_workspace', $stat['uid']);
1111 if ($workspaceRec['custom_stages'] > 0 && $stage !== 0 && $stage !== -10) {
1112 // Get custom stage record
1113 $workspaceStageRec = BackendUtility::getRecord('sys_workspace_stage', $stage);
1114 // Check if the user is responsible for the current stage
1115 if (
1116 $stat['_ACCESS'] === 'owner'
1117 || $stat['_ACCESS'] === 'member'
1118 && GeneralUtility::inList($workspaceStageRec['responsible_persons'], 'be_users_' . $this->user['uid'])
1119 ) {
1120 return true;
1121 }
1122 // Check if the user is in a group which is responsible for the current stage
1123 foreach ($this->userGroupsUID as $groupUid) {
1124 if (
1125 $stat['_ACCESS'] === 'owner'
1126 || $stat['_ACCESS'] === 'member'
1127 && GeneralUtility::inList($workspaceStageRec['responsible_persons'], 'be_groups_' . $groupUid)
1128 ) {
1129 return true;
1130 }
1131 }
1132 } elseif ($stage == -10 || $stage == -20) {
1133 if ($stat['_ACCESS'] === 'owner') {
1134 return true;
1135 }
1136 return false;
1137 } else {
1138 $memberStageLimit = $this->workspaceRec['review_stage_edit'] ? 1 : 0;
1139 if (
1140 $stat['_ACCESS'] === 'owner'
1141 || $stat['_ACCESS'] === 'reviewer' && $stage <= 1
1142 || $stat['_ACCESS'] === 'member' && $stage <= $memberStageLimit
1143 ) {
1144 return true;
1145 }
1146 }
1147 } else {
1148 // Always OK for live workspace.
1149 return true;
1150 }
1151 return false;
1152 }
1153
1154 /**
1155 * Returns TRUE if the user has access to publish content from the workspace ID given.
1156 * Admin-users are always granted access to do this
1157 * If the workspace ID is 0 (live) all users have access also
1158 * For custom workspaces it depends on whether the user is owner OR like with
1159 * draft workspace if the user has access to Live workspace.
1160 *
1161 * @param int $wsid Workspace UID; 0,1+
1162 * @return bool Returns TRUE if the user has access to publish content from the workspace ID given.
1163 */
1164 public function workspacePublishAccess($wsid)
1165 {
1166 if ($this->isAdmin()) {
1167 return true;
1168 }
1169 // If no access to workspace, of course you cannot publish!
1170 $retVal = false;
1171 $wsAccess = $this->checkWorkspace($wsid);
1172 if ($wsAccess) {
1173 switch ($wsAccess['uid']) {
1174 case 0:
1175 // Live workspace
1176 // If access to Live workspace, no problem.
1177 $retVal = true;
1178 break;
1179 default:
1180 // Custom workspace
1181 $retVal = $wsAccess['_ACCESS'] === 'owner' || $this->checkWorkspace(0) && !($wsAccess['publish_access'] & Permission::PAGE_EDIT);
1182 // Either be an adminuser OR have access to online
1183 // workspace which is OK as well as long as publishing
1184 // access is not limited by workspace option.
1185 }
1186 }
1187 return $retVal;
1188 }
1189
1190 /**
1191 * Workspace swap-mode access?
1192 *
1193 * @return bool Returns TRUE if records can be swapped in the current workspace, otherwise FALSE
1194 */
1195 public function workspaceSwapAccess()
1196 {
1197 if ($this->workspace > 0 && (int)$this->workspaceRec['swap_modes'] === 2) {
1198 return false;
1199 }
1200 return true;
1201 }
1202
1203 /**
1204 * Returns fully parsed user TSconfig array.
1205 *
1206 * Returns the value/properties of a TS-object as given by $objectString, eg. 'options.dontMountAdminMounts'
1207 *
1208 * @param string $objectString Pointer to an "object" in the TypoScript array, fx. 'options.dontMountAdminMounts'
1209 * @param array|string $config Optional TSconfig array: If array, then this is used and not $this->userTS. If not array, $this->userTS is used.
1210 * @return array An array with two keys, "value" and "properties" where "value" is a string with the value of the object string and "properties" is an array with the properties of the object string.
1211 */
1212 public function getTSConfig($objectString = '', $config = '')
1213 {
1214 if (empty($objectString) && empty($config)) {
1215 return $this->userTS;
1216 }
1217
1218 if (!is_array($config)) {
1219 // Getting Root-ts if not sent
1220 $config = $this->userTS;
1221 }
1222 $TSConf = ['value' => null, 'properties' => null];
1223 $parts = GeneralUtility::trimExplode('.', $objectString, true, 2);
1224 $key = $parts[0];
1225 if ($key !== '') {
1226 if (count($parts) > 1 && $parts[1] !== '') {
1227 // Go on, get the next level
1228 if (is_array($config[$key . '.'] ?? false)) {
1229 $TSConf = $this->getTSConfig($parts[1], $config[$key . '.']);
1230 }
1231 } else {
1232 $TSConf['value'] = $config[$key] ?? null;
1233 $TSConf['properties'] = $config[$key . '.'] ?? null;
1234 }
1235 }
1236 return $TSConf;
1237 }
1238
1239 /**
1240 * Returns the "value" of the $objectString from the BE_USERS "User TSconfig" array
1241 *
1242 * @param string $objectString Object string, eg. "somestring.someproperty.somesubproperty
1243 * @return string The value for that object string (object path)
1244 * @see getTSConfig()
1245 */
1246 public function getTSConfigVal($objectString)
1247 {
1248 $TSConf = $this->getTSConfig($objectString);
1249 return $TSConf['value'];
1250 }
1251
1252 /**
1253 * Returns the "properties" of the $objectString from the BE_USERS "User TSconfig" array
1254 *
1255 * @param string $objectString Object string, eg. "somestring.someproperty.somesubproperty
1256 * @return array The properties for that object string (object path) - if any
1257 * @see getTSConfig()
1258 */
1259 public function getTSConfigProp($objectString)
1260 {
1261 $TSConf = $this->getTSConfig($objectString);
1262 return $TSConf['properties'];
1263 }
1264
1265 /**
1266 * Returns an array with the webmounts.
1267 * If no webmounts, and empty array is returned.
1268 * NOTICE: Deleted pages WILL NOT be filtered out! So if a mounted page has been deleted
1269 * it is STILL coming out as a webmount. This is not checked due to performance.
1270 *
1271 * @return array
1272 */
1273 public function returnWebmounts()
1274 {
1275 return (string)$this->groupData['webmounts'] != '' ? explode(',', $this->groupData['webmounts']) : [];
1276 }
1277
1278 /**
1279 * Initializes the given mount points for the current Backend user.
1280 *
1281 * @param array $mountPointUids Page UIDs that should be used as web mountpoints
1282 * @param bool $append If TRUE the given mount point will be appended. Otherwise the current mount points will be replaced.
1283 */
1284 public function setWebmounts(array $mountPointUids, $append = false)
1285 {
1286 if (empty($mountPointUids)) {
1287 return;
1288 }
1289 if ($append) {
1290 $currentWebMounts = GeneralUtility::intExplode(',', $this->groupData['webmounts']);
1291 $mountPointUids = array_merge($currentWebMounts, $mountPointUids);
1292 }
1293 $this->groupData['webmounts'] = implode(',', array_unique($mountPointUids));
1294 }
1295
1296 /**
1297 * Returns TRUE or FALSE, depending if an alert popup (a javascript confirmation) should be shown
1298 * call like $GLOBALS['BE_USER']->jsConfirmation($BITMASK).
1299 *
1300 * @param int $bitmask Bitmask, one of \TYPO3\CMS\Core\Type\Bitmask\JsConfirmation
1301 * @return bool TRUE if the confirmation should be shown
1302 * @see JsConfirmation
1303 */
1304 public function jsConfirmation($bitmask)
1305 {
1306 try {
1307 $alertPopupsSetting = trim((string)$this->getTSConfig('options.alertPopups')['value']);
1308 $alertPopup = JsConfirmation::cast($alertPopupsSetting === '' ? null : (int)$alertPopupsSetting);
1309 } catch (InvalidEnumerationValueException $e) {
1310 $alertPopup = new JsConfirmation();
1311 }
1312
1313 return JsConfirmation::cast($bitmask)->matches($alertPopup);
1314 }
1315
1316 /**
1317 * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
1318 * This method is called by ->backendCheckLogin() (from extending BackendUserAuthentication)
1319 * if the backend user login has verified OK.
1320 * Generally this is required initialization of a backend user.
1321 *
1322 * @access private
1323 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1324 */
1325 public function fetchGroupData()
1326 {
1327 if ($this->user['uid']) {
1328 // Get lists for the be_user record and set them as default/primary values.
1329 // Enabled Backend Modules
1330 $this->dataLists['modList'] = $this->user['userMods'];
1331 // Add Allowed Languages
1332 $this->dataLists['allowed_languages'] = $this->user['allowed_languages'];
1333 // Set user value for workspace permissions.
1334 $this->dataLists['workspace_perms'] = $this->user['workspace_perms'];
1335 // Database mountpoints
1336 $this->dataLists['webmount_list'] = $this->user['db_mountpoints'];
1337 // File mountpoints
1338 $this->dataLists['filemount_list'] = $this->user['file_mountpoints'];
1339 // Fileoperation permissions
1340 $this->dataLists['file_permissions'] = $this->user['file_permissions'];
1341 // Setting default User TSconfig:
1342 $this->TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
1343 // Default TSconfig for admin-users
1344 if ($this->isAdmin()) {
1345 $this->TSdataArray[] = 'admPanel.enable.all = 1';
1346 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('sys_note')) {
1347 $this->TSdataArray[] = '
1348 // Setting defaults for sys_note author / email...
1349 TCAdefaults.sys_note.author = ' . $this->user['realName'] . '
1350 TCAdefaults.sys_note.email = ' . $this->user['email'] . '
1351 ';
1352 }
1353 }
1354 // BE_GROUPS:
1355 // Get the groups...
1356 if (!empty($this->user[$this->usergroup_column])) {
1357 // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc.
1358 // Refer to fetchGroups() function.
1359 $this->fetchGroups($this->user[$this->usergroup_column]);
1360 }
1361
1362 // Populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
1363 $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
1364 // Finally this is the list of group_uid's in the order they are parsed (including subgroups!)
1365 // and without duplicates (duplicates are presented with their last entrance in the list,
1366 // which thus reflects the order of the TypoScript in TSconfig)
1367 $this->groupList = implode(',', $this->userGroupsUID);
1368 $this->setCachedList($this->groupList);
1369
1370 // Add the TSconfig for this specific user:
1371 $this->TSdataArray[] = $this->user['TSconfig'];
1372 // Check include lines.
1373 $this->TSdataArray = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines_array($this->TSdataArray);
1374 // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
1375 $this->userTS_text = implode(LF . '[GLOBAL]' . LF, $this->TSdataArray);
1376 if (!$this->userTS_dontGetCached) {
1377 // @deprecated: Property userTS_dontGetCached is deprecated since v9 and will be removed in v10
1378 // Perform TS-Config parsing with condition matching
1379 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Configuration\TsConfigParser::class);
1380 $res = $parseObj->parseTSconfig($this->userTS_text, 'userTS');
1381 if ($res) {
1382 $this->userTS = $res['TSconfig'];
1383 $this->userTSUpdated = (bool)$res['cached'];
1384 }
1385 } else {
1386 // Parsing the user TSconfig (or getting from cache)
1387 $hash = md5('userTS:' . $this->userTS_text);
1388 $cache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash');
1389 $cachedContent = $cache->get($hash);
1390 if (is_array($cachedContent) && !$this->userTS_dontGetCached) {
1391 // @deprecated: Property userTS_dontGetCached is deprecated since v9 and will be removed in v10
1392 $this->userTS = $cachedContent;
1393 } else {
1394 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
1395 $parseObj->parse($this->userTS_text);
1396 $this->userTS = $parseObj->setup;
1397 $cache->set($hash, $this->userTS, ['ident_BE_USER_TSconfig'], 0);
1398 // Update UC:
1399 $this->userTSUpdated = true;
1400 }
1401 }
1402 // Processing webmounts
1403 // Admin's always have the root mounted
1404 if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) {
1405 $this->dataLists['webmount_list'] = '0,' . $this->dataLists['webmount_list'];
1406 }
1407 // The lists are cleaned for duplicates
1408 $this->groupData['webmounts'] = GeneralUtility::uniqueList($this->dataLists['webmount_list']);
1409 $this->groupData['pagetypes_select'] = GeneralUtility::uniqueList($this->dataLists['pagetypes_select']);
1410 $this->groupData['tables_select'] = GeneralUtility::uniqueList($this->dataLists['tables_modify'] . ',' . $this->dataLists['tables_select']);
1411 $this->groupData['tables_modify'] = GeneralUtility::uniqueList($this->dataLists['tables_modify']);
1412 $this->groupData['non_exclude_fields'] = GeneralUtility::uniqueList($this->dataLists['non_exclude_fields']);
1413 $this->groupData['explicit_allowdeny'] = GeneralUtility::uniqueList($this->dataLists['explicit_allowdeny']);
1414 $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($this->dataLists['allowed_languages']);
1415 $this->groupData['custom_options'] = GeneralUtility::uniqueList($this->dataLists['custom_options']);
1416 $this->groupData['modules'] = GeneralUtility::uniqueList($this->dataLists['modList']);
1417 $this->groupData['file_permissions'] = GeneralUtility::uniqueList($this->dataLists['file_permissions']);
1418 $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
1419
1420 // Checking read access to webmounts:
1421 if (trim($this->groupData['webmounts']) !== '') {
1422 $webmounts = explode(',', $this->groupData['webmounts']);
1423 // Explode mounts
1424 // Selecting all webmounts with permission clause for reading
1425 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1426 $queryBuilder->getRestrictions()
1427 ->removeAll()
1428 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1429
1430 $MProws = $queryBuilder->select('uid')
1431 ->from('pages')
1432 // @todo DOCTRINE: check how to make getPagePermsClause() portable
1433 ->where(
1434 $this->getPagePermsClause(Permission::PAGE_SHOW),
1435 $queryBuilder->expr()->in(
1436 'uid',
1437 $queryBuilder->createNamedParameter(
1438 GeneralUtility::intExplode(',', $this->groupData['webmounts']),
1439 Connection::PARAM_INT_ARRAY
1440 )
1441 )
1442 )
1443 ->execute()
1444 ->fetchAll();
1445 $MProws = array_column(($MProws ?: []), 'uid', 'uid');
1446 foreach ($webmounts as $idx => $mountPointUid) {
1447 // If the mount ID is NOT found among selected pages, unset it:
1448 if ($mountPointUid > 0 && !isset($MProws[$mountPointUid])) {
1449 unset($webmounts[$idx]);
1450 }
1451 }
1452 // Implode mounts in the end.
1453 $this->groupData['webmounts'] = implode(',', $webmounts);
1454 }
1455 // Setting up workspace situation (after webmounts are processed!):
1456 $this->workspaceInit();
1457 }
1458 }
1459
1460 /**
1461 * Fetches the group records, subgroups and fills internal arrays.
1462 * Function is called recursively to fetch subgroups
1463 *
1464 * @param string $grList Commalist of be_groups uid numbers
1465 * @param string $idList List of already processed be_groups-uids so the function will not fall into an eternal recursion.
1466 * @access private
1467 */
1468 public function fetchGroups($grList, $idList = '')
1469 {
1470 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
1471 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->usergroup_table);
1472 $expressionBuilder = $queryBuilder->expr();
1473 $constraints = $expressionBuilder->andX(
1474 $expressionBuilder->eq(
1475 'pid',
1476 $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
1477 ),
1478 $expressionBuilder->in(
1479 'uid',
1480 $queryBuilder->createNamedParameter(
1481 GeneralUtility::intExplode(',', $grList),
1482 Connection::PARAM_INT_ARRAY
1483 )
1484 ),
1485 $expressionBuilder->orX(
1486 $expressionBuilder->eq('lockToDomain', $queryBuilder->quote('')),
1487 $expressionBuilder->isNull('lockToDomain'),
1488 $expressionBuilder->eq(
1489 'lockToDomain',
1490 $queryBuilder->createNamedParameter(GeneralUtility::getIndpEnv('HTTP_HOST'), \PDO::PARAM_STR)
1491 )
1492 )
1493 );
1494 // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
1495 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] ?? [] as $className) {
1496 $hookObj = GeneralUtility::makeInstance($className);
1497 if (method_exists($hookObj, 'fetchGroupQuery_processQuery')) {
1498 $constraints = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, (string)$constraints);
1499 }
1500 }
1501 $res = $queryBuilder->select('*')
1502 ->from($this->usergroup_table)
1503 ->where($constraints)
1504 ->execute();
1505 // The userGroups array is filled
1506 while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
1507 $this->userGroups[$row['uid']] = $row;
1508 }
1509 // Traversing records in the correct order
1510 foreach (explode(',', $grList) as $uid) {
1511 // Get row:
1512 $row = $this->userGroups[$uid];
1513 // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
1514 if (is_array($row) && !GeneralUtility::inList($idList, $uid)) {
1515 // Include sub groups
1516 if (trim($row['subgroup'])) {
1517 // Make integer list
1518 $theList = implode(',', GeneralUtility::intExplode(',', $row['subgroup']));
1519 // Call recursively, pass along list of already processed groups so they are not recursed again.
1520 $this->fetchGroups($theList, $idList . ',' . $uid);
1521 }
1522 // Add the group uid, current list, TSconfig to the internal arrays.
1523 $this->includeGroupArray[] = $uid;
1524 $this->TSdataArray[] = $row['TSconfig'];
1525 // Mount group database-mounts
1526 if (($this->user['options'] & Permission::PAGE_SHOW) == 1) {
1527 $this->dataLists['webmount_list'] .= ',' . $row['db_mountpoints'];
1528 }
1529 // Mount group file-mounts
1530 if (($this->user['options'] & Permission::PAGE_EDIT) == 2) {
1531 $this->dataLists['filemount_list'] .= ',' . $row['file_mountpoints'];
1532 }
1533 // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
1534 $this->dataLists['modList'] .= ',' . $row['groupMods'];
1535 $this->dataLists['tables_select'] .= ',' . $row['tables_select'];
1536 $this->dataLists['tables_modify'] .= ',' . $row['tables_modify'];
1537 $this->dataLists['pagetypes_select'] .= ',' . $row['pagetypes_select'];
1538 $this->dataLists['non_exclude_fields'] .= ',' . $row['non_exclude_fields'];
1539 $this->dataLists['explicit_allowdeny'] .= ',' . $row['explicit_allowdeny'];
1540 $this->dataLists['allowed_languages'] .= ',' . $row['allowed_languages'];
1541 $this->dataLists['custom_options'] .= ',' . $row['custom_options'];
1542 $this->dataLists['file_permissions'] .= ',' . $row['file_permissions'];
1543 // Setting workspace permissions:
1544 $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
1545 // If this function is processing the users OWN group-list (not subgroups) AND
1546 // if the ->firstMainGroup is not set, then the ->firstMainGroup will be set.
1547 if ($idList === '' && !$this->firstMainGroup) {
1548 $this->firstMainGroup = $uid;
1549 }
1550 }
1551 }
1552 // HOOK: fetchGroups_postProcessing
1553 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] ?? [] as $_funcRef) {
1554 $_params = [];
1555 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1556 }
1557 }
1558
1559 /**
1560 * Updates the field be_users.usergroup_cached_list if the groupList of the user
1561 * has changed/is different from the current list.
1562 * The field "usergroup_cached_list" contains the list of groups which the user is a member of.
1563 * After authentication (where these functions are called...) one can depend on this list being
1564 * a representation of the exact groups/subgroups which the BE_USER has membership with.
1565 *
1566 * @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.
1567 * @access private
1568 */
1569 public function setCachedList($cList)
1570 {
1571 if ((string)$cList != (string)$this->user['usergroup_cached_list']) {
1572 GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
1573 'be_users',
1574 ['usergroup_cached_list' => $cList],
1575 ['uid' => (int)$this->user['uid']]
1576 );
1577 }
1578 }
1579
1580 /**
1581 * Sets up all file storages for a user.
1582 * Needs to be called AFTER the groups have been loaded.
1583 */
1584 protected function initializeFileStorages()
1585 {
1586 $this->fileStorages = [];
1587 /** @var $storageRepository \TYPO3\CMS\Core\Resource\StorageRepository */
1588 $storageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
1589 // Admin users have all file storages visible, without any filters
1590 if ($this->isAdmin()) {
1591 $storageObjects = $storageRepository->findAll();
1592 foreach ($storageObjects as $storageObject) {
1593 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1594 }
1595 } else {
1596 // Regular users only have storages that are defined in their filemounts
1597 // Permissions and file mounts for the storage are added in StoragePermissionAspect
1598 foreach ($this->getFileMountRecords() as $row) {
1599 if (!array_key_exists((int)$row['base'], $this->fileStorages)) {
1600 $storageObject = $storageRepository->findByUid($row['base']);
1601 if ($storageObject) {
1602 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1603 }
1604 }
1605 }
1606 }
1607
1608 // This has to be called always in order to set certain filters
1609 $this->evaluateUserSpecificFileFilterSettings();
1610 }
1611
1612 /**
1613 * Returns an array of category mount points. The category permissions from BE Groups
1614 * are also taken into consideration and are merged into User permissions.
1615 *
1616 * @return array
1617 */
1618 public function getCategoryMountPoints()
1619 {
1620 $categoryMountPoints = '';
1621
1622 // Category mounts of the groups
1623 if (is_array($this->userGroups)) {
1624 foreach ($this->userGroups as $group) {
1625 if ($group['category_perms']) {
1626 $categoryMountPoints .= ',' . $group['category_perms'];
1627 }
1628 }
1629 }
1630
1631 // Category mounts of the user record
1632 if ($this->user['category_perms']) {
1633 $categoryMountPoints .= ',' . $this->user['category_perms'];
1634 }
1635
1636 // Make the ids unique
1637 $categoryMountPoints = GeneralUtility::trimExplode(',', $categoryMountPoints);
1638 $categoryMountPoints = array_filter($categoryMountPoints); // remove empty value
1639 $categoryMountPoints = array_unique($categoryMountPoints); // remove unique value
1640
1641 return $categoryMountPoints;
1642 }
1643
1644 /**
1645 * Returns an array of file mount records, taking workspaces and user home and group home directories into account
1646 * Needs to be called AFTER the groups have been loaded.
1647 *
1648 * @return array
1649 * @internal
1650 */
1651 public function getFileMountRecords()
1652 {
1653 static $fileMountRecordCache = [];
1654
1655 if (!empty($fileMountRecordCache)) {
1656 return $fileMountRecordCache;
1657 }
1658
1659 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
1660
1661 // Processing file mounts (both from the user and the groups)
1662 $fileMounts = array_unique(GeneralUtility::intExplode(',', $this->dataLists['filemount_list'], true));
1663
1664 // Limit file mounts if set in workspace record
1665 if ($this->workspace > 0 && !empty($this->workspaceRec['file_mountpoints'])) {
1666 $workspaceFileMounts = GeneralUtility::intExplode(',', $this->workspaceRec['file_mountpoints'], true);
1667 $fileMounts = array_intersect($fileMounts, $workspaceFileMounts);
1668 }
1669
1670 if (!empty($fileMounts)) {
1671 $orderBy = $GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'] ?? 'sorting';
1672
1673 $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_filemounts');
1674 $queryBuilder->getRestrictions()
1675 ->removeAll()
1676 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
1677 ->add(GeneralUtility::makeInstance(HiddenRestriction::class))
1678 ->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
1679
1680 $queryBuilder->select('*')
1681 ->from('sys_filemounts')
1682 ->where(
1683 $queryBuilder->expr()->in('uid', $queryBuilder->createNamedParameter($fileMounts, Connection::PARAM_INT_ARRAY))
1684 );
1685
1686 foreach (QueryHelper::parseOrderBy($orderBy) as $fieldAndDirection) {
1687 $queryBuilder->addOrderBy(...$fieldAndDirection);
1688 }
1689
1690 $fileMountRecords = $queryBuilder->execute()->fetchAll(\PDO::FETCH_ASSOC);
1691 if ($fileMountRecords !== false) {
1692 foreach ($fileMountRecords as $fileMount) {
1693 $fileMountRecordCache[$fileMount['base'] . $fileMount['path']] = $fileMount;
1694 }
1695 }
1696 }
1697
1698 // Read-only file mounts
1699 $readOnlyMountPoints = trim($GLOBALS['BE_USER']->getTSConfigVal('options.folderTree.altElementBrowserMountPoints'));
1700 if ($readOnlyMountPoints) {
1701 // We cannot use the API here but need to fetch the default storage record directly
1702 // to not instantiate it (which directly applies mount points) before all mount points are resolved!
1703 $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file_storage');
1704 $defaultStorageRow = $queryBuilder->select('uid')
1705 ->from('sys_file_storage')
1706 ->where(
1707 $queryBuilder->expr()->eq('is_default', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT))
1708 )
1709 ->setMaxResults(1)
1710 ->execute()
1711 ->fetch(\PDO::FETCH_ASSOC);
1712
1713 $readOnlyMountPointArray = GeneralUtility::trimExplode(',', $readOnlyMountPoints);
1714 foreach ($readOnlyMountPointArray as $readOnlyMountPoint) {
1715 $readOnlyMountPointConfiguration = GeneralUtility::trimExplode(':', $readOnlyMountPoint);
1716 if (count($readOnlyMountPointConfiguration) === 2) {
1717 // A storage is passed in the configuration
1718 $storageUid = (int)$readOnlyMountPointConfiguration[0];
1719 $path = $readOnlyMountPointConfiguration[1];
1720 } else {
1721 if (empty($defaultStorageRow)) {
1722 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);
1723 }
1724 // Backwards compatibility: If no storage is passed, we use the default storage
1725 $storageUid = $defaultStorageRow['uid'];
1726 $path = $readOnlyMountPointConfiguration[0];
1727 }
1728 $fileMountRecordCache[$storageUid . $path] = [
1729 'base' => $storageUid,
1730 'title' => $path,
1731 'path' => $path,
1732 'read_only' => true
1733 ];
1734 }
1735 }
1736
1737 // Personal or Group filemounts are not accessible if file mount list is set in workspace record
1738 if ($this->workspace <= 0 || empty($this->workspaceRec['file_mountpoints'])) {
1739 // If userHomePath is set, we attempt to mount it
1740 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
1741 list($userHomeStorageUid, $userHomeFilter) = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'], 2);
1742 $userHomeStorageUid = (int)$userHomeStorageUid;
1743 $userHomeFilter = '/' . ltrim($userHomeFilter, '/');
1744 if ($userHomeStorageUid > 0) {
1745 // Try and mount with [uid]_[username]
1746 $path = $userHomeFilter . $this->user['uid'] . '_' . $this->user['username'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1747 $fileMountRecordCache[$userHomeStorageUid . $path] = [
1748 'base' => $userHomeStorageUid,
1749 'title' => $this->user['username'],
1750 'path' => $path,
1751 'read_only' => false,
1752 'user_mount' => true
1753 ];
1754 // Try and mount with only [uid]
1755 $path = $userHomeFilter . $this->user['uid'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1756 $fileMountRecordCache[$userHomeStorageUid . $path] = [
1757 'base' => $userHomeStorageUid,
1758 'title' => $this->user['username'],
1759 'path' => $path,
1760 'read_only' => false,
1761 'user_mount' => true
1762 ];
1763 }
1764 }
1765
1766 // Mount group home-dirs
1767 if ((is_array($this->user) && $this->user['options'] & Permission::PAGE_EDIT) == 2 && $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'] != '') {
1768 // If groupHomePath is set, we attempt to mount it
1769 list($groupHomeStorageUid, $groupHomeFilter) = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'], 2);
1770 $groupHomeStorageUid = (int)$groupHomeStorageUid;
1771 $groupHomeFilter = '/' . ltrim($groupHomeFilter, '/');
1772 if ($groupHomeStorageUid > 0) {
1773 foreach ($this->userGroups as $groupData) {
1774 $path = $groupHomeFilter . $groupData['uid'];
1775 $fileMountRecordCache[$groupHomeStorageUid . $path] = [
1776 'base' => $groupHomeStorageUid,
1777 'title' => $groupData['title'],
1778 'path' => $path,
1779 'read_only' => false,
1780 'user_mount' => true
1781 ];
1782 }
1783 }
1784 }
1785 }
1786
1787 return $fileMountRecordCache;
1788 }
1789
1790 /**
1791 * Returns an array with the filemounts for the user.
1792 * Each filemount is represented with an array of a "name", "path" and "type".
1793 * If no filemounts an empty array is returned.
1794 *
1795 * @api
1796 * @return \TYPO3\CMS\Core\Resource\ResourceStorage[]
1797 */
1798 public function getFileStorages()
1799 {
1800 // Initializing file mounts after the groups are fetched
1801 if ($this->fileStorages === null) {
1802 $this->initializeFileStorages();
1803 }
1804 return $this->fileStorages;
1805 }
1806
1807 /**
1808 * Adds filters based on what the user has set
1809 * this should be done in this place, and called whenever needed,
1810 * but only when needed
1811 */
1812 public function evaluateUserSpecificFileFilterSettings()
1813 {
1814 // Add the option for also displaying the non-hidden files
1815 if ($this->uc['showHiddenFilesAndFolders']) {
1816 \TYPO3\CMS\Core\Resource\Filter\FileNameFilter::setShowHiddenFilesAndFolders(true);
1817 }
1818 }
1819
1820 /**
1821 * Returns the information about file permissions.
1822 * Previously, this was stored in the DB field fileoper_perms now it is file_permissions.
1823 * Besides it can be handled via userTSconfig
1824 *
1825 * permissions.file.default {
1826 * addFile = 1
1827 * readFile = 1
1828 * writeFile = 1
1829 * copyFile = 1
1830 * moveFile = 1
1831 * renameFile = 1
1832 * deleteFile = 1
1833 *
1834 * addFolder = 1
1835 * readFolder = 1
1836 * writeFolder = 1
1837 * copyFolder = 1
1838 * moveFolder = 1
1839 * renameFolder = 1
1840 * deleteFolder = 1
1841 * recursivedeleteFolder = 1
1842 * }
1843 *
1844 * # overwrite settings for a specific storageObject
1845 * permissions.file.storage.StorageUid {
1846 * readFile = 1
1847 * recursivedeleteFolder = 0
1848 * }
1849 *
1850 * Please note that these permissions only apply, if the storage has the
1851 * capabilities (browseable, writable), and if the driver allows for writing etc
1852 *
1853 * @api
1854 * @return array
1855 */
1856 public function getFilePermissions()
1857 {
1858 if (!isset($this->filePermissions)) {
1859 $filePermissions = [
1860 // File permissions
1861 'addFile' => false,
1862 'readFile' => false,
1863 'writeFile' => false,
1864 'copyFile' => false,
1865 'moveFile' => false,
1866 'renameFile' => false,
1867 'deleteFile' => false,
1868 // Folder permissions
1869 'addFolder' => false,
1870 'readFolder' => false,
1871 'writeFolder' => false,
1872 'copyFolder' => false,
1873 'moveFolder' => false,
1874 'renameFolder' => false,
1875 'deleteFolder' => false,
1876 'recursivedeleteFolder' => false
1877 ];
1878 if ($this->isAdmin()) {
1879 $filePermissions = array_map('is_bool', $filePermissions);
1880 } else {
1881 $userGroupRecordPermissions = GeneralUtility::trimExplode(',', $this->groupData['file_permissions'] ?? '', true);
1882 array_walk(
1883 $userGroupRecordPermissions,
1884 function ($permission) use (&$filePermissions) {
1885 $filePermissions[$permission] = true;
1886 }
1887 );
1888
1889 // Finally overlay any userTSconfig
1890 $permissionsTsConfig = $this->getTSConfig()['permissions.']['file.']['default.'] ?? [];
1891 if (!empty($permissionsTsConfig)) {
1892 array_walk(
1893 $permissionsTsConfig,
1894 function ($value, $permission) use (&$filePermissions) {
1895 $filePermissions[$permission] = (bool)$value;
1896 }
1897 );
1898 }
1899 }
1900 $this->filePermissions = $filePermissions;
1901 }
1902 return $this->filePermissions;
1903 }
1904
1905 /**
1906 * Gets the file permissions for a storage
1907 * by merging any storage-specific permissions for a
1908 * storage with the default settings.
1909 * Admin users will always get the default settings.
1910 *
1911 * @api
1912 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storageObject
1913 * @return array
1914 */
1915 public function getFilePermissionsForStorage(\TYPO3\CMS\Core\Resource\ResourceStorage $storageObject)
1916 {
1917 $finalUserPermissions = $this->getFilePermissions();
1918 if (!$this->isAdmin()) {
1919 $storageFilePermissions = $this->getTSConfig()['permissions.']['file.']['storage.'][$storageObject->getUid() . '.'] ?? [];
1920 if (!empty($storageFilePermissions)) {
1921 array_walk(
1922 $storageFilePermissions,
1923 function ($value, $permission) use (&$finalUserPermissions) {
1924 $finalUserPermissions[$permission] = (bool)$value;
1925 }
1926 );
1927 }
1928 }
1929 return $finalUserPermissions;
1930 }
1931
1932 /**
1933 * Returns a \TYPO3\CMS\Core\Resource\Folder object that is used for uploading
1934 * files by default.
1935 * This is used for RTE and its magic images, as well as uploads
1936 * in the TCEforms fields.
1937 *
1938 * The default upload folder for a user is the defaultFolder on the first
1939 * filestorage/filemount that the user can access and to which files are allowed to be added
1940 * however, you can set the users' upload folder like this:
1941 *
1942 * options.defaultUploadFolder = 3:myfolder/yourfolder/
1943 *
1944 * @param int $pid PageUid
1945 * @param string $table Table name
1946 * @param string $field Field name
1947 * @return \TYPO3\CMS\Core\Resource\Folder|bool The default upload folder for this user
1948 */
1949 public function getDefaultUploadFolder($pid = null, $table = null, $field = null)
1950 {
1951 $uploadFolder = $this->getTSConfigVal('options.defaultUploadFolder');
1952 if ($uploadFolder) {
1953 $uploadFolder = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->getFolderObjectFromCombinedIdentifier($uploadFolder);
1954 } else {
1955 foreach ($this->getFileStorages() as $storage) {
1956 if ($storage->isDefault() && $storage->isWritable()) {
1957 try {
1958 $uploadFolder = $storage->getDefaultFolder();
1959 if ($uploadFolder->checkActionPermission('write')) {
1960 break;
1961 }
1962 $uploadFolder = null;
1963 } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
1964 // If the folder is not accessible (no permissions / does not exist) we skip this one.
1965 }
1966 break;
1967 }
1968 }
1969 if (!$uploadFolder instanceof \TYPO3\CMS\Core\Resource\Folder) {
1970 /** @var ResourceStorage $storage */
1971 foreach ($this->getFileStorages() as $storage) {
1972 if ($storage->isWritable()) {
1973 try {
1974 $uploadFolder = $storage->getDefaultFolder();
1975 if ($uploadFolder->checkActionPermission('write')) {
1976 break;
1977 }
1978 $uploadFolder = null;
1979 } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
1980 // If the folder is not accessible (no permissions / does not exist) try the next one.
1981 }
1982 }
1983 }
1984 }
1985 }
1986
1987 // HOOK: getDefaultUploadFolder
1988 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getDefaultUploadFolder'] ?? [] as $_funcRef) {
1989 $_params = [
1990 'uploadFolder' => $uploadFolder,
1991 'pid' => $pid,
1992 'table' => $table,
1993 'field' => $field,
1994 ];
1995 $uploadFolder = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1996 }
1997
1998 if ($uploadFolder instanceof \TYPO3\CMS\Core\Resource\Folder) {
1999 return $uploadFolder;
2000 }
2001 return false;
2002 }
2003
2004 /**
2005 * Returns a \TYPO3\CMS\Core\Resource\Folder object that could be used for uploading
2006 * temporary files in user context. The folder _temp_ below the default upload folder
2007 * of the user is used.
2008 *
2009 * @return \TYPO3\CMS\Core\Resource\Folder|null
2010 * @see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::getDefaultUploadFolder();
2011 */
2012 public function getDefaultUploadTemporaryFolder()
2013 {
2014 $defaultTemporaryFolder = null;
2015 $defaultFolder = $this->getDefaultUploadFolder();
2016
2017 if ($defaultFolder !== false) {
2018 $tempFolderName = '_temp_';
2019 $createFolder = !$defaultFolder->hasFolder($tempFolderName);
2020 if ($createFolder === true) {
2021 try {
2022 $defaultTemporaryFolder = $defaultFolder->createFolder($tempFolderName);
2023 } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
2024 }
2025 } else {
2026 $defaultTemporaryFolder = $defaultFolder->getSubfolder($tempFolderName);
2027 }
2028 }
2029
2030 return $defaultTemporaryFolder;
2031 }
2032
2033 /**
2034 * Creates a TypoScript comment with the string text inside.
2035 *
2036 * @param string $str The text to wrap in comment prefixes and delimiters.
2037 * @return string TypoScript comment with the string text inside.
2038 * @deprecated since core v9, will be removed with core v10
2039 */
2040 public function addTScomment($str)
2041 {
2042 trigger_error('This method will be removed in TYPO3 v10.', E_USER_DEPRECATED);
2043 $delimiter = '# ***********************************************';
2044 $out = $delimiter . LF;
2045 $lines = GeneralUtility::trimExplode(LF, $str);
2046 foreach ($lines as $v) {
2047 $out .= '# ' . $v . LF;
2048 }
2049 $out .= $delimiter . LF;
2050 return $out;
2051 }
2052
2053 /**
2054 * Initializing workspace.
2055 * Called from within this function, see fetchGroupData()
2056 *
2057 * @see fetchGroupData()
2058 */
2059 public function workspaceInit()
2060 {
2061 // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
2062 $this->setWorkspace($this->user['workspace_id']);
2063 // Limiting the DB mountpoints if there any selected in the workspace record
2064 $this->initializeDbMountpointsInWorkspace();
2065 if ($allowed_languages = $this->getTSConfigVal('options.workspaces.allowed_languages.' . $this->workspace)) {
2066 $this->groupData['allowed_languages'] = $allowed_languages;
2067 $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($this->groupData['allowed_languages']);
2068 }
2069 }
2070
2071 /**
2072 * Limiting the DB mountpoints if there any selected in the workspace record
2073 */
2074 protected function initializeDbMountpointsInWorkspace()
2075 {
2076 $dbMountpoints = trim($this->workspaceRec['db_mountpoints'] ?? '');
2077 if ($this->workspace > 0 && $dbMountpoints != '') {
2078 $filteredDbMountpoints = [];
2079 // Notice: We cannot call $this->getPagePermsClause(1);
2080 // as usual because the group-list is not available at this point.
2081 // But bypassing is fine because all we want here is check if the
2082 // workspace mounts are inside the current webmounts rootline.
2083 // The actual permission checking on page level is done elsewhere
2084 // as usual anyway before the page tree is rendered.
2085 $readPerms = '1=1';
2086 // Traverse mount points of the
2087 $dbMountpoints = GeneralUtility::intExplode(',', $dbMountpoints);
2088 foreach ($dbMountpoints as $mpId) {
2089 if ($this->isInWebMount($mpId, $readPerms)) {
2090 $filteredDbMountpoints[] = $mpId;
2091 }
2092 }
2093 // Re-insert webmounts:
2094 $filteredDbMountpoints = array_unique($filteredDbMountpoints);
2095 $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
2096 }
2097 }
2098
2099 /**
2100 * Checking if a workspace is allowed for backend user
2101 *
2102 * @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)
2103 * @param string $fields List of fields to select. Default fields are: uid,title,adminusers,members,reviewers,publish_access,stagechg_notification
2104 * @return array Output will also show how access was granted. Admin users will have a true output regardless of input.
2105 */
2106 public function checkWorkspace($wsRec, $fields = 'uid,title,adminusers,members,reviewers,publish_access,stagechg_notification')
2107 {
2108 $retVal = false;
2109 // If not array, look up workspace record:
2110 if (!is_array($wsRec)) {
2111 switch ((string)$wsRec) {
2112 case '0':
2113 $wsRec = ['uid' => $wsRec];
2114 break;
2115 default:
2116 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
2117 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2118 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2119 $wsRec = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields))
2120 ->from('sys_workspace')
2121 ->where($queryBuilder->expr()->eq(
2122 'uid',
2123 $queryBuilder->createNamedParameter($wsRec, \PDO::PARAM_INT)
2124 ))
2125 ->orderBy('title')
2126 ->setMaxResults(1)
2127 ->execute()
2128 ->fetch(\PDO::FETCH_ASSOC);
2129 }
2130 }
2131 }
2132 // If wsRec is set to an array, evaluate it:
2133 if (is_array($wsRec)) {
2134 if ($this->isAdmin()) {
2135 return array_merge($wsRec, ['_ACCESS' => 'admin']);
2136 }
2137 switch ((string)$wsRec['uid']) {
2138 case '0':
2139 $retVal = $this->groupData['workspace_perms'] & Permission::PAGE_SHOW
2140 ? array_merge($wsRec, ['_ACCESS' => 'online'])
2141 : false;
2142 break;
2143 default:
2144 // Checking if the guy is admin:
2145 if (GeneralUtility::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
2146 return array_merge($wsRec, ['_ACCESS' => 'owner']);
2147 }
2148 // Checking if he is owner through a user group of his:
2149 foreach ($this->userGroupsUID as $groupUid) {
2150 if (GeneralUtility::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
2151 return array_merge($wsRec, ['_ACCESS' => 'owner']);
2152 }
2153 }
2154 // Checking if he is reviewer user:
2155 if (GeneralUtility::inList($wsRec['reviewers'], 'be_users_' . $this->user['uid'])) {
2156 return array_merge($wsRec, ['_ACCESS' => 'reviewer']);
2157 }
2158 // Checking if he is reviewer through a user group of his:
2159 foreach ($this->userGroupsUID as $groupUid) {
2160 if (GeneralUtility::inList($wsRec['reviewers'], 'be_groups_' . $groupUid)) {
2161 return array_merge($wsRec, ['_ACCESS' => 'reviewer']);
2162 }
2163 }
2164 // Checking if he is member as user:
2165 if (GeneralUtility::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
2166 return array_merge($wsRec, ['_ACCESS' => 'member']);
2167 }
2168 // Checking if he is member through a user group of his:
2169 foreach ($this->userGroupsUID as $groupUid) {
2170 if (GeneralUtility::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
2171 return array_merge($wsRec, ['_ACCESS' => 'member']);
2172 }
2173 }
2174 }
2175 }
2176 return $retVal;
2177 }
2178
2179 /**
2180 * Uses checkWorkspace() to check if current workspace is available for user.
2181 * This function caches the result and so can be called many times with no performance loss.
2182 *
2183 * @return array See checkWorkspace()
2184 * @see checkWorkspace()
2185 */
2186 public function checkWorkspaceCurrent()
2187 {
2188 if (!isset($this->checkWorkspaceCurrent_cache)) {
2189 $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
2190 }
2191 return $this->checkWorkspaceCurrent_cache;
2192 }
2193
2194 /**
2195 * Setting workspace ID
2196 *
2197 * @param int $workspaceId ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
2198 */
2199 public function setWorkspace($workspaceId)
2200 {
2201 // Check workspace validity and if not found, revert to default workspace.
2202 if (!$this->setTemporaryWorkspace($workspaceId)) {
2203 $this->setDefaultWorkspace();
2204 }
2205 // Unset access cache:
2206 $this->checkWorkspaceCurrent_cache = null;
2207 // If ID is different from the stored one, change it:
2208 if ((int)$this->workspace !== (int)$this->user['workspace_id']) {
2209 $this->user['workspace_id'] = $this->workspace;
2210 GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
2211 'be_users',
2212 ['workspace_id' => $this->user['workspace_id']],
2213 ['uid' => (int)$this->user['uid']]
2214 );
2215 $this->writelog(4, 0, 0, 0, 'User changed workspace to "' . $this->workspace . '"', []);
2216 }
2217 }
2218
2219 /**
2220 * Sets a temporary workspace in the context of the current backend user.
2221 *
2222 * @param int $workspaceId
2223 * @return bool
2224 */
2225 public function setTemporaryWorkspace($workspaceId)
2226 {
2227 $result = false;
2228 $workspaceRecord = $this->checkWorkspace($workspaceId, '*');
2229
2230 if ($workspaceRecord) {
2231 $this->workspaceRec = $workspaceRecord;
2232 $this->workspace = (int)$workspaceId;
2233 $result = true;
2234 }
2235
2236 return $result;
2237 }
2238
2239 /**
2240 * Sets the default workspace in the context of the current backend user.
2241 */
2242 public function setDefaultWorkspace()
2243 {
2244 $this->workspace = (int)$this->getDefaultWorkspace();
2245 $this->workspaceRec = $this->checkWorkspace($this->workspace, '*');
2246 }
2247
2248 /**
2249 * Return default workspace ID for user,
2250 * if EXT:workspaces is not installed the user will be pushed to the
2251 * Live workspace, if he has access to. If no workspace is available for the user, the workspace ID is set to "-99"
2252 *
2253 * @return int Default workspace id.
2254 */
2255 public function getDefaultWorkspace()
2256 {
2257 if (!ExtensionManagementUtility::isLoaded('workspaces')) {
2258 return 0;
2259 }
2260 // Online is default
2261 if ($this->checkWorkspace(0)) {
2262 return 0;
2263 }
2264 // Otherwise -99 is the fallback
2265 $defaultWorkspace = -99;
2266 // Traverse all workspaces
2267 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_workspace');
2268 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
2269 $result = $queryBuilder->select('*')
2270 ->from('sys_workspace')
2271 ->orderBy('title')
2272 ->execute();
2273 while ($workspaceRecord = $result->fetch()) {
2274 if ($this->checkWorkspace($workspaceRecord)) {
2275 $defaultWorkspace = (int)$workspaceRecord['uid'];
2276 break;
2277 }
2278 }
2279 return $defaultWorkspace;
2280 }
2281
2282 /**
2283 * Writes an entry in the logfile/table
2284 * Documentation in "TYPO3 Core API"
2285 *
2286 * @param int $type Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
2287 * @param int $action Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
2288 * @param int $error Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2289 * @param int $details_nr The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
2290 * @param string $details Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
2291 * @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
2292 * @param string $tablename Table name. Special field used by tce_main.php.
2293 * @param int|string $recuid Record UID. Special field used by tce_main.php.
2294 * @param int|string $recpid Record PID. Special field used by tce_main.php. OBSOLETE
2295 * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
2296 * @param string $NEWid Special field used by tce_main.php. NEWid string of newly created records.
2297 * @param int $userId Alternative Backend User ID (used for logging login actions where this is not yet known).
2298 * @return int Log entry ID.
2299 */
2300 public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0)
2301 {
2302 if (!$userId && !empty($this->user['uid'])) {
2303 $userId = $this->user['uid'];
2304 }
2305
2306 if (!empty($this->user['ses_backuserid'])) {
2307 if (empty($data)) {
2308 $data = [];
2309 }
2310 $data['originalUser'] = $this->user['ses_backuserid'];
2311 }
2312
2313 $fields = [
2314 'userid' => (int)$userId,
2315 'type' => (int)$type,
2316 'action' => (int)$action,
2317 'error' => (int)$error,
2318 'details_nr' => (int)$details_nr,
2319 'details' => $details,
2320 'log_data' => serialize($data),
2321 'tablename' => $tablename,
2322 'recuid' => (int)$recuid,
2323 'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2324 'tstamp' => $GLOBALS['EXEC_TIME'] ?? time(),
2325 'event_pid' => (int)$event_pid,
2326 'NEWid' => $NEWid,
2327 'workspace' => $this->workspace
2328 ];
2329
2330 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('sys_log');
2331 $connection->insert(
2332 'sys_log',
2333 $fields,
2334 [
2335 \PDO::PARAM_INT,
2336 \PDO::PARAM_INT,
2337 \PDO::PARAM_INT,
2338 \PDO::PARAM_INT,
2339 \PDO::PARAM_INT,
2340 \PDO::PARAM_STR,
2341 \PDO::PARAM_STR,
2342 \PDO::PARAM_STR,
2343 \PDO::PARAM_INT,
2344 \PDO::PARAM_STR,
2345 \PDO::PARAM_INT,
2346 \PDO::PARAM_INT,
2347 \PDO::PARAM_STR,
2348 \PDO::PARAM_STR,
2349 ]
2350 );
2351
2352 return (int)$connection->lastInsertId('sys_log');
2353 }
2354
2355 /**
2356 * Simple logging function
2357 *
2358 * @param string $message Log message
2359 * @param string $extKey Option extension key / module name
2360 * @param int $error Error level. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2361 * @return int Log entry UID
2362 * @deprecated since core v9, will be removed with core v10
2363 */
2364 public function simplelog($message, $extKey = '', $error = 0)
2365 {
2366 trigger_error('This method will be removed in TYPO3 v10.', E_USER_DEPRECATED);
2367 return $this->writelog(4, 0, $error, 0, ($extKey ? '[' . $extKey . '] ' : '') . $message, []);
2368 }
2369
2370 /**
2371 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
2372 * If a login fails, this function is called. It will look up the sys_log to see if there
2373 * have been more than $max failed logins the last $secondsBack seconds (default 3600).
2374 * If so, an email with a warning is sent to $email.
2375 *
2376 * @param string $email Email address
2377 * @param int $secondsBack Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
2378 * @param int $max Max allowed failures before a warning mail is sent
2379 * @access private
2380 */
2381 public function checkLogFailures($email, $secondsBack = 3600, $max = 3)
2382 {
2383 if ($email) {
2384 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
2385
2386 // Get last flag set in the log for sending
2387 $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
2388 $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_log');
2389 $queryBuilder->select('tstamp')
2390 ->from('sys_log')
2391 ->where(
2392 $queryBuilder->expr()->eq(
2393 'type',
2394 $queryBuilder->createNamedParameter(255, \PDO::PARAM_INT)
2395 ),
2396 $queryBuilder->expr()->eq(
2397 'action',
2398 $queryBuilder->createNamedParameter(4, \PDO::PARAM_INT)
2399 ),
2400 $queryBuilder->expr()->gt(
2401 'tstamp',
2402 $queryBuilder->createNamedParameter($theTimeBack, \PDO::PARAM_INT)
2403 )
2404 )
2405 ->orderBy('tstamp', 'DESC')
2406 ->setMaxResults(1);
2407 if ($testRow = $queryBuilder->execute()->fetch(\PDO::FETCH_ASSOC)) {
2408 $theTimeBack = $testRow['tstamp'];
2409 }
2410
2411 $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_log');
2412 $result = $queryBuilder->select('*')
2413 ->from('sys_log')
2414 ->where(
2415 $queryBuilder->expr()->eq(
2416 'type',
2417 $queryBuilder->createNamedParameter(255, \PDO::PARAM_INT)
2418 ),
2419 $queryBuilder->expr()->eq(
2420 'action',
2421 $queryBuilder->createNamedParameter(3, \PDO::PARAM_INT)
2422 ),
2423 $queryBuilder->expr()->neq(
2424 'error',
2425 $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
2426 ),
2427 $queryBuilder->expr()->gt(
2428 'tstamp',
2429 $queryBuilder->createNamedParameter($theTimeBack, \PDO::PARAM_INT)
2430 )
2431 )
2432 ->orderBy('tstamp')
2433 ->execute();
2434
2435 // Check for more than $max number of error failures with the last period.
2436 if ($result->rowCount() > $max) {
2437 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
2438 $subject = 'TYPO3 Login Failure Warning (at ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . ')';
2439 $email_body = 'There have been some attempts (' . $result->rowCount() . ') to login at the TYPO3
2440 site "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '" (' . GeneralUtility::getIndpEnv('HTTP_HOST') . ').
2441
2442 This is a dump of the failures:
2443
2444 ';
2445 while ($row = $result->fetch(\PDO::FETCH_ASSOC)) {
2446 $theData = unserialize($row['log_data']);
2447 $email_body .= date(
2448 $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
2449 $row['tstamp']
2450 ) . ': ' . @sprintf($row['details'], (string)$theData[0], (string)$theData[1], (string)$theData[2]);
2451 $email_body .= LF;
2452 }
2453 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2454 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2455 $mail->setTo($email)->setSubject($subject)->setBody($email_body);
2456 $mail->send();
2457 // Logout written to log
2458 $this->writelog(255, 4, 0, 3, 'Failure warning (%s failures within %s seconds) sent by email to %s', [$result->rowCount(), $secondsBack, $email]);
2459 }
2460 }
2461 }
2462
2463 /**
2464 * Getter for the cookie name
2465 *
2466 * @static
2467 * @return string returns the configured cookie name
2468 */
2469 public static function getCookieName()
2470 {
2471 $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
2472 if (empty($configuredCookieName)) {
2473 $configuredCookieName = 'be_typo_user';
2474 }
2475 return $configuredCookieName;
2476 }
2477
2478 /**
2479 * If TYPO3_CONF_VARS['BE']['enabledBeUserIPLock'] is enabled and
2480 * an IP-list is found in the User TSconfig objString "options.lockToIP",
2481 * then make an IP comparison with REMOTE_ADDR and check if the IP address matches
2482 *
2483 * @return bool TRUE, if IP address validates OK (or no check is done at all because no restriction is set)
2484 */
2485 public function checkLockToIP()
2486 {
2487 $isValid = true;
2488 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['enabledBeUserIPLock']) {
2489 $IPList = $this->getTSConfigVal('options.lockToIP');
2490 if (trim($IPList)) {
2491 $isValid = GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $IPList);
2492 }
2493 }
2494 return $isValid;
2495 }
2496
2497 /**
2498 * Check if user is logged in and if so, call ->fetchGroupData() to load group information and
2499 * access lists of all kind, further check IP, set the ->uc array and send login-notification email if required.
2500 * If no user is logged in the default behaviour is to exit with an error message.
2501 * This function is called right after ->start() in fx. the TYPO3 Bootstrap.
2502 *
2503 * @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.
2504 * @throws \RuntimeException
2505 */
2506 public function backendCheckLogin($proceedIfNoUserIsLoggedIn = false)
2507 {
2508 if (empty($this->user['uid'])) {
2509 if ($proceedIfNoUserIsLoggedIn === false) {
2510 $url = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir;
2511 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($url);
2512 }
2513 } else {
2514 // ...and if that's the case, call these functions
2515 $this->fetchGroupData();
2516 // The groups are fetched and ready for permission checking in this initialization.
2517 // Tables.php must be read before this because stuff like the modules has impact in this
2518 if ($this->checkLockToIP()) {
2519 if ($this->isUserAllowedToLogin()) {
2520 // Setting the UC array. It's needed with fetchGroupData first, due to default/overriding of values.
2521 $this->backendSetUC();
2522 if ($this->loginSessionStarted) {
2523 // Process hooks
2524 $hooks = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['backendUserLogin'];
2525 foreach ($hooks ?? [] as $_funcRef) {
2526 $_params = ['user' => $this->user];
2527 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2528 }
2529 // Email at login, if feature is enabled in configuration
2530 $this->emailAtLogin();
2531 }
2532 } else {
2533 throw new \RuntimeException('Login Error: TYPO3 is in maintenance mode at the moment. Only administrators are allowed access.', 1294585860);
2534 }
2535 } else {
2536 throw new \RuntimeException('Login Error: IP locking prevented you from being authorized. Can\'t proceed, sorry.', 1294585861);
2537 }
2538 }
2539 }
2540
2541 /**
2542 * Initialize the internal ->uc array for the backend user
2543 * Will make the overrides if necessary, and write the UC back to the be_users record if changes has happened
2544 *
2545 * @internal
2546 */
2547 public function backendSetUC()
2548 {
2549 // UC - user configuration is a serialized array inside the user object
2550 // If there is a saved uc we implement that instead of the default one.
2551 $this->unpack_uc();
2552 // Setting defaults if uc is empty
2553 $updated = false;
2554 $originalUc = [];
2555 if (is_array($this->uc) && isset($this->uc['ucSetByInstallTool'])) {
2556 $originalUc = $this->uc;
2557 unset($originalUc['ucSetByInstallTool'], $this->uc);
2558 }
2559 if (!is_array($this->uc)) {
2560 $this->uc = array_merge(
2561 $this->uc_default,
2562 (array)$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUC'],
2563 GeneralUtility::removeDotsFromTS((array)$this->getTSConfigProp('setup.default')),
2564 $originalUc
2565 );
2566 $this->overrideUC();
2567 $updated = true;
2568 }
2569 // If TSconfig is updated, update the defaultUC.
2570 if ($this->userTSUpdated) {
2571 $this->overrideUC();
2572 $updated = true;
2573 }
2574 // Setting default lang from be_user record.
2575 if (!isset($this->uc['lang'])) {
2576 $this->uc['lang'] = $this->user['lang'];
2577 $updated = true;
2578 }
2579 // Setting the time of the first login:
2580 if (!isset($this->uc['firstLoginTimeStamp'])) {
2581 $this->uc['firstLoginTimeStamp'] = $GLOBALS['EXEC_TIME'];
2582 $updated = true;
2583 }
2584 // Saving if updated.
2585 if ($updated) {
2586 $this->writeUC();
2587 }
2588 }
2589
2590 /**
2591 * Override: Call this function every time the uc is updated.
2592 * That is 1) by reverting to default values, 2) in the setup-module, 3) userTS changes (userauthgroup)
2593 *
2594 * @internal
2595 */
2596 public function overrideUC()
2597 {
2598 $this->uc = array_merge((array)$this->uc, (array)$this->getTSConfigProp('setup.override'));
2599 }
2600
2601 /**
2602 * Clears the user[uc] and ->uc to blank strings. Then calls ->backendSetUC() to fill it again with reset contents
2603 *
2604 * @internal
2605 */
2606 public function resetUC()
2607 {
2608 $this->user['uc'] = '';
2609 $this->uc = '';
2610 $this->backendSetUC();
2611 }
2612
2613 /**
2614 * Sends an email notification to warning_email_address and/or the logged-in user's email address.
2615 *
2616 * @access private
2617 */
2618 private function emailAtLogin()
2619 {
2620 // Send notify-mail
2621 $subject = 'At "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '"' . ' from '
2622 . GeneralUtility::getIndpEnv('REMOTE_ADDR')
2623 . (GeneralUtility::getIndpEnv('REMOTE_HOST') ? ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')' : '');
2624 $msg = sprintf(
2625 'User "%s" logged in from %s (%s) at "%s" (%s)',
2626 $this->user['username'],
2627 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2628 GeneralUtility::getIndpEnv('REMOTE_HOST'),
2629 $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
2630 GeneralUtility::getIndpEnv('HTTP_HOST')
2631 );
2632 // Warning email address
2633 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr']) {
2634 $warn = 0;
2635 $prefix = '';
2636 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode'] & 1) {
2637 // first bit: All logins
2638 $warn = 1;
2639 $prefix = $this->isAdmin() ? '[AdminLoginWarning]' : '[LoginWarning]';
2640 }
2641 if ($this->isAdmin() && (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode'] & 2) {
2642 // second bit: Only admin-logins
2643 $warn = 1;
2644 $prefix = '[AdminLoginWarning]';
2645 }
2646 if ($warn) {
2647 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2648 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2649 $mail->setTo($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'])->setSubject($prefix . ' ' . $subject)->setBody($msg);
2650 $mail->send();
2651 }
2652 }
2653 // Trigger an email to the current BE user, if this has been enabled in the user configuration
2654 if ($this->uc['emailMeAtLogin'] && strstr($this->user['email'], '@')) {
2655 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2656 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2657 $mail->setTo($this->user['email'])->setSubject($subject)->setBody($msg);
2658 $mail->send();
2659 }
2660 }
2661
2662 /**
2663 * Determines whether a backend user is allowed to access the backend.
2664 *
2665 * The conditions are:
2666 * + backend user is a regular user and adminOnly is not defined
2667 * + backend user is an admin user
2668 * + backend user is used in CLI context and adminOnly is explicitly set to "2" (see CommandLineUserAuthentication)
2669 * + backend user is being controlled by an admin user
2670 *
2671 * @return bool Whether a backend user is allowed to access the backend
2672 */
2673 protected function isUserAllowedToLogin()
2674 {
2675 $isUserAllowedToLogin = false;
2676 $adminOnlyMode = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'];
2677 // Backend user is allowed if adminOnly is not set or user is an admin:
2678 if (!$adminOnlyMode || $this->isAdmin()) {
2679 $isUserAllowedToLogin = true;
2680 } elseif ($this->user['ses_backuserid']) {
2681 $backendUserId = (int)$this->user['ses_backuserid'];
2682 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('be_users');
2683 $isUserAllowedToLogin = (bool)$queryBuilder->count('uid')
2684 ->from('be_users')
2685 ->where(
2686 $queryBuilder->expr()->eq(
2687 'uid',
2688 $queryBuilder->createNamedParameter($backendUserId, \PDO::PARAM_INT)
2689 ),
2690 $queryBuilder->expr()->eq('admin', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT))
2691 )
2692 ->execute()
2693 ->fetchColumn(0);
2694 }
2695 return $isUserAllowedToLogin;
2696 }
2697
2698 /**
2699 * Logs out the current user and clears the form protection tokens.
2700 */
2701 public function logoff()
2702 {
2703 if (isset($GLOBALS['BE_USER']) && $GLOBALS['BE_USER'] instanceof self && isset($GLOBALS['BE_USER']->user['uid'])) {
2704 \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->clean();
2705 }
2706 parent::logoff();
2707 }
2708 }