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