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