[TASK] Correct DBAL ux_* class mapping in migrations file
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_userauthgroup.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Extension to class.t3lib_userauth.php; Authentication of users in TYPO3 Backend
29 *
30 * Actually this class is extended again by t3lib_beuserauth which is the actual backend user class that will be instantiated.
31 * In fact the two classes t3lib_beuserauth and this class could just as well be one, single class since t3lib_userauthgroup is not - to my knowledge - used separately elsewhere. But for historical reasons they are two separate classes.
32 *
33 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
34 * @package TYPO3
35 * @subpackage t3lib
36 * @deprecated since 6.0, will be removed in 6.2. The functionality was merged wih t3lib_beUserAuth
37 */
38 abstract class t3lib_userAuthGroup extends t3lib_userAuth {
39
40 // Should be set to the usergroup-column (id-list) in the user-record
41 /**
42 * @todo Define visibility
43 */
44 public $usergroup_column = 'usergroup';
45
46 // The name of the group-table
47 /**
48 * @todo Define visibility
49 */
50 public $usergroup_table = 'be_groups';
51
52 // Internal
53 // This array holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
54 /**
55 * @todo Define visibility
56 */
57 public $groupData = array(
58 'filemounts' => array()
59 );
60
61 // User workspace. -99 is ERROR (none available), -1 is offline, 0 is online, >0 is custom workspaces.
62 /**
63 * @todo Define visibility
64 */
65 public $workspace = -99;
66
67 // Custom workspace record if any
68 /**
69 * @todo Define visibility
70 */
71 public $workspaceRec = array();
72
73 // This array will hold the groups that the user is a member of
74 /**
75 * @todo Define visibility
76 */
77 public $userGroups = array();
78
79 // This array holds the uid's of the groups in the listed order
80 /**
81 * @todo Define visibility
82 */
83 public $userGroupsUID = array();
84
85 // This is $this->userGroupsUID imploded to a comma list... Will correspond to the 'usergroup_cached_list'
86 /**
87 * @todo Define visibility
88 */
89 public $groupList = '';
90
91 // Used internally to accumulate data for the user-group. DONT USE THIS EXTERNALLY! Use $this->groupData instead
92 /**
93 * @todo Define visibility
94 */
95 public $dataLists = array(
96 'webmount_list' => '',
97 'filemount_list' => '',
98 'fileoper_perms' => 0,
99 'modList' => '',
100 'tables_select' => '',
101 'tables_modify' => '',
102 'pagetypes_select' => '',
103 'non_exclude_fields' => '',
104 'explicit_allowdeny' => '',
105 'allowed_languages' => '',
106 'workspace_perms' => '',
107 'custom_options' => ''
108 );
109
110 // For debugging/display of order in which subgroups are included.
111 /**
112 * @todo Define visibility
113 */
114 public $includeHierarchy = array();
115
116 // List of group_id's in the order they are processed.
117 /**
118 * @todo Define visibility
119 */
120 public $includeGroupArray = array();
121
122 // Set to 'WIN', if windows
123 /**
124 * @todo Define visibility
125 */
126 public $OS = '';
127
128 // Used to accumulate the TSconfig data of the user
129 /**
130 * @todo Define visibility
131 */
132 public $TSdataArray = array();
133
134 // Contains the non-parsed user TSconfig
135 /**
136 * @todo Define visibility
137 */
138 public $userTS_text = '';
139
140 // Contains the parsed user TSconfig
141 /**
142 * @todo Define visibility
143 */
144 public $userTS = array();
145
146 // Set internally if the user TSconfig was parsed and needs to be cached.
147 /**
148 * @todo Define visibility
149 */
150 public $userTSUpdated = 0;
151
152 // Set this from outside if you want the user TSconfig to ALWAYS be parsed and not fetched from cache.
153 /**
154 * @todo Define visibility
155 */
156 public $userTS_dontGetCached = 0;
157
158 // RTE availability errors collected.
159 /**
160 * @todo Define visibility
161 */
162 public $RTE_errors = array();
163
164 // Contains last error message
165 /**
166 * @todo Define visibility
167 */
168 public $errorMsg = '';
169
170 // Cache for checkWorkspaceCurrent()
171 /**
172 * @todo Define visibility
173 */
174 public $checkWorkspaceCurrent_cache = NULL;
175
176 /**
177 * @var t3lib_file_Storage[]
178 */
179 protected $fileStorages;
180
181 /**
182 * @var array
183 */
184 protected $filePermissions;
185
186 /**
187 * Constructor deprecates class.
188 */
189 public function __construct() {
190 t3lib_div::logDeprecatedFunction('Class t3lib_userAuthGroup is deprecated and unused since TYPO3 6.0. ' . 'All methods are merged with t3lib_beUserAuth.');
191 }
192
193 /************************************
194 *
195 * Permission checking functions:
196 *
197 ************************************/
198 /**
199 * Returns TRUE if user is admin
200 * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
201 *
202 * @return boolean
203 * @todo Define visibility
204 */
205 public function isAdmin() {
206 return ($this->user['admin'] & 1) == 1;
207 }
208
209 /**
210 * Returns TRUE if the current user is a member of group $groupId
211 * $groupId must be set. $this->groupList must contain groups
212 * Will return TRUE also if the user is a member of a group through subgroups.
213 *
214 * @param integer $groupId Group ID to look for in $this->groupList
215 * @return boolean
216 * @todo Define visibility
217 */
218 public function isMemberOfGroup($groupId) {
219 $groupId = intval($groupId);
220 if ($this->groupList && $groupId) {
221 return t3lib_div::inList($this->groupList, $groupId);
222 }
223 }
224
225 /**
226 * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
227 *
228 * Bits for permissions, see $perms variable:
229 *
230 * 1 - Show: See/Copy page and the pagecontent.
231 * 16- Edit pagecontent: Change/Add/Delete/Move pagecontent.
232 * 2- Edit page: Change/Move the page, eg. change title, startdate, hidden.
233 * 4- Delete page: Delete the page and pagecontent.
234 * 8- New pages: Create new pages under the page.
235 *
236 * @param array $row Is the pagerow for which the permissions is checked
237 * @param integer $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.
238 * @return boolean TRUE or False upon evaluation
239 * @todo Define visibility
240 */
241 public function doesUserHaveAccess($row, $perms) {
242 $userPerms = $this->calcPerms($row);
243 return ($userPerms & $perms) == $perms;
244 }
245
246 /**
247 * Checks if the page id, $id, is found within the webmounts set up for the user.
248 * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
249 * The point is that this will add the security that a user can NEVER touch parts outside his mounted pages in the page tree. This is otherwise possible if the raw page permissions allows for it. So this security check just makes it easier to make safe user configurations.
250 * If the user is admin OR if this feature is disabled (fx. by setting TYPO3_CONF_VARS['BE']['lockBeUserToDBmounts']=0) then it returns "1" right away
251 * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
252 *
253 * @param integer $id Page ID to check
254 * @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!)
255 * @param boolean $exitOnError If set, then the function will exit with an error message.
256 * @return integer The page UID of a page in the rootline that matched a mount point
257 * @todo Define visibility
258 */
259 public function isInWebMount($id, $readPerms = '', $exitOnError = 0) {
260 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['lockBeUserToDBmounts'] || $this->isAdmin()) {
261 return 1;
262 }
263 $id = intval($id);
264 // Check if input id is an offline version page in which case we will map id to the online version:
265 $checkRec = t3lib_beFUnc::getRecord('pages', $id, 'pid,t3ver_oid');
266 if ($checkRec['pid'] == -1) {
267 $id = intval($checkRec['t3ver_oid']);
268 }
269 if (!$readPerms) {
270 $readPerms = $this->getPagePermsClause(1);
271 }
272 if ($id > 0) {
273 $wM = $this->returnWebmounts();
274 $rL = t3lib_BEfunc::BEgetRootLine($id, ' AND ' . $readPerms);
275 foreach ($rL as $v) {
276 if ($v['uid'] && in_array($v['uid'], $wM)) {
277 return $v['uid'];
278 }
279 }
280 }
281 if ($exitOnError) {
282 throw new RuntimeException('Access Error: This page is not within your DB-mounts', 1294586445);
283 }
284 }
285
286 /**
287 * Checks access to a backend module with the $MCONF passed as first argument
288 *
289 * @param array $conf $MCONF array of a backend module!
290 * @param boolean $exitOnError If set, an array will issue an error message and exit.
291 * @return boolean 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
292 * @todo Define visibility
293 */
294 public function modAccess($conf, $exitOnError) {
295 if (!t3lib_BEfunc::isModuleSetInTBE_MODULES($conf['name'])) {
296 if ($exitOnError) {
297 throw new RuntimeException(('Fatal Error: This module "' . $conf['name']) . '" is not enabled in TBE_MODULES', 1294586446);
298 }
299 return FALSE;
300 }
301 // Workspaces check:
302 if (t3lib_extMgm::isLoaded('workspaces') && $conf['workspaces']) {
303 if (($this->workspace === 0 && t3lib_div::inList($conf['workspaces'], 'online') || $this->workspace === -1 && t3lib_div::inList($conf['workspaces'], 'offline')) || $this->workspace > 0 && t3lib_div::inList($conf['workspaces'], 'custom')) {
304
305 } else {
306 if ($exitOnError) {
307 throw new RuntimeException(('Workspace Error: This module "' . $conf['name']) . '" is not available under the current workspace', 1294586447);
308 }
309 return FALSE;
310 }
311 }
312 // Returns TRUE if conf[access] is not set at all or if the user is admin
313 if (!$conf['access'] || $this->isAdmin()) {
314 return TRUE;
315 }
316 // If $conf['access'] is set but not with 'admin' then we return TRUE, if the module is found in the modList
317 if (!strstr($conf['access'], 'admin') && $conf['name']) {
318 $acs = $this->check('modules', $conf['name']);
319 }
320 if (!$acs && $exitOnError) {
321 throw new RuntimeException('Access Error: You don\'t have access to this module.', 1294586448);
322 } else {
323 return $acs;
324 }
325 }
326
327 /**
328 * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
329 * $perms is the "mask" used to select. Fx. if $perms is 1 then you'll get all pages that a user can actually see!
330 * 2^0 = show (1)
331 * 2^1 = edit (2)
332 * 2^2 = delete (4)
333 * 2^3 = new (8)
334 * If the user is 'admin' " 1=1" is returned (no effect)
335 * 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)
336 * The 95% use of this function is "->getPagePermsClause(1)" which will return WHERE clauses for *selecting* pages in backend listings - in other words this will check read permissions.
337 *
338 * @param integer $perms Permission mask to use, see function description
339 * @return string Part of where clause. Prefix " AND " to this.
340 * @todo Define visibility
341 */
342 public function getPagePermsClause($perms) {
343 if (is_array($this->user)) {
344 if ($this->isAdmin()) {
345 return ' 1=1';
346 }
347 $perms = intval($perms);
348 // Make sure it's integer.
349 $str = (((((((((((' (' . '(pages.perms_everybody & ') . $perms) . ' = ') . $perms) . ')') . ' OR (pages.perms_userid = ') . $this->user['uid']) . ' AND pages.perms_user & ') . $perms) . ' = ') . $perms) . ')';
350 // User
351 if ($this->groupList) {
352 // Group (if any is set)
353 $str .= (((((' OR (pages.perms_groupid in (' . $this->groupList) . ') AND pages.perms_group & ') . $perms) . ' = ') . $perms) . ')';
354 }
355 $str .= ')';
356 // ****************
357 // getPagePermsClause-HOOK
358 // ****************
359 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'])) {
360 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'] as $_funcRef) {
361 $_params = array('currentClause' => $str, 'perms' => $perms);
362 $str = t3lib_div::callUserFunction($_funcRef, $_params, $this);
363 }
364 }
365 return $str;
366 } else {
367 return ' 1=0';
368 }
369 }
370
371 /**
372 * Returns a combined binary representation of the current users permissions for the page-record, $row.
373 * The perms for user, group and everybody is OR'ed together (provided that the page-owner is the user and for the groups that the user is a member of the group
374 * If the user is admin, 31 is returned (full permissions for all five flags)
375 *
376 * @param array $row Input page row with all perms_* fields available.
377 * @return integer Bitwise representation of the users permissions in relation to input page row, $row
378 * @todo Define visibility
379 */
380 public function calcPerms($row) {
381 // Return 31 for admin users.
382 if ($this->isAdmin()) {
383 return 31;
384 }
385 $out = 0;
386 if (((((isset($row['perms_userid']) && isset($row['perms_user'])) && isset($row['perms_groupid'])) && isset($row['perms_group'])) && isset($row['perms_everybody'])) && isset($this->groupList)) {
387 if ($this->user['uid'] == $row['perms_userid']) {
388 $out |= $row['perms_user'];
389 }
390 if ($this->isMemberOfGroup($row['perms_groupid'])) {
391 $out |= $row['perms_group'];
392 }
393 $out |= $row['perms_everybody'];
394 }
395 // ****************
396 // CALCPERMS hook
397 // ****************
398 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'])) {
399 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'] as $_funcRef) {
400 $_params = array(
401 'row' => $row,
402 'outputPermissions' => $out
403 );
404 $out = t3lib_div::callUserFunction($_funcRef, $_params, $this);
405 }
406 }
407 return $out;
408 }
409
410 /**
411 * Returns TRUE if the RTE (Rich Text Editor) can be enabled for the user
412 * Strictly this is not permissions being checked but rather a series of settings like a loaded extension, browser/client type and a configuration option in ->uc[edit_RTE]
413 * The reasons for a FALSE return can be found in $this->RTE_errors
414 *
415 * @return boolean
416 * @todo Define visibility
417 */
418 public function isRTE() {
419 // Start:
420 $this->RTE_errors = array();
421 if (!$this->uc['edit_RTE']) {
422 $this->RTE_errors[] = 'RTE is not enabled for user!';
423 }
424 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['RTEenabled']) {
425 $this->RTE_errors[] = 'RTE is not enabled in $TYPO3_CONF_VARS["BE"]["RTEenabled"]';
426 }
427 // Acquire RTE object:
428 $RTE = t3lib_BEfunc::RTEgetObj();
429 if (!is_object($RTE)) {
430 $this->RTE_errors = array_merge($this->RTE_errors, $RTE);
431 }
432 if (!count($this->RTE_errors)) {
433 return TRUE;
434 } else {
435 return FALSE;
436 }
437 }
438
439 /**
440 * Returns TRUE if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
441 * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
442 * If user is admin TRUE is also returned
443 * Please see the document Inside TYPO3 for examples.
444 *
445 * @param string $type The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules
446 * @param string $value String to search for in the groupData-list
447 * @return boolean TRUE if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
448 * @todo Define visibility
449 */
450 public function check($type, $value) {
451 if (isset($this->groupData[$type])) {
452 if ($this->isAdmin() || t3lib_div::inList($this->groupData[$type], $value)) {
453 return TRUE;
454 }
455 }
456 return FALSE;
457 }
458
459 /**
460 * Checking the authMode of a select field with authMode set
461 *
462 * @param string $table Table name
463 * @param string $field Field name (must be configured in TCA and of type "select" with authMode set!)
464 * @param string $value Value to evaluation (single value, must not contain any of the chars ":,|")
465 * @param string $authMode Auth mode keyword (explicitAllow, explicitDeny, individual)
466 * @return boolean TRUE or FALSE whether access is granted or not.
467 * @todo Define visibility
468 */
469 public function checkAuthMode($table, $field, $value, $authMode) {
470 // Admin users can do anything:
471 if ($this->isAdmin()) {
472 return TRUE;
473 }
474 // Allow all blank values:
475 if (!strcmp($value, '')) {
476 return TRUE;
477 }
478 // Certain characters are not allowed in the value
479 if (preg_match('/[:|,]/', $value)) {
480 return FALSE;
481 }
482 // Initialize:
483 $testValue = ((($table . ':') . $field) . ':') . $value;
484 $out = TRUE;
485 // Checking value:
486 switch ((string) $authMode) {
487 case 'explicitAllow':
488 if (!t3lib_div::inList($this->groupData['explicit_allowdeny'], ($testValue . ':ALLOW'))) {
489 $out = FALSE;
490 }
491 break;
492 case 'explicitDeny':
493 if (t3lib_div::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
494 $out = FALSE;
495 }
496 break;
497 case 'individual':
498 t3lib_div::loadTCA($table);
499 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
500 $items = $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'];
501 if (is_array($items)) {
502 foreach ($items as $iCfg) {
503 if (!strcmp($iCfg[1], $value) && $iCfg[4]) {
504 switch ((string) $iCfg[4]) {
505 case 'EXPL_ALLOW':
506 if (!t3lib_div::inList($this->groupData['explicit_allowdeny'], ($testValue . ':ALLOW'))) {
507 $out = FALSE;
508 }
509 break;
510 case 'EXPL_DENY':
511 if (t3lib_div::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
512 $out = FALSE;
513 }
514 break;
515 }
516 break;
517 }
518 }
519 }
520 }
521 break;
522 }
523 return $out;
524 }
525
526 /**
527 * Checking if a language value (-1, 0 and >0 for sys_language records) is allowed to be edited by the user.
528 *
529 * @param integer $langValue Language value to evaluate
530 * @return boolean Returns TRUE if the language value is allowed, otherwise FALSE.
531 * @todo Define visibility
532 */
533 public function checkLanguageAccess($langValue) {
534 // The users language list must be non-blank - otherwise all languages are allowed.
535 if (strcmp(trim($this->groupData['allowed_languages']), '')) {
536 $langValue = intval($langValue);
537 // Language must either be explicitly allowed OR the lang Value be "-1" (all languages)
538 if ($langValue != -1 && !$this->check('allowed_languages', $langValue)) {
539 return FALSE;
540 }
541 }
542 return TRUE;
543 }
544
545 /**
546 * Check if user has access to all existing localizations for a certain record
547 *
548 * @param string $table The table
549 * @param array $record The current record
550 * @return boolean
551 * @todo Define visibility
552 */
553 public function checkFullLanguagesAccess($table, $record) {
554 $recordLocalizationAccess = $this->checkLanguageAccess(0);
555 if ($recordLocalizationAccess && (t3lib_BEfunc::isTableLocalizable($table) || isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable']))) {
556 if (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])) {
557 $l10nTable = $GLOBALS['TCA'][$table]['ctrl']['transForeignTable'];
558 $pointerField = $GLOBALS['TCA'][$l10nTable]['ctrl']['transOrigPointerField'];
559 $pointerValue = $record['uid'];
560 } else {
561 $l10nTable = $table;
562 $pointerField = $GLOBALS['TCA'][$l10nTable]['ctrl']['transOrigPointerField'];
563 $pointerValue = $record[$pointerField] > 0 ? $record[$pointerField] : $record['uid'];
564 }
565 $recordLocalizations = t3lib_BEfunc::getRecordsByField($l10nTable, $pointerField, $pointerValue, '', '', '', '1');
566 if (is_array($recordLocalizations)) {
567 foreach ($recordLocalizations as $localization) {
568 $recordLocalizationAccess = $recordLocalizationAccess && $this->checkLanguageAccess($localization[$GLOBALS['TCA'][$l10nTable]['ctrl']['languageField']]);
569 if (!$recordLocalizationAccess) {
570 break;
571 }
572 }
573 }
574 }
575 return $recordLocalizationAccess;
576 }
577
578 /**
579 * Checking if a user has editing access to a record from a $GLOBALS['TCA'] table.
580 * The checks does not take page permissions and other "environmental" things into account. It only deal with record internals; If any values in the record fields disallows it.
581 * For instance languages settings, authMode selector boxes are evaluated (and maybe more in the future).
582 * It will check for workspace dependent access.
583 * The function takes an ID (integer) or row (array) as second argument.
584 *
585 * @param string $table Table name
586 * @param mixed $idOrRow If integer, then this is the ID of the record. If Array this just represents fields in the record.
587 * @param boolean $newRecord Set, if testing a new (non-existing) record array. Will disable certain checks that doesn't make much sense in that context.
588 * @param boolean $deletedRecord Set, if testing a deleted record array.
589 * @param boolean $checkFullLanguageAccess Set, whenever access to all translations of the record is required
590 * @return boolean TRUE if OK, otherwise FALSE
591 * @todo Define visibility
592 */
593 public function recordEditAccessInternals($table, $idOrRow, $newRecord = FALSE, $deletedRecord = FALSE, $checkFullLanguageAccess = FALSE) {
594 if (isset($GLOBALS['TCA'][$table])) {
595 t3lib_div::loadTCA($table);
596 // Always return TRUE for Admin users.
597 if ($this->isAdmin()) {
598 return TRUE;
599 }
600 // Fetching the record if the $idOrRow variable was not an array on input:
601 if (!is_array($idOrRow)) {
602 if ($deletedRecord) {
603 $idOrRow = t3lib_BEfunc::getRecord($table, $idOrRow, '*', '', FALSE);
604 } else {
605 $idOrRow = t3lib_BEfunc::getRecord($table, $idOrRow);
606 }
607 if (!is_array($idOrRow)) {
608 $this->errorMsg = 'ERROR: Record could not be fetched.';
609 return FALSE;
610 }
611 }
612 // Checking languages:
613 if ($GLOBALS['TCA'][$table]['ctrl']['languageField']) {
614 // Language field must be found in input row - otherwise it does not make sense.
615 if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
616 if (!$this->checkLanguageAccess($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
617 $this->errorMsg = 'ERROR: Language was not allowed.';
618 return FALSE;
619 } elseif (($checkFullLanguageAccess && $idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']] == 0) && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
620 $this->errorMsg = 'ERROR: Related/affected language was not allowed.';
621 return FALSE;
622 }
623 } else {
624 $this->errorMsg = ('ERROR: The "languageField" field named "' . $GLOBALS['TCA'][$table]['ctrl']['languageField']) . '" was not found in testing record!';
625 return FALSE;
626 }
627 } elseif ((isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable']) && $checkFullLanguageAccess) && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
628 return FALSE;
629 }
630 // Checking authMode fields:
631 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
632 foreach ($GLOBALS['TCA'][$table]['columns'] as $fieldName => $fieldValue) {
633 if (isset($idOrRow[$fieldName])) {
634 if (($fieldValue['config']['type'] == 'select' && $fieldValue['config']['authMode']) && !strcmp($fieldValue['config']['authMode_enforce'], 'strict')) {
635 if (!$this->checkAuthMode($table, $fieldName, $idOrRow[$fieldName], $fieldValue['config']['authMode'])) {
636 $this->errorMsg = ((((('ERROR: authMode "' . $fieldValue['config']['authMode']) . '" failed for field "') . $fieldName) . '" with value "') . $idOrRow[$fieldName]) . '" evaluated';
637 return FALSE;
638 }
639 }
640 }
641 }
642 }
643 // Checking "editlock" feature (doesn't apply to new records)
644 if (!$newRecord && $GLOBALS['TCA'][$table]['ctrl']['editlock']) {
645 if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']])) {
646 if ($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']]) {
647 $this->errorMsg = 'ERROR: Record was locked for editing. Only admin users can change this state.';
648 return FALSE;
649 }
650 } else {
651 $this->errorMsg = ('ERROR: The "editLock" field named "' . $GLOBALS['TCA'][$table]['ctrl']['editlock']) . '" was not found in testing record!';
652 return FALSE;
653 }
654 }
655 // Checking record permissions
656 // THIS is where we can include a check for "perms_" fields for other records than pages...
657 // Process any hooks
658 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'])) {
659 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'] as $funcRef) {
660 $params = array(
661 'table' => $table,
662 'idOrRow' => $idOrRow,
663 'newRecord' => $newRecord
664 );
665 if (!t3lib_div::callUserFunction($funcRef, $params, $this)) {
666 return FALSE;
667 }
668 }
669 }
670 // Finally, return TRUE if all is well.
671 return TRUE;
672 }
673 }
674
675 /**
676 * Checks a type of permission against the compiled permission integer, $compiledPermissions, and in relation to table, $tableName
677 *
678 * @param integer $compiledPermissions Could typically be the "compiled permissions" integer returned by ->calcPerms
679 * @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)
680 * @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)
681 * @return boolean
682 * @access public (used by typo3/alt_clickmenu.php)
683 */
684 public function isPSet($compiledPermissions, $tableName, $actionType = '') {
685 if ($this->isAdmin()) {
686 $result = TRUE;
687 } elseif ($tableName == 'pages') {
688 switch ($actionType) {
689 case 'edit':
690 $result = ($compiledPermissions & 2) !== 0;
691 break;
692 case 'new':
693 // Create new page OR page content
694 $result = ($compiledPermissions & 8 + 16) !== 0;
695 break;
696 case 'delete':
697 $result = ($compiledPermissions & 4) !== 0;
698 break;
699 case 'editcontent':
700 $result = ($compiledPermissions & 16) !== 0;
701 break;
702 default:
703 $result = FALSE;
704 }
705 } else {
706 $result = ($compiledPermissions & 16) !== 0;
707 }
708 return $result;
709 }
710
711 /**
712 * Returns TRUE if the BE_USER is allowed to *create* shortcuts in the backend modules
713 *
714 * @return boolean
715 * @todo Define visibility
716 */
717 public function mayMakeShortcut() {
718 return $this->getTSConfigVal('options.enableBookmarks') && !$this->getTSConfigVal('options.mayNotCreateEditBookmarks');
719 }
720
721 /**
722 * Checking if editing of an existing record is allowed in current workspace if that is offline.
723 * Rules for editing in offline mode:
724 * - record supports versioning and is an offline version from workspace and has the corrent stage
725 * - or record (any) is in a branch where there is a page which is a version from the workspace and where the stage is not preventing records
726 *
727 * @param string $table Table of record
728 * @param array $recData Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
729 * @return string String error code, telling the failure state. FALSE=All ok
730 * @todo Define visibility
731 */
732 public function workspaceCannotEditRecord($table, $recData) {
733 // Only test offline spaces:
734 if ($this->workspace !== 0) {
735 if (!is_array($recData)) {
736 $recData = t3lib_BEfunc::getRecord($table, $recData, 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : ''));
737 }
738 if (is_array($recData)) {
739 // We are testing a "version" (identified by a pid of -1): it can be edited provided that workspace matches and versioning is enabled for the table.
740 if ((int) $recData['pid'] === -1) {
741 // No versioning, basic error, inconsistency even! Such records should not have a pid of -1!
742 if (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
743 return 'Versioning disabled for table';
744 } elseif ((int) $recData['t3ver_wsid'] !== $this->workspace) {
745 // So does workspace match?
746 return 'Workspace ID of record didn\'t match current workspace';
747 } else {
748 // So is the user allowed to "use" the edit stage within the workspace?
749 return $this->workspaceCheckStageForCurrent(0) ? FALSE : 'User\'s access level did not allow for editing';
750 }
751 } else {
752 // We are testing a "live" record:
753 // For "Live" records, check that PID for table allows editing
754 if ($res = $this->workspaceAllowLiveRecordsInPID($recData['pid'], $table)) {
755 // Live records are OK in this branch, but what about the stage of branch point, if any:
756 // OK
757 return $res > 0 ? FALSE : 'Stage for versioning root point and users access level did not allow for editing';
758 } else {
759 // If not offline and not in versionized branch, output error:
760 return 'Online record was not in versionized branch!';
761 }
762 }
763 } else {
764 return 'No record';
765 }
766 } else {
767 // OK because workspace is 0
768 return FALSE;
769 }
770 }
771
772 /**
773 * Evaluates if a user is allowed to edit the offline version
774 *
775 * @param string $table Table of record
776 * @param array $recData Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
777 * @return string String error code, telling the failure state. FALSE=All ok
778 * @see workspaceCannotEditRecord()
779 * @todo Define visibility
780 */
781 public function workspaceCannotEditOfflineVersion($table, $recData) {
782 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
783 if (!is_array($recData)) {
784 $recData = t3lib_BEfunc::getRecord($table, $recData, 'uid,pid,t3ver_wsid,t3ver_stage');
785 }
786 if (is_array($recData)) {
787 if ((int) $recData['pid'] === -1) {
788 return $this->workspaceCannotEditRecord($table, $recData);
789 } else {
790 return 'Not an offline version';
791 }
792 } else {
793 return 'No record';
794 }
795 } else {
796 return 'Table does not support versioning.';
797 }
798 }
799
800 /**
801 * Check if "live" records from $table may be created or edited in this PID.
802 * If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
803 * 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 of versioning because the element was within a versionized branch but NOT ok in terms of the state the root point had!
804 *
805 * @param integer $pid PID value to check for.
806 * @param string $table Table name
807 * @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.
808 * @todo Define visibility
809 */
810 public function workspaceAllowLiveRecordsInPID($pid, $table) {
811 // Always for Live workspace AND if live-edit is enabled and tables are completely without versioning it is ok as well.
812 if (($this->workspace === 0 || $this->workspaceRec['live_edit'] && !$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) || $GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']) {
813 // OK to create for this table.
814 return 2;
815 } else {
816 // If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
817 return FALSE;
818 }
819 }
820
821 /**
822 * Evaluates if a record from $table can be created in $pid
823 *
824 * @param integer $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!
825 * @param string $table Table name
826 * @return boolean TRUE if OK.
827 * @todo Define visibility
828 */
829 public function workspaceCreateNewRecord($pid, $table) {
830 if ($res = $this->workspaceAllowLiveRecordsInPID($pid, $table)) {
831 // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
832 if ($res < 0) {
833 // Stage for versioning root point and users access level did not allow for editing
834 return FALSE;
835 }
836 } elseif (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
837 // So, if no live records were allowed, we have to create a new version of this record:
838 return FALSE;
839 }
840 return TRUE;
841 }
842
843 /**
844 * Evaluates if auto creation of a version of a record is allowed.
845 *
846 * @param string $table Table of the record
847 * @param integer $id UID of record
848 * @param integer $recpid PID of record
849 * @return boolean TRUE if ok.
850 * @todo Define visibility
851 */
852 public function workspaceAllowAutoCreation($table, $id, $recpid) {
853 // Auto-creation of version: In offline workspace, test if versioning is
854 // enabled and look for workspace version of input record.
855 // If there is no versionized record found we will create one and save to that.
856 if (((($this->workspace !== 0 && !$this->workspaceRec['disable_autocreate']) && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) && $recpid >= 0) && !t3lib_BEfunc::getWorkspaceVersionOfRecord($this->workspace, $table, $id, 'uid')) {
857 // There must be no existing version of this record in workspace.
858 return TRUE;
859 } elseif ($this->workspaceRec['disable_autocreate']) {
860 t3lib_div::deprecationLog('Usage of disable_autocreate feature is deprecated since 4.5.');
861 }
862 }
863
864 /**
865 * Checks if an element stage allows access for the user in the current workspace
866 * In live workspace (= 0) access is always granted for any stage.
867 * Admins are always allowed.
868 * An option for custom workspaces allows members to also edit when the stage is "Review"
869 *
870 * @param integer $stage Stage id from an element: -1,0 = editing, 1 = reviewer, >1 = owner
871 * @return boolean TRUE if user is allowed access
872 * @todo Define visibility
873 */
874 public function workspaceCheckStageForCurrent($stage) {
875 // Always allow for admins
876 if ($this->isAdmin()) {
877 return TRUE;
878 }
879 if ($this->workspace !== 0 && t3lib_extMgm::isLoaded('workspaces')) {
880 $stage = intval($stage);
881 $stat = $this->checkWorkspaceCurrent();
882 // Check if custom staging is activated
883 $workspaceRec = t3lib_BEfunc::getRecord('sys_workspace', $stat['uid']);
884 if (($workspaceRec['custom_stages'] > 0 && $stage !== 0) && $stage !== -10) {
885 // Get custom stage record
886 $workspaceStageRec = t3lib_BEfunc::getRecord('sys_workspace_stage', $stage);
887 // Check if the user is responsible for the current stage
888 if (t3lib_div::inList($workspaceStageRec['responsible_persons'], 'be_users_' . $this->user['uid']) && $stat['_ACCESS'] === 'member' || $stat['_ACCESS'] === 'owner') {
889 return TRUE;
890 }
891 // Check if the user is in a group which is responsible for the current stage
892 foreach ($this->userGroupsUID as $groupUid) {
893 if (t3lib_div::inList($workspaceStageRec['responsible_persons'], 'be_groups_' . $groupUid) && $stat['_ACCESS'] === 'member' || $stat['_ACCESS'] === 'owner') {
894 return TRUE;
895 }
896 }
897 } elseif ($stage == -10 || $stage == -20) {
898 if ($stat['_ACCESS'] === 'owner') {
899 return TRUE;
900 } else {
901 return FALSE;
902 }
903 } else {
904 $memberStageLimit = $this->workspaceRec['review_stage_edit'] ? 1 : 0;
905 if (($stage <= $memberStageLimit && $stat['_ACCESS'] === 'member' || $stage <= 1 && $stat['_ACCESS'] === 'reviewer') || $stat['_ACCESS'] === 'owner') {
906 return TRUE;
907 }
908 }
909 } else {
910 // Always OK for live workspace.
911 return TRUE;
912 }
913 }
914
915 /**
916 * Returns TRUE if the user has access to publish content from the workspace ID given.
917 * Admin-users are always granted access to do this
918 * If the workspace ID is 0 (live) all users have access also
919 * For custom workspaces it depends on whether the user is owner OR like with draft workspace if the user has access to Live workspace.
920 *
921 * @param integer $wsid Workspace UID; 0,1+
922 * @return boolean Returns TRUE if the user has access to publish content from the workspace ID given.
923 * @todo Define visibility
924 */
925 public function workspacePublishAccess($wsid) {
926 if ($this->isAdmin()) {
927 return TRUE;
928 }
929 // If no access to workspace, of course you cannot publish!
930 $retVal = FALSE;
931 $wsAccess = $this->checkWorkspace($wsid);
932 if ($wsAccess) {
933 switch ($wsAccess['uid']) {
934 case 0:
935 // Live workspace
936 // If access to Live workspace, no problem.
937 $retVal = TRUE;
938 break;
939 default:
940 // Custom workspace
941 $retVal = $wsAccess['_ACCESS'] === 'owner' || $this->checkWorkspace(0) && !($wsAccess['publish_access'] & 2);
942 // Either be an adminuser OR have access to online workspace which is OK as well as long as publishing access is not limited by workspace option.
943 break;
944 }
945 }
946 return $retVal;
947 }
948
949 /**
950 * Workspace swap-mode access?
951 *
952 * @return boolean Returns TRUE if records can be swapped in the current workspace, otherwise FALSE
953 * @todo Define visibility
954 */
955 public function workspaceSwapAccess() {
956 if ($this->workspace > 0 && (int) $this->workspaceRec['swap_modes'] === 2) {
957 return FALSE;
958 } else {
959 return TRUE;
960 }
961 }
962
963 /**
964 * Workspace Versioning type access. Check wether the requsted type of versioning (element/page/branch) is allowd in current workspace
965 * (element/pages/branches type of versioning can/could be set on custom workspaces on filed "vtype")
966 *
967 * @todo workspacecleanup: this seems mostly obsolete and should be removed
968 * @param integer $type Versioning type to evaluation: -1, 0, >1
969 * @return boolean TRUE if OK
970 * @deprecated since TYPO3 4.4, will be removed in TYPO3 6.0 as only element versioning is supported now
971 * @todo Define visibility
972 */
973 public function workspaceVersioningTypeAccess($type) {
974 t3lib_div::logDeprecatedFunction();
975 $type = t3lib_utility_Math::forceIntegerInRange($type, -1);
976 // only element versioning is allowed now
977 return $type == -1;
978 }
979
980 /**
981 * Finding "closest" versioning type, used for creation of new records.
982 *
983 * @see workspaceVersioningTypeAccess() for hints on $type
984 * @param integer $type Versioning type to evaluation: -1, 0, >1
985 * @return integer Returning versioning type
986 * @deprecated since TYPO3 4.4, will be removed in TYPO3 6.0 as only element versioning is supported now
987 * @todo Define visibility
988 */
989 public function workspaceVersioningTypeGetClosest($type) {
990 t3lib_div::logDeprecatedFunction();
991 $type = t3lib_utility_Math::forceIntegerInRange($type, -1);
992 if ($this->workspace > 0) {
993 switch ((int) $type) {
994 case -1:
995 $type = -1;
996 break;
997 case 0:
998 $type = $this->workspaceVersioningTypeAccess($type) ? $type : -1;
999 break;
1000 default:
1001 $type = $this->workspaceVersioningTypeAccess($type) ? $type : ($this->workspaceVersioningTypeAccess(0) ? 0 : -1);
1002 break;
1003 }
1004 }
1005 return $type;
1006 }
1007
1008 /*************************************
1009 *
1010 * Miscellaneous functions
1011 *
1012 *************************************/
1013 /**
1014 * Returns the value/properties of a TS-object as given by $objectString, eg. 'options.dontMountAdminMounts'
1015 * Nice (general!) function for returning a part of a TypoScript array!
1016 *
1017 * @param string $objectString Pointer to an "object" in the TypoScript array, fx. 'options.dontMountAdminMounts'
1018 * @param array $config Optional TSconfig array: If array, then this is used and not $this->userTS. If not array, $this->userTS is used.
1019 * @return array An array with two keys, "value" and "properties" where "value" is a string with the value of the objectsting and "properties" is an array with the properties of the objectstring.
1020 * @todo Define visibility
1021 */
1022 public function getTSConfig($objectString, $config = '') {
1023 if (!is_array($config)) {
1024 // Getting Root-ts if not sent
1025 $config = $this->userTS;
1026 }
1027 $TSConf = array();
1028 $parts = explode('.', $objectString, 2);
1029 $key = $parts[0];
1030 if (trim($key)) {
1031 if (count($parts) > 1 && trim($parts[1])) {
1032 // Go on, get the next level
1033 if (is_array($config[$key . '.'])) {
1034 $TSConf = $this->getTSConfig($parts[1], $config[$key . '.']);
1035 }
1036 } else {
1037 $TSConf['value'] = $config[$key];
1038 $TSConf['properties'] = $config[$key . '.'];
1039 }
1040 }
1041 return $TSConf;
1042 }
1043
1044 /**
1045 * Returns the "value" of the $objectString from the BE_USERS "User TSconfig" array
1046 *
1047 * @param string $objectString Object string, eg. "somestring.someproperty.somesubproperty
1048 * @return string The value for that object string (object path)
1049 * @see getTSConfig()
1050 * @todo Define visibility
1051 */
1052 public function getTSConfigVal($objectString) {
1053 $TSConf = $this->getTSConfig($objectString);
1054 return $TSConf['value'];
1055 }
1056
1057 /**
1058 * Returns the "properties" of the $objectString from the BE_USERS "User TSconfig" array
1059 *
1060 * @param string $objectString Object string, eg. "somestring.someproperty.somesubproperty
1061 * @return array The properties for that object string (object path) - if any
1062 * @see getTSConfig()
1063 * @todo Define visibility
1064 */
1065 public function getTSConfigProp($objectString) {
1066 $TSConf = $this->getTSConfig($objectString);
1067 return $TSConf['properties'];
1068 }
1069
1070 /**
1071 * Returns TRUE if $item is in $in_list
1072 *
1073 * @param string $in_list Comma list with items, no spaces between items!
1074 * @param string $item The string to find in the list of items
1075 * @return string Boolean
1076 * @deprecated since TYPO3 4.7, should be removed in TYPO3 6.1, use equivalent function t3lib_div::inList()
1077 * @todo Define visibility
1078 */
1079 public function inList($in_list, $item) {
1080 t3lib_div::logDeprecatedFunction();
1081 return t3lib_div::inList($in_list, $item);
1082 }
1083
1084 /**
1085 * Returns an array with the webmounts.
1086 * If no webmounts, and empty array is returned.
1087 * NOTICE: Deleted pages WILL NOT be filtered out! So if a mounted page has been deleted it is STILL coming out as a webmount. This is not checked due to performance.
1088 *
1089 * @return array
1090 * @todo Define visibility
1091 */
1092 public function returnWebmounts() {
1093 return (string) $this->groupData['webmounts'] != '' ? explode(',', $this->groupData['webmounts']) : array();
1094 }
1095
1096 /**
1097 * Returns TRUE or FALSE, depending if an alert popup (a javascript confirmation) should be shown
1098 * call like $GLOBALS['BE_USER']->jsConfirmation($BITMASK)
1099 *
1100 * 1 - typeChange
1101 * 2 - copy/move/paste
1102 * 4 - delete
1103 * 8 - frontend editing
1104 * 128 - other (not used yet)
1105 *
1106 * @param integer $bitmask Bitmask
1107 * @return boolean TRUE if the confirmation should be shown
1108 * @todo Define visibility
1109 */
1110 public function jsConfirmation($bitmask) {
1111 $alertPopup = $GLOBALS['BE_USER']->getTSConfig('options.alertPopups');
1112 if (empty($alertPopup['value'])) {
1113 // Default: show all warnings
1114 $alertPopup = 255;
1115 } else {
1116 $alertPopup = (int) $alertPopup['value'];
1117 }
1118 // Show confirmation
1119 if (($alertPopup & $bitmask) == $bitmask) {
1120 return 1;
1121 } else {
1122 // don't show confirmation
1123 return 0;
1124 }
1125 }
1126
1127 /*************************************
1128 *
1129 * Authentication methods
1130 *
1131 *************************************/
1132 /**
1133 * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
1134 * This method is called by ->backendCheckLogin() (from extending class t3lib_beuserauth) if the backend user login has verified OK.
1135 * Generally this is required initialization of a backend user.
1136 *
1137 * @return void
1138 * @access private
1139 * @see t3lib_TSparser
1140 * @todo Define visibility
1141 */
1142 public function fetchGroupData() {
1143 if ($this->user['uid']) {
1144 // Get lists for the be_user record and set them as default/primary values.
1145 // Enabled Backend Modules
1146 $this->dataLists['modList'] = $this->user['userMods'];
1147 // Add Allowed Languages
1148 $this->dataLists['allowed_languages'] = $this->user['allowed_languages'];
1149 // Set user value for workspace permissions.
1150 $this->dataLists['workspace_perms'] = $this->user['workspace_perms'];
1151 // Database mountpoints
1152 $this->dataLists['webmount_list'] = $this->user['db_mountpoints'];
1153 // File mountpoints
1154 $this->dataLists['filemount_list'] = $this->user['file_mountpoints'];
1155 // Fileoperation permissions
1156 $this->dataLists['fileoper_perms'] = (int) $this->user['fileoper_perms'];
1157 // Setting default User TSconfig:
1158 $this->TSdataArray[] = $this->addTScomment('From $GLOBALS["TYPO3_CONF_VARS"]["BE"]["defaultUserTSconfig"]:') . $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
1159 // Default TSconfig for admin-users
1160 if ($this->isAdmin()) {
1161 $this->TSdataArray[] = $this->addTScomment('"admin" user presets:') . '
1162 admPanel.enable.all = 1
1163 ';
1164 if (t3lib_extMgm::isLoaded('sys_note')) {
1165 $this->TSdataArray[] = ((('
1166 // Setting defaults for sys_note author / email...
1167 TCAdefaults.sys_note.author = ' . $this->user['realName']) . '
1168 TCAdefaults.sys_note.email = ') . $this->user['email']) . '
1169 ';
1170 }
1171 }
1172 // BE_GROUPS:
1173 // Get the groups...
1174 // 240203: Since the group-field never contains any references to groups with a prepended table name
1175 // we think it's safe to just intExplode and re-implode - which should be much faster than the other function call.
1176 $grList = $GLOBALS['TYPO3_DB']->cleanIntList($this->user[$this->usergroup_column]);
1177 if ($grList) {
1178 // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc. Refer to fetchGroups() function.
1179 $this->fetchGroups($grList);
1180 }
1181 // Add the TSconfig for this specific user:
1182 $this->TSdataArray[] = $this->addTScomment('USER TSconfig field') . $this->user['TSconfig'];
1183 // Check include lines.
1184 $this->TSdataArray = t3lib_TSparser::checkIncludeLines_array($this->TSdataArray);
1185 // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
1186 $this->userTS_text = implode((LF . '[GLOBAL]') . LF, $this->TSdataArray);
1187 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions'] && !$this->userTS_dontGetCached) {
1188 // Perform TS-Config parsing with condition matching
1189 $parseObj = t3lib_div::makeInstance('t3lib_TSparser_TSconfig');
1190 $res = $parseObj->parseTSconfig($this->userTS_text, 'userTS');
1191 if ($res) {
1192 $this->userTS = $res['TSconfig'];
1193 $this->userTSUpdated = $res['cached'] ? 0 : 1;
1194 }
1195 } else {
1196 // Parsing the user TSconfig (or getting from cache)
1197 $hash = md5('userTS:' . $this->userTS_text);
1198 $cachedContent = t3lib_BEfunc::getHash($hash);
1199 if (isset($cachedContent) && !$this->userTS_dontGetCached) {
1200 $this->userTS = unserialize($cachedContent);
1201 } else {
1202 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
1203 $parseObj->parse($this->userTS_text);
1204 $this->userTS = $parseObj->setup;
1205 t3lib_BEfunc::storeHash($hash, serialize($this->userTS), 'BE_USER_TSconfig');
1206 // Update UC:
1207 $this->userTSUpdated = 1;
1208 }
1209 }
1210 // Processing webmounts
1211 // Admin's always have the root mounted
1212 if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) {
1213 $this->dataLists['webmount_list'] = '0,' . $this->dataLists['webmount_list'];
1214 }
1215 // The lists are cleaned for duplicates
1216 $this->groupData['webmounts'] = t3lib_div::uniqueList($this->dataLists['webmount_list']);
1217 $this->groupData['pagetypes_select'] = t3lib_div::uniqueList($this->dataLists['pagetypes_select']);
1218 $this->groupData['tables_select'] = t3lib_div::uniqueList(($this->dataLists['tables_modify'] . ',') . $this->dataLists['tables_select']);
1219 $this->groupData['tables_modify'] = t3lib_div::uniqueList($this->dataLists['tables_modify']);
1220 $this->groupData['non_exclude_fields'] = t3lib_div::uniqueList($this->dataLists['non_exclude_fields']);
1221 $this->groupData['explicit_allowdeny'] = t3lib_div::uniqueList($this->dataLists['explicit_allowdeny']);
1222 $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->dataLists['allowed_languages']);
1223 $this->groupData['custom_options'] = t3lib_div::uniqueList($this->dataLists['custom_options']);
1224 $this->groupData['modules'] = t3lib_div::uniqueList($this->dataLists['modList']);
1225 $this->groupData['fileoper_perms'] = $this->dataLists['fileoper_perms'];
1226 $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
1227 // Populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
1228 $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
1229 // Finally this is the list of group_uid's in the order they are parsed (including subgroups!) and without duplicates (duplicates are presented with their last entrance in the list, which thus reflects the order of the TypoScript in TSconfig)
1230 $this->groupList = implode(',', $this->userGroupsUID);
1231 $this->setCachedList($this->groupList);
1232 // Checking read access to webmounts:
1233 if (trim($this->groupData['webmounts']) !== '') {
1234 $webmounts = explode(',', $this->groupData['webmounts']);
1235 // Explode mounts
1236 // Selecting all webmounts with permission clause for reading
1237 $MProws = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', 'pages', (('deleted=0 AND uid IN (' . $this->groupData['webmounts']) . ') AND ') . $this->getPagePermsClause(1), '', '', '', 'uid');
1238 foreach ($webmounts as $idx => $mountPointUid) {
1239 // If the mount ID is NOT found among selected pages, unset it:
1240 if ($mountPointUid > 0 && !isset($MProws[$mountPointUid])) {
1241 unset($webmounts[$idx]);
1242 }
1243 }
1244 // Implode mounts in the end.
1245 $this->groupData['webmounts'] = implode(',', $webmounts);
1246 }
1247 // Setting up workspace situation (after webmounts are processed!):
1248 $this->workspaceInit();
1249 }
1250 }
1251
1252 /**
1253 * Fetches the group records, subgroups and fills internal arrays.
1254 * Function is called recursively to fetch subgroups
1255 *
1256 * @param string $grList Commalist of be_groups uid numbers
1257 * @param string $idList List of already processed be_groups-uids so the function will not fall into a eternal recursion.
1258 * @return void
1259 * @access private
1260 * @todo Define visibility
1261 */
1262 public function fetchGroups($grList, $idList = '') {
1263 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
1264 $lockToDomain_SQL = (' AND (lockToDomain=\'\' OR lockToDomain IS NULL OR lockToDomain=\'' . t3lib_div::getIndpEnv('HTTP_HOST')) . '\')';
1265 $whereSQL = (('deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $grList) . ')') . $lockToDomain_SQL;
1266 // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
1267 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'])) {
1268 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] as $classRef) {
1269 $hookObj = t3lib_div::getUserObj($classRef);
1270 if (method_exists($hookObj, 'fetchGroupQuery_processQuery')) {
1271 $whereSQL = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, $whereSQL);
1272 }
1273 }
1274 }
1275 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->usergroup_table, $whereSQL);
1276 // The userGroups array is filled
1277 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1278 $this->userGroups[$row['uid']] = $row;
1279 }
1280 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1281 // Traversing records in the correct order
1282 $include_staticArr = t3lib_div::intExplode(',', $grList);
1283 // Traversing list
1284 foreach ($include_staticArr as $key => $uid) {
1285 // Get row:
1286 $row = $this->userGroups[$uid];
1287 // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
1288 if (is_array($row) && !t3lib_div::inList($idList, $uid)) {
1289 // Include sub groups
1290 if (trim($row['subgroup'])) {
1291 // Make integer list
1292 $theList = implode(',', t3lib_div::intExplode(',', $row['subgroup']));
1293 // Call recursively, pass along list of already processed groups so they are not recursed again.
1294 $this->fetchGroups($theList, ($idList . ',') . $uid);
1295 }
1296 // Add the group uid, current list, TSconfig to the internal arrays.
1297 $this->includeGroupArray[] = $uid;
1298 $this->includeHierarchy[] = $idList;
1299 $this->TSdataArray[] = $this->addTScomment((((('Group "' . $row['title']) . '" [') . $row['uid']) . '] TSconfig field:')) . $row['TSconfig'];
1300 // Mount group database-mounts
1301 if (($this->user['options'] & 1) == 1) {
1302 $this->dataLists['webmount_list'] .= ',' . $row['db_mountpoints'];
1303 }
1304 // Mount group file-mounts
1305 if (($this->user['options'] & 2) == 2) {
1306 $this->dataLists['filemount_list'] .= ',' . $row['file_mountpoints'];
1307 }
1308 // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
1309 if ($row['inc_access_lists'] == 1) {
1310 $this->dataLists['modList'] .= ',' . $row['groupMods'];
1311 $this->dataLists['tables_select'] .= ',' . $row['tables_select'];
1312 $this->dataLists['tables_modify'] .= ',' . $row['tables_modify'];
1313 $this->dataLists['pagetypes_select'] .= ',' . $row['pagetypes_select'];
1314 $this->dataLists['non_exclude_fields'] .= ',' . $row['non_exclude_fields'];
1315 $this->dataLists['explicit_allowdeny'] .= ',' . $row['explicit_allowdeny'];
1316 $this->dataLists['allowed_languages'] .= ',' . $row['allowed_languages'];
1317 $this->dataLists['custom_options'] .= ',' . $row['custom_options'];
1318 }
1319 // Setting fileoperation permissions
1320 $this->dataLists['fileoper_perms'] |= (int) $row['fileoper_perms'];
1321 // Setting workspace permissions:
1322 $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
1323 // If this function is processing the users OWN group-list (not subgroups) AND if the ->firstMainGroup is not set, then the ->firstMainGroup will be set.
1324 if (!strcmp($idList, '') && !$this->firstMainGroup) {
1325 $this->firstMainGroup = $uid;
1326 }
1327 }
1328 }
1329 // ****************
1330 // HOOK: fetchGroups_postProcessing
1331 // ****************
1332 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'])) {
1333 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] as $_funcRef) {
1334 $_params = array();
1335 t3lib_div::callUserFunction($_funcRef, $_params, $this);
1336 }
1337 }
1338 }
1339
1340 /**
1341 * Updates the field be_users.usergroup_cached_list if the groupList of the user has changed/is different from the current list.
1342 * The field "usergroup_cached_list" contains the list of groups which the user is a member of. After authentication (where these functions are called...) one can depend on this list being a representation of the exact groups/subgroups which the BE_USER has membership with.
1343 *
1344 * @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.
1345 * @return void
1346 * @access private
1347 * @todo Define visibility
1348 */
1349 public function setCachedList($cList) {
1350 if ((string) $cList != (string) $this->user['usergroup_cached_list']) {
1351 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('usergroup_cached_list' => $cList));
1352 }
1353 }
1354
1355 /***********************
1356 * FILE MOUNT FUNCTIONS
1357 **********************/
1358 /**
1359 * Sets up all file storages for a user.
1360 * Needs to be called AFTER the groups have been loaded.
1361 *
1362 * @return void
1363 */
1364 protected function initializeFileStorages() {
1365 $this->fileStorages = array();
1366 /** @var $storageRepository t3lib_file_Repository_StorageRepository */
1367 $storageRepository = t3lib_div::makeInstance('t3lib_file_Repository_StorageRepository');
1368 // Admin users have all file storages visible, without any filters
1369 if ($this->isAdmin()) {
1370 $storageObjects = $storageRepository->findAll();
1371 foreach ($storageObjects as $storageObject) {
1372 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1373 }
1374 } else {
1375 // If userHomePath is set, we attempt to mount it
1376 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
1377 list($userHomeStorageUid, $userHomeFilter) = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'], 2);
1378 $userHomeStorageUid = intval($userHomeStorageUid);
1379 if ($userHomeStorageUid > 0) {
1380 $storageObject = $storageRepository->findByUid($userHomeStorageUid);
1381 // First try and mount with [uid]_[username]
1382 $userHomeFilterIdentifier = ((($userHomeFilter . $this->user['uid']) . '_') . $this->user['username']) . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1383 $didMount = $storageObject->injectFileMount($userHomeFilterIdentifier);
1384 // If that failed, try and mount with only [uid]
1385 if (!$didMount) {
1386 $userHomeFilterIdentifier = ((($userHomeFilter . $this->user['uid']) . '_') . $this->user['username']) . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'];
1387 $storageObject->injectFileMount($userHomeFilterIdentifier);
1388 }
1389 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1390 }
1391 }
1392 // Mount group home-dirs
1393 if (($this->user['options'] & 2) == 2 && $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'] != '') {
1394 // If groupHomePath is set, we attempt to mount it
1395 list($groupHomeStorageUid, $groupHomeFilter) = explode(':', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'], 2);
1396 $groupHomeStorageUid = intval($groupHomeStorageUid);
1397 if ($groupHomeStorageUid > 0) {
1398 $storageObject = $storageRepository->findByUid($groupHomeStorageUid);
1399 foreach ($this->userGroups as $groupUid => $groupData) {
1400 $groupHomeFilterIdentifier = $groupHomeFilter . $groupData['uid'];
1401 $storageObject->injectFileMount($groupHomeFilterIdentifier);
1402 }
1403 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1404 }
1405 }
1406 // Processing filemounts (both from the user and the groups)
1407 $this->dataLists['filemount_list'] = t3lib_div::uniqueList($this->dataLists['filemount_list']);
1408 if ($this->dataLists['filemount_list']) {
1409 $orderBy = $GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'] ? $GLOBALS['TYPO3_DB']->stripOrderBy($GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby']) : 'sorting';
1410 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_filemounts', ('deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $this->dataLists['filemount_list']) . ')', '', $orderBy);
1411 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1412 $storageObject = $storageRepository->findByUid($row['base']);
1413 $storageObject->injectFileMount($row['path'], $row);
1414 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1415 }
1416 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1417 }
1418 }
1419 // Injects the users' permissions to each storage
1420 foreach ($this->fileStorages as $storageObject) {
1421 $storagePermissions = $this->getFilePermissionsForStorage($storageObject);
1422 $storageObject->injectUserPermissions($storagePermissions);
1423 }
1424 // more narrowing down through the workspace
1425 $this->initializeFileStoragesForWorkspace();
1426 // this has to be called always in order to set certain filters
1427 // @todo Should be in BE_USER object then
1428 $GLOBALS['BE_USER']->evaluateUserSpecificFileFilterSettings();
1429 }
1430
1431 /**
1432 * Returns an array with the filemounts for the user.
1433 * Each filemount is represented with an array of a "name", "path" and "type".
1434 * If no filemounts an empty array is returned.
1435 *
1436 * @api
1437 * @return t3lib_file_Storage[]
1438 */
1439 public function getFileStorages() {
1440 // Initializing file mounts after the groups are fetched
1441 if ($this->fileStorages === NULL) {
1442 $this->initializeFileStorages();
1443 }
1444 return $this->fileStorages;
1445 }
1446
1447 /**
1448 * Adds filters based on what the user has set
1449 * this should be done in this place, and called whenever needed,
1450 * but only when needed
1451 *
1452 * @return void
1453 * @todo Should be in BE_USER object then
1454 */
1455 public function evaluateUserSpecificFileFilterSettings() {
1456 // Add the option for also displaying the non-hidden files
1457 if ($this->uc['showHiddenFilesAndFolders']) {
1458 t3lib_file_Utility_FilenameFilters::setShowHiddenFilesAndFolders(TRUE);
1459 }
1460 }
1461
1462 /**
1463 * Returns the information about file permissions
1464 * previously, this was stored in the DB fields (fileoper_perms)
1465 * but is now handled via userTSconfig
1466 *
1467 * permissions.file.default {
1468 * addFile = 1
1469 * readFile = 1
1470 * editFile = 1
1471 * writeFile = 1
1472 * uploadFile = 1
1473 * copyFile = 1
1474 * moveFile = 1
1475 * renameFile = 1
1476 * unzipFile = 1
1477 * removeFile = 1
1478 *
1479 * addFolder = 1
1480 * browseFolder = 1
1481 * moveFolder = 1
1482 * writeFolder = 1
1483 * renameFolder = 1
1484 * removeFolder = 1
1485 * removeSubfolders = 1
1486 * }
1487 *
1488 * # overwrite settings for a specific storageObject
1489 * permissions.file.storage.StorageUid {
1490 * readFile = 0
1491 * removeSubfolders = 1
1492 * }
1493 *
1494 * Please note that these permissions only apply, if the storage has the
1495 * capabilities (browseable, writable), and if the driver allows for writing etc
1496 *
1497 * @api
1498 * @return array
1499 */
1500 public function getFilePermissions() {
1501 if (!isset($this->filePermissions)) {
1502 $defaultOptions = array(
1503 'addFile' => TRUE,
1504 // new option
1505 'readFile' => TRUE,
1506 // new option, generic check of the user rights
1507 'editFile' => TRUE,
1508 // new option
1509 'writeFile' => TRUE,
1510 // new option, generic check of the user rights
1511 'uploadFile' => TRUE,
1512 'copyFile' => TRUE,
1513 'moveFile' => TRUE,
1514 'renameFile' => TRUE,
1515 'unzipFile' => TRUE,
1516 'removeFile' => TRUE,
1517 'addFolder' => TRUE,
1518 'browseFolder' => TRUE,
1519 // new option,, generic check of the user rights
1520 'moveFolder' => TRUE,
1521 'renameFolder' => TRUE,
1522 'writeFolder' => TRUE,
1523 // new option, generic check of the user rights
1524 'removeFolder' => TRUE,
1525 'removeSubfolders' => TRUE
1526 );
1527 if (!$this->isAdmin()) {
1528 $this->filePermissions = $this->getTSConfig('permissions.file.default');
1529 if (!is_array($this->filePermissions)) {
1530 $oldFileOperationPermissions = $this->getFileoperationPermissions();
1531 // Lower permissions if the old file operation permissions are not set
1532 if ($oldFileOperationPermissions ^ 1) {
1533 $defaultOptions['addFile'] = FALSE;
1534 $defaultOptions['uploadFile'] = FALSE;
1535 $defaultOptions['copyFile'] = FALSE;
1536 $defaultOptions['moveFile'] = FALSE;
1537 $defaultOptions['renameFile'] = FALSE;
1538 $defaultOptions['removeFile'] = FALSE;
1539 }
1540 if ($oldFileOperationPermissions ^ 2) {
1541 $defaultOptions['unzipFile'] = FALSE;
1542 }
1543 if ($oldFileOperationPermissions ^ 4) {
1544 $defaultOptions['addFolder'] = FALSE;
1545 $defaultOptions['moveFolder'] = FALSE;
1546 $defaultOptions['renameFolder'] = FALSE;
1547 $defaultOptions['removeFolder'] = FALSE;
1548 }
1549 if ($oldFileOperationPermissions ^ 8) {
1550 $defaultOptions['copyFolder'] = FALSE;
1551 }
1552 if ($oldFileOperationPermissions ^ 16) {
1553 $defaultOptions['removeSubfolders'] = FALSE;
1554 }
1555 }
1556 }
1557 $this->filePermissions = $defaultOptions;
1558 }
1559 return $this->filePermissions;
1560 }
1561
1562 /**
1563 * Gets the file permissions for a storage
1564 * by merging any storage-specific permissions for a
1565 * storage with the default settings
1566 *
1567 * @api
1568 * @param t3lib_file_Storage $storageObject
1569 * @return array
1570 */
1571 public function getFilePermissionsForStorage(t3lib_file_Storage $storageObject) {
1572 $defaultFilePermissions = $this->getFilePermissions();
1573 $storageFilePermissions = $this->getTSConfig('permissions.file.storage.' . $storageObject->getUid());
1574 if (is_array($storageFilePermissions) && count($storageFilePermissions)) {
1575 return array_merge($storageFilePermissions, $defaultFilePermissions);
1576 } else {
1577 return $defaultFilePermissions;
1578 }
1579 }
1580
1581 /**
1582 * Returns a t3lib_file_Folder object that is used for uploading
1583 * files by default.
1584 * This is used for RTE and its magic images, as well as uploads
1585 * in the TCEforms fields, unless otherwise configured (will be added in the future)
1586 *
1587 * the default upload folder for a user is the defaultFolder on the first
1588 * filestorage/filemount that the user can access
1589 * however, you can set the users' upload folder like this:
1590 *
1591 * options.defaultUploadFolder = 3:myfolder/yourfolder/
1592 *
1593 * @return t3lib_file_Folder|boolean The default upload folder for this user
1594 */
1595 public function getDefaultUploadFolder() {
1596 $uploadFolder = $this->getTSConfigVal('options.defaultUploadFolder');
1597 if ($uploadFolder) {
1598 $uploadFolder = t3lib_file_Factory::getInstance()->getFolderObjectFromCombinedIdentifier($uploadFolder);
1599 } else {
1600 $storages = $this->getFileStorages();
1601 if (count($storages) > 0) {
1602 /** @var $firstStorage t3lib_file_Storage */
1603 $firstStorage = reset($storages);
1604 $uploadFolder = $firstStorage->getDefaultFolder();
1605 }
1606 }
1607 if ($uploadFolder instanceof t3lib_file_Folder) {
1608 return $uploadFolder;
1609 } else {
1610 return FALSE;
1611 }
1612 }
1613
1614 /**
1615 * Returns an integer bitmask that represents the permissions for file operations.
1616 * Permissions of the user and groups the user is a member of were combined by a logical OR.
1617 *
1618 * Meaning of each bit:
1619 * 1 - Files: Upload,Copy,Move,Delete,Rename
1620 * 2 - Files: Unzip
1621 * 4 - Directory: Move,Delete,Rename,New
1622 * 8 - Directory: Copy
1623 * 16 - Directory: Delete recursively (rm -Rf)
1624 *
1625 * @return integer File operation permission bitmask
1626 * @deprecated since TYPO3 6.0, use the TSconfig settings instead
1627 */
1628 public function getFileoperationPermissions() {
1629 t3lib_div::logDeprecatedFunction();
1630 if ($this->isAdmin()) {
1631 return 31;
1632 } else {
1633 return $this->groupData['fileoper_perms'];
1634 }
1635 }
1636
1637 /**
1638 * Adds a filemount to the users array of filemounts, $this->groupData['filemounts'][hash_key] = Array ('name'=>$name, 'path'=>$path, 'type'=>$type);
1639 * Is a part of the authentication proces of the user.
1640 * A final requirement for a path being mounted is that a) it MUST return TRUE on is_dir(), b) must contain either PATH_site+'fileadminDir' OR 'lockRootPath' - if lockRootPath is set - as first part of string!
1641 * Paths in the mounted information will always be absolute and have a trailing slash.
1642 *
1643 * @param string $title Will be the (root)name of the filemount in the folder tree
1644 * @param string $altTitle Will be the (root)name of the filemount IF $title is not TRUE (blank or zero)
1645 * @param string $path Is the path which should be mounted. Will accept backslash in paths on windows servers (will substituted with forward slash). The path should be 1) relative to TYPO3_CONF_VARS[BE][fileadminDir] if $webspace is set, otherwise absolute.
1646 * @param boolean $webspace If $webspace is set, the $path is relative to 'fileadminDir' in TYPO3_CONF_VARS, otherwise $path is absolute. 'fileadminDir' must be set to allow mounting of relative paths.
1647 * @param string $type Type of filemount; Can be blank (regular) or "user" / "group" (for user and group filemounts presumably). Probably sets the icon first and foremost.
1648 * @return boolean Returns "1" if the requested filemount was mounted, otherwise no return value.
1649 * @deprecated since TYPO3 6.0, will be removed in TYPO3 6.1, all data is stored in $this->fileStorages now, see initializeFileStorages()
1650 * @access private
1651 * @todo Define visibility
1652 */
1653 public function addFileMount($title, $altTitle, $path, $webspace, $type) {
1654 t3lib_div::logDeprecatedFunction();
1655 // Return FALSE if fileadminDir is not set and we try to mount a relative path
1656 if ($webspace && !$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
1657 return FALSE;
1658 }
1659 // Trimming and pre-processing
1660 $path = trim($path);
1661 // with WINDOWS convert backslash to slash!!
1662 if ($this->OS == 'WIN') {
1663 $path = str_replace('\\', '/', $path);
1664 }
1665 // If the path is TRUE and validates as a valid path string:
1666 if ($path && t3lib_div::validPathStr($path)) {
1667 // normalize path: remove leading '/' and './', and trailing '/' and '/.'
1668 $path = trim($path);
1669 $path = preg_replace('#^\\.?/|/\\.?$#', '', $path);
1670 // There must be some chars in the path
1671 if ($path) {
1672 // Fileadmin dir, absolute
1673 $fdir = PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'];
1674 if ($webspace) {
1675 $path = $fdir . $path;
1676 } else {
1677 // With WINDOWS no prepending!!
1678 if ($this->OS != 'WIN') {
1679 // With WINDOWS no prepending!!
1680 $path = '/' . $path;
1681 }
1682 }
1683 $path .= '/';
1684 // We now have a path with slash after and slash before (if unix)
1685 if (@is_dir($path) && ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']) || t3lib_div::isFirstPartOfStr($path, $fdir))) {
1686 // Alternative title?
1687 $name = $title ? $title : $altTitle;
1688 // Adds the filemount. The same filemount with same name, type and path cannot be set up twice because of the hash string used as key.
1689 $this->groupData['filemounts'][md5(((($name . '|') . $path) . '|') . $type)] = array('name' => $name, 'path' => $path, 'type' => $type);
1690 // Return TRUE - went well, success!
1691 return 1;
1692 }
1693 }
1694 }
1695 }
1696
1697 /**
1698 * Returns an array with the filemounts for the user. Each filemount is represented with an array of a "name", "path" and "type".
1699 * If no filemounts an empty array is returned.
1700 *
1701 * @return array
1702 * @deprecated since TYPO3 6.0, will be removed in TYPO3 6.1 as getFileStorages() should be the one to be used
1703 * @todo Define visibility
1704 */
1705 public function returnFilemounts() {
1706 t3lib_div::logDeprecatedFunction();
1707 // initialize the file storages in order to set some default settings in any time
1708 $this->getFileStorages();
1709 return $this->groupData['filemounts'];
1710 }
1711
1712 /**
1713 * Creates a TypoScript comment with the string text inside.
1714 *
1715 * @param string $str The text to wrap in comment prefixes and delimiters.
1716 * @return string TypoScript comment with the string text inside.
1717 * @todo Define visibility
1718 */
1719 public function addTScomment($str) {
1720 $delimiter = '# ***********************************************';
1721 $out = $delimiter . LF;
1722 $lines = t3lib_div::trimExplode(LF, $str);
1723 foreach ($lines as $v) {
1724 $out .= ('# ' . $v) . LF;
1725 }
1726 $out .= $delimiter . LF;
1727 return $out;
1728 }
1729
1730 /************************************
1731 *
1732 * Workspaces
1733 *
1734 ************************************/
1735 /**
1736 * Initializing workspace.
1737 * Called from within this function, see fetchGroupData()
1738 *
1739 * @return void
1740 * @see fetchGroupData()
1741 * @todo Define visibility
1742 */
1743 public function workspaceInit() {
1744 // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
1745 $this->setWorkspace($this->user['workspace_id']);
1746 // Limiting the DB mountpoints if there any selected in the workspace record
1747 $this->initializeDbMountpointsInWorkspace();
1748 if ($allowed_languages = $this->getTSConfigVal('options.workspaces.allowed_languages.' . $this->workspace)) {
1749 $this->groupData['allowed_languages'] = $allowed_languages;
1750 $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->groupData['allowed_languages']);
1751 }
1752 }
1753
1754 /**
1755 * Limiting the DB mountpoints if there any selected in the workspace record
1756 *
1757 * @return void
1758 */
1759 protected function initializeDbMountpointsInWorkspace() {
1760 $dbMountpoints = trim($this->workspaceRec['db_mountpoints']);
1761 if ($this->workspace > 0 && $dbMountpoints != '') {
1762 $filteredDbMountpoints = array();
1763 // Notice: We cannot call $this->getPagePermsClause(1); as usual because the group-list is not available at this point. But bypassing is fine because all we want here is check if the workspace mounts are inside the current webmounts rootline.
1764 // The actual permission checking on page level is done elsewhere as usual anyway before the page tree is rendered.
1765 $readPerms = '1=1';
1766 // Traverse mount points of the
1767 $dbMountpoints = t3lib_div::intExplode(',', $dbMountpoints);
1768 foreach ($dbMountpoints as $mpId) {
1769 if ($this->isInWebMount($mpId, $readPerms)) {
1770 $filteredDbMountpoints[] = $mpId;
1771 }
1772 }
1773 // Re-insert webmounts:
1774 $filteredDbMountpoints = array_unique($filteredDbMountpoints);
1775 $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
1776 }
1777 }
1778
1779 /**
1780 * Adds more limitations for users who are no admins
1781 * this was previously in workspaceInit but has now been moved to "
1782 *
1783 * @return void
1784 */
1785 protected function initializeFileStoragesForWorkspace() {
1786 // Filtering the file mountpoints
1787 // if there some selected in the workspace record
1788 if ($this->workspace > 0) {
1789 $storageFiltersInWorkspace = trim($this->workspaceRec['file_mountpoints']);
1790 // no custom filemounts that should serve as filter or user is admin
1791 // so all user mountpoints are re-applied
1792 if (!$this->isAdmin() && $storageFiltersInWorkspace !== '') {
1793 // empty the fileStorages (will be re-applied later)
1794 $existingFileStoragesOfUser = $this->fileStorages;
1795 $this->fileStorages = array();
1796 $storageRepository = t3lib_div::makeInstance('t3lib_file_Repository_StorageRepository');
1797 // Fetching all filemounts from the workspace
1798 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_filemounts', ('deleted = 0 AND hidden = 0 AND pid = 0 AND uid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($storageFiltersInWorkspace)) . ')');
1799 // add every filemount of this workspace record
1800 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1801 // get the added entry, and check if it was in the users' original filemounts
1802 // if not, remove it from the new filemount list again
1803 // see self::addFileMount
1804 // TODO: check if the filter is narrowing down the existing user
1805 $storageObject = $storageRepository->findByUid($row['base']);
1806 if (isset($existingFileStoragesOfUser[$storageObject->getUid()])) {
1807 $storageObject->injectFileMount($row['path']);
1808 $this->fileStorages[$storageObject->getUid()] = $storageObject;
1809 }
1810 }
1811 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1812 }
1813 }
1814 }
1815
1816 /**
1817 * Checking if a workspace is allowed for backend user
1818 *
1819 * @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)
1820 * @param string $fields List of fields to select. Default fields are: uid,title,adminusers,members,reviewers,publish_access,stagechg_notification
1821 * @return array TRUE if access. Output will also show how access was granted. Admin users will have a true output regardless of input.
1822 * @todo Define visibility
1823 */
1824 public function checkWorkspace($wsRec, $fields = 'uid,title,adminusers,members,reviewers,publish_access,stagechg_notification') {
1825 $retVal = FALSE;
1826 // If not array, look up workspace record:
1827 if (!is_array($wsRec)) {
1828 switch ((string) $wsRec) {
1829 case '0':
1830 $wsRec = array('uid' => $wsRec);
1831 break;
1832 default:
1833 if (t3lib_extMgm::isLoaded('workspaces')) {
1834 $wsRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow($fields, 'sys_workspace', ('pid=0 AND uid=' . intval($wsRec)) . t3lib_BEfunc::deleteClause('sys_workspace'), '', 'title');
1835 }
1836 break;
1837 }
1838 }
1839 // If wsRec is set to an array, evaluate it:
1840 if (is_array($wsRec)) {
1841 if ($this->isAdmin()) {
1842 return array_merge($wsRec, array('_ACCESS' => 'admin'));
1843 } else {
1844 switch ((string) $wsRec['uid']) {
1845 case '0':
1846 $retVal = $this->groupData['workspace_perms'] & 1 ? array_merge($wsRec, array('_ACCESS' => 'online')) : FALSE;
1847 break;
1848 default:
1849 // Checking if the guy is admin:
1850 if (t3lib_div::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
1851 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1852 }
1853 // Checking if he is owner through a user group of his:
1854 foreach ($this->userGroupsUID as $groupUid) {
1855 if (t3lib_div::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
1856 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1857 }
1858 }
1859 // Checking if he is reviewer user:
1860 if (t3lib_div::inList($wsRec['reviewers'], 'be_users_' . $this->user['uid'])) {
1861 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1862 }
1863 // Checking if he is reviewer through a user group of his:
1864 foreach ($this->userGroupsUID as $groupUid) {
1865 if (t3lib_div::inList($wsRec['reviewers'], 'be_groups_' . $groupUid)) {
1866 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1867 }
1868 }
1869 // Checking if he is member as user:
1870 if (t3lib_div::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
1871 return array_merge($wsRec, array('_ACCESS' => 'member'));
1872 }
1873 // Checking if he is member through a user group of his:
1874 foreach ($this->userGroupsUID as $groupUid) {
1875 if (t3lib_div::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
1876 return array_merge($wsRec, array('_ACCESS' => 'member'));
1877 }
1878 }
1879 break;
1880 }
1881 }
1882 }
1883 return $retVal;
1884 }
1885
1886 /**
1887 * Uses checkWorkspace() to check if current workspace is available for user. This function caches the result and so can be called many times with no performance loss.
1888 *
1889 * @return array See checkWorkspace()
1890 * @see checkWorkspace()
1891 * @todo Define visibility
1892 */
1893 public function checkWorkspaceCurrent() {
1894 if (!isset($this->checkWorkspaceCurrent_cache)) {
1895 $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
1896 }
1897 return $this->checkWorkspaceCurrent_cache;
1898 }
1899
1900 /**
1901 * Setting workspace ID
1902 *
1903 * @param integer $workspaceId ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
1904 * @return void
1905 * @todo Define visibility
1906 */
1907 public function setWorkspace($workspaceId) {
1908 // Check workspace validity and if not found, revert to default workspace.
1909 if ($this->workspaceRec = $this->checkWorkspace($workspaceId, '*')) {
1910 // Set workspace ID internally
1911 $this->workspace = (int) $workspaceId;
1912 } else {
1913 $this->workspace = (int) $this->getDefaultWorkspace();
1914 $this->workspaceRec = $this->checkWorkspace($this->workspace, '*');
1915 }
1916 // Unset access cache:
1917 unset($this->checkWorkspaceCurrent_cache);
1918 // If ID is different from the stored one, change it:
1919 if (strcmp($this->workspace, $this->user['workspace_id'])) {
1920 $this->user['workspace_id'] = $this->workspace;
1921 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('workspace_id' => $this->user['workspace_id']));
1922 $this->simplelog(('User changed workspace to "' . $this->workspace) . '"');
1923 }
1924 }
1925
1926 /**
1927 * Setting workspace preview state for user:
1928 *
1929 * @param boolean $previewState State of user preview.
1930 * @return void
1931 * @todo Define visibility
1932 */
1933 public function setWorkspacePreview($previewState) {
1934 $this->user['workspace_preview'] = $previewState;
1935 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('workspace_preview' => $this->user['workspace_preview']));
1936 }
1937
1938 /**
1939 * Return default workspace ID for user,
1940 * If EXT:workspaces is not installed the user will be pushed the the
1941 * Live workspace
1942 *
1943 * @return integer Default workspace id. If no workspace is available it will be "-99
1944 * @todo Define visibility
1945 */
1946 public function getDefaultWorkspace() {
1947 $defaultWorkspace = -99;
1948 if (!t3lib_extMgm::isLoaded('workspaces') || $this->checkWorkspace(0)) {
1949 // Check online
1950 $defaultWorkspace = 0;
1951 } elseif ($this->checkWorkspace(-1)) {
1952 // Check offline
1953 $defaultWorkspace = -1;
1954 } elseif (t3lib_extMgm::isLoaded('workspaces')) {
1955 // Traverse custom workspaces:
1956 $workspaces = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,title,adminusers,members,reviewers', 'sys_workspace', 'pid=0' . t3lib_BEfunc::deleteClause('sys_workspace'), '', 'title');
1957 foreach ($workspaces as $rec) {
1958 if ($this->checkWorkspace($rec)) {
1959 $defaultWorkspace = $rec['uid'];
1960 break;
1961 }
1962 }
1963 }
1964 return $defaultWorkspace;
1965 }
1966
1967 /************************************
1968 *
1969 * Logging
1970 *
1971 ************************************/
1972 /**
1973 * Writes an entry in the logfile/table
1974 * Documentation in "TYPO3 Core API"
1975 *
1976 * @param integer $type Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
1977 * @param integer $action Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
1978 * @param integer $error Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1979 * @param integer $details_nr The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
1980 * @param string $details Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
1981 * @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
1982 * @param string $tablename Table name. Special field used by tce_main.php.
1983 * @param integer $recuid Record UID. Special field used by tce_main.php.
1984 * @param integer $recpid Record PID. Special field used by tce_main.php. OBSOLETE
1985 * @param integer $event_pid The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
1986 * @param string $NEWid Special field used by tce_main.php. NEWid string of newly created records.
1987 * @param integer $userId Alternative Backend User ID (used for logging login actions where this is not yet known).
1988 * @return integer Log entry ID.
1989 * @todo Define visibility
1990 */
1991 public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0) {
1992 $fields_values = array(
1993 'userid' => $userId ? $userId : intval($this->user['uid']),
1994 'type' => intval($type),
1995 'action' => intval($action),
1996 'error' => intval($error),
1997 'details_nr' => intval($details_nr),
1998 'details' => $details,
1999 'log_data' => serialize($data),
2000 'tablename' => $tablename,
2001 'recuid' => intval($recuid),
2002 'IP' => t3lib_div::getIndpEnv('REMOTE_ADDR'),
2003 'tstamp' => $GLOBALS['EXEC_TIME'],
2004 'event_pid' => intval($event_pid),
2005 'NEWid' => $NEWid,
2006 'workspace' => $this->workspace
2007 );
2008 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_log', $fields_values);
2009 return $GLOBALS['TYPO3_DB']->sql_insert_id();
2010 }
2011
2012 /**
2013 * Simple logging function
2014 *
2015 * @param string $message Log message
2016 * @param string $extKey Option extension key / module name
2017 * @param integer $error Error level. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
2018 * @return integer Log entry UID
2019 * @todo Define visibility
2020 */
2021 public function simplelog($message, $extKey = '', $error = 0) {
2022 return $this->writelog(4, 0, $error, 0, ($extKey ? ('[' . $extKey) . '] ' : '') . $message, array());
2023 }
2024
2025 /**
2026 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
2027 * If a login fails, this function is called. It will look up the sys_log to see if there has been more than $max failed logins the last $secondsBack seconds (default 3600). If so, an email with a warning is sent to $email.
2028 *
2029 * @param string $email Email address
2030 * @param integer $secondsBack Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
2031 * @param integer $max Max allowed failures before a warning mail is sent
2032 * @return void
2033 * @access private
2034 * @todo Define visibility
2035 */
2036 public function checkLogFailures($email, $secondsBack = 3600, $max = 3) {
2037 if ($email) {
2038 // Get last flag set in the log for sending
2039 $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
2040 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tstamp', 'sys_log', 'type=255 AND action=4 AND tstamp>' . intval($theTimeBack), '', 'tstamp DESC', '1');
2041 if ($testRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2042 $theTimeBack = $testRow['tstamp'];
2043 }
2044 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2045 // Check for more than $max number of error failures with the last period.
2046 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_log', 'type=255 AND action=3 AND error<>0 AND tstamp>' . intval($theTimeBack), '', 'tstamp');
2047 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) > $max) {
2048 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
2049 $subject = ('TYPO3 Login Failure Warning (at ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']) . ')';
2050 $email_body = ((((('There have been some attempts (' . $GLOBALS['TYPO3_DB']->sql_num_rows($res)) . ') to login at the TYPO3
2051 site "') . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']) . '" (') . t3lib_div::getIndpEnv('HTTP_HOST')) . ').
2052
2053 This is a dump of the failures:
2054
2055 ';
2056 while ($testRows = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2057 $theData = unserialize($testRows['log_data']);
2058 $email_body .= (date((($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ') . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm']), $testRows['tstamp']) . ': ') . @sprintf($testRows['details'], ('' . $theData[0]), ('' . $theData[1]), ('' . $theData[2]));
2059 $email_body .= LF;
2060 }
2061 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2062 $from = t3lib_utility_Mail::getSystemFrom();
2063 /** @var $mail t3lib_mail_Message */
2064 $mail = t3lib_div::makeInstance('t3lib_mail_Message');
2065 $mail->setTo($email)->setFrom($from)->setSubject($subject)->setBody($email_body);
2066 $mail->send();
2067 // Logout written to log
2068 $this->writelog(255, 4, 0, 3, 'Failure warning (%s failures within %s seconds) sent by email to %s', array($GLOBALS['TYPO3_DB']->sql_num_rows($res), $secondsBack, $email));
2069 }
2070 }
2071 }
2072
2073 }
2074
2075 ?>