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