[BUGFIX] Prevent search upload folder in write protected storages
[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() && $storage->isWritable()) {
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 if ($storage->isWritable()) {
1807 try {
1808 $uploadFolder = $storage->getDefaultFolder();
1809 if ($uploadFolder->checkActionPermission('add')) {
1810 break;
1811 }
1812 $uploadFolder = NULL;
1813 } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {
1814 // If the folder is not accessible (no permissions / does not exist) try the next one.
1815 }
1816 }
1817 }
1818 }
1819 }
1820 if ($uploadFolder instanceof \TYPO3\CMS\Core\Resource\Folder) {
1821 return $uploadFolder;
1822 } else {
1823 return FALSE;
1824 }
1825 }
1826
1827 /**
1828 * Returns a \TYPO3\CMS\Core\Resource\Folder object that could be used for uploading
1829 * temporary files in user context. The folder _temp_ below the default upload folder
1830 * of the user is used.
1831 *
1832 * @return NULL|\TYPO3\CMS\Core\Resource\Folder
1833 * @see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::getDefaultUploadFolder();
1834 */
1835 public function getDefaultUploadTemporaryFolder() {
1836 $defaultTemporaryFolder = NULL;
1837 $defaultFolder = $this->getDefaultUploadFolder();
1838
1839 if ($defaultFolder !== FALSE) {
1840 $tempFolderName = '_temp_';
1841 $createFolder = !$defaultFolder->hasFolder($tempFolderName);
1842 if ($createFolder === TRUE) {
1843 try {
1844 $defaultTemporaryFolder = $defaultFolder->createFolder($tempFolderName);
1845 } catch (\TYPO3\CMS\Core\Resource\Exception $folderAccessException) {}
1846 } else {
1847 $defaultTemporaryFolder = $defaultFolder->getSubfolder($tempFolderName);
1848 }
1849 }
1850
1851 return $defaultTemporaryFolder;
1852 }
1853
1854 /**
1855 * Creates a TypoScript comment with the string text inside.
1856 *
1857 * @param string $str The text to wrap in comment prefixes and delimiters.
1858 * @return string TypoScript comment with the string text inside.
1859 */
1860 public function addTScomment($str) {
1861 $delimiter = '# ***********************************************';
1862 $out = $delimiter . LF;
1863 $lines = GeneralUtility::trimExplode(LF, $str);
1864 foreach ($lines as $v) {
1865 $out .= '# ' . $v . LF;
1866 }
1867 $out .= $delimiter . LF;
1868 return $out;
1869 }
1870
1871 /**
1872 * Initializing workspace.
1873 * Called from within this function, see fetchGroupData()
1874 *
1875 * @return void
1876 * @see fetchGroupData()
1877 */
1878 public function workspaceInit() {
1879 // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
1880 $this->setWorkspace($this->user['workspace_id']);
1881 // Limiting the DB mountpoints if there any selected in the workspace record
1882 $this->initializeDbMountpointsInWorkspace();
1883 if ($allowed_languages = $this->getTSConfigVal('options.workspaces.allowed_languages.' . $this->workspace)) {
1884 $this->groupData['allowed_languages'] = $allowed_languages;
1885 $this->groupData['allowed_languages'] = GeneralUtility::uniqueList($this->groupData['allowed_languages']);
1886 }
1887 }
1888
1889 /**
1890 * Limiting the DB mountpoints if there any selected in the workspace record
1891 *
1892 * @return void
1893 */
1894 protected function initializeDbMountpointsInWorkspace() {
1895 $dbMountpoints = trim($this->workspaceRec['db_mountpoints']);
1896 if ($this->workspace > 0 && $dbMountpoints != '') {
1897 $filteredDbMountpoints = array();
1898 // Notice: We cannot call $this->getPagePermsClause(1);
1899 // as usual because the group-list is not available at this point.
1900 // But bypassing is fine because all we want here is check if the
1901 // workspace mounts are inside the current webmounts rootline.
1902 // The actual permission checking on page level is done elsewhere
1903 // as usual anyway before the page tree is rendered.
1904 $readPerms = '1=1';
1905 // Traverse mount points of the
1906 $dbMountpoints = GeneralUtility::intExplode(',', $dbMountpoints);
1907 foreach ($dbMountpoints as $mpId) {
1908 if ($this->isInWebMount($mpId, $readPerms)) {
1909 $filteredDbMountpoints[] = $mpId;
1910 }
1911 }
1912 // Re-insert webmounts:
1913 $filteredDbMountpoints = array_unique($filteredDbMountpoints);
1914 $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
1915 }
1916 }
1917
1918 /**
1919 * Checking if a workspace is allowed for backend user
1920 *
1921 * @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)
1922 * @param string $fields List of fields to select. Default fields are: uid,title,adminusers,members,reviewers,publish_access,stagechg_notification
1923 * @return array Output will also show how access was granted. Admin users will have a true output regardless of input.
1924 */
1925 public function checkWorkspace($wsRec, $fields = 'uid,title,adminusers,members,reviewers,publish_access,stagechg_notification') {
1926 $retVal = FALSE;
1927 // If not array, look up workspace record:
1928 if (!is_array($wsRec)) {
1929 switch ((string)$wsRec) {
1930 case '0':
1931 $wsRec = array('uid' => $wsRec);
1932 break;
1933 default:
1934 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
1935 $wsRec = $this->db->exec_SELECTgetSingleRow($fields,
1936 'sys_workspace',
1937 'pid=0 AND uid=' . (int)$wsRec . BackendUtility::deleteClause('sys_workspace'),
1938 '',
1939 'title'
1940 );
1941 }
1942 }
1943 }
1944 // If wsRec is set to an array, evaluate it:
1945 if (is_array($wsRec)) {
1946 if ($this->isAdmin()) {
1947 return array_merge($wsRec, array('_ACCESS' => 'admin'));
1948 } else {
1949 switch ((string)$wsRec['uid']) {
1950 case '0':
1951 $retVal = $this->groupData['workspace_perms'] & Permission::PAGE_SHOW
1952 ? array_merge($wsRec, array('_ACCESS' => 'online'))
1953 : FALSE;
1954 break;
1955 default:
1956 // Checking if the guy is admin:
1957 if (GeneralUtility::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
1958 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1959 }
1960 // Checking if he is owner through a user group of his:
1961 foreach ($this->userGroupsUID as $groupUid) {
1962 if (GeneralUtility::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
1963 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1964 }
1965 }
1966 // Checking if he is reviewer user:
1967 if (GeneralUtility::inList($wsRec['reviewers'], 'be_users_' . $this->user['uid'])) {
1968 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1969 }
1970 // Checking if he is reviewer through a user group of his:
1971 foreach ($this->userGroupsUID as $groupUid) {
1972 if (GeneralUtility::inList($wsRec['reviewers'], 'be_groups_' . $groupUid)) {
1973 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1974 }
1975 }
1976 // Checking if he is member as user:
1977 if (GeneralUtility::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
1978 return array_merge($wsRec, array('_ACCESS' => 'member'));
1979 }
1980 // Checking if he is member through a user group of his:
1981 foreach ($this->userGroupsUID as $groupUid) {
1982 if (GeneralUtility::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
1983 return array_merge($wsRec, array('_ACCESS' => 'member'));
1984 }
1985 }
1986 }
1987 }
1988 }
1989 return $retVal;
1990 }
1991
1992 /**
1993 * Uses checkWorkspace() to check if current workspace is available for user.
1994 * This function caches the result and so can be called many times with no performance loss.
1995 *
1996 * @return array See checkWorkspace()
1997 * @see checkWorkspace()
1998 */
1999 public function checkWorkspaceCurrent() {
2000 if (!isset($this->checkWorkspaceCurrent_cache)) {
2001 $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
2002 }
2003 return $this->checkWorkspaceCurrent_cache;
2004 }
2005
2006 /**
2007 * Setting workspace ID
2008 *
2009 * @param int $workspaceId ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
2010 * @return void
2011 */
2012 public function setWorkspace($workspaceId) {
2013 // Check workspace validity and if not found, revert to default workspace.
2014 if (!$this->setTemporaryWorkspace($workspaceId)) {
2015 $this->setDefaultWorkspace();
2016 }
2017 // Unset access cache:
2018 $this->checkWorkspaceCurrent_cache = NULL;
2019 // If ID is different from the stored one, change it:
2020 if ((int)$this->workspace !== (int)$this->user['workspace_id']) {
2021 $this->user['workspace_id'] = $this->workspace;
2022 $this->db->exec_UPDATEquery('be_users', 'uid=' . (int)$this->user['uid'], array('workspace_id' => $this->user['workspace_id']));
2023 $this->simplelog('User changed workspace to "' . $this->workspace . '"');
2024 }
2025 }
2026
2027 /**
2028 * Sets a temporary workspace in the context of the current backend user.
2029 *
2030 * @param int $workspaceId
2031 * @return bool
2032 */
2033 public function setTemporaryWorkspace($workspaceId) {
2034 $result = FALSE;
2035 $workspaceRecord = $this->checkWorkspace($workspaceId, '*');
2036
2037 if ($workspaceRecord) {
2038 $this->workspaceRec = $workspaceRecord;
2039 $this->workspace = (int)$workspaceId;
2040 $result = TRUE;
2041 }
2042
2043 return $result;
2044 }
2045
2046 /**
2047 * Sets the default workspace in the context of the current backend user.
2048 *
2049 * @return void
2050 */
2051 public function setDefaultWorkspace() {
2052 $this->workspace = (int)$this->getDefaultWorkspace();
2053 $this->workspaceRec = $this->checkWorkspace($this->workspace, '*');
2054 }
2055
2056 /**
2057 * Setting workspace preview state for user:
2058 *
2059 * @param bool $previewState State of user preview.
2060 * @return void
2061 */
2062 public function setWorkspacePreview($previewState) {
2063 $this->user['workspace_preview'] = $previewState;
2064 $this->db->exec_UPDATEquery('be_users', 'uid=' . (int)$this->user['uid'], array('workspace_preview' => $this->user['workspace_preview']));
2065 }
2066
2067 /**
2068 * Return default workspace ID for user,
2069 * If EXT:workspaces is not installed the user will be pushed the the
2070 * Live workspace
2071 *
2072 * @return int Default workspace id. If no workspace is available it will be "-99
2073 */
2074 public function getDefaultWorkspace() {
2075 $defaultWorkspace = -99;
2076 if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces') || $this->checkWorkspace(0)) {
2077 // Check online
2078 $defaultWorkspace = 0;
2079 } elseif ($this->checkWorkspace(-1)) {
2080 // Check offline
2081 $defaultWorkspace = -1;
2082 } elseif (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
2083 // Traverse custom workspaces:
2084 $workspaces = $this->db->exec_SELECTgetRows('uid,title,adminusers,members,reviewers', 'sys_workspace', 'pid=0' . BackendUtility::deleteClause('sys_workspace'), '', 'title');
2085 foreach ($workspaces as $rec) {
2086 if ($this->checkWorkspace($rec)) {
2087 $defaultWorkspace = $rec['uid'];
2088 break;
2089 }
2090 }
2091 }
2092 return $defaultWorkspace;
2093 }
2094
2095 /**
2096 * Writes an entry in the logfile/table
2097 * Documentation in "TYPO3 Core API"
2098 *
2099 * @param int $type Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
2100 * @param int $action Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
2101 * @param int $error Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2102 * @param int $details_nr The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
2103 * @param string $details Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
2104 * @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
2105 * @param string $tablename Table name. Special field used by tce_main.php.
2106 * @param int|string $recuid Record UID. Special field used by tce_main.php.
2107 * @param int|string $recpid Record PID. Special field used by tce_main.php. OBSOLETE
2108 * @param int $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
2109 * @param string $NEWid Special field used by tce_main.php. NEWid string of newly created records.
2110 * @param int $userId Alternative Backend User ID (used for logging login actions where this is not yet known).
2111 * @return int Log entry ID.
2112 */
2113 public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0) {
2114 if (!$userId && isset($this->user['uid'])) {
2115 $userId = $this->user['uid'];
2116 }
2117
2118 $fields_values = array(
2119 'userid' => (int)$userId,
2120 'type' => (int)$type,
2121 'action' => (int)$action,
2122 'error' => (int)$error,
2123 'details_nr' => (int)$details_nr,
2124 'details' => $details,
2125 'log_data' => serialize($data),
2126 'tablename' => $tablename,
2127 'recuid' => (int)$recuid,
2128 'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2129 'tstamp' => time(),
2130 'event_pid' => (int)$event_pid,
2131 'NEWid' => $NEWid,
2132 'workspace' => $this->workspace
2133 );
2134 $this->db->exec_INSERTquery('sys_log', $fields_values);
2135 return $this->db->sql_insert_id();
2136 }
2137
2138 /**
2139 * Simple logging function
2140 *
2141 * @param string $message Log message
2142 * @param string $extKey Option extension key / module name
2143 * @param int $error Error level. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2144 * @return int Log entry UID
2145 */
2146 public function simplelog($message, $extKey = '', $error = 0) {
2147 return $this->writelog(4, 0, $error, 0, ($extKey ? '[' . $extKey . '] ' : '') . $message, array());
2148 }
2149
2150 /**
2151 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
2152 * If a login fails, this function is called. It will look up the sys_log to see if there
2153 * have been more than $max failed logins the last $secondsBack seconds (default 3600).
2154 * If so, an email with a warning is sent to $email.
2155 *
2156 * @param string $email Email address
2157 * @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.
2158 * @param int $max Max allowed failures before a warning mail is sent
2159 * @return void
2160 * @access private
2161 */
2162 public function checkLogFailures($email, $secondsBack = 3600, $max = 3) {
2163 if ($email) {
2164 // Get last flag set in the log for sending
2165 $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
2166 $res = $this->db->exec_SELECTquery('tstamp', 'sys_log', 'type=255 AND action=4 AND tstamp>' . (int)$theTimeBack, '', 'tstamp DESC', '1');
2167 if ($testRow = $this->db->sql_fetch_assoc($res)) {
2168 $theTimeBack = $testRow['tstamp'];
2169 }
2170 $this->db->sql_free_result($res);
2171 // Check for more than $max number of error failures with the last period.
2172 $res = $this->db->exec_SELECTquery('*', 'sys_log', 'type=255 AND action=3 AND error<>0 AND tstamp>' . (int)$theTimeBack, '', 'tstamp');
2173 if ($this->db->sql_num_rows($res) > $max) {
2174 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
2175 $subject = 'TYPO3 Login Failure Warning (at ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . ')';
2176 $email_body = 'There have been some attempts (' . $this->db->sql_num_rows($res) . ') to login at the TYPO3
2177 site "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '" (' . GeneralUtility::getIndpEnv('HTTP_HOST') . ').
2178
2179 This is a dump of the failures:
2180
2181 ';
2182 while ($testRows = $this->db->sql_fetch_assoc($res)) {
2183 $theData = unserialize($testRows['log_data']);
2184 $email_body .= date(
2185 $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
2186 $testRows['tstamp']
2187 ) . ': ' . @sprintf($testRows['details'], (string)$theData[0], (string)$theData[1], (string)$theData[2]);
2188 $email_body .= LF;
2189 }
2190 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
2191 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2192 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2193 $mail->setTo($email)->setFrom($from)->setSubject($subject)->setBody($email_body);
2194 $mail->send();
2195 // Logout written to log
2196 $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));
2197 $this->db->sql_free_result($res);
2198 }
2199 }
2200 }
2201
2202 /**
2203 * Getter for the cookie name
2204 *
2205 * @static
2206 * @return string returns the configured cookie name
2207 */
2208 static public function getCookieName() {
2209 $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
2210 if (empty($configuredCookieName)) {
2211 $configuredCookieName = 'be_typo_user';
2212 }
2213 return $configuredCookieName;
2214 }
2215
2216 /**
2217 * If TYPO3_CONF_VARS['BE']['enabledBeUserIPLock'] is enabled and
2218 * an IP-list is found in the User TSconfig objString "options.lockToIP",
2219 * then make an IP comparison with REMOTE_ADDR and return the outcome (TRUE/FALSE)
2220 *
2221 * @return bool TRUE, if IP address validates OK (or no check is done at all)
2222 */
2223 public function checkLockToIP() {
2224 $out = 1;
2225 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['enabledBeUserIPLock']) {
2226 $IPList = $this->getTSConfigVal('options.lockToIP');
2227 if (trim($IPList)) {
2228 $baseIP = GeneralUtility::getIndpEnv('REMOTE_ADDR');
2229 $out = GeneralUtility::cmpIP($baseIP, $IPList);
2230 }
2231 }
2232 return $out;
2233 }
2234
2235 /**
2236 * Check if user is logged in and if so, call ->fetchGroupData() to load group information and
2237 * access lists of all kind, further check IP, set the ->uc array and send login-notification email if required.
2238 * If no user is logged in the default behaviour is to exit with an error message,
2239 * but this will happen ONLY if the constant TYPO3_PROCEED_IF_NO_USER is set TRUE.
2240 * This function is called right after ->start() in fx. the TYPO3 CMS bootsrap
2241 *
2242 * @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.
2243 * @throws \RuntimeException
2244 * @return void
2245 */
2246 public function backendCheckLogin($proceedIfNoUserIsLoggedIn = FALSE) {
2247 if (empty($this->user['uid'])) {
2248 if ($proceedIfNoUserIsLoggedIn === FALSE) {
2249 $url = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir;
2250 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($url);
2251 }
2252 } else {
2253 // ...and if that's the case, call these functions
2254 $this->fetchGroupData();
2255 // The groups are fetched and ready for permission checking in this initialization.
2256 // Tables.php must be read before this because stuff like the modules has impact in this
2257 if ($this->checkLockToIP()) {
2258 if ($this->isUserAllowedToLogin()) {
2259 // Setting the UC array. It's needed with fetchGroupData first, due to default/overriding of values.
2260 $this->backendSetUC();
2261 // Email at login - if option set.
2262 $this->emailAtLogin();
2263 } else {
2264 throw new \RuntimeException('Login Error: TYPO3 is in maintenance mode at the moment. Only administrators are allowed access.', 1294585860);
2265 }
2266 } else {
2267 throw new \RuntimeException('Login Error: IP locking prevented you from being authorized. Can\'t proceed, sorry.', 1294585861);
2268 }
2269 }
2270 }
2271
2272 /**
2273 * If the backend script is in CLI mode, it will try to load a backend user named by the CLI module name (in lowercase)
2274 *
2275 * @return bool Returns TRUE if a CLI user was loaded, otherwise FALSE!
2276 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. Please implement this functionality in your own application directly from the outside
2277 */
2278 public function checkCLIuser() {
2279 GeneralUtility::logDeprecatedFunction();
2280 // First, check if cliMode is enabled:
2281 if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
2282 if (!$this->user['uid']) {
2283 if (substr($GLOBALS['MCONF']['name'], 0, 5) == '_CLI_') {
2284 $userName = strtolower($GLOBALS['MCONF']['name']);
2285 $this->setBeUserByName($userName);
2286 if ($this->user['uid']) {
2287 if (!$this->isAdmin()) {
2288 return TRUE;
2289 } else {
2290 fwrite(STDERR, 'ERROR: CLI backend user "' . $userName . '" was ADMIN which is not allowed!' . LF . LF);
2291 die(3);
2292 }
2293 } else {
2294 fwrite(STDERR, 'ERROR: No backend user named "' . $userName . '" was found!' . LF . LF);
2295 die(3);
2296 }
2297 } else {
2298 fwrite(STDERR, 'ERROR: Module name, "' . $GLOBALS['MCONF']['name'] . '", was not prefixed with "_CLI_"' . LF . LF);
2299 die(3);
2300 }
2301 } else {
2302 fwrite(STDERR, 'ERROR: Another user was already loaded which is impossible in CLI mode!' . LF . LF);
2303 die(3);
2304 }
2305 }
2306 return FALSE;
2307 }
2308
2309 /**
2310 * Initialize the internal ->uc array for the backend user
2311 * Will make the overrides if necessary, and write the UC back to the be_users record if changes has happened
2312 *
2313 * @return void
2314 * @internal
2315 */
2316 public function backendSetUC() {
2317 // UC - user configuration is a serialized array inside the user object
2318 // If there is a saved uc we implement that instead of the default one.
2319 $temp_theSavedUC = unserialize($this->user['uc']);
2320 if (is_array($temp_theSavedUC)) {
2321 $this->unpack_uc($temp_theSavedUC);
2322 }
2323 // Setting defaults if uc is empty
2324 $updated = FALSE;
2325 $originalUc = array();
2326 if (is_array($this->uc) && isset($this->uc['ucSetByInstallTool'])) {
2327 $originalUc = $this->uc;
2328 unset($originalUc['ucSetByInstallTool'], $this->uc);
2329 }
2330 if (!is_array($this->uc)) {
2331 $this->uc = array_merge(
2332 $this->uc_default,
2333 (array)$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUC'],
2334 GeneralUtility::removeDotsFromTS((array)$this->getTSConfigProp('setup.default')),
2335 $originalUc
2336 );
2337 $this->overrideUC();
2338 $updated = TRUE;
2339 }
2340 // If TSconfig is updated, update the defaultUC.
2341 if ($this->userTSUpdated) {
2342 $this->overrideUC();
2343 $updated = TRUE;
2344 }
2345 // Setting default lang from be_user record.
2346 if (!isset($this->uc['lang'])) {
2347 $this->uc['lang'] = $this->user['lang'];
2348 $updated = TRUE;
2349 }
2350 // Setting the time of the first login:
2351 if (!isset($this->uc['firstLoginTimeStamp'])) {
2352 $this->uc['firstLoginTimeStamp'] = $GLOBALS['EXEC_TIME'];
2353 $updated = TRUE;
2354 }
2355 // Saving if updated.
2356 if ($updated) {
2357 $this->writeUC();
2358 }
2359 }
2360
2361 /**
2362 * Override: Call this function every time the uc is updated.
2363 * That is 1) by reverting to default values, 2) in the setup-module, 3) userTS changes (userauthgroup)
2364 *
2365 * @return void
2366 * @internal
2367 */
2368 public function overrideUC() {
2369 $this->uc = array_merge((array)$this->uc, (array)$this->getTSConfigProp('setup.override'));
2370 }
2371
2372 /**
2373 * Clears the user[uc] and ->uc to blank strings. Then calls ->backendSetUC() to fill it again with reset contents
2374 *
2375 * @return void
2376 * @internal
2377 */
2378 public function resetUC() {
2379 $this->user['uc'] = '';
2380 $this->uc = '';
2381 $this->backendSetUC();
2382 }
2383
2384 /**
2385 * Will send an email notification to warning_email_address/the login users email address when a login session is just started.
2386 * Depends on various parameters whether mails are send and to whom.
2387 *
2388 * @return void
2389 * @access private
2390 */
2391 private function emailAtLogin() {
2392 if ($this->loginSessionStarted) {
2393 // Send notify-mail
2394 $subject = 'At "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '"' . ' from '
2395 . GeneralUtility::getIndpEnv('REMOTE_ADDR')
2396 . (GeneralUtility::getIndpEnv('REMOTE_HOST') ? ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')' : '');
2397 $msg = sprintf(
2398 'User "%s" logged in from %s (%s) at "%s" (%s)',
2399 $this->user['username'],
2400 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
2401 GeneralUtility::getIndpEnv('REMOTE_HOST'),
2402 $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
2403 GeneralUtility::getIndpEnv('HTTP_HOST')
2404 );
2405 // Warning email address
2406 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr']) {
2407 $warn = 0;
2408 $prefix = '';
2409 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode'] & 1) {
2410 // first bit: All logins
2411 $warn = 1;
2412 $prefix = $this->isAdmin() ? '[AdminLoginWarning]' : '[LoginWarning]';
2413 }
2414 if ($this->isAdmin() && (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode'] & 2) {
2415 // second bit: Only admin-logins
2416 $warn = 1;
2417 $prefix = '[AdminLoginWarning]';
2418 }
2419 if ($warn) {
2420 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
2421 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2422 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2423 $mail->setTo($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'])->setFrom($from)->setSubject($prefix . ' ' . $subject)->setBody($msg);
2424 $mail->send();
2425 }
2426 }
2427 // If An email should be sent to the current user, do that:
2428 if ($this->uc['emailMeAtLogin'] && strstr($this->user['email'], '@')) {
2429 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
2430 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
2431 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
2432 $mail->setTo($this->user['email'])->setFrom($from)->setSubject($subject)->setBody($msg);
2433 $mail->send();
2434 }
2435 }
2436 }
2437
2438 /**
2439 * Determines whether a backend user is allowed to access the backend.
2440 *
2441 * The conditions are:
2442 * + backend user is a regular user and adminOnly is not defined
2443 * + backend user is an admin user
2444 * + backend user is used in CLI context and adminOnly is explicitly set to "2"
2445 * + backend user is being controlled by an admin user
2446 *
2447 * @return bool Whether a backend user is allowed to access the backend
2448 */
2449 protected function isUserAllowedToLogin() {
2450 $isUserAllowedToLogin = FALSE;
2451 $adminOnlyMode = $GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'];
2452 // Backend user is allowed if adminOnly is not set or user is an admin:
2453 if (!$adminOnlyMode || $this->isAdmin()) {
2454 $isUserAllowedToLogin = TRUE;
2455 } elseif ($adminOnlyMode == 2 && TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
2456 $isUserAllowedToLogin = TRUE;
2457 } elseif ($this->user['ses_backuserid']) {
2458 $backendUserId = (int)$this->user['ses_backuserid'];
2459 $whereAdmin = 'uid=' . $backendUserId . ' AND admin=1' . BackendUtility::BEenableFields('be_users');
2460 if ($this->db->exec_SELECTcountRows('uid', 'be_users', $whereAdmin) > 0) {
2461 $isUserAllowedToLogin = TRUE;
2462 }
2463 }
2464 return $isUserAllowedToLogin;
2465 }
2466
2467 /**
2468 * Logs out the current user and clears the form protection tokens.
2469 */
2470 public function logoff() {
2471 if (isset($GLOBALS['BE_USER'])) {
2472 \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->clean();
2473 }
2474 parent::logoff();
2475 }
2476
2477 }