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