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