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