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