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