[TASK] Cleanup draft workspace usages
[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 { // So what about the stage of the version, does that allow editing for this user?
685 return $this->workspaceCheckStageForCurrent($recData['t3ver_stage']) ? FALSE : 'Record stage "' . $recData['t3ver_stage'] . '" and users access level did not allow for editing';
686 }
687 } else { // We are testing a "live" record:
688 if ($res = $this->workspaceAllowLiveRecordsInPID($recData['pid'], $table)) { // For "Live" records, check that PID for table allows editing
689 // Live records are OK in this branch, but what about the stage of branch point, if any:
690 return $res > 0 ? FALSE : 'Stage for versioning root point and users access level did not allow for editing'; // OK
691 } else { // If not offline and not in versionized branch, output error:
692 return 'Online record was not in versionized branch!';
693 }
694 }
695 } else {
696 return 'No record';
697 }
698 } else {
699 return FALSE; // OK because workspace is 0
700 }
701 }
702
703 /**
704 * Evaluates if a user is allowed to edit the offline version
705 *
706 * @param string Table of record
707 * @param array Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
708 * @return string String error code, telling the failure state. FALSE=All ok
709 * @see workspaceCannotEditRecord()
710 */
711 function workspaceCannotEditOfflineVersion($table, $recData) {
712 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
713
714 if (!is_array($recData)) {
715 $recData = t3lib_BEfunc::getRecord($table, $recData, 'uid,pid,t3ver_wsid,t3ver_stage');
716 }
717 if (is_array($recData)) {
718 if ((int) $recData['pid'] === -1) {
719 return $this->workspaceCannotEditRecord($table, $recData);
720 } else {
721 return 'Not an offline version';
722 }
723 } else {
724 return 'No record';
725 }
726 } else {
727 return 'Table does not support versioning.';
728 }
729 }
730
731 /**
732 * Check if "live" records from $table may be created or edited in this PID.
733 * If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
734 * 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!
735 *
736 * @param integer PID value to check for.
737 * @param string Table name
738 * @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.
739 */
740 function workspaceAllowLiveRecordsInPID($pid, $table) {
741
742 // Always for Live workspace AND if live-edit is enabled and tables are completely without versioning it is ok as well.
743 if ($this->workspace === 0 || ($this->workspaceRec['live_edit'] && !$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) || $GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']) {
744 return 2; // OK to create for this table.
745 } 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.
746 // Now, check what the stage of that "page" or "branch" version type is:
747 $stage = t3lib_BEfunc::isPidInVersionizedBranch($pid, $table, TRUE);
748 return $this->workspaceCheckStageForCurrent($stage) ? 1 : -1;
749 } else {
750 return FALSE; // If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
751 }
752 }
753
754 /**
755 * Evaluates if a record from $table can be created in $pid
756 *
757 * @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!
758 * @param string Table name
759 * @return boolean TRUE if OK.
760 */
761 function workspaceCreateNewRecord($pid, $table) {
762 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
763 if ($res < 0) {
764 return FALSE; // Stage for versioning root point and users access level did not allow for editing
765 }
766 } elseif (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) { // So, if no live records were allowed, we have to create a new version of this record:
767 return FALSE;
768 }
769 return TRUE;
770 }
771
772 /**
773 * Evaluates if auto creation of a version of a record is allowed.
774 *
775 * @param string Table of the record
776 * @param integer UID of record
777 * @param integer PID of record
778 * @return boolean TRUE if ok.
779 */
780 function workspaceAllowAutoCreation($table, $id, $recpid) {
781 // 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.
782 if ($this->workspace !== 0 // Only in draft workspaces
783 && !$this->workspaceRec['disable_autocreate'] // Auto-creation must not be disabled.
784 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] // Table must be versionizable
785 && $recpid >= 0 // The PID of the record must NOT be -1 or less (would indicate that it already was a version!)
786 && !t3lib_BEfunc::getWorkspaceVersionOfRecord($this->workspace, $table, $id, 'uid') // There must be no existing version of this record in workspace.
787 && !t3lib_BEfunc::isPidInVersionizedBranch($recpid, $table)) { // PID must NOT be in a versionized branch either
788 return TRUE;
789 } elseif ($this->workspaceRec['disable_autocreate']) {
790 t3lib_div::deprecationLog('Usage of disable_autocreate feature is deprecated since 4.5.');
791 }
792 }
793
794 /**
795 * Checks if an element stage allows access for the user in the current workspace
796 * In workspaces 0 (Live) and -1 (Default draft) access is always granted for any stage.
797 * Admins are always allowed.
798 * An option for custom workspaces allows members to also edit when the stage is "Review"
799 *
800 * @param integer Stage id from an element: -1,0 = editing, 1 = reviewer, >1 = owner
801 * @return boolean TRUE if user is allowed access
802 */
803 function workspaceCheckStageForCurrent($stage) {
804 $stage = intval($stage);
805 if ($this->isAdmin()) {
806 return TRUE;
807 }
808
809 if ($this->workspace > 0 && t3lib_extMgm::isLoaded('workspaces')) {
810 $stat = $this->checkWorkspaceCurrent();
811
812 // Check if custom staging is activated
813 $workspaceRec = t3lib_BEfunc::getRecord('sys_workspace', $stat['uid']);
814 if ($workspaceRec['custom_stages'] > 0 && $stage !== 0 && $stage !== '-10') {
815
816 // Get custom stage record
817 $workspaceStageRec = t3lib_BEfunc::getRecord('sys_workspace_stage', $stage);
818 // Check if the user is responsible for the current stage
819 if ((t3lib_div::inList($workspaceStageRec['responsible_persons'], 'be_users_' . $this->user['uid'])
820 && $stat['_ACCESS'] === 'member')
821 || $stat['_ACCESS'] === 'owner') {
822 return TRUE;
823 }
824
825 // Check if the user is in a group which is responsible for the current stage
826 foreach ($this->userGroupsUID as $groupUid) {
827 if ((t3lib_div::inList($workspaceStageRec['responsible_persons'], 'be_groups_' . $groupUid)
828 && $stat['_ACCESS'] === 'member')
829 || $stat['_ACCESS'] === 'owner') {
830 return TRUE;
831 }
832 }
833 // only owner is allowed to change records which are "ready to publish"
834 } elseif ($stage == '-10' || $stage == '-20') {
835 if ($stat['_ACCESS'] === 'owner') {
836 return TRUE;
837 } else {
838 return FALSE;
839 }
840 } else {
841 $memberStageLimit = $this->workspaceRec['review_stage_edit'] ? 1 : 0;
842 if (($stage <= $memberStageLimit && $stat['_ACCESS'] === 'member')
843 || ($stage <= 1 && $stat['_ACCESS'] === 'reviewer')
844 || $stat['_ACCESS'] === 'owner') {
845 return TRUE;
846 }
847 }
848 } else {
849 return TRUE;
850 } // Always OK for live and draft workspaces.
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 */
908 function workspaceVersioningTypeAccess($type) {
909 $retVal = FALSE;
910
911 $type = t3lib_div::intInRange($type, -1);
912
913 // Check if only element versioning is allowed:
914 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['elementVersioningOnly'] && $type != -1) {
915 return FALSE;
916 }
917
918 if ($this->workspace > 0 && !$this->isAdmin()) {
919 $stat = $this->checkWorkspaceCurrent();
920 if ($stat['_ACCESS'] !== 'owner') {
921
922 switch ((int) $type) {
923 case -1:
924 $retVal = $this->workspaceRec['vtypes'] & 1 ? FALSE : TRUE;
925 break;
926 case 0:
927 $retVal = $this->workspaceRec['vtypes'] & 2 ? FALSE : TRUE;
928 break;
929 default:
930 $retVal = $this->workspaceRec['vtypes'] & 4 ? FALSE : TRUE;
931 break;
932 }
933 } else {
934 $retVal = TRUE;
935 }
936 } else {
937 $retVal = TRUE;
938 }
939
940 return $retVal;
941 }
942
943 /**
944 * Finding "closest" versioning type, used for creation of new records.
945 *
946 * @see workspaceVersioningTypeAccess() for hints on $type
947 * @param integer Versioning type to evaluation: -1, 0, >1
948 * @return integer Returning versioning type
949 */
950 function workspaceVersioningTypeGetClosest($type) {
951 $type = t3lib_div::intInRange($type, -1);
952
953 if ($this->workspace > 0) {
954 switch ((int) $type) {
955 case -1:
956 $type = -1;
957 break;
958 case 0:
959 $type = $this->workspaceVersioningTypeAccess($type) ? $type : -1;
960 break;
961 default:
962 $type = $this->workspaceVersioningTypeAccess($type) ? $type : ($this->workspaceVersioningTypeAccess(0) ? 0 : -1);
963 break;
964 }
965 }
966 return $type;
967 }
968
969
970 /*************************************
971 *
972 * Miscellaneous functions
973 *
974 *************************************/
975
976 /**
977 * Returns the value/properties of a TS-object as given by $objectString, eg. 'options.dontMountAdminMounts'
978 * Nice (general!) function for returning a part of a TypoScript array!
979 *
980 * @param string Pointer to an "object" in the TypoScript array, fx. 'options.dontMountAdminMounts'
981 * @param array Optional TSconfig array: If array, then this is used and not $this->userTS. If not array, $this->userTS is used.
982 * @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.
983 * @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.
984 */
985 function getTSConfig($objectString, $config = '') {
986 if (!is_array($config)) {
987 $config = $this->userTS; // Getting Root-ts if not sent
988 }
989 $TSConf = array();
990 $parts = explode('.', $objectString, 2);
991 $key = $parts[0];
992 if (trim($key)) {
993 if (count($parts) > 1 && trim($parts[1])) {
994 // Go on, get the next level
995 if (is_array($config[$key . '.'])) {
996 $TSConf = $this->getTSConfig($parts[1], $config[$key . '.']);
997 }
998 } else {
999 $TSConf['value'] = $config[$key];
1000 $TSConf['properties'] = $config[$key . '.'];
1001 }
1002 }
1003 return $TSConf;
1004 }
1005
1006 /**
1007 * Returns the "value" of the $objectString from the BE_USERS "User TSconfig" array
1008 *
1009 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
1010 * @return string The value for that object string (object path)
1011 * @see getTSConfig()
1012 */
1013 function getTSConfigVal($objectString) {
1014 $TSConf = $this->getTSConfig($objectString);
1015 return $TSConf['value'];
1016 }
1017
1018 /**
1019 * Returns the "properties" of the $objectString from the BE_USERS "User TSconfig" array
1020 *
1021 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
1022 * @return array The properties for that object string (object path) - if any
1023 * @see getTSConfig()
1024 */
1025 function getTSConfigProp($objectString) {
1026 $TSConf = $this->getTSConfig($objectString);
1027 return $TSConf['properties'];
1028 }
1029
1030 /**
1031 * Returns TRUE if $item is in $in_list
1032 *
1033 * @param string Comma list with items, no spaces between items!
1034 * @param string The string to find in the list of items
1035 * @return string Boolean
1036 */
1037 function inList($in_list, $item) {
1038 return strstr(',' . $in_list . ',', ',' . $item . ',');
1039 }
1040
1041 /**
1042 * Returns an array with the webmounts.
1043 * If no webmounts, and empty array is returned.
1044 * 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.
1045 *
1046 * @return array
1047 */
1048 function returnWebmounts() {
1049 return (string) ($this->groupData['webmounts']) != '' ? explode(',', $this->groupData['webmounts']) : array();
1050 }
1051
1052 /**
1053 * Returns an array with the filemounts for the user. Each filemount is represented with an array of a "name", "path" and "type".
1054 * If no filemounts an empty array is returned.
1055 *
1056 * @return array
1057 */
1058 function returnFilemounts() {
1059 return $this->groupData['filemounts'];
1060 }
1061
1062 /**
1063 * Returns an integer bitmask that represents the permissions for file operations.
1064 * Permissions of the user and groups the user is a member of were combined by a logical OR.
1065 *
1066 * Meaning of each bit:
1067 * 1 - Files: Upload,Copy,Move,Delete,Rename
1068 * 2 - Files: Unzip
1069 * 4 - Directory: Move,Delete,Rename,New
1070 * 8 - Directory: Copy
1071 * 16 - Directory: Delete recursively (rm -Rf)
1072 *
1073 * @return integer File operation permission bitmask
1074 */
1075 public function getFileoperationPermissions() {
1076 if ($this->isAdmin()) {
1077 return 31;
1078 } else {
1079 return $this->groupData['fileoper_perms'];
1080 }
1081 }
1082
1083 /**
1084 * Returns TRUE or FALSE, depending if an alert popup (a javascript confirmation) should be shown
1085 * call like $GLOBALS['BE_USER']->jsConfirmation($BITMASK)
1086 *
1087 * 1 - typeChange
1088 * 2 - copy/move/paste
1089 * 4 - delete
1090 * 8 - frontend editing
1091 * 128 - other (not used yet)
1092 *
1093 * @param integer Bitmask
1094 * @return boolean TRUE if the confirmation should be shown
1095 */
1096 function jsConfirmation($bitmask) {
1097 $alertPopup = $GLOBALS['BE_USER']->getTSConfig('options.alertPopups');
1098 if (empty($alertPopup['value'])) {
1099 $alertPopup = 255; // default: show all warnings
1100 } else {
1101 $alertPopup = (int) $alertPopup['value'];
1102 }
1103 if (($alertPopup & $bitmask) == $bitmask) { // show confirmation
1104 return 1;
1105 } else { // don't show confirmation
1106 return 0;
1107 }
1108 }
1109
1110
1111 /*************************************
1112 *
1113 * Authentication methods
1114 *
1115 *************************************/
1116
1117
1118 /**
1119 * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
1120 * This method is called by ->backendCheckLogin() (from extending class t3lib_beuserauth) if the backend user login has verified OK.
1121 * Generally this is required initialization of a backend user.
1122 *
1123 * @return void
1124 * @access private
1125 * @see t3lib_TSparser
1126 */
1127 function fetchGroupData() {
1128 if ($this->user['uid']) {
1129
1130 // Get lists for the be_user record and set them as default/primary values.
1131 $this->dataLists['modList'] = $this->user['userMods']; // Enabled Backend Modules
1132 $this->dataLists['allowed_languages'] = $this->user['allowed_languages']; // Add Allowed Languages
1133 $this->dataLists['workspace_perms'] = $this->user['workspace_perms']; // Set user value for workspace permissions.
1134 $this->dataLists['webmount_list'] = $this->user['db_mountpoints']; // Database mountpoints
1135 $this->dataLists['filemount_list'] = $this->user['file_mountpoints']; // File mountpoints
1136 $this->dataLists['fileoper_perms'] = (int) $this->user['fileoper_perms']; // Fileoperation permissions
1137
1138 // Setting default User TSconfig:
1139 $this->TSdataArray[] = $this->addTScomment('From $GLOBALS["TYPO3_CONF_VARS"]["BE"]["defaultUserTSconfig"]:') .
1140 $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
1141
1142 // Default TSconfig for admin-users
1143 if ($this->isAdmin()) {
1144 $this->TSdataArray[] = $this->addTScomment('"admin" user presets:') . '
1145 admPanel.enable.all = 1
1146 ';
1147 if (t3lib_extMgm::isLoaded('sys_note')) {
1148 $this->TSdataArray[] = '
1149 // Setting defaults for sys_note author / email...
1150 TCAdefaults.sys_note.author = ' . $this->user['realName'] . '
1151 TCAdefaults.sys_note.email = ' . $this->user['email'] . '
1152 ';
1153 }
1154 }
1155
1156 // FILE MOUNTS:
1157 // Admin users has the base fileadmin dir mounted
1158 if ($this->isAdmin() && $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
1159 $this->addFileMount($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '', PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], 0, '');
1160 }
1161
1162 // If userHomePath is set, we attempt to mount it
1163 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
1164 // First try and mount with [uid]_[username]
1165 $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');
1166 if (!$didMount) {
1167 // If that failed, try and mount with only [uid]
1168 $this->addFileMount($this->user['username'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'] . $this->user['uid'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'], 0, 'user');
1169 }
1170 }
1171
1172 // BE_GROUPS:
1173 // Get the groups...
1174 # $grList = t3lib_BEfunc::getSQLselectableList($this->user[$this->usergroup_column],$this->usergroup_table,$this->usergroup_table);
1175 $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.
1176 if ($grList) {
1177 // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc. Refer to fetchGroups() function.
1178 $this->fetchGroups($grList);
1179 }
1180
1181 // Add the TSconfig for this specific user:
1182 $this->TSdataArray[] = $this->addTScomment('USER TSconfig field') . $this->user['TSconfig'];
1183 // Check include lines.
1184 $this->TSdataArray = t3lib_TSparser::checkIncludeLines_array($this->TSdataArray);
1185
1186 $this->userTS_text = implode(LF . '[GLOBAL]' . LF, $this->TSdataArray); // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
1187
1188 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions'] && !$this->userTS_dontGetCached) {
1189 // Perform TS-Config parsing with condition matching
1190 $parseObj = t3lib_div::makeInstance('t3lib_TSparser_TSconfig');
1191 $res = $parseObj->parseTSconfig($this->userTS_text, 'userTS');
1192 if ($res) {
1193 $this->userTS = $res['TSconfig'];
1194 $this->userTSUpdated = ($res['cached'] ? 0 : 1);
1195 }
1196 } else {
1197 // Parsing the user TSconfig (or getting from cache)
1198 $hash = md5('userTS:' . $this->userTS_text);
1199 $cachedContent = t3lib_BEfunc::getHash($hash);
1200 if (isset($cachedContent) && !$this->userTS_dontGetCached) {
1201 $this->userTS = unserialize($cachedContent);
1202 } else {
1203 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
1204 $parseObj->parse($this->userTS_text);
1205 $this->userTS = $parseObj->setup;
1206 t3lib_BEfunc::storeHash($hash, serialize($this->userTS), 'BE_USER_TSconfig');
1207 // Update UC:
1208 $this->userTSUpdated = 1;
1209 }
1210 }
1211
1212 // Processing webmounts
1213 if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) { // Admin's always have the root mounted
1214 $this->dataLists['webmount_list'] = '0,' . $this->dataLists['webmount_list'];
1215 }
1216
1217 // Processing filemounts
1218 t3lib_div::loadTCA('sys_filemounts');
1219 $orderBy = $GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'] ? $GLOBALS['TYPO3_DB']->stripOrderBy($GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby']) : 'sorting';
1220 $this->dataLists['filemount_list'] = t3lib_div::uniqueList($this->dataLists['filemount_list']);
1221 if ($this->dataLists['filemount_list']) {
1222 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_filemounts', 'deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $this->dataLists['filemount_list'] . ')', '', $orderBy);
1223 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1224 $this->addFileMount($row['title'], $row['path'], $row['path'], $row['base'] ? 1 : 0, '');
1225 }
1226 }
1227
1228 // The lists are cleaned for duplicates
1229 $this->groupData['webmounts'] = t3lib_div::uniqueList($this->dataLists['webmount_list']);
1230 $this->groupData['pagetypes_select'] = t3lib_div::uniqueList($this->dataLists['pagetypes_select']);
1231 $this->groupData['tables_select'] = t3lib_div::uniqueList($this->dataLists['tables_modify'] . ',' . $this->dataLists['tables_select']);
1232 $this->groupData['tables_modify'] = t3lib_div::uniqueList($this->dataLists['tables_modify']);
1233 $this->groupData['non_exclude_fields'] = t3lib_div::uniqueList($this->dataLists['non_exclude_fields']);
1234 $this->groupData['explicit_allowdeny'] = t3lib_div::uniqueList($this->dataLists['explicit_allowdeny']);
1235 $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->dataLists['allowed_languages']);
1236 $this->groupData['custom_options'] = t3lib_div::uniqueList($this->dataLists['custom_options']);
1237 $this->groupData['modules'] = t3lib_div::uniqueList($this->dataLists['modList']);
1238 $this->groupData['fileoper_perms'] = $this->dataLists['fileoper_perms'];
1239 $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
1240
1241 // populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
1242 $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
1243
1244 // 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)
1245 $this->groupList = implode(',', $this->userGroupsUID);
1246 $this->setCachedList($this->groupList);
1247
1248 // Checking read access to webmounts:
1249 if (trim($this->groupData['webmounts']) !== '') {
1250 $webmounts = explode(',', $this->groupData['webmounts']); // Explode mounts
1251 $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
1252 foreach ($webmounts as $idx => $mountPointUid) {
1253 if ($mountPointUid > 0 && !isset($MProws[$mountPointUid])) { // If the mount ID is NOT found among selected pages, unset it:
1254 unset($webmounts[$idx]);
1255 }
1256 }
1257 $this->groupData['webmounts'] = implode(',', $webmounts); // Implode mounts in the end.
1258 }
1259
1260 // Setting up workspace situation (after webmounts are processed!):
1261 $this->workspaceInit();
1262 }
1263 }
1264
1265 /**
1266 * Fetches the group records, subgroups and fills internal arrays.
1267 * Function is called recursively to fetch subgroups
1268 *
1269 * @param string Commalist of be_groups uid numbers
1270 * @param string List of already processed be_groups-uids so the function will not fall into a eternal recursion.
1271 * @return void
1272 * @access private
1273 */
1274 function fetchGroups($grList, $idList = '') {
1275 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
1276 $lockToDomain_SQL = ' AND (lockToDomain=\'\' OR lockToDomain IS NULL OR lockToDomain=\'' . t3lib_div::getIndpEnv('HTTP_HOST') . '\')';
1277 $whereSQL = 'deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $grList . ')' . $lockToDomain_SQL;
1278
1279 // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
1280 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'])) {
1281 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] as $classRef) {
1282 $hookObj = t3lib_div::getUserObj($classRef);
1283 if (method_exists($hookObj, 'fetchGroupQuery_processQuery')) {
1284 $whereSQL = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, $whereSQL);
1285 }
1286 }
1287 }
1288
1289 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->usergroup_table, $whereSQL);
1290
1291 // The userGroups array is filled
1292 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1293 $this->userGroups[$row['uid']] = $row;
1294 }
1295
1296 // Traversing records in the correct order
1297 $include_staticArr = t3lib_div::intExplode(',', $grList);
1298 // traversing list
1299 foreach ($include_staticArr as $key => $uid) {
1300
1301 // Get row:
1302 $row = $this->userGroups[$uid];
1303 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
1304
1305 // Include sub groups
1306 if (trim($row['subgroup'])) {
1307 $theList = implode(',', t3lib_div::intExplode(',', $row['subgroup'])); // Make integer list
1308 $this->fetchGroups($theList, $idList . ',' . $uid); // Call recursively, pass along list of already processed groups so they are not recursed again.
1309 }
1310 // Add the group uid, current list, TSconfig to the internal arrays.
1311 $this->includeGroupArray[] = $uid;
1312 $this->includeHierarchy[] = $idList;
1313 $this->TSdataArray[] = $this->addTScomment('Group "' . $row['title'] . '" [' . $row['uid'] . '] TSconfig field:') . $row['TSconfig'];
1314
1315 // Mount group database-mounts
1316 if (($this->user['options'] & 1) == 1) {
1317 $this->dataLists['webmount_list'] .= ',' . $row['db_mountpoints'];
1318 }
1319
1320 // Mount group file-mounts
1321 if (($this->user['options'] & 2) == 2) {
1322 $this->dataLists['filemount_list'] .= ',' . $row['file_mountpoints'];
1323 }
1324
1325 // Mount group home-dirs
1326 if (($this->user['options'] & 2) == 2) {
1327 // If groupHomePath is set, we attempt to mount it
1328 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath']) {
1329 $this->addFileMount($row['title'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'] . $row['uid'], 0, 'group');
1330 }
1331 }
1332
1333 // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
1334 if ($row['inc_access_lists'] == 1) {
1335 $this->dataLists['modList'] .= ',' . $row['groupMods'];
1336 $this->dataLists['tables_select'] .= ',' . $row['tables_select'];
1337 $this->dataLists['tables_modify'] .= ',' . $row['tables_modify'];
1338 $this->dataLists['pagetypes_select'] .= ',' . $row['pagetypes_select'];
1339 $this->dataLists['non_exclude_fields'] .= ',' . $row['non_exclude_fields'];
1340 $this->dataLists['explicit_allowdeny'] .= ',' . $row['explicit_allowdeny'];
1341 $this->dataLists['allowed_languages'] .= ',' . $row['allowed_languages'];
1342 $this->dataLists['custom_options'] .= ',' . $row['custom_options'];
1343 }
1344
1345 // Setting fileoperation permissions
1346 $this->dataLists['fileoper_perms'] |= (int) $row['fileoper_perms'];
1347
1348 // Setting workspace permissions:
1349 $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
1350
1351 // 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.
1352 if (!strcmp($idList, '') && !$this->firstMainGroup) {
1353 $this->firstMainGroup = $uid;
1354 }
1355 }
1356 }
1357
1358 // ****************
1359 // HOOK: fetchGroups_postProcessing
1360 // ****************
1361 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'])) {
1362 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] as $_funcRef) {
1363 $_params = array();
1364 t3lib_div::callUserFunction($_funcRef, $_params, $this);
1365 }
1366 }
1367 }
1368
1369 /**
1370 * Updates the field be_users.usergroup_cached_list if the groupList of the user has changed/is different from the current list.
1371 * 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.
1372 *
1373 * @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.
1374 * @return void
1375 * @access private
1376 */
1377 function setCachedList($cList) {
1378 if ((string) $cList != (string) $this->user['usergroup_cached_list']) {
1379 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('usergroup_cached_list' => $cList));
1380 }
1381 }
1382
1383 /**
1384 * Adds a filemount to the users array of filemounts, $this->groupData['filemounts'][hash_key] = Array ('name'=>$name, 'path'=>$path, 'type'=>$type);
1385 * Is a part of the authentication proces of the user.
1386 * 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!
1387 * Paths in the mounted information will always be absolute and have a trailing slash.
1388 *
1389 * @param string $title will be the (root)name of the filemount in the folder tree
1390 * @param string $altTitle will be the (root)name of the filemount IF $title is not TRUE (blank or zero)
1391 * @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.
1392 * @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.
1393 * @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.
1394 * @return boolean Returns "1" if the requested filemount was mounted, otherwise no return value.
1395 * @access private
1396 */
1397 function addFileMount($title, $altTitle, $path, $webspace, $type) {
1398 // Return FALSE if fileadminDir is not set and we try to mount a relative path
1399 if ($webspace && !$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
1400 return FALSE;
1401 }
1402
1403 // Trimming and pre-processing
1404 $path = trim($path);
1405 if ($this->OS == 'WIN') { // with WINDOWS convert backslash to slash!!
1406 $path = str_replace('\\', '/', $path);
1407 }
1408 // If the path is TRUE and validates as a valid path string:
1409 if ($path && t3lib_div::validPathStr($path)) {
1410 // normalize path: remove leading '/' and './', and trailing '/' and '/.'
1411 $path = trim($path);
1412 $path = preg_replace('#^\.?/|/\.?$#', '', $path);
1413
1414 if ($path) { // there must be some chars in the path
1415 $fdir = PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']; // fileadmin dir, absolute
1416 if ($webspace) {
1417 $path = $fdir . $path; // PATH_site + fileadmin dir is prepended
1418 } else {
1419 if ($this->OS != 'WIN') { // with WINDOWS no prepending!!
1420 $path = '/' . $path; // root-level is the start...
1421 }
1422 }
1423 $path .= '/';
1424
1425 // We now have a path with slash after and slash before (if unix)
1426 if (@is_dir($path) &&
1427 (($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'])) || t3lib_div::isFirstPartOfStr($path, $fdir))) {
1428 // Alternative title?
1429 $name = $title ? $title : $altTitle;
1430 // 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.
1431 $this->groupData['filemounts'][md5($name . '|' . $path . '|' . $type)] = array('name' => $name, 'path' => $path, 'type' => $type);
1432 // Return TRUE - went well, success!
1433 return 1;
1434 }
1435 }
1436 }
1437 }
1438
1439 /**
1440 * Creates a TypoScript comment with the string text inside.
1441 *
1442 * @param string The text to wrap in comment prefixes and delimiters.
1443 * @return string TypoScript comment with the string text inside.
1444 */
1445 function addTScomment($str) {
1446 $delimiter = '# ***********************************************';
1447
1448 $out = $delimiter . LF;
1449 $lines = t3lib_div::trimExplode(LF, $str);
1450 foreach ($lines as $v) {
1451 $out .= '# ' . $v . LF;
1452 }
1453 $out .= $delimiter . LF;
1454 return $out;
1455 }
1456
1457
1458 /************************************
1459 *
1460 * Workspaces
1461 *
1462 ************************************/
1463
1464 /**
1465 * Initializing workspace.
1466 * Called from within this function, see fetchGroupData()
1467 *
1468 * @return void
1469 * @see fetchGroupData()
1470 */
1471 function workspaceInit() {
1472
1473 // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
1474 $this->setWorkspace($this->user['workspace_id']);
1475
1476 // Limiting the DB mountpoints if there any selected in the workspace record
1477 $dbMountpoints = trim($this->workspaceRec['db_mountpoints']);
1478 if ($this->workspace > 0 && $dbMountpoints != '') {
1479 $filteredDbMountpoints = array();
1480 $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.
1481
1482 // Traverse mount points of the
1483 $dbMountpoints = t3lib_div::intExplode(',', $dbMountpoints);
1484 foreach ($dbMountpoints as $mpId) {
1485 if ($this->isInWebMount($mpId, $readPerms)) {
1486 $filteredDbMountpoints[] = $mpId;
1487 }
1488 }
1489
1490 // Re-insert webmounts:
1491 $filteredDbMountpoints = array_unique($filteredDbMountpoints);
1492 $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
1493 }
1494
1495 // Filtering the file mountpoints
1496 // if there some selected in the workspace record
1497 if ($this->workspace !== 0) {
1498 $usersFileMounts = $this->groupData['filemounts'];
1499 $this->groupData['filemounts'] = array();
1500 }
1501 $fileMountpoints = trim($this->workspaceRec['file_mountpoints']);
1502 if ($this->workspace > 0) {
1503
1504 // no custom filemounts that should serve as filter or user is admin
1505 // so all user mountpoints are re-applied
1506 if ($this->isAdmin() || $fileMountpoints === '') {
1507 $this->groupData['filemounts'] = $usersFileMounts;
1508 } else {
1509 // Fetching all filemounts from the workspace
1510 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1511 '*',
1512 'sys_filemounts',
1513 'deleted = 0 AND hidden = 0 AND pid = 0 AND uid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($fileMountpoints) . ')'
1514 );
1515
1516 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1517 // add every filemount of this workspace record
1518 $this->addFileMount($row['title'], $row['path'], $row['path'], ($row['base'] ? 1 : 0), '');
1519
1520 // get the added entry, and check if it was in the users' original filemounts
1521 // if not, remove it from the new filemount list again
1522 // see self::addFileMount
1523 end($this->groupData['filemounts']);
1524 $md5hash = key($this->groupData['filemounts']);
1525 if (!array_key_exists($md5hash, $usersFileMounts)) {
1526 unset($this->groupData['filemounts'][$md5hash]);
1527 }
1528 }
1529 }
1530 }
1531
1532 if ($allowed_languages = $this->getTSConfigVal('options.workspaces.allowed_languages.' . $this->workspace)) {
1533 $this->groupData['allowed_languages'] = $allowed_languages;
1534 $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->groupData['allowed_languages']);
1535 }
1536 }
1537
1538 /**
1539 * Checking if a workspace is allowed for backend user
1540 *
1541 * @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)
1542 * @param string List of fields to select. Default fields are: uid,title,adminusers,members,reviewers,publish_access,stagechg_notification
1543 * @return array TRUE if access. Output will also show how access was granted. Admin users will have a true output regardless of input.
1544 */
1545 function checkWorkspace($wsRec, $fields = 'uid,title,adminusers,members,reviewers,publish_access,stagechg_notification') {
1546 $retVal = FALSE;
1547
1548 // If not array, look up workspace record:
1549 if (!is_array($wsRec)) {
1550 switch ((string) $wsRec) {
1551 case '0':
1552 $wsRec = array('uid' => $wsRec);
1553 break;
1554 default:
1555 if (t3lib_extMgm::isLoaded('workspaces')) {
1556 $wsRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
1557 $fields,
1558 'sys_workspace',
1559 'pid=0 AND uid=' . intval($wsRec) .
1560 t3lib_BEfunc::deleteClause('sys_workspace'),
1561 '',
1562 'title'
1563 );
1564 }
1565 break;
1566 }
1567 }
1568
1569 // If wsRec is set to an array, evaluate it:
1570 if (is_array($wsRec)) {
1571 if ($this->isAdmin()) {
1572 return array_merge($wsRec, array('_ACCESS' => 'admin'));
1573 } else {
1574
1575 switch ((string) $wsRec['uid']) {
1576 case '0':
1577 $retVal = ($this->groupData['workspace_perms'] & 1) ? array_merge($wsRec, array('_ACCESS' => 'online')) : FALSE;
1578 break;
1579 default:
1580 // Checking if the guy is admin:
1581 if (t3lib_div::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
1582 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1583 }
1584 // Checking if he is owner through a user group of his:
1585 foreach ($this->userGroupsUID as $groupUid) {
1586 if (t3lib_div::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
1587 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1588 }
1589 }
1590 // Checking if he is reviewer user:
1591 if (t3lib_div::inList($wsRec['reviewers'], 'be_users_' . $this->user['uid'])) {
1592 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1593 }
1594 // Checking if he is reviewer through a user group of his:
1595 foreach ($this->userGroupsUID as $groupUid) {
1596 if (t3lib_div::inList($wsRec['reviewers'], 'be_groups_' . $groupUid)) {
1597 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1598 }
1599 }
1600 // Checking if he is member as user:
1601 if (t3lib_div::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
1602 return array_merge($wsRec, array('_ACCESS' => 'member'));
1603 }
1604 // Checking if he is member through a user group of his:
1605 foreach ($this->userGroupsUID as $groupUid) {
1606 if (t3lib_div::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
1607 return array_merge($wsRec, array('_ACCESS' => 'member'));
1608 }
1609 }
1610 break;
1611 }
1612 }
1613 }
1614
1615 return $retVal;
1616 }
1617
1618 /**
1619 * 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.
1620 *
1621 * @return array See checkWorkspace()
1622 * @see checkWorkspace()
1623 */
1624 function checkWorkspaceCurrent() {
1625 if (!isset($this->checkWorkspaceCurrent_cache)) {
1626 $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
1627 }
1628 return $this->checkWorkspaceCurrent_cache;
1629 }
1630
1631 /**
1632 * Setting workspace ID
1633 *
1634 * @param integer ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
1635 * @return void
1636 */
1637 function setWorkspace($workspaceId) {
1638
1639 // Check workspace validity and if not found, revert to default workspace.
1640 if ($this->workspaceRec = $this->checkWorkspace($workspaceId, '*')) {
1641 // Set workspace ID internally
1642 $this->workspace = (int) $workspaceId;
1643 } else {
1644 $this->workspace = (int) $this->getDefaultWorkspace();
1645 $this->workspaceRec = $this->checkWorkspace($this->workspace, '*');
1646 }
1647
1648 // Unset access cache:
1649 unset($this->checkWorkspaceCurrent_cache);
1650
1651 // If ID is different from the stored one, change it:
1652 if (strcmp($this->workspace, $this->user['workspace_id'])) {
1653 $this->user['workspace_id'] = $this->workspace;
1654 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('workspace_id' => $this->user['workspace_id']));
1655 $this->simplelog('User changed workspace to "' . $this->workspace . '"');
1656 }
1657 }
1658
1659 /**
1660 * Setting workspace preview state for user:
1661 *
1662 * @param boolean State of user preview.
1663 * @return void
1664 */
1665 function setWorkspacePreview($previewState) {
1666 $this->user['workspace_preview'] = $previewState;
1667 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('workspace_preview' => $this->user['workspace_preview']));
1668 }
1669
1670 /**
1671 * Return default workspace ID for user
1672 *
1673 * @return integer Default workspace id. If no workspace is available it will be "-99"
1674 */
1675 function getDefaultWorkspace() {
1676
1677 if ($this->checkWorkspace(0)) { // Check online
1678 return 0;
1679 } elseif ($this->checkWorkspace(-1)) { // Check offline
1680 return -1;
1681 } elseif (t3lib_extMgm::isLoaded('workspaces')) { // Traverse custom workspaces:
1682 $workspaces = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,title,adminusers,members,reviewers', 'sys_workspace', 'pid=0' . t3lib_BEfunc::deleteClause('sys_workspace'), '', 'title');
1683 foreach ($workspaces as $rec) {
1684 if ($this->checkWorkspace($rec)) {
1685 return $rec['uid'];
1686 }
1687 }
1688 }
1689 return -99;
1690 }
1691
1692
1693 /************************************
1694 *
1695 * Logging
1696 *
1697 ************************************/
1698
1699 /**
1700 * Writes an entry in the logfile/table
1701 * Documentation in "TYPO3 Core API"
1702 *
1703 * @param integer Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
1704 * @param integer Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
1705 * @param integer Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1706 * @param integer The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
1707 * @param string Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
1708 * @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
1709 * @param string Table name. Special field used by tce_main.php.
1710 * @param integer Record UID. Special field used by tce_main.php.
1711 * @param integer Record PID. Special field used by tce_main.php. OBSOLETE
1712 * @param integer The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
1713 * @param string Special field used by tce_main.php. NEWid string of newly created records.
1714 * @param integer Alternative Backend User ID (used for logging login actions where this is not yet known).
1715 * @return integer Log entry ID.
1716 */
1717 function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0) {
1718
1719 $fields_values = array(
1720 'userid' => $userId ? $userId : intval($this->user['uid']),
1721 'type' => intval($type),
1722 'action' => intval($action),
1723 'error' => intval($error),
1724 'details_nr' => intval($details_nr),
1725 'details' => $details,
1726 'log_data' => serialize($data),
1727 'tablename' => $tablename,
1728 'recuid' => intval($recuid),
1729 # 'recpid' => intval($recpid),
1730 'IP' => t3lib_div::getIndpEnv('REMOTE_ADDR'),
1731 'tstamp' => $GLOBALS['EXEC_TIME'],
1732 'event_pid' => intval($event_pid),
1733 'NEWid' => $NEWid,
1734 'workspace' => $this->workspace
1735 );
1736
1737 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_log', $fields_values);
1738 return $GLOBALS['TYPO3_DB']->sql_insert_id();
1739 }
1740
1741 /**
1742 * Simple logging function
1743 *
1744 * @param string Log message
1745 * @param string Option extension key / module name
1746 * @param integer Error level. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1747 * @return integer Log entry UID
1748 */
1749 function simplelog($message, $extKey = '', $error = 0) {
1750 return $this->writelog(
1751 4,
1752 0,
1753 $error,
1754 0,
1755 ($extKey ? '[' . $extKey . '] ' : '') . $message,
1756 array()
1757 );
1758 }
1759
1760 /**
1761 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
1762 * 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.
1763 *
1764 * @param string Email address
1765 * @param integer Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
1766 * @param integer Max allowed failures before a warning mail is sent
1767 * @return void
1768 * @access private
1769 */
1770 function checkLogFailures($email, $secondsBack = 3600, $max = 3) {
1771
1772 if ($email) {
1773
1774 // get last flag set in the log for sending
1775 $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
1776 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1777 'tstamp',
1778 'sys_log',
1779 'type=255 AND action=4 AND tstamp>' . intval($theTimeBack),
1780 '',
1781 'tstamp DESC',
1782 '1'
1783 );
1784 if ($testRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1785 $theTimeBack = $testRow['tstamp'];
1786 }
1787
1788 // Check for more than $max number of error failures with the last period.
1789 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1790 '*',
1791 'sys_log',
1792 'type=255 AND action=3 AND error!=0 AND tstamp>' . intval($theTimeBack),
1793 '',
1794 'tstamp'
1795 );
1796 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) > $max) {
1797 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
1798 $subject = 'TYPO3 Login Failure Warning (at ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . ')';
1799 $email_body = 'There have been some attempts (' . $GLOBALS['TYPO3_DB']->sql_num_rows($res) . ') to login at the TYPO3
1800 site "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '" (' . t3lib_div::getIndpEnv('HTTP_HOST') . ').
1801
1802 This is a dump of the failures:
1803
1804 ';
1805 while ($testRows = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1806 $theData = unserialize($testRows['log_data']);
1807 $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]);
1808 $email_body .= LF;
1809 }
1810 $from = t3lib_utility_Mail::getSystemFrom();
1811 /** @var $mail t3lib_mail_Message */
1812 $mail = t3lib_div::makeInstance('t3lib_mail_Message');
1813 $mail->setTo($email)
1814 ->setFrom($from)
1815 ->setSubject($subject)
1816 ->setBody($email_body);
1817 $mail->send();
1818 $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
1819 }
1820 }
1821 }
1822 }
1823
1824
1825 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php'])) {
1826 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']);
1827 }
1828
1829 ?>