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