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