5450d6a3bbc58ccc35c4bf41491da74cc50f60a5
[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 // User mount points are only added if the user is not an admin as admins do not have visible
1232 // mountpoints fields. Processing them loads mountpoints defined when the user was a non-admin.
1233 if (!$this->isAdmin()) {
1234 // Database mountpoints
1235 $this->dataLists['webmount_list'] = $this->user['db_mountpoints'];
1236 // File mountpoints
1237 $this->dataLists['filemount_list'] = $this->user['file_mountpoints'];
1238 }
1239 // Fileoperation permissions
1240 $this->dataLists['file_permissions'] = $this->user['file_permissions'];
1241 // Setting default User TSconfig:
1242 $this->TSdataArray[] = $this->addTScomment('From $GLOBALS["TYPO3_CONF_VARS"]["BE"]["defaultUserTSconfig"]:')
1243 . $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
1244 // Default TSconfig for admin-users
1245 if ($this->isAdmin()) {
1246 $this->TSdataArray[] = $this->addTScomment('"admin" user presets:') . '
1247 admPanel.enable.all = 1
1248 ';
1249 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('sys_note')) {
1250 $this->TSdataArray[] = '
1251 // Setting defaults for sys_note author / email...
1252 TCAdefaults.sys_note.author = ' . $this->user['realName'] . '
1253 TCAdefaults.sys_note.email = ' . $this->user['email'] . '
1254 ';
1255 }
1256 }
1257 // BE_GROUPS:
1258 // Get the groups...
1259 // 240203: Since the group-field never contains any references to groups with a prepended table name
1260 // we think it's safe to just intExplode and re-implode - which should be much faster than the other function call.
1261 $grList = $this->db->cleanIntList($this->user[$this->usergroup_column]);
1262 if ($grList) {
1263 // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc.
1264 // Refer to fetchGroups() function.
1265 $this->fetchGroups($grList);
1266 }
1267
1268 // Populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
1269 $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
1270 // Finally this is the list of group_uid's in the order they are parsed (including subgroups!)
1271 // and without duplicates (duplicates are presented with their last entrance in the list,
1272 // which thus reflects the order of the TypoScript in TSconfig)
1273 $this->groupList = implode(',', $this->userGroupsUID);
1274 $this->setCachedList($this->groupList);
1275
1276 // Add the TSconfig for this specific user:
1277 $this->TSdataArray[] = $this->addTScomment('USER TSconfig field') . $this->user['TSconfig'];
1278 // Check include lines.
1279 $this->TSdataArray = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines_array($this->TSdataArray);
1280 // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
1281 $this->userTS_text = implode(LF . '[GLOBAL]' . LF, $this->TSdataArray);
1282 if (!$this->userTS_dontGetCached) {
1283 // Perform TS-Config parsing with condition matching
1284 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Configuration\TsConfigParser::class);
1285 $res = $parseObj->parseTSconfig($this->userTS_text, 'userTS');
1286 if ($res) {
1287 $this->userTS = $res['TSconfig'];
1288 $this->userTSUpdated = (bool)$res['cached'];
1289 }
1290 } else {
1291 // Parsing the user TSconfig (or getting from cache)
1292 $hash = md5('userTS:' . $this->userTS_text);
1293 $cachedContent = BackendUtility::getHash($hash);
1294 if (is_array($cachedContent) && !$this->userTS_dontGetCached) {
1295 $this->userTS = $cachedContent;
1296 } else {
1297 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
1298 $parseObj->parse($this->userTS_text);
1299 $this->userTS = $parseObj->setup;
1300 BackendUtility::storeHash($hash, $this->userTS, 'BE_USER_TSconfig');
1301 // Update UC:
1302 $this->userTSUpdated = TRUE;
1303 }
1304 }
1305 // Processing webmounts
1306 // Admin's always have the root mounted
1307 if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) {
1308 $this->dataLists['webmount_list'] = '0,' . $this->dataLists['webmount_list'];
1309 }
1310 // The lists are cleaned for duplicates
1311 $this->groupData['webmounts'] = GeneralUtility::uniqueList($this->dataLists['webmount_list']);
1312 $this->groupData['pagetypes_select'] = GeneralUtility::uniqueList($this->dataLists['pagetypes_select']);
1313 $this->groupData['tables_select'] = GeneralUtility::uniqueList($this->dataLists['tables_modify'] . ',' . $this->dataLists['tables_select']);
1314 $this->groupData['tables_modify'] = GeneralUtility::uniqueList($this->dataLists['tables_modify']);
1315 $this->groupData['non_exclude_fields'] = GeneralUtility::uniqueList($this->dataLists['non_exclude_fields']);
1316 $this->groupData['explicit_allowdeny'] = GeneralUtility::uniqueList($this->dataLists['explicit_allowdeny']);
1317 $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($this->dataLists['allowed_languages']);
1318 $this->groupData['custom_options'] = GeneralUtility::uniqueList($this->dataLists['custom_options']);
1319 $this->groupData['modules'] = GeneralUtility::uniqueList($this->dataLists['modList']);
1320 $this->groupData['file_permissions'] = GeneralUtility::uniqueList($this->dataLists['file_permissions']);
1321 $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
1322
1323 // Checking read access to webmounts:
1324 if (trim($this->groupData['webmounts']) !== '') {
1325 $webmounts = explode(',', $this->groupData['webmounts']);
1326 // Explode mounts
1327 // Selecting all webmounts with permission clause for reading
1328 $where = 'deleted=0 AND uid IN (' . $this->groupData['webmounts'] . ') AND ' . $this->getPagePermsClause(1);
1329 $MProws = $this->db->exec_SELECTgetRows('uid', 'pages', $where, '', '', '', 'uid');
1330 foreach ($webmounts as $idx => $mountPointUid) {
1331 // If the mount ID is NOT found among selected pages, unset it:
1332 if ($mountPointUid > 0 && !isset($MProws[$mountPointUid])) {
1333 unset($webmounts[$idx]);
1334 }
1335 }
1336 // Implode mounts in the end.
1337 $this->groupData['webmounts'] = implode(',', $webmounts);
1338 }
1339 // Setting up workspace situation (after webmounts are processed!):
1340 $this->workspaceInit();
1341 }
1342 }
1343
1344 /**
1345 * Fetches the group records, subgroups and fills internal arrays.
1346 * Function is called recursively to fetch subgroups
1347 *
1348 * @param string $grList Commalist of be_groups uid numbers
1349 * @param string $idList List of already processed be_groups-uids so the function will not fall into an eternal recursion.
1350 * @return void
1351 * @access private
1352 */
1353 public function fetchGroups($grList, $idList = '') {
1354 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
1355 $lockToDomain_SQL = ' AND (lockToDomain=\'\' OR lockToDomain IS NULL OR lockToDomain=\'' . GeneralUtility::getIndpEnv('HTTP_HOST') . '\')';
1356 $whereSQL = 'deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $grList . ')' . $lockToDomain_SQL;
1357 // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
1358 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'])) {
1359 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] as $classRef) {
1360 $hookObj = GeneralUtility::getUserObj($classRef);
1361 if (method_exists($hookObj, 'fetchGroupQuery_processQuery')) {
1362 $whereSQL = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, $whereSQL);
1363 }
1364 }
1365 }
1366 $res = $this->db->exec_SELECTquery('*', $this->usergroup_table, $whereSQL);
1367 // The userGroups array is filled
1368 while ($row = $this->db->sql_fetch_assoc($res)) {
1369 $this->userGroups[$row['uid']] = $row;
1370 }
1371 $this->db->sql_free_result($res);
1372 // Traversing records in the correct order
1373 $include_staticArr = GeneralUtility::intExplode(',', $grList);
1374 // Traversing list
1375 foreach ($include_staticArr as $uid) {
1376 // Get row:
1377 $row = $this->userGroups[$uid];
1378 // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
1379 if (is_array($row) && !GeneralUtility::inList($idList, $uid)) {
1380 // Include sub groups
1381 if (trim($row['subgroup'])) {
1382 // Make integer list
1383 $theList = implode(',', GeneralUtility::intExplode(',', $row['subgroup']));
1384 // Call recursively, pass along list of already processed groups so they are not recursed again.
1385 $this->fetchGroups($theList, $idList . ',' . $uid);
1386 }
1387 // Add the group uid, current list, TSconfig to the internal arrays.
1388 $this->includeGroupArray[] = $uid;
1389 $this->includeHierarchy[] = $idList;
1390 $this->TSdataArray[] = $this->addTScomment('Group "' . $row['title'] . '" [' . $row['uid'] . '] TSconfig field:') . $row['TSconfig'];
1391 // Mount group database-mounts
1392 if (($this->user['options'] & Permission::PAGE_SHOW) == 1) {
1393 $this->dataLists['webmount_list'] .= ',' . $row['db_mountpoints'];
1394 }
1395 // Mount group file-mounts
1396 if (($this->user['options'] & Permission::PAGE_EDIT) == 2) {
1397 $this->dataLists['filemount_list'] .= ',' . $row['file_mountpoints'];
1398 }
1399 // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
1400 $this->dataLists['modList'] .= ',' . $row['groupMods'];
1401 $this->dataLists['tables_select'] .= ',' . $row['tables_select'];
1402 $this->dataLists['tables_modify'] .= ',' . $row['tables_modify'];
1403 $this->dataLists['pagetypes_select'] .= ',' . $row['pagetypes_select'];
1404 $this->dataLists['non_exclude_fields'] .= ',' . $row['non_exclude_fields'];
1405 $this->dataLists['explicit_allowdeny'] .= ',' . $row['explicit_allowdeny'];
1406 $this->dataLists['allowed_languages'] .= ',' . $row['allowed_languages'];
1407 $this->dataLists['custom_options'] .= ',' . $row['custom_options'];
1408 $this->dataLists['file_permissions'] .= ',' . $row['file_permissions'];
1409 // Setting workspace permissions:
1410 $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
1411 // If this function is processing the users OWN group-list (not subgroups) AND
1412 // if the ->firstMainGroup is not set, then the ->firstMainGroup will be set.
1413 if ($idList === '' && !$this->firstMainGroup) {
1414 $this->firstMainGroup = $uid;
1415 }
1416 }
1417 }
1418 // HOOK: fetchGroups_postProcessing
1419 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'])) {
1420 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] as $_funcRef) {
1421 $_params = array();
1422 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1423 }
1424 }
1425 }
1426
1427 /**
1428 * Updates the field be_users.usergroup_cached_list if the groupList of the user
1429 * has changed/is different from the current list.
1430 * The field "usergroup_cached_list" contains the list of groups which the user is a member of.
1431 * After authentication (where these functions are called...) one can depend on this list being
1432 * a representation of the exact groups/subgroups which the BE_USER has membership with.
1433 *
1434 * @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.
1435 * @return void
1436 * @access private
1437 */
1438 public function setCachedList($cList) {
1439 if ((string)$cList != (string)$this->user['usergroup_cached_list']) {
1440 $this->db->exec_UPDATEquery('be_users', 'uid=' . (int)$this->user['uid'], array('usergroup_cached_list' => $cList));
1441 }
1442 }
1443
1444 /**
1445 * Sets up all file storages for a user.
1446 * Needs to be called AFTER the groups have been loaded.
1447 *
1448 * @return void
1449 */
1450 protected function initializeFileStorages() {
1451 $this->fileStorages = array();
1452 /** @var $storageRepository \TYPO3\CMS\Core\Resource\StorageRepository */
1453 $storageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
1454 // Admin users have all file storages visible, without any filters
1455 if ($this->isAdmin()) {
1456 $storageObjects = $storageRepository->findAll();
1457 foreach ($storageObjects as $storageObject) {
1458 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1459 }
1460 } else {
1461 // Regular users only have storages that are defined in their filemounts
1462 // Permissions and file mounts for the storage are added in StoragePermissionAspect
1463 foreach ($this->getFileMountRecords() as $row) {
1464 if (!array_key_exists((int)$row['base'], $this->fileStorages)) {
1465 $storageObject = $storageRepository->findByUid($row['base']);
1466 if ($storageObject) {
1467 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1468 }
1469 }
1470 }
1471 }
1472
1473 // This has to be called always in order to set certain filters
1474 $this->evaluateUserSpecificFileFilterSettings();
1475 }
1476
1477 /**
1478 * Returns an array of category mount points. The category permissions from BE Groups
1479 * are also taken into consideration and are merged into User permissions.
1480 *
1481 * @return array
1482 */
1483 public function getCategoryMountPoints() {
1484 $categoryMountPoints = '';
1485
1486 // Category mounts of the groups
1487 if (is_array($this->userGroups)) {
1488 foreach ($this->userGroups as $group) {
1489 if ($group['category_perms']) {
1490 $categoryMountPoints .= ',' . $group['category_perms'];
1491 }
1492 }
1493 }
1494
1495 // Category mounts of the user record
1496 if ($this->user['category_perms']) {
1497 $categoryMountPoints .= ',' . $this->user['category_perms'];
1498 }
1499
1500 // Make the ids unique
1501 $categoryMountPoints = GeneralUtility::trimExplode(',', $categoryMountPoints);
1502 $categoryMountPoints = array_filter($categoryMountPoints); // remove empty value
1503 $categoryMountPoints = array_unique($categoryMountPoints); // remove unique value
1504
1505 return $categoryMountPoints;
1506 }
1507
1508 /**
1509 * Returns an array of file mount records, taking workspaces and user home and group home directories into account
1510 * Needs to be called AFTER the groups have been loaded.
1511 *
1512 * @return array
1513 * @internal
1514 */
1515 public function getFileMountRecords() {
1516 static $fileMountRecordCache = array();
1517
1518 if (!empty($fileMountRecordCache)) {
1519 return $fileMountRecordCache;
1520 }
1521
1522 // Processing file mounts (both from the user and the groups)
1523 $fileMounts = array_unique(GeneralUtility::intExplode(',', $this->dataLists['filemount_list'], TRUE));
1524
1525 // Limit file mounts if set in workspace record
1526 if ($this->workspace > 0 && !empty($this->workspaceRec['file_mountpoints'])) {
1527 $workspaceFileMounts = GeneralUtility::intExplode(',', $this->workspaceRec['file_mountpoints'], TRUE);
1528 $fileMounts = array_intersect($fileMounts, $workspaceFileMounts);
1529 }
1530
1531 if (!empty($fileMounts)) {
1532 $orderBy = isset($GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'])
1533 ? $this->db->stripOrderBy($GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'])
1534 : 'sorting';
1535 $fileMountRecords = $this->db->exec_SELECTgetRows(
1536 '*',
1537 'sys_filemounts',
1538 'deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . implode(',', $fileMounts) . ')',
1539 '',
1540 $orderBy
1541 );
1542 foreach ($fileMountRecords as $fileMount) {
1543 $fileMountRecordCache[$fileMount['base'] . $fileMount['path']] = $fileMount;
1544 }
1545 }
1546
1547 // Read-only file mounts
1548 $readOnlyMountPoints = trim($GLOBALS['BE_USER']->getTSConfigVal('options.folderTree.altElementBrowserMountPoints'));
1549 if ($readOnlyMountPoints) {
1550 // We cannot use the API here but need to fetch the default storage record directly
1551 // to not instantiate it (which directly applies mount points) before all mount points are resolved!
1552 $whereClause = 'is_default=1 ' . BackendUtility::BEenableFields('sys_file_storage') . BackendUtility::deleteClause('sys_file_storage');
1553 $defaultStorageRow = $this->db->exec_SELECTgetSingleRow('uid', 'sys_file_storage', $whereClause);
1554 $readOnlyMountPointArray = GeneralUtility::trimExplode(',', $readOnlyMountPoints);
1555 foreach ($readOnlyMountPointArray as $readOnlyMountPoint) {
1556 $readOnlyMountPointConfiguration = GeneralUtility::trimExplode(':', $readOnlyMountPoint);
1557 if (count($readOnlyMountPointConfiguration) === 2) {
1558 // A storage is passed in the configuration
1559 $storageUid = (int)$readOnlyMountPointConfiguration[0];
1560 $path = $readOnlyMountPointConfiguration[1];
1561 } else {
1562 if (empty($defaultStorageRow)) {
1563 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);
1564 }
1565 // Backwards compatibility: If no storage is passed, we use the default storage
1566 $storageUid = $defaultStorageRow['uid'];
1567 $path = $readOnlyMountPointConfiguration[0];
1568 }
1569 $fileMountRecordCache[$storageUid . $path] = array(
1570 'base' => $storageUid,
1571 'title' => $path,
1572 'path' => $path,
1573 'read_only' => TRUE
1574 );
1575 }
1576 }
1577
1578
1579 // Personal or Group filemounts are not accessible if file mount list is set in workspace record
1580 if ($this->workspace <= 0 || empty($this->workspaceRec['file_mountpoints'])) {
1581 // If userHomePath is set, we attempt to mount it
1582 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
1583 list($userHomeStorageUid, $userHomeFilter) = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'], 2);
1584 $userHomeStorageUid = (int)$userHomeStorageUid;
1585 $userHomeFilter = '/' . ltrim($userHomeFilter, '/');
1586 if ($userHomeStorageUid > 0) {
1587 // Try and mount with [uid]_[username]
1588 $path = $userHomeFilter . $this->user['uid'] . '_' . $this->user['username'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1589 $fileMountRecordCache[$userHomeStorageUid . $path] = array(
1590 'base' => $userHomeStorageUid,
1591 'title' => $this->user['username'],
1592 'path' => $path,
1593 'read_only' => FALSE,
1594 'user_mount' => TRUE
1595 );
1596 // Try and mount with only [uid]
1597 $path = $userHomeFilter . $this->user['uid'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1598 $fileMountRecordCache[$userHomeStorageUid . $path] = array(
1599 'base' => $userHomeStorageUid,
1600 'title' => $this->user['username'],
1601 'path' => $path,
1602 'read_only' => FALSE,
1603 'user_mount' => TRUE
1604 );
1605 }
1606 }
1607
1608 // Mount group home-dirs
1609 if ((is_array($this->user) && $this->user['options'] & Permission::PAGE_EDIT) == 2 && $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'] != '') {
1610 // If groupHomePath is set, we attempt to mount it
1611 list($groupHomeStorageUid, $groupHomeFilter) = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'], 2);
1612 $groupHomeStorageUid = (int)$groupHomeStorageUid;
1613 $groupHomeFilter = '/' . ltrim($groupHomeFilter, '/');
1614 if ($groupHomeStorageUid > 0) {
1615 foreach ($this->userGroups as $groupData) {
1616 $path = $groupHomeFilter . $groupData['uid'];
1617 $fileMountRecordCache[$groupHomeStorageUid . $path] = array(
1618 'base' => $groupHomeStorageUid,
1619 'title' => $groupData['title'],
1620 'path' => $path,
1621 'read_only' => FALSE,
1622 'user_mount' => TRUE
1623 );
1624 }
1625 }
1626 }
1627 }
1628
1629 return $fileMountRecordCache;
1630 }
1631
1632 /**
1633 * Returns an array with the filemounts for the user.
1634 * Each filemount is represented with an array of a "name", "path" and "type".
1635 * If no filemounts an empty array is returned.
1636 *
1637 * @api
1638 * @return \TYPO3\CMS\Core\Resource\ResourceStorage[]
1639 */
1640 public function getFileStorages() {
1641 // Initializing file mounts after the groups are fetched
1642 if ($this->fileStorages === NULL) {
1643 $this->initializeFileStorages();
1644 }
1645 return $this->fileStorages;
1646 }
1647
1648 /**
1649 * Adds filters based on what the user has set
1650 * this should be done in this place, and called whenever needed,
1651 * but only when needed
1652 *
1653 * @return void
1654 */
1655 public function evaluateUserSpecificFileFilterSettings() {
1656 // Add the option for also displaying the non-hidden files
1657 if ($this->uc['showHiddenFilesAndFolders']) {
1658 \TYPO3\CMS\Core\Resource\Filter\FileNameFilter::setShowHiddenFilesAndFolders(TRUE);
1659 }
1660 }
1661
1662 /**
1663 * Returns the information about file permissions.
1664 * Previously, this was stored in the DB field fileoper_perms now it is file_permissions.
1665 * Besides it can be handled via userTSconfig
1666 *
1667 * permissions.file.default {
1668 * addFile = 1
1669 * readFile = 1
1670 * writeFile = 1
1671 * copyFile = 1
1672 * moveFile = 1
1673 * renameFile = 1
1674 * unzipFile = 1
1675 * deleteFile = 1
1676 *
1677 * addFolder = 1
1678 * readFolder = 1
1679 * writeFolder = 1
1680 * copyFolder = 1
1681 * moveFolder = 1
1682 * renameFolder = 1
1683 * deleteFolder = 1
1684 * recursivedeleteFolder = 1
1685 * }
1686 *
1687 * # overwrite settings for a specific storageObject
1688 * permissions.file.storage.StorageUid {
1689 * readFile = 1
1690 * recursivedeleteFolder = 0
1691 * }
1692 *
1693 * Please note that these permissions only apply, if the storage has the
1694 * capabilities (browseable, writable), and if the driver allows for writing etc
1695 *
1696 * @api
1697 * @return array
1698 */
1699 public function getFilePermissions() {
1700 if (!isset($this->filePermissions)) {
1701 $filePermissions = array(
1702 // File permissions
1703 'addFile' => FALSE,
1704 'readFile' => FALSE,
1705 'writeFile' => FALSE,
1706 'copyFile' => FALSE,
1707 'moveFile' => FALSE,
1708 'renameFile' => FALSE,
1709 'unzipFile' => FALSE,
1710 'deleteFile' => FALSE,
1711 // Folder permissions
1712 'addFolder' => FALSE,
1713 'readFolder' => FALSE,
1714 'writeFolder' => FALSE,
1715 'copyFolder' => FALSE,
1716 'moveFolder' => FALSE,
1717 'renameFolder' => FALSE,
1718 'deleteFolder' => FALSE,
1719 'recursivedeleteFolder' => FALSE
1720 );
1721 if ($this->isAdmin()) {
1722 $filePermissions = array_map('is_bool', $filePermissions);
1723 } else {
1724 $userGroupRecordPermissions = GeneralUtility::trimExplode(',', $this->groupData['file_permissions'], TRUE);
1725 array_walk(
1726 $userGroupRecordPermissions,
1727 function($permission) use (&$filePermissions) {
1728 $filePermissions[$permission] = TRUE;
1729 }
1730 );
1731
1732 // Finally overlay any userTSconfig
1733 $permissionsTsConfig = $this->getTSConfigProp('permissions.file.default');
1734 if (!empty($permissionsTsConfig)) {
1735 array_walk(
1736 $permissionsTsConfig,
1737 function($value, $permission) use (&$filePermissions) {
1738 $filePermissions[$permission] = (bool)$value;
1739 }
1740 );
1741 }
1742 }
1743 $this->filePermissions = $filePermissions;
1744 }
1745 return $this->filePermissions;
1746 }
1747
1748 /**
1749 * Gets the file permissions for a storage
1750 * by merging any storage-specific permissions for a
1751 * storage with the default settings.
1752 * Admin users will always get the default settings.
1753 *
1754 * @api
1755 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storageObject
1756 * @return array
1757 */
1758 public function getFilePermissionsForStorage(\TYPO3\CMS\Core\Resource\ResourceStorage $storageObject) {
1759 $finalUserPermissions = $this->getFilePermissions();
1760 if (!$this->isAdmin()) {
1761 $storageFilePermissions = $this->getTSConfigProp('permissions.file.storage.' . $storageObject->getUid());
1762 if (!empty($storageFilePermissions)) {
1763 array_walk(
1764 $storageFilePermissions,
1765 function($value, $permission) use (&$finalUserPermissions) {
1766 $finalUserPermissions[$permission] = (bool)$value;
1767 }
1768 );
1769 }
1770 }
1771 return $finalUserPermissions;
1772 }
1773
1774 /**
1775 * Returns a \TYPO3\CMS\Core\Resource\Folder object that is used for uploading
1776 * files by default.
1777 * This is used for RTE and its magic images, as well as uploads
1778 * in the TCEforms fields, unless otherwise configured (will be added in the future)
1779 *
1780 * The default upload folder for a user is the defaultFolder on the first
1781 * filestorage/filemount that the user can access and to which files are allowed to be added
1782 * however, you can set the users' upload folder like this:
1783 *
1784 * options.defaultUploadFolder = 3:myfolder/yourfolder/
1785 *
1786 * @return \TYPO3\CMS\Core\Resource\Folder|boolean The default upload folder for this user
1787 */
1788 public function getDefaultUploadFolder() {
1789 $uploadFolder = $this->getTSConfigVal('options.defaultUploadFolder');
1790 if ($uploadFolder) {
1791 $uploadFolder = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->getFolderObjectFromCombinedIdentifier($uploadFolder);
1792 } else {
1793 foreach($this->getFileStorages() as $storage) {
1794 if ($storage->isDefault()) {
1795 try {
1796 $uploadFolder = $storage->getDefaultFolder();
1797 if ($uploadFolder->checkActionPermission('add')) {
1798 break;
1799 }
1800 $uploadFolder = NULL;
1801 } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
1802 // If the folder is not accessible (no permissions / does not exist) we skip this one.
1803 }
1804 break;
1805 }
1806 }
1807 if (!$uploadFolder instanceof \TYPO3\CMS\Core\Resource\Folder) {
1808 /** @var ResourceStorage $storage */
1809 foreach ($this->getFileStorages() as $storage) {
1810 try {
1811 $uploadFolder = $storage->getDefaultFolder();
1812 if ($uploadFolder->checkActionPermission('add')) {
1813 break;
1814 }
1815 $uploadFolder = NULL;
1816 } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
1817 // If the folder is not accessible (no permissions / does not exist) try the next one.
1818 }
1819 }
1820 }
1821 }
1822 if ($uploadFolder instanceof \TYPO3\CMS\Core\Resource\Folder) {
1823 return $uploadFolder;
1824 } else {
1825 return FALSE;
1826 }
1827 }
1828
1829 /**
1830 * Returns a \TYPO3\CMS\Core\Resource\Folder object that could be used for uploading
1831 * temporary files in user context. The folder _temp_ below the default upload folder
1832 * of the user is used.
1833 *
1834 * @return NULL|\TYPO3\CMS\Core\Resource\Folder
1835 * @see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::getDefaultUploadFolder();
1836 */
1837 public function getDefaultUploadTemporaryFolder() {
1838 $defaultTemporaryFolder = NULL;
1839 $defaultFolder = $this->getDefaultUploadFolder();
1840
1841 if ($defaultFolder !== FALSE) {
1842 $tempFolderName = '_temp_';
1843 $createFolder = !$defaultFolder->hasFolder($tempFolderName);
1844 if ($createFolder === TRUE) {
1845 try {
1846 $defaultTemporaryFolder = $defaultFolder->createFolder($tempFolderName);
1847 } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {}
1848 } else {
1849 $defaultTemporaryFolder = $defaultFolder->getSubfolder($tempFolderName);
1850 }
1851 }
1852
1853 return $defaultTemporaryFolder;
1854 }
1855
1856 /**
1857 * Creates a TypoScript comment with the string text inside.
1858 *
1859 * @param string $str The text to wrap in comment prefixes and delimiters.
1860 * @return string TypoScript comment with the string text inside.
1861 */
1862 public function addTScomment($str) {
1863 $delimiter = '# ***********************************************';
1864 $out = $delimiter . LF;
1865 $lines = GeneralUtility::trimExplode(LF, $str);
1866 foreach ($lines as $v) {
1867 $out .= '# ' . $v . LF;
1868 }
1869 $out .= $delimiter . LF;
1870 return $out;
1871 }
1872
1873 /**
1874 * Initializing workspace.
1875 * Called from within this function, see fetchGroupData()
1876 *
1877 * @return void
1878 * @see fetchGroupData()
1879 */
1880 public function workspaceInit() {
1881 // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
1882 $this->setWorkspace($this->user['workspace_id']);
1883 // Limiting the DB mountpoints if there any selected in the workspace record
1884 $this->initializeDbMountpointsInWorkspace();
1885 if ($allowed_languages = $this->getTSConfigVal('options.workspaces.allowed_languages.' . $this->workspace)) {
1886 $this->groupData['allowed_languages'] = $allowed_languages;
1887 $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($this->groupData['allowed_languages']);
1888 }
1889 }
1890
1891 /**
1892 * Limiting the DB mountpoints if there any selected in the workspace record
1893 *
1894 * @return void
1895 */
1896 protected function initializeDbMountpointsInWorkspace() {
1897 $dbMountpoints = trim($this->workspaceRec['db_mountpoints']);
1898 if ($this->workspace > 0 && $dbMountpoints != '') {
1899 $filteredDbMountpoints = array();
1900 // Notice: We cannot call $this->getPagePermsClause(1);
1901 // as usual because the group-list is not available at this point.
1902 // But bypassing is fine because all we want here is check if the
1903 // workspace mounts are inside the current webmounts rootline.
1904 // The actual permission checking on page level is done elsewhere
1905 // as usual anyway before the page tree is rendered.
1906 $readPerms = '1=1';
1907 // Traverse mount points of the
1908 $dbMountpoints = GeneralUtility::intExplode(',', $dbMountpoints);
1909 foreach ($dbMountpoints as $mpId) {
1910 if ($this->isInWebMount($mpId, $readPerms)) {
1911 $filteredDbMountpoints[] = $mpId;
1912 }
1913 }
1914 // Re-insert webmounts:
1915 $filteredDbMountpoints = array_unique($filteredDbMountpoints);
1916 $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
1917 }
1918 }
1919
1920 /**
1921 * Checking if a workspace is allowed for backend user
1922 *
1923 * @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)
1924 * @param string $fields List of fields to select. Default fields are: uid,title,adminusers,members,reviewers,publish_access,stagechg_notification
1925 * @return array Output will also show how access was granted. Admin users will have a true output regardless of input.
1926 */
1927 public function checkWorkspace($wsRec, $fields = 'uid,title,adminusers,members,reviewers,publish_access,stagechg_notification') {
1928 $retVal = FALSE;
1929 // If not array, look up workspace record:
1930 if (!is_array($wsRec)) {
1931 switch ((string)$wsRec) {
1932 case '0':
1933 $wsRec = array('uid' => $wsRec);
1934 break;
1935 default:
1936 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
1937 $wsRec = $this->db->exec_SELECTgetSingleRow($fields,
1938 'sys_workspace',
1939 'pid=0 AND uid=' . (int)$wsRec . BackendUtility::deleteClause('sys_workspace'),
1940 '',
1941 'title'
1942 );
1943 }
1944 }
1945 }
1946 // If wsRec is set to an array, evaluate it:
1947 if (is_array($wsRec)) {
1948 if ($this->isAdmin()) {
1949 return array_merge($wsRec, array('_ACCESS' => 'admin'));
1950 } else {
1951 switch ((string)$wsRec['uid']) {
1952 case '0':
1953 $retVal = $this->groupData['workspace_perms'] & Permission::PAGE_SHOW
1954 ? array_merge($wsRec, array('_ACCESS' => 'online'))
1955 : FALSE;
1956 break;
1957 default:
1958 // Checking if the guy is admin:
1959 if (GeneralUtility::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
1960 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1961 }
1962 // Checking if he is owner through a user group of his:
1963 foreach ($this->userGroupsUID as $groupUid) {
1964 if (GeneralUtility::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
1965 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1966 }
1967 }
1968 // Checking if he is reviewer user:
1969 if (GeneralUtility::inList($wsRec['reviewers'], 'be_users_' . $this->user['uid'])) {
1970 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1971 }
1972 // Checking if he is reviewer through a user group of his:
1973 foreach ($this->userGroupsUID as $groupUid) {
1974 if (GeneralUtility::inList($wsRec['reviewers'], 'be_groups_' . $groupUid)) {
1975 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1976 }
1977 }
1978 // Checking if he is member as user:
1979 if (GeneralUtility::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
1980 return array_merge($wsRec, array('_ACCESS' => 'member'));
1981 }
1982 // Checking if he is member through a user group of his:
1983 foreach ($this->userGroupsUID as $groupUid) {
1984 if (GeneralUtility::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
1985 return array_merge($wsRec, array('_ACCESS' => 'member'));
1986 }
1987 }
1988 }
1989 }
1990 }
1991 return $retVal;
1992 }
1993
1994 /**
1995 * Uses checkWorkspace() to check if current workspace is available for user.
1996 * This function caches the result and so can be called many times with no performance loss.
1997 *
1998 * @return array See checkWorkspace()
1999 * @see checkWorkspace()
2000 */
2001 public function checkWorkspaceCurrent() {
2002 if (!isset($this->checkWorkspaceCurrent_cache)) {
2003 $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
2004 }
2005 return $this->checkWorkspaceCurrent_cache;
2006 }
2007
2008 /**
2009 * Setting workspace ID
2010 *
2011 * @param int $workspaceId ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
2012 * @return void
2013 */
2014 public function setWorkspace($workspaceId) {
2015 // Check workspace validity and if not found, revert to default workspace.
2016 if (!$this->setTemporaryWorkspace($workspaceId)) {
2017 $this->setDefaultWorkspace();
2018 }
2019 // Unset access cache:
2020 $this->checkWorkspaceCurrent_cache = NULL;
2021 // If ID is different from the stored one, change it:
2022 if ((int)$this->workspace !== (int)$this->user['workspace_id']) {
2023 $this->user['workspace_id'] = $this->workspace;
2024 $this->db->exec_UPDATEquery('be_users', 'uid=' . (int)$this->user['uid'], array('workspace_id' => $this->user['workspace_id']));
2025 $this->simplelog('User changed workspace to "' . $this->workspace . '"');
2026 }
2027 }
2028
2029 /**
2030 * Sets a temporary workspace in the context of the current backend user.
2031 *
2032 * @param int $workspaceId
2033 * @return bool
2034 */
2035 public function setTemporaryWorkspace($workspaceId) {
2036 $result = FALSE;
2037 $workspaceRecord = $this->checkWorkspace($workspaceId, '*');
2038
2039 if ($workspaceRecord) {
2040 $this->workspaceRec = $workspaceRecord;
2041 $this->workspace = (int)$workspaceId;
2042 $result = TRUE;
2043 }
2044
2045 return $result;
2046 }
2047
2048 /**
2049 * Sets the default workspace in the context of the current backend user.
2050 *
2051 * @return void
2052 */
2053 public function setDefaultWorkspace() {
2054 $this->workspace = (int)$this->getDefaultWorkspace();
2055 $this->workspaceRec = $this->checkWorkspace($this->workspace, '*');
2056 }
2057
2058 /**
2059 * Setting workspace preview state for user:
2060 *
2061 * @param bool $previewState State of user preview.
2062 * @return void
2063 */
2064 public function setWorkspacePreview($previewState) {
2065 $this->user['workspace_preview'] = $previewState;
2066 $this->db->exec_UPDATEquery('be_users', 'uid=' . (int)$this->user['uid'], array('workspace_preview' => $this->user['workspace_preview']));
2067 }
2068
2069 /**
2070 * Return default workspace ID for user,
2071 * If EXT:workspaces is not installed the user will be pushed the the
2072 * Live workspace
2073 *
2074 * @return int Default workspace id. If no workspace is available it will be "-99
2075 */
2076 public function getDefaultWorkspace() {
2077 $defaultWorkspace = -99;
2078 if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces') || $this->checkWorkspace(0)) {
2079 // Check online
2080 $defaultWorkspace = 0;
2081 } elseif ($this->checkWorkspace(-1)) {
2082 // Check offline
2083 $defaultWorkspace = -1;
2084 } elseif (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
2085 // Traverse custom workspaces:
2086 $workspaces = $this->db->exec_SELECTgetRows('uid,title,adminusers,members,reviewers', 'sys_workspace', 'pid=0' . BackendUtility::deleteClause('sys_workspace'), '', 'title');
2087 foreach ($workspaces as $rec) {
2088 if ($this->checkWorkspace($rec)) {
2089 $defaultWorkspace = $rec['uid'];
2090 break;
2091 }
2092 }
2093 }
2094 return $defaultWorkspace;
2095 }
2096
2097 /**
2098 * Writes an entry in the logfile/table
2099 * Documentation in "TYPO3 Core API"
2100 *
2101 * @param int $type Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
2102 * @param int $action Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
2103 * @param int $error Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2104 * @param int $details_nr The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
2105 * @param string $details Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
2106 * @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
2107 * @param string $tablename Table name. Special field used by tce_main.php.
2108 * @param int|string $recuid Record UID. Special field used by tce_main.php.
2109 * @param int|string $recpid Record PID. Special field used by tce_main.php. OBSOLETE
2110 * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
2111 * @param string $NEWid Special field used by tce_main.php. NEWid string of newly created records.
2112 * @param int $userId Alternative Backend User ID (used for logging login actions where this is not yet known).
2113 * @return int Log entry ID.
2114 */
2115 public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0) {
2116 if (!$userId && isset($this->user['uid'])) {
2117 $userId = $this->user['uid'];
2118 }
2119
2120 $fields_values = array(
2121 'userid' => (int)$userId,
2122 'type' => (int)$type,
2123 'action' => (int)$action,
2124 'error' => (int)$error,
2125 'details_nr' => (int)$details_nr,
2126 'details' => $details,
2127 'log_data' => serialize($data),
2128 'tablename' => $tablename,
2129 'recuid' => (int)$recuid,
2130 'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2131 'tstamp' => time(),
2132 'event_pid' => (int)$event_pid,
2133 'NEWid' => $NEWid,
2134 'workspace' => $this->workspace
2135 );
2136 $this->db->exec_INSERTquery('sys_log', $fields_values);
2137 return $this->db->sql_insert_id();
2138 }
2139
2140 /**
2141 * Simple logging function
2142 *
2143 * @param string $message Log message
2144 * @param string $extKey Option extension key / module name
2145 * @param int $error Error level. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2146 * @return int Log entry UID
2147 */
2148 public function simplelog($message, $extKey = '', $error = 0) {
2149 return $this->writelog(4, 0, $error, 0, ($extKey ? '[' . $extKey . '] ' : '') . $message, array());
2150 }
2151
2152 /**
2153 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
2154 * If a login fails, this function is called. It will look up the sys_log to see if there
2155 * have been more than $max failed logins the last $secondsBack seconds (default 3600).
2156 * If so, an email with a warning is sent to $email.
2157 *
2158 * @param string $email Email address
2159 * @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.
2160 * @param int $max Max allowed failures before a warning mail is sent
2161 * @return void
2162 * @access private
2163 */
2164 public function checkLogFailures($email, $secondsBack = 3600, $max = 3) {
2165 if ($email) {
2166 // Get last flag set in the log for sending
2167 $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
2168 $res = $this->db->exec_SELECTquery('tstamp', 'sys_log', 'type=255 AND action=4 AND tstamp>' . (int)$theTimeBack, '', 'tstamp DESC', '1');
2169 if ($testRow = $this->db->sql_fetch_assoc($res)) {
2170 $theTimeBack = $testRow['tstamp'];
2171 }
2172 $this->db->sql_free_result($res);
2173 // Check for more than $max number of error failures with the last period.
2174 $res = $this->db->exec_SELECTquery('*', 'sys_log', 'type=255 AND action=3 AND error<>0 AND tstamp>' . (int)$theTimeBack, '', 'tstamp');
2175 if ($this->db->sql_num_rows($res) > $max) {
2176 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
2177 $subject = 'TYPO3 Login Failure Warning (at ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . ')';
2178 $email_body = 'There have been some attempts (' . $this->db->sql_num_rows($res) . ') to login at the TYPO3
2179 site "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '" (' . GeneralUtility::getIndpEnv('HTTP_HOST') . ').
2180
2181 This is a dump of the failures:
2182
2183 ';
2184 while ($testRows = $this->db->sql_fetch_assoc($res)) {
2185 $theData = unserialize($testRows['log_data']);
2186 $email_body .= date(
2187 $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
2188 $testRows['tstamp']
2189 ) . ': ' . @sprintf($testRows['details'], (string)$theData[0], (string)$theData[1], (string)$theData[2]);
2190 $email_body .= LF;
2191 }
2192 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
2193 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2194 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2195 $mail->setTo($email)->setFrom($from)->setSubject($subject)->setBody($email_body);
2196 $mail->send();
2197 // Logout written to log
2198 $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));
2199 $this->db->sql_free_result($res);
2200 }
2201 }
2202 }
2203
2204 /**
2205 * Getter for the cookie name
2206 *
2207 * @static
2208 * @return string returns the configured cookie name
2209 */
2210 static public function getCookieName() {
2211 $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
2212 if (empty($configuredCookieName)) {
2213 $configuredCookieName = 'be_typo_user';
2214 }
2215 return $configuredCookieName;
2216 }
2217
2218 /**
2219 * If TYPO3_CONF_VARS['BE']['enabledBeUserIPLock'] is enabled and
2220 * an IP-list is found in the User TSconfig objString "options.lockToIP",
2221 * then make an IP comparison with REMOTE_ADDR and return the outcome (TRUE/FALSE)
2222 *
2223 * @return bool TRUE, if IP address validates OK (or no check is done at all)
2224 */
2225 public function checkLockToIP() {
2226 $out = 1;
2227 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['enabledBeUserIPLock']) {
2228 $IPList = $this->getTSConfigVal('options.lockToIP');
2229 if (trim($IPList)) {
2230 $baseIP = GeneralUtility::getIndpEnv('REMOTE_ADDR');
2231 $out = GeneralUtility::cmpIP($baseIP, $IPList);
2232 }
2233 }
2234 return $out;
2235 }
2236
2237 /**
2238 * Check if user is logged in and if so, call ->fetchGroupData() to load group information and
2239 * access lists of all kind, further check IP, set the ->uc array and send login-notification email if required.
2240 * If no user is logged in the default behaviour is to exit with an error message,
2241 * but this will happen ONLY if the constant TYPO3_PROCEED_IF_NO_USER is set TRUE.
2242 * This function is called right after ->start() in fx. the TYPO3 CMS bootsrap
2243 *
2244 * @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.
2245 * @throws \RuntimeException
2246 * @return void
2247 */
2248 public function backendCheckLogin($proceedIfNoUserIsLoggedIn = FALSE) {
2249 if (empty($this->user['uid'])) {
2250 if ($proceedIfNoUserIsLoggedIn === FALSE) {
2251 $url = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir;
2252 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($url);
2253 }
2254 } else {
2255 // ...and if that's the case, call these functions
2256 $this->fetchGroupData();
2257 // The groups are fetched and ready for permission checking in this initialization.
2258 // Tables.php must be read before this because stuff like the modules has impact in this
2259 if ($this->checkLockToIP()) {
2260 if ($this->isUserAllowedToLogin()) {
2261 // Setting the UC array. It's needed with fetchGroupData first, due to default/overriding of values.
2262 $this->backendSetUC();
2263 // Email at login - if option set.
2264 $this->emailAtLogin();
2265 } else {
2266 throw new \RuntimeException('Login Error: TYPO3 is in maintenance mode at the moment. Only administrators are allowed access.', 1294585860);
2267 }
2268 } else {
2269 throw new \RuntimeException('Login Error: IP locking prevented you from being authorized. Can\'t proceed, sorry.', 1294585861);
2270 }
2271 }
2272 }
2273
2274 /**
2275 * If the backend script is in CLI mode, it will try to load a backend user named by the CLI module name (in lowercase)
2276 *
2277 * @return bool Returns TRUE if a CLI user was loaded, otherwise FALSE!
2278 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. Please implement this functionality in your own application directly from the outside
2279 */
2280 public function checkCLIuser() {
2281 GeneralUtility::logDeprecatedFunction();
2282 // First, check if cliMode is enabled:
2283 if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
2284 if (!$this->user['uid']) {
2285 if (substr($GLOBALS['MCONF']['name'], 0, 5) == '_CLI_') {
2286 $userName = strtolower($GLOBALS['MCONF']['name']);
2287 $this->setBeUserByName($userName);
2288 if ($this->user['uid']) {
2289 if (!$this->isAdmin()) {
2290 return TRUE;
2291 } else {
2292 fwrite(STDERR, 'ERROR: CLI backend user "' . $userName . '" was ADMIN which is not allowed!' . LF . LF);
2293 die(3);
2294 }
2295 } else {
2296 fwrite(STDERR, 'ERROR: No backend user named "' . $userName . '" was found!' . LF . LF);
2297 die(3);
2298 }
2299 } else {
2300 fwrite(STDERR, 'ERROR: Module name, "' . $GLOBALS['MCONF']['name'] . '", was not prefixed with "_CLI_"' . LF . LF);
2301 die(3);
2302 }
2303 } else {
2304 fwrite(STDERR, 'ERROR: Another user was already loaded which is impossible in CLI mode!' . LF . LF);
2305 die(3);
2306 }
2307 }
2308 return FALSE;
2309 }
2310
2311 /**
2312 * Initialize the internal ->uc array for the backend user
2313 * Will make the overrides if necessary, and write the UC back to the be_users record if changes has happened
2314 *
2315 * @return void
2316 * @internal
2317 */
2318 public function backendSetUC() {
2319 // UC - user configuration is a serialized array inside the user object
2320 // If there is a saved uc we implement that instead of the default one.
2321 $temp_theSavedUC = unserialize($this->user['uc']);
2322 if (is_array($temp_theSavedUC)) {
2323 $this->unpack_uc($temp_theSavedUC);
2324 }
2325 // Setting defaults if uc is empty
2326 $updated = FALSE;
2327 $originalUc = array();
2328 if (is_array($this->uc) && isset($this->uc['ucSetByInstallTool'])) {
2329 $originalUc = $this->uc;
2330 unset($originalUc['ucSetByInstallTool'], $this->uc);
2331 }
2332 if (!is_array($this->uc)) {
2333 $this->uc = array_merge(
2334 $this->uc_default,
2335 (array)$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUC'],
2336 GeneralUtility::removeDotsFromTS((array)$this->getTSConfigProp('setup.default')),
2337 $originalUc
2338 );
2339 $this->overrideUC();
2340 $updated = TRUE;
2341 }
2342 // If TSconfig is updated, update the defaultUC.
2343 if ($this->userTSUpdated) {
2344 $this->overrideUC();
2345 $updated = TRUE;
2346 }
2347 // Setting default lang from be_user record.
2348 if (!isset($this->uc['lang'])) {
2349 $this->uc['lang'] = $this->user['lang'];
2350 $updated = TRUE;
2351 }
2352 // Setting the time of the first login:
2353 if (!isset($this->uc['firstLoginTimeStamp'])) {
2354 $this->uc['firstLoginTimeStamp'] = $GLOBALS['EXEC_TIME'];
2355 $updated = TRUE;
2356 }
2357 // Saving if updated.
2358 if ($updated) {
2359 $this->writeUC();
2360 }
2361 }
2362
2363 /**
2364 * Override: Call this function every time the uc is updated.
2365 * That is 1) by reverting to default values, 2) in the setup-module, 3) userTS changes (userauthgroup)
2366 *
2367 * @return void
2368 * @internal
2369 */
2370 public function overrideUC() {
2371 $this->uc = array_merge((array)$this->uc, (array)$this->getTSConfigProp('setup.override'));
2372 }
2373
2374 /**
2375 * Clears the user[uc] and ->uc to blank strings. Then calls ->backendSetUC() to fill it again with reset contents
2376 *
2377 * @return void
2378 * @internal
2379 */
2380 public function resetUC() {
2381 $this->user['uc'] = '';
2382 $this->uc = '';
2383 $this->backendSetUC();
2384 }
2385
2386 /**
2387 * Will send an email notification to warning_email_address/the login users email address when a login session is just started.
2388 * Depends on various parameters whether mails are send and to whom.
2389 *
2390 * @return void
2391 * @access private
2392 */
2393 private function emailAtLogin() {
2394 if ($this->loginSessionStarted) {
2395 // Send notify-mail
2396 $subject = 'At "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '"' . ' from '
2397 . GeneralUtility::getIndpEnv('REMOTE_ADDR')
2398 . (GeneralUtility::getIndpEnv('REMOTE_HOST') ? ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')' : '');
2399 $msg = sprintf(
2400 'User "%s" logged in from %s (%s) at "%s" (%s)',
2401 $this->user['username'],
2402 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2403 GeneralUtility::getIndpEnv('REMOTE_HOST'),
2404 $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
2405 GeneralUtility::getIndpEnv('HTTP_HOST')
2406 );
2407 // Warning email address
2408 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr']) {
2409 $warn = 0;
2410 $prefix = '';
2411 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode'] & 1) {
2412 // first bit: All logins
2413 $warn = 1;
2414 $prefix = $this->isAdmin() ? '[AdminLoginWarning]' : '[LoginWarning]';
2415 }
2416 if ($this->isAdmin() && (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode'] & 2) {
2417 // second bit: Only admin-logins
2418 $warn = 1;
2419 $prefix = '[AdminLoginWarning]';
2420 }
2421 if ($warn) {
2422 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
2423 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2424 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2425 $mail->setTo($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'])->setFrom($from)->setSubject($prefix . ' ' . $subject)->setBody($msg);
2426 $mail->send();
2427 }
2428 }
2429 // If An email should be sent to the current user, do that:
2430 if ($this->uc['emailMeAtLogin'] && strstr($this->user['email'], '@')) {
2431 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
2432 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2433 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2434 $mail->setTo($this->user['email'])->setFrom($from)->setSubject($subject)->setBody($msg);
2435 $mail->send();
2436 }
2437 }
2438 }
2439
2440 /**
2441 * Determines whether a backend user is allowed to access the backend.
2442 *
2443 * The conditions are:
2444 * + backend user is a regular user and adminOnly is not defined
2445 * + backend user is an admin user
2446 * + backend user is used in CLI context and adminOnly is explicitly set to "2"
2447 * + backend user is being controlled by an admin user
2448 *
2449 * @return bool Whether a backend user is allowed to access the backend
2450 */
2451 protected function isUserAllowedToLogin() {
2452 $isUserAllowedToLogin = FALSE;
2453 $adminOnlyMode = $GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'];
2454 // Backend user is allowed if adminOnly is not set or user is an admin:
2455 if (!$adminOnlyMode || $this->isAdmin()) {
2456 $isUserAllowedToLogin = TRUE;
2457 } elseif ($adminOnlyMode == 2 && TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
2458 $isUserAllowedToLogin = TRUE;
2459 } elseif ($this->user['ses_backuserid']) {
2460 $backendUserId = (int)$this->user['ses_backuserid'];
2461 $whereAdmin = 'uid=' . $backendUserId . ' AND admin=1' . BackendUtility::BEenableFields('be_users');
2462 if ($this->db->exec_SELECTcountRows('uid', 'be_users', $whereAdmin) > 0) {
2463 $isUserAllowedToLogin = TRUE;
2464 }
2465 }
2466 return $isUserAllowedToLogin;
2467 }
2468
2469 /**
2470 * Logs out the current user and clears the form protection tokens.
2471 */
2472 public function logoff() {
2473 if (isset($GLOBALS['BE_USER'])) {
2474 \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->clean();
2475 }
2476 parent::logoff();
2477 }
2478
2479 }