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