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