Added initial support for workspaces in core.
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_userauthgroup.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2005 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 * 115: class t3lib_userAuthGroup extends t3lib_userAuth
41 *
42 * SECTION: Permission checking functions:
43 * 176: function isAdmin()
44 * 188: function isMemberOfGroup($groupId)
45 * 210: function doesUserHaveAccess($row,$perms)
46 * 227: function isInWebMount($id,$readPerms='',$exitOnError=0)
47 * 254: function modAccess($conf,$exitOnError)
48 * 290: function getPagePermsClause($perms)
49 * 329: function calcPerms($row)
50 * 367: function isRTE()
51 * 401: function check($type,$value)
52 * 418: function checkAuthMode($table,$field,$value,$authMode)
53 * 484: function checkLanguageAccess($langValue)
54 * 504: function recordEditAccessInternals($table,$idOrRow)
55 * 569: function isPSet($lCP,$table,$type='')
56 * 586: function mayMakeShortcut()
57 *
58 * SECTION: Miscellaneous functions
59 * 614: function getTSConfig($objectString,$config='')
60 * 640: function getTSConfigVal($objectString)
61 * 652: function getTSConfigProp($objectString)
62 * 664: function inList($in_list,$item)
63 * 675: function returnWebmounts()
64 * 685: function returnFilemounts()
65 *
66 * SECTION: Authentication methods
67 * 715: function fetchGroupData()
68 * 838: function fetchGroups($grList,$idList='')
69 * 910: function setCachedList($cList)
70 * 930: function addFileMount($title, $altTitle, $path, $webspace, $type)
71 * 977: function addTScomment($str)
72 *
73 * SECTION: Logging
74 * 1024: function writelog($type,$action,$error,$details_nr,$details,$data,$tablename='',$recuid='',$recpid='',$event_pid=-1,$NEWid='')
75 * 1057: function checkLogFailures($email, $secondsBack=3600, $max=3)
76 *
77 * TOTAL FUNCTIONS: 27
78 * (This index is automatically created/updated by the extension "extdeveval")
79 *
80 */
81
82 // Need this for parsing User TSconfig
83 require_once (PATH_t3lib.'class.t3lib_tsparser.php');
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105 /**
106 * Extension to class.t3lib_userauth.php; Authentication of users in TYPO3 Backend
107 *
108 * Actually this class is extended again by t3lib_beuserauth which is the actual backend user class that will be instantiated.
109 * 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.
110 *
111 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
112 * @package TYPO3
113 * @subpackage t3lib
114 */
115 class t3lib_userAuthGroup extends t3lib_userAuth {
116 var $usergroup_column = 'usergroup'; // Should be set to the usergroup-column (id-list) in the user-record
117 var $usergroup_table = 'be_groups'; // The name of the group-table
118
119 // internal
120 var $groupData = Array( // This array holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
121 'filemounts' => Array() // Filemounts are loaded here
122 );
123 var $workspace = -99; // User workspace. -99 is ERROR (none available), -1 is offline, 0 is online, >0 is custom workspaces.
124 var $workspaceRec = array(); // Custom workspace record if any
125
126 var $userGroups = Array(); // This array will hold the groups that the user is a member of
127 var $userGroupsUID = Array(); // This array holds the uid's of the groups in the listed order
128 var $groupList =''; // This is $this->userGroupsUID imploded to a comma list... Will correspond to the 'usergroup_cached_list'
129 var $dataLists=array( // Used internally to accumulate data for the user-group. DONT USE THIS EXTERNALLY! Use $this->groupData instead
130 'webmount_list'=>'',
131 'filemount_list'=>'',
132 'modList'=>'',
133 'tables_select'=>'',
134 'tables_modify'=>'',
135 'pagetypes_select'=>'',
136 'non_exclude_fields'=>'',
137 'explicit_allowdeny'=>'',
138 'allowed_languages' => '',
139 'workspace_perms' => '',
140 'custom_options' => '',
141 );
142 var $includeHierarchy=array(); // For debugging/display of order in which subgroups are included.
143 var $includeGroupArray=array(); // List of group_id's in the order they are processed.
144
145 var $OS=''; // Set to 'WIN', if windows
146 var $TSdataArray=array(); // Used to accumulate the TSconfig data of the user
147 var $userTS_text = ''; // Contains the non-parsed user TSconfig
148 var $userTS = array(); // Contains the parsed user TSconfig
149 var $userTSUpdated=0; // Set internally if the user TSconfig was parsed and needs to be cached.
150 var $userTS_dontGetCached=0; // Set this from outside if you want the user TSconfig to ALWAYS be parsed and not fetched from cache.
151
152 var $RTE_errors = array(); // RTE availability errors collected.
153 var $errorMsg = ''; // Contains last error message
154
155
156
157
158
159
160
161
162
163
164
165
166
167 /************************************
168 *
169 * Permission checking functions:
170 *
171 ************************************/
172
173 /**
174 * Returns true if user is admin
175 * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
176 *
177 * @return boolean
178 */
179 function isAdmin() {
180 return (($this->user['admin']&1) ==1);
181 }
182
183 /**
184 * Returns true if the current user is a member of group $groupId
185 * $groupId must be set. $this->groupList must contain groups
186 * Will return true also if the user is a member of a group through subgroups.
187 *
188 * @param integer Group ID to look for in $this->groupList
189 * @return boolean
190 */
191 function isMemberOfGroup($groupId) {
192 $groupId = intval($groupId);
193 if ($this->groupList && $groupId) {
194 return $this->inList($this->groupList, $groupId);
195 }
196 }
197
198 /**
199 * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
200 *
201 * Bits for permissions, see $perms variable:
202 *
203 * 1 - Show: See/Copy page and the pagecontent.
204 * 16- Edit pagecontent: Change/Add/Delete/Move pagecontent.
205 * 2- Edit page: Change/Move the page, eg. change title, startdate, hidden.
206 * 4- Delete page: Delete the page and pagecontent.
207 * 8- New pages: Create new pages under the page.
208 *
209 * @param array $row is the pagerow for which the permissions is checked
210 * @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.
211 * @return boolean True or False upon evaluation
212 */
213 function doesUserHaveAccess($row,$perms) {
214 $userPerms = $this->calcPerms($row);
215 return ($userPerms & $perms)==$perms;
216 }
217
218 /**
219 * Checks if the page id, $id, is found within the webmounts set up for the user.
220 * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
221 * 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.
222 * 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
223 * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
224 *
225 * @param integer Page ID to check
226 * @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!)
227 * @param boolean If set, then the function will exit with an error message.
228 * @return integer The page UID of a page in the rootline that matched a mount point
229 */
230 function isInWebMount($id,$readPerms='',$exitOnError=0) {
231 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['lockBeUserToDBmounts'] || $this->isAdmin()) return 1;
232 $id = intval($id);
233 if (!$readPerms) $readPerms = $this->getPagePermsClause(1);
234 if ($id>0) {
235 $wM = $this->returnWebmounts();
236 $rL = t3lib_BEfunc::BEgetRootLine($id,' AND '.$readPerms);
237 foreach($rL as $v) {
238 if ($v['uid'] && in_array($v['uid'],$wM)) {
239 return $v['uid'];
240 }
241 }
242 }
243 if ($exitOnError) {
244 t3lib_BEfunc::typo3PrintError ('Access Error','This page is not within your DB-mounts',0);
245 exit;
246 }
247 }
248
249 /**
250 * Checks access to a backend module with the $MCONF passed as first argument
251 *
252 * @param array $MCONF array of a backend module!
253 * @param boolean If set, an array will issue an error message and exit.
254 * @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
255 */
256 function modAccess($conf,$exitOnError) {
257 if (!t3lib_BEfunc::isModuleSetInTBE_MODULES($conf['name'])) {
258 if ($exitOnError) {
259 t3lib_BEfunc::typo3PrintError ('Fatal Error','This module "'.$conf['name'].'" is not enabled in TBE_MODULES',0);
260 exit;
261 }
262 return FALSE;
263 }
264
265 // Workspaces check:
266 if ($conf['workspaces']) {
267 if (($this->workspace===0 && t3lib_div::inList($conf['workspaces'],'online')) ||
268 ($this->workspace===-1 && t3lib_div::inList($conf['workspaces'],'offline')) ||
269 ($this->workspace>0 && t3lib_div::inList($conf['workspaces'],'custom'))) {
270 // ok, go on...
271 } else {
272 if ($exitOnError) {
273 t3lib_BEfunc::typo3PrintError ('Workspace Error','This module "'.$conf['name'].'" is not available under the current workspace',0);
274 exit;
275 }
276 return FALSE;
277 }
278 }
279
280 // Returns true if conf[access] is not set at all or if the user is admin
281 if (!$conf['access'] || $this->isAdmin()) return TRUE;
282
283 // If $conf['access'] is set but not with 'admin' then we return true, if the module is found in the modList
284 if (!strstr($conf['access'],'admin') && $conf['name']) {
285 $acs = $this->check('modules',$conf['name']);
286 }
287 if (!$acs && $exitOnError) {
288 t3lib_BEfunc::typo3PrintError ('Access Error','You don\'t have access to this module.',0);
289 exit;
290 } else return $acs;
291 }
292
293 /**
294 * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
295 * $perms is the 'mask' used to select. Fx. if $perms is 1 then you'll get all pages that a user can actually see!
296 * 2^0 = show (1)
297 * 2^1 = edit (2)
298 * 2^2 = delete (4)
299 * 2^3 = new (8)
300 * If the user is 'admin' " 1=1" is returned (no effect)
301 * 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)
302 * The 95% use of this function is "->getPagePermsClause(1)" which will return WHERE clauses for *selecting* pages in backend listings - in other words will this check read permissions.
303 *
304 * @param integer Permission mask to use, see function description
305 * @return string Part of where clause. Prefix " AND " to this.
306 */
307 function getPagePermsClause($perms) {
308 global $TYPO3_CONF_VARS;
309 if (is_array($this->user)) {
310 if ($this->isAdmin()) {
311 return ' 1=1';
312 }
313
314 $perms = intval($perms); // Make sure it's integer.
315 $str= ' ('.
316 '(pages.perms_everybody & '.$perms.' = '.$perms.')'. // Everybody
317 'OR(pages.perms_userid = '.$this->user['uid'].' AND pages.perms_user & '.$perms.' = '.$perms.')'; // User
318 if ($this->groupList){$str.='OR(pages.perms_groupid in ('.$this->groupList.') AND pages.perms_group & '.$perms.' = '.$perms.')';} // Group (if any is set)
319 $str.=')';
320
321 // ****************
322 // getPagePermsClause-HOOK
323 // ****************
324 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'])) {
325
326 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'] as $_funcRef) {
327 $_params = array('currentClause' => $str, 'perms' => $perms);
328 $str = t3lib_div::callUserFunction($_funcRef, $_params, $this);
329 }
330 }
331
332 return $str;
333 } else {
334 return ' 1=0';
335 }
336 }
337
338 /**
339 * Returns a combined binary representation of the current users permissions for the page-record, $row.
340 * 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
341 * If the user is admin, 31 is returned (full permissions for all five flags)
342 *
343 * @param array Input page row with all perms_* fields available.
344 * @return integer Bitwise representation of the users permissions in relation to input page row, $row
345 */
346 function calcPerms($row) {
347 global $TYPO3_CONF_VARS;
348 if ($this->isAdmin()) {return 31;} // Return 31 for admin users.
349
350 $out=0;
351 if (isset($row['perms_userid']) && isset($row['perms_user']) && isset($row['perms_groupid']) && isset($row['perms_group']) && isset($row['perms_everybody']) && isset($this->groupList)) {
352 if ($this->user['uid']==$row['perms_userid']) {
353 $out|=$row['perms_user'];
354 }
355 if ($this->isMemberOfGroup($row['perms_groupid'])) {
356 $out|=$row['perms_group'];
357 }
358 $out|=$row['perms_everybody'];
359 }
360
361 // ****************
362 // CALCPERMS hook
363 // ****************
364 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'])) {
365 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'] as $_funcRef) {
366 $_params = array(
367 'row' => $row,
368 'outputPermissions' => $out
369 );
370 $out = t3lib_div::callUserFunction($_funcRef, $_params, $this);
371 }
372 }
373
374 return $out;
375 }
376
377 /**
378 * Returns true if the RTE (Rich Text Editor) can be enabled for the user
379 * 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]
380 * The reasons for a FALSE return can be found in $this->RTE_errors
381 *
382 * @return boolean
383 */
384 function isRTE() {
385 global $CLIENT;
386
387 // Start:
388 $this->RTE_errors = array();
389 if (!$this->uc['edit_RTE'])
390 $this->RTE_errors[] = 'RTE is not enabled for user!';
391 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['RTEenabled'])
392 $this->RTE_errors[] = 'RTE is not enabled in $TYPO3_CONF_VARS["BE"]["RTEenabled"]';
393
394
395 // Acquire RTE object:
396 $RTE = &t3lib_BEfunc::RTEgetObj();
397 if (!is_object($RTE)) {
398 $this->RTE_errors = array_merge($this->RTE_errors, $RTE);
399 }
400
401 if (!count($this->RTE_errors)) {
402 return TRUE;
403 } else {
404 return FALSE;
405 }
406 }
407
408 /**
409 * Returns true if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
410 * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
411 * If user is admin true is also returned
412 * Please see the document Inside TYPO3 for examples.
413 *
414 * @param string The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules"
415 * @param string String to search for in the groupData-list
416 * @return boolean True if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
417 */
418 function check($type,$value) {
419 if (isset($this->groupData[$type])) {
420 if ($this->isAdmin() || $this->inList($this->groupData[$type],$value)) {
421 return 1;
422 }
423 }
424 }
425
426 /**
427 * Checking the authMode of a select field with authMode set
428 *
429 * @param string Table name
430 * @param string Field name (must be configured in TCA and of type "select" with authMode set!)
431 * @param string Value to evaluation (single value, must not contain any of the chars ":,|")
432 * @param string Auth mode keyword (explicitAllow, explicitDeny, individual)
433 * @return boolean True or false whether access is granted or not.
434 */
435 function checkAuthMode($table,$field,$value,$authMode) {
436 global $TCA;
437
438 // Admin users can do anything:
439 if ($this->isAdmin()) return TRUE;
440
441 // Allow all blank values:
442 if (!strcmp($value,'')) return TRUE;
443
444 // Certain characters are not allowed in the value
445 if (ereg('[:|,]',$value)) {
446 return FALSE;
447 }
448
449 // Initialize:
450 $testValue = $table.':'.$field.':'.$value;
451 $out = TRUE;
452
453 // Checking value:
454 switch((string)$authMode) {
455 case 'explicitAllow':
456 if (!$this->inList($this->groupData['explicit_allowdeny'],$testValue.':ALLOW')) {
457 $out = FALSE;
458 }
459 break;
460 case 'explicitDeny':
461 if ($this->inList($this->groupData['explicit_allowdeny'],$testValue.':DENY')) {
462 $out = FALSE;
463 }
464 break;
465 case 'individual':
466 t3lib_div::loadTCA($table);
467 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field])) {
468 $items = $TCA[$table]['columns'][$field]['config']['items'];
469 if (is_array($items)) {
470 foreach($items as $iCfg) {
471 if (!strcmp($iCfg[1],$value) && $iCfg[4]) {
472 switch((string)$iCfg[4]) {
473 case 'EXPL_ALLOW':
474 if (!$this->inList($this->groupData['explicit_allowdeny'],$testValue.':ALLOW')) {
475 $out = FALSE;
476 }
477 break;
478 case 'EXPL_DENY':
479 if ($this->inList($this->groupData['explicit_allowdeny'],$testValue.':DENY')) {
480 $out = FALSE;
481 }
482 break;
483 }
484 break;
485 }
486 }
487 }
488 }
489 break;
490 }
491
492 return $out;
493 }
494
495 /**
496 * Checking if a language value (-1, 0 and >0 for sys_language records) is allowed to be edited by the user.
497 *
498 * @param integer Language value to evaluate
499 * @return boolean Returns true if the language value is allowed, otherwise false.
500 */
501 function checkLanguageAccess($langValue) {
502 if (strcmp($this->groupData['allowed_languages'],'')) { // The users language list must be non-blank - otherwise all languages are allowed.
503 $langValue = intval($langValue);
504 if ($langValue != -1 && !$this->check('allowed_languages',$langValue)) { // Language must either be explicitly allowed OR the lang Value be "-1" (all languages)
505 return FALSE;
506 }
507 }
508 return TRUE;
509 }
510
511 /**
512 * Checking if editing of an existing record is allowed in current workspace if that is offline.
513 * Rules for editing in offline mode:
514 * - record supports versioning and is an offline version from workspace
515 * - or record (any) is in a branch where there is a page which is a version from the workspace
516 *
517 * @param string Table of record
518 * @param string PID of record to test (real record PID for both pages and other records)
519 * @param string Workspace ID from record (t3ver_wsid field value, if available)
520 * @return string String error code, telling the failure state. FALSE=All ok
521 */
522 function workspaceEditState($table,$pid,$wsid) {
523 if ($this->workspace!==0) { // Only test offline spaces:
524 if ((int)$pid===-1) { // Record is offline, so it can be edited provided that workspace matches and versioning is enabled:
525 if (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) return 'Versioning disabled for table';
526 if ((int)$wsid!==$this->workspace) return 'Workspace ID of record didn\'t match current workspace';
527 return FALSE; // OK
528 } elseif ($this->workspaceTestPID($pid, $table)) { // For "online" records, check that PID for table allows editing
529 return FALSE; // OK
530 } else { // If not offline and not in versionized branch, output error:
531 return 'Online record was not in versionized branch!';
532 }
533 } else {
534 return FALSE; // OK because workspace is 0
535 }
536 }
537
538 /**
539 * Returns true if PID value is OK for creating/editing etc records in workspace.
540 */
541 function workspaceTestPID($pid, $table) {
542 return $this->workspace===0 || t3lib_BEfunc::isPidInVersionizedBranch($pid, $table) || ($this->workspaceRec['live_edit'] && !$GLOBALS['TCA'][$table]['ctrl']['versioningWS']);
543 }
544
545 /**
546 * Checking if a user has editing access to a record from a $TCA table.
547 * 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.
548 * For instance languages settings, authMode selector boxes are evaluated (and maybe more in the future).
549 * It will check for workspace dependent access.
550 * The function takes an ID (integer) or row (array) as second argument.
551 *
552 * @param string Table name
553 * @param mixed If integer, then this is the ID of the record. If Array this just represents fields in the record.
554 * @return boolean True if OK, otherwise false
555 */
556 function recordEditAccessInternals($table,$idOrRow) {
557 global $TCA;
558
559 if (isset($TCA[$table])) {
560 t3lib_div::loadTCA($table);
561
562 // Always return true for Admin users.
563 if ($this->isAdmin()) return TRUE;
564
565 // Fetching the record if the $idOrRow variable was not an array on input:
566 if (!is_array($idOrRow)) {
567 $idOrRow = t3lib_BEfunc::getRecord($table, $idOrRow);
568 if (!is_array($idOrRow)) {
569 $this->errorMsg = 'ERROR: Record could not be fetched.';
570 return FALSE;
571 }
572 }
573
574 // Checking languages:
575 if ($TCA[$table]['ctrl']['languageField']) {
576 if (isset($idOrRow[$TCA[$table]['ctrl']['languageField']])) { // Language field must be found in input row - otherwise it does not make sense.
577 if (!$this->checkLanguageAccess($idOrRow[$TCA[$table]['ctrl']['languageField']])) {
578 $this->errorMsg = 'ERROR: Language was not allowed.';
579 return FALSE;
580 }
581 }
582 }
583
584 // Checking authMode fields:
585 if (is_array($TCA[$table]['columns'])) {
586 foreach($TCA[$table]['columns'] as $fN => $fV) {
587 if (isset($idOrRow[$fN])) { //
588 if ($fV['config']['type']=='select' && $fV['config']['authMode'] && !strcmp($fV['config']['authMode_enforce'],'strict')) {
589 if (!$this->checkAuthMode($table,$fN,$idOrRow[$fN],$fV['config']['authMode'])) {
590 $this->errorMsg = 'ERROR: authMode "'.$fV['config']['authMode'].'" failed for field "'.$fN.'" with value "'.$idOrRow[$fN].'" evaluated';
591 return FALSE;
592 }
593 }
594 }
595 }
596 }
597
598 // Checking "editlock" feature
599 if ($TCA[$table]['ctrl']['editlock'] && $idOrRow[$TCA[$table]['ctrl']['editlock']]) {
600 $this->errorMsg = 'ERROR: Record was locked for editing. Only admin users can change this state.';
601 return FALSE;
602 }
603
604 // Checking record permissions
605 // THIS is where we can include a check for "perms_" fields for other records than pages...
606
607 // Finally, return true if all is well.
608 return TRUE;
609 }
610 }
611
612 /**
613 * Will check a type of permission against the compiled permission integer, $lCP, and in relation to table, $table
614 *
615 * @param integer $lCP could typically be the "compiled permissions" integer returned by ->calcPerms
616 * @param string $table 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)
617 * @param string For $table='pages' this can be 'edit' (2), 'new' (8 or 16), 'delete' (4), 'editcontent' (16). For all other tables this is ignored. (16 is used)
618 * @return boolean
619 * @access private
620 */
621 function isPSet($lCP,$table,$type='') {
622 if ($this->isAdmin()) return true;
623 if ($table=='pages') {
624 if ($type=='edit') return $lCP & 2;
625 if ($type=='new') return ($lCP & 8) || ($lCP & 16); // Create new page OR pagecontent
626 if ($type=='delete') return $lCP & 4;
627 if ($type=='editcontent') return $lCP & 16;
628 } else {
629 return $lCP & 16;
630 }
631 }
632
633 /**
634 * Returns true if the BE_USER is allowed to *create* shortcuts in the backend modules
635 *
636 * @return boolean
637 */
638 function mayMakeShortcut() {
639 return $this->getTSConfigVal('options.shortcutFrame') && !$this->getTSConfigVal('options.mayNotCreateEditShortcuts');
640 }
641
642
643
644
645
646
647
648
649
650
651 /*************************************
652 *
653 * Miscellaneous functions
654 *
655 *************************************/
656
657 /**
658 * Returns the value/properties of a TS-object as given by $objectString, eg. 'options.dontMountAdminMounts'
659 * Nice (general!) function for returning a part of a TypoScript array!
660 *
661 * @param string Pointer to an "object" in the TypoScript array, fx. 'options.dontMountAdminMounts'
662 * @param array Optional TSconfig array: If array, then this is used and not $this->userTS. If not array, $this->userTS is used.
663 * @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.
664 * @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.
665 */
666 function getTSConfig($objectString,$config='') {
667 if (!is_array($config)) {
668 $config=$this->userTS; // Getting Root-ts if not sent
669 }
670 $TSConf=array();
671 $parts = explode('.',$objectString,2);
672 $key = $parts[0];
673 if (trim($key)) {
674 if (count($parts)>1 && trim($parts[1])) {
675 // Go on, get the next level
676 if (is_array($config[$key.'.'])) $TSConf = $this->getTSConfig($parts[1],$config[$key.'.']);
677 } else {
678 $TSConf['value']=$config[$key];
679 $TSConf['properties']=$config[$key.'.'];
680 }
681 }
682 return $TSConf;
683 }
684
685 /**
686 * Returns the "value" of the $objectString from the BE_USERS "User TSconfig" array
687 *
688 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
689 * @return string The value for that object string (object path)
690 * @see getTSConfig()
691 */
692 function getTSConfigVal($objectString) {
693 $TSConf = $this->getTSConfig($objectString);
694 return $TSConf['value'];
695 }
696
697 /**
698 * Returns the "properties" of the $objectString from the BE_USERS "User TSconfig" array
699 *
700 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
701 * @return array The properties for that object string (object path) - if any
702 * @see getTSConfig()
703 */
704 function getTSConfigProp($objectString) {
705 $TSConf = $this->getTSConfig($objectString);
706 return $TSConf['properties'];
707 }
708
709 /**
710 * Returns true if $item is in $in_list
711 *
712 * @param string Comma list with items, no spaces between items!
713 * @param string The string to find in the list of items
714 * @return string Boolean
715 */
716 function inList($in_list,$item) {
717 return strstr(','.$in_list.',', ','.$item.',');
718 }
719
720 /**
721 * Returns an array with the webmounts.
722 * If no webmounts, and empty array is returned.
723 * 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.
724 *
725 * @return array
726 */
727 function returnWebmounts() {
728 return (string)($this->groupData['webmounts'])!='' ? explode(',',$this->groupData['webmounts']) : Array();
729 }
730
731 /**
732 * Returns an array with the filemounts for the user. Each filemount is represented with an array of a "name", "path" and "type".
733 * If no filemounts an empty array is returned.
734 *
735 * @return array
736 */
737 function returnFilemounts() {
738 return $this->groupData['filemounts'];
739 }
740
741
742
743
744
745
746
747
748
749
750
751
752 /*************************************
753 *
754 * Authentication methods
755 *
756 *************************************/
757
758
759 /**
760 * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
761 * This method is called by ->backendCheckLogin() (from extending class t3lib_beuserauth) if the backend user login has verified OK.
762 * Generally this is required initialization of a backend user.
763 *
764 * @return void
765 * @access private
766 * @see t3lib_TSparser
767 */
768 function fetchGroupData() {
769 if ($this->user['uid']) {
770
771 // Get lists for the be_user record and set them as default/primary values.
772 $this->dataLists['modList'] = $this->user['userMods']; // Enabled Backend Modules
773 $this->dataLists['allowed_languages'] = $this->user['allowed_languages']; // Add Allowed Languages
774 $this->dataLists['workspace_perms'] = $this->user['workspace_perms']; // Set user value for workspace permissions.
775 $this->dataLists['webmount_list'] = $this->user['db_mountpoints']; // Database mountpoints
776 $this->dataLists['filemount_list'] = $this->user['file_mountpoints']; // File mountpoints
777
778 // Setting default User TSconfig:
779 $this->TSdataArray[]=$this->addTScomment('From $GLOBALS["TYPO3_CONF_VARS"]["BE"]["defaultUserTSconfig"]:').
780 $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
781
782 // Default TSconfig for admin-users
783 if ($this->isAdmin()) {
784 $this->TSdataArray[]=$this->addTScomment('"admin" user presets:').'
785 admPanel.enable.all = 1
786 options.shortcutFrame = 1
787 ';
788 if (t3lib_extMgm::isLoaded('sys_note')) {
789 $this->TSdataArray[]='
790 // Setting defaults for sys_note author / email...
791 TCAdefaults.sys_note.author = '.$this->user['realName'].'
792 TCAdefaults.sys_note.email = '.$this->user['email'].'
793 ';
794 }
795 }
796
797 // FILE MOUNTS:
798 // Admin users has the base fileadmin dir mounted
799 if ($this->isAdmin() && $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
800 $this->addFileMount($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '', PATH_site.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], 0, '');
801 }
802
803 // If userHomePath is set, we attempt to mount it
804 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
805 // First try and mount with [uid]_[username]
806 $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');
807 if (!$didMount) {
808 // If that failed, try and mount with only [uid]
809 $this->addFileMount($this->user['username'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'].$this->user['uid'].$GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'], 0, 'user');
810 }
811 }
812
813 // BE_GROUPS:
814 // Get the groups...
815 # $grList = t3lib_BEfunc::getSQLselectableList($this->user[$this->usergroup_column],$this->usergroup_table,$this->usergroup_table);
816 $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.
817 if ($grList) {
818 // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc. Refer to fetchGroups() function.
819 $this->fetchGroups($grList);
820 }
821
822 // Add the TSconfig for this specific user:
823 $this->TSdataArray[] = $this->addTScomment('USER TSconfig field').$this->user['TSconfig'];
824 // Check include lines.
825 $this->TSdataArray = t3lib_TSparser::checkIncludeLines_array($this->TSdataArray);
826
827 // Parsing the user TSconfig (or getting from cache)
828 $this->userTS_text = implode(chr(10).'[GLOBAL]'.chr(10),$this->TSdataArray); // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
829 $hash = md5('userTS:'.$this->userTS_text);
830 $cachedContent = t3lib_BEfunc::getHash($hash,0);
831 if (isset($cachedContent) && !$this->userTS_dontGetCached) {
832 $this->userTS = unserialize($cachedContent);
833 } else {
834 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
835 $parseObj->parse($this->userTS_text);
836 $this->userTS = $parseObj->setup;
837 t3lib_BEfunc::storeHash($hash,serialize($this->userTS),'BE_USER_TSconfig');
838 // Update UC:
839 $this->userTSUpdated=1;
840 }
841
842 // Processing webmounts
843 if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) { // Admin's always have the root mounted
844 $this->dataLists['webmount_list']='0,'.$this->dataLists['webmount_list'];
845 }
846
847 // Processing filemounts
848 $this->dataLists['filemount_list'] = t3lib_div::uniqueList($this->dataLists['filemount_list']);
849 if ($this->dataLists['filemount_list']) {
850 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_filemounts', 'deleted=0 AND hidden=0 AND pid=0 AND uid IN ('.$this->dataLists['filemount_list'].')');
851 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
852 $this->addFileMount($row['title'], $row['path'], $row['path'], $row['base']?1:0, '');
853 }
854 }
855
856 // The lists are cleaned for duplicates
857 $this->groupData['webmounts'] = t3lib_div::uniqueList($this->dataLists['webmount_list']);
858 $this->groupData['pagetypes_select'] = t3lib_div::uniqueList($this->dataLists['pagetypes_select']);
859 $this->groupData['tables_select'] = t3lib_div::uniqueList($this->dataLists['tables_modify'].','.$this->dataLists['tables_select']);
860 $this->groupData['tables_modify'] = t3lib_div::uniqueList($this->dataLists['tables_modify']);
861 $this->groupData['non_exclude_fields'] = t3lib_div::uniqueList($this->dataLists['non_exclude_fields']);
862 $this->groupData['explicit_allowdeny'] = t3lib_div::uniqueList($this->dataLists['explicit_allowdeny']);
863 $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->dataLists['allowed_languages']);
864 $this->groupData['custom_options'] = t3lib_div::uniqueList($this->dataLists['custom_options']);
865 $this->groupData['modules'] = t3lib_div::uniqueList($this->dataLists['modList']);
866
867 $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
868
869 // Setting up workspace situation (after webmounts are processed!):
870 $this->workspaceInit();
871
872 // populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
873 $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
874
875 // 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)
876 $this->groupList = implode(',',$this->userGroupsUID);
877 $this->setCachedList($this->groupList);
878 }
879 }
880
881 /**
882 * Fetches the group records, subgroups and fills internal arrays.
883 * Function is called recursively to fetch subgroups
884 *
885 * @param string Commalist of be_groups uid numbers
886 * @param string List of already processed be_groups-uids so the function will not fall into a eternal recursion.
887 * @return void
888 * @access private
889 */
890 function fetchGroups($grList,$idList='') {
891
892 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
893 $lockToDomain_SQL = ' AND (lockToDomain=\'\' OR lockToDomain=\''.t3lib_div::getIndpEnv('HTTP_HOST').'\')';
894 $whereSQL = 'deleted=0 AND hidden=0 AND pid=0 AND uid IN ('.$grList.')'.$lockToDomain_SQL;
895
896 // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
897 if (is_array ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'])) {
898 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] as $classRef) {
899 $hookObj = &t3lib_div::getUserObj($classRef);
900 if(method_exists($hookObj,'fetchGroupQuery_processQuery')){
901 $whereSQL = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, $whereSQL);
902 }
903 }
904 }
905
906 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->usergroup_table, $whereSQL);
907
908 // The userGroups array is filled
909 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
910 $this->userGroups[$row['uid']] = $row;
911 }
912
913 // Traversing records in the correct order
914 $include_staticArr = t3lib_div::intExplode(',',$grList);
915 reset($include_staticArr);
916 while(list(,$uid)=each($include_staticArr)) { // traversing list
917
918 // Get row:
919 $row=$this->userGroups[$uid];
920 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
921
922 // Include sub groups
923 if (trim($row['subgroup'])) {
924 $theList = implode(',',t3lib_div::intExplode(',',$row['subgroup'])); // Make integer list
925 $this->fetchGroups($theList, $idList.','.$uid); // Call recursively, pass along list of already processed groups so they are not recursed again.
926 }
927 // Add the group uid, current list, TSconfig to the internal arrays.
928 $this->includeGroupArray[]=$uid;
929 $this->includeHierarchy[]=$idList;
930 $this->TSdataArray[] = $this->addTScomment('Group "'.$row['title'].'" ['.$row['uid'].'] TSconfig field:').$row['TSconfig'];
931
932 // Mount group database-mounts
933 if (($this->user['options']&1) == 1) { $this->dataLists['webmount_list'].= ','.$row['db_mountpoints']; }
934
935 // Mount group file-mounts
936 if (($this->user['options']&2) == 2) { $this->dataLists['filemount_list'].= ','.$row['file_mountpoints']; }
937
938 // Mount group home-dirs
939 if (($this->user['options']&2) == 2) {
940 // If groupHomePath is set, we attempt to mount it
941 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath']) {
942 $this->addFileMount($row['title'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'].$row['uid'], 0, 'group');
943 }
944 }
945
946 // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
947 if ($row['inc_access_lists']==1) {
948 $this->dataLists['modList'].= ','.$row['groupMods'];
949 $this->dataLists['tables_select'].= ','.$row['tables_select'];
950 $this->dataLists['tables_modify'].= ','.$row['tables_modify'];
951 $this->dataLists['pagetypes_select'].= ','.$row['pagetypes_select'];
952 $this->dataLists['non_exclude_fields'].= ','.$row['non_exclude_fields'];
953 $this->dataLists['explicit_allowdeny'].= ','.$row['explicit_allowdeny'];
954 $this->dataLists['allowed_languages'].= ','.$row['allowed_languages'];
955 $this->dataLists['custom_options'].= ','.$row['custom_options'];
956 }
957
958 // Setting workspace permissions:
959 $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
960
961 // 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.
962 if (!strcmp($idList,'') && !$this->firstMainGroup) {
963 $this->firstMainGroup=$uid;
964 }
965 }
966 }
967 }
968
969 /**
970 * Updates the field be_users.usergroup_cached_list if the groupList of the user has changed/is different from the current list.
971 * 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.
972 *
973 * @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.
974 * @return void
975 * @access private
976 */
977 function setCachedList($cList) {
978 if ((string)$cList != (string)$this->user['usergroup_cached_list']) {
979 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid='.intval($this->user['uid']), array('usergroup_cached_list' => $cList));
980 }
981 }
982
983 /**
984 * Adds a filemount to the users array of filemounts, $this->groupData['filemounts'][hash_key] = Array ('name'=>$name, 'path'=>$path, 'type'=>$type);
985 * Is a part of the authentication proces of the user.
986 * 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!
987 * Paths in the mounted information will always be absolute and have a trailing slash.
988 *
989 * @param string $title will be the (root)name of the filemount in the folder tree
990 * @param string $altTitle will be the (root)name of the filemount IF $title is not true (blank or zero)
991 * @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.
992 * @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.
993 * @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.
994 * @return boolean Returns "1" if the requested filemount was mounted, otherwise no return value.
995 * @access private
996 */
997 function addFileMount($title, $altTitle, $path, $webspace, $type) {
998 // Return false if fileadminDir is not set and we try to mount a relative path
999 if ($webspace && !$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) return false;
1000
1001 // Trimming and pre-processing
1002 $path=trim($path);
1003 if ($this->OS=='WIN') { // with WINDOWS convert backslash to slash!!
1004 $path=str_replace('\\','/',$path);
1005 }
1006 // If the path is true and validates as a valid path string:
1007 if ($path && t3lib_div::validPathStr($path)) {
1008 // these lines remove all slashes and dots before and after the path
1009 $path=ereg_replace('^[\/\. ]*','',$path);
1010 $path=trim(ereg_replace('[\/\. ]*$','',$path));
1011
1012
1013 if ($path) { // there must be some chars in the path
1014 $fdir=PATH_site.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']; // fileadmin dir, absolute
1015 if ($webspace) {
1016 $path=$fdir.$path; // PATH_site + fileadmin dir is prepended
1017 } else {
1018 if ($this->OS!='WIN') { // with WINDOWS no prepending!!
1019 $path='/'.$path; // root-level is the start...
1020 }
1021 }
1022 $path.='/';
1023
1024 // We now have a path with slash after and slash before (if unix)
1025 if (@is_dir($path) &&
1026 (($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'])) || t3lib_div::isFirstPartOfStr($path,$fdir))) {
1027 // Alternative title?
1028 $name = $title ? $title : $altTitle;
1029 // 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.
1030 $this->groupData['filemounts'][md5($name.'|'.$path.'|'.$type)] = Array('name'=>$name, 'path'=>$path, 'type'=>$type);
1031 // Return true - went well, success!
1032 return 1;
1033 }
1034 }
1035 }
1036 }
1037
1038 /**
1039 * Creates a TypoScript comment with the string text inside.
1040 *
1041 * @param string The text to wrap in comment prefixes and delimiters.
1042 * @return string TypoScript comment with the string text inside.
1043 */
1044 function addTScomment($str) {
1045 $delimiter = '# ***********************************************';
1046
1047 $out = $delimiter.chr(10);
1048 $lines = t3lib_div::trimExplode(chr(10),$str);
1049 foreach($lines as $v) {
1050 $out.= '# '.$v.chr(10);
1051 }
1052 $out.= $delimiter.chr(10);
1053 return $out;
1054 }
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067 /************************************
1068 *
1069 * Workspaces
1070 *
1071 ************************************/
1072
1073 /**
1074 * Initializing workspace
1075 *
1076 * @return void
1077 */
1078 function workspaceInit() {
1079
1080 // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
1081 $this->setWorkspace($this->user['workspace_id']);
1082
1083 // Setting up the db mount points of the (custom) workspace, if any:
1084 if ($this->workspace>0 && $this->workspaceRec['db_mountpoints']!=='') {
1085
1086 // Initialize:
1087 $newMounts = array();
1088 $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.
1089
1090 // Traverse mount points of the
1091 $mountPoints = t3lib_div::intExplode(',',$this->workspaceRec['db_mountpoints']);
1092 foreach($mountPoints as $mpId) {
1093 if ($this->isInWebMount($mpId,$readPerms)) {
1094 $newMounts[] = $mpId;
1095 }
1096 }
1097
1098 // Re-insert webmounts:
1099 $this->groupData['webmounts'] = implode(',',array_unique($newMounts));
1100 }
1101
1102 // Setting up the file mount points of the (custom) workspace, if any:
1103 if ($this->workspace!==0) $this->groupData['filemounts'] = array();
1104 if ($this->workspace>0 && $this->workspaceRec['file_mountpoints']!=='') {
1105
1106 // Processing filemounts
1107 $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']).')');
1108 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1109 $this->addFileMount($row['title'], $row['path'], $row['path'], $row['base']?1:0, '');
1110 }
1111 }
1112 }
1113
1114 /**
1115 * Checking if a workspace is allowed for backend user
1116 *
1117 * @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)
1118 * @return string TRUE if access. Output will also show how access was granted. Admin users will have a true output regardless of input.
1119 */
1120 function checkWorkspace($wsRec,$fields='uid,title,adminusers,members,reviewers') {
1121
1122 // If not array, look up workspace record:
1123 if (!is_array($wsRec)) {
1124 switch((string)$wsRec) {
1125 case '0':
1126 case '-1':
1127 $wsRec = array('uid' => $wsRec);
1128 break;
1129 default:
1130 list($wsRec) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
1131 $fields,
1132 'sys_workspace',
1133 'pid=0 AND uid='.intval($wsRec).
1134 t3lib_BEfunc::deleteClause('sys_workspace'),
1135 '',
1136 'title'
1137 );
1138 break;
1139 }
1140 }
1141
1142 // If wsRec is set to an array, evaluate it:
1143 if (is_array($wsRec)) {
1144 if ($this->isAdmin()) {
1145 return array_merge($wsRec,array('_ACCESS' => 'admin'));
1146 } else {
1147
1148 switch((string)$wsRec['uid']) {
1149 case '0':
1150 return ($this->groupData['workspace_perms']&1) ? array_merge($wsRec,array('_ACCESS' => 'online')) : FALSE;
1151 break;
1152 case '-1':
1153 return ($this->groupData['workspace_perms']&2) ? array_merge($wsRec,array('_ACCESS' => 'offline')) : FALSE;
1154 break;
1155 default:
1156 // Checking if the guy is admin:
1157 if (t3lib_div::inList($wsRec['adminusers'],$this->user['uid'])) {
1158 return array_merge($wsRec, array('_ACCESS' => 'adminuser'));
1159 }
1160 // Checking if he is reviewer user:
1161 if (t3lib_div::inList($wsRec['reviewers'],'be_users_'.$this->user['uid'])) {
1162 return array_merge($wsRec, array('_ACCESS' => 'revieweruser'));
1163 }
1164 // Checking if he is reviewer through a user group of his:
1165 foreach($this->userGroupsUID as $groupUid) {
1166 if (t3lib_div::inList($wsRec['reviewers'],'be_groups_'.$groupUid)) {
1167 return array_merge($wsRec, array('_ACCESS' => 'reviewergroup:'.$groupUid));
1168 }
1169 }
1170 // Checking if he is member as user:
1171 if (t3lib_div::inList($wsRec['members'],'be_users_'.$this->user['uid'])) {
1172 return array_merge($wsRec, array('_ACCESS' => 'memberuser'));
1173 }
1174 // Checking if he is member through a user group of his:
1175 foreach($this->userGroupsUID as $groupUid) {
1176 if (t3lib_div::inList($wsRec['members'],'be_groups_'.$groupUid)) {
1177 return array_merge($wsRec, array('_ACCESS' => 'membergroup:'.$groupUid));
1178 }
1179 }
1180 break;
1181 }
1182 }
1183 }
1184
1185 return FALSE;
1186 }
1187
1188 /**
1189 * Setting workspace ID
1190 *
1191 * @param integer ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
1192 * @return void
1193 */
1194 function setWorkspace($workspaceId) {
1195
1196 // Check workspace validity and if not found, revert to default workspace.
1197 if ($this->workspaceRec = $this->checkWorkspace($workspaceId,'*')) {
1198 // Set workspace ID internally
1199 $this->workspace = (int)$workspaceId;
1200 } else {
1201 $this->workspace = (int)$this->getDefaultWorkspace();
1202 $this->workspaceRec = $this->checkWorkspace($this->workspace,'*');
1203 }
1204
1205 // If ID is different from the stored one, change it:
1206 if (strcmp($this->workspace, $this->user['workspace_id'])) {
1207 $this->user['workspace_id'] = $this->workspace;
1208 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users','uid='.intval($this->user['uid']),array('workspace_id' => $this->user['workspace_id']));
1209 }
1210 }
1211
1212 /**
1213 * Setting workspace preview state for user:
1214 *
1215 * @param boolean State
1216 * @return void
1217 */
1218 function setWorkspacePreview($previewState) {
1219 $this->user['workspace_preview'] = $previewState;
1220 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users','uid='.intval($this->user['uid']),array('workspace_preview' => $this->user['workspace_preview']));
1221 }
1222
1223 /**
1224 * Return default workspace ID for user
1225 *
1226 * @return integer Default workspace id. If no workspace is available it will be "-99"
1227 */
1228 function getDefaultWorkspace() {
1229
1230 if ($this->checkWorkspace(0)) { // Check online
1231 return 0;
1232 } elseif ($this->checkWorkspace(-1)) { // Check offline
1233 return -1;
1234 } else { // Traverse custom workspaces:
1235 $workspaces = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,title,adminusers,members,reviewers','sys_workspace','pid=0'.t3lib_BEfunc::deleteClause('sys_workspace'),'','title');
1236 foreach($workspaces as $rec) {
1237 if ($this->checkWorkspace($rec)) {
1238 return $rec['uid'];
1239 }
1240 }
1241 }
1242 return -99;
1243 }
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255 /************************************
1256 *
1257 * Logging
1258 *
1259 ************************************/
1260
1261 /**
1262 * Writes an entry in the logfile
1263 * ... Still missing documentation for syntax etc...
1264 *
1265 * @param integer $type: denotes which module that has submitted the entry. This is the current list: 1=tce_db; 2=tce_file; 3=system (eg. sys_history save); 4=modules; 254=Personal settings changed; 255=login / out action: 1=login, 2=logout, 3=failed login (+ errorcode 3), 4=failure_warning_email sent
1266 * @param integer $action: denotes which specific operation that wrote the entry (eg. 'delete', 'upload', 'update' and so on...). Specific for each $type. Also used to trigger update of the interface. (see the log-module for the meaning of each number !!)
1267 * @param integer $error: flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1268 * @param integer $details_nr: The message number. Specific for each $type and $action. in the future this will make it possible to translate errormessages to other languages
1269 * @param string $details: Default text that follows the message
1270 * @param array $data: Data that follows the log. Might be used to carry special information. If an array the first 5 entries (0-4) will be sprintf'ed the details-text...
1271 * @param string $tablename: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1272 * @param integer $recuid: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1273 * @param integer $recpid: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1274 * @param integer $event_pid: The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
1275 * @param string $NEWid: NEWid string
1276 * @return void
1277 */
1278 function writelog($type,$action,$error,$details_nr,$details,$data,$tablename='',$recuid='',$recpid='',$event_pid=-1,$NEWid='') {
1279
1280 $fields_values = Array (
1281 'userid' => intval($this->user['uid']),
1282 'type' => intval($type),
1283 'action' => intval($action),
1284 'error' => intval($error),
1285 'details_nr' => intval($details_nr),
1286 'details' => $details,
1287 'log_data' => serialize($data),
1288 'tablename' => $tablename,
1289 'recuid' => intval($recuid),
1290 'recpid' => intval($recpid),
1291 'IP' => t3lib_div::getIndpEnv('REMOTE_ADDR'),
1292 'tstamp' => $GLOBALS['EXEC_TIME'],
1293 'event_pid' => intval($event_pid),
1294 'NEWid' => $NEWid
1295 );
1296
1297 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_log', $fields_values);
1298 return $GLOBALS['TYPO3_DB']->sql_insert_id();
1299 }
1300
1301 /**
1302 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
1303 * 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.
1304 *
1305 * @param string Email address
1306 * @param integer Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
1307 * @param integer Max allowed failures before a warning mail is sent
1308 * @return void
1309 * @access private
1310 */
1311 function checkLogFailures($email, $secondsBack=3600, $max=3) {
1312
1313 if ($email) {
1314
1315 // get last flag set in the log for sending
1316 $theTimeBack = time()-$secondsBack;
1317 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1318 'tstamp',
1319 'sys_log',
1320 'type=255 AND action=4 AND tstamp>'.intval($theTimeBack),
1321 '',
1322 'tstamp DESC',
1323 '1'
1324 );
1325 if ($testRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1326 $theTimeBack = $testRow['tstamp'];
1327 }
1328
1329 // Check for more than $max number of error failures with the last period.
1330 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1331 '*',
1332 'sys_log',
1333 'type=255 AND action=3 AND error!=0 AND tstamp>'.intval($theTimeBack),
1334 '',
1335 'tstamp'
1336 );
1337 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) > $max) {
1338 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
1339 $subject = 'TYPO3 Login Failure Warning (at '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'].')';
1340 $email_body = '
1341 There has been numerous attempts ('.$GLOBALS['TYPO3_DB']->sql_num_rows($res).') to login at the TYPO3
1342 site "'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'].'" ('.t3lib_div::getIndpEnv('HTTP_HOST').').
1343
1344 This is a dump of the failures:
1345
1346 ';
1347 while($testRows = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1348 $theData = unserialize($testRows['log_data']);
1349 $email_body.=date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' H:i',$testRows['tstamp']).': '.@sprintf($testRows['details'],''.$theData[0],''.$theData[1],''.$theData[2]);
1350 $email_body.=chr(10);
1351 }
1352 mail( $email,
1353 $subject,
1354 $email_body,
1355 'From: TYPO3 Login WARNING<>'
1356 );
1357 $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
1358 }
1359 }
1360 }
1361 }
1362
1363
1364
1365 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']) {
1366 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']);
1367 }
1368 ?>