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