Tons of changes made to the CORE. All scripts has more a less been modified. Primaril...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_userauthgroup.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2003 Kasper Skaarhoj (kasper@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 <kasper@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 112: class t3lib_userAuthGroup extends t3lib_userAuth
41 *
42 * SECTION: Permission checking functions:
43 * 170: function isAdmin()
44 * 182: function isMemberOfGroup($groupId)
45 * 204: function doesUserHaveAccess($row,$perms)
46 * 221: function isInWebMount($id,$readPerms='',$exitOnError=0)
47 * 248: function modAccess($conf,$exitOnError)
48 * 284: function getPagePermsClause($perms)
49 * 310: function calcPerms($row)
50 * 332: function isRTE()
51 * 358: function check ($type,$value)
52 * 375: function isPSet($lCP,$table,$type='')
53 * 392: function mayMakeShortcut()
54 *
55 * SECTION: Miscellaneous functions
56 * 420: function getTSConfig($objectString,$config='')
57 * 446: function getTSConfigVal($objectString)
58 * 458: function getTSConfigProp($objectString)
59 * 470: function inList($in_list,$item)
60 * 480: function returnWebmounts()
61 * 490: function returnFilemounts()
62 *
63 * SECTION: Authentication methods
64 * 520: function fetchGroupData()
65 * 645: function fetchGroups($grList,$idList='')
66 * 719: function setCachedList($cList)
67 * 740: function addFileMount($title, $altTitle, $path, $webspace, $type)
68 * 787: function addTScomment($str)
69 *
70 * SECTION: Logging
71 * 834: function writelog($type,$action,$error,$details_nr,$details,$data,$tablename='',$recuid='',$recpid='',$event_pid=-1,$NEWid='')
72 * 871: function checkLogFailures($email, $secondsBack=3600, $max=3)
73 *
74 * TOTAL FUNCTIONS: 24
75 * (This index is automatically created/updated by the extension "extdeveval")
76 *
77 */
78
79 // Need this for parsing User TSconfig
80 require_once (PATH_t3lib.'class.t3lib_tsparser.php');
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 /**
103 * Extension to class.t3lib_userauth.php; Authentication of users in TYPO3 Backend
104 *
105 * Actually this class is extended again by t3lib_beuserauth which is the actual backend user class that will be instantiated.
106 * 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.
107 *
108 * @author Kasper Skaarhoj <kasper@typo3.com>
109 * @package TYPO3
110 * @subpackage t3lib
111 */
112 class t3lib_userAuthGroup extends t3lib_userAuth {
113 var $usergroup_column = 'usergroup'; // Should be set to the usergroup-column (id-list) in the user-record
114 var $usergroup_table = 'be_groups'; // The name of the group-table
115
116 // internal
117 var $groupData = Array( // This array holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
118 'filemounts' => Array() // Filemounts are loaded here
119 );
120
121 var $userGroups = Array(); // This array will hold the groups that the user is a member of
122 var $userGroupsUID = Array(); // This array holds the uid's of the groups in the listed order
123 var $groupList =''; // This is $this->userGroupsUID imploded to a comma list... Will correspond to the 'usergroup_cached_list'
124 var $dataLists=array( // Used internally to accumulate data for the user-group. DONT USE THIS EXTERNALLY! Use $this->groupData instead
125 'webmount_list'=>'',
126 'filemount_list'=>'',
127 'modList'=>'',
128 'tables_select'=>'',
129 'tables_modify'=>'',
130 'pagetypes_select'=>'',
131 'non_exclude_fields'=>''
132 );
133 var $includeHierarchy=array(); // For debugging/display of order in which subgroups are included.
134 var $includeGroupArray=array(); // List of group_id's in the order they are processed.
135
136 var $OS=''; // Set to 'WIN', if windows
137 var $TSdataArray=array(); // Used to accumulate the TSconfig data of the user
138 var $userTS_text = ''; // Contains the non-parsed user TSconfig
139 var $userTS = array(); // Contains the parsed user TSconfig
140 var $userTSUpdated=0; // Set internally if the user TSconfig was parsed and needs to be cached.
141 var $userTS_dontGetCached=0; // Set this from outside if you want the user TSconfig to ALWAYS be parsed and not fetched from cache.
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158 /************************************
159 *
160 * Permission checking functions:
161 *
162 ************************************/
163
164 /**
165 * Returns true if user is admin
166 * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
167 *
168 * @return boolean
169 */
170 function isAdmin() {
171 return (($this->user['admin']&1) ==1);
172 }
173
174 /**
175 * Returns true if the current user is a member of group $groupId
176 * $groupId must be set. $this->groupList must contain groups
177 * Will return true also if the user is a member of a group through subgroups.
178 *
179 * @param integer Group ID to look for in $this->groupList
180 * @return boolean
181 */
182 function isMemberOfGroup($groupId) {
183 $groupId = intval($groupId);
184 if ($this->groupList && $groupId) {
185 return $this->inList($this->groupList, $groupId);
186 }
187 }
188
189 /**
190 * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
191 *
192 * Bits for permissions, see $perms variable:
193 *
194 * 1 - Show: See/Copy page and the pagecontent.
195 * 16- Edit pagecontent: Change/Add/Delete/Move pagecontent.
196 * 2- Edit page: Change/Move the page, eg. change title, startdate, hidden.
197 * 4- Delete page: Delete the page and pagecontent.
198 * 8- New pages: Create new pages under the page.
199 *
200 * @param array $row is the pagerow for which the permissions is checked
201 * @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.
202 * @return boolean True or False upon evaluation
203 */
204 function doesUserHaveAccess($row,$perms) {
205 $userPerms = $this->calcPerms($row);
206 return ($userPerms & $perms)==$perms;
207 }
208
209 /**
210 * Checks if the page id, $id, is found within the webmounts set up for the user.
211 * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
212 * 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.
213 * 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
214 * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
215 *
216 * @param integer Page ID to check
217 * @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!)
218 * @param boolean If set, then the function will exit with an error message.
219 * @return integer The page UID of a page in the rootline that matched a mount point
220 */
221 function isInWebMount($id,$readPerms='',$exitOnError=0) {
222 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['lockBeUserToDBmounts'] || $this->isAdmin()) return 1;
223 $id = intval($id);
224 if (!$readPerms) $readPerms = $this->getPagePermsClause(1);
225 if ($id>0) {
226 $wM=$this->returnWebmounts();
227 $rL=t3lib_BEfunc::BEgetRootLine($id,' AND '.$readPerms);
228 reset($rL);
229 while(list(,$v)=each($rL)) {
230 if ($v['uid'] && in_array($v['uid'],$wM)) {
231 return $v['uid'];
232 }
233 }
234 }
235 if ($exitOnError) {
236 t3lib_BEfunc::typo3PrintError ('Access Error','This page is not within your DB-mounts',0);
237 exit;
238 }
239 }
240
241 /**
242 * Checks access to a backend module with the $MCONF passed as first argument
243 *
244 * @param array $MCONF array of a backend module!
245 * @param boolean If set, an array will issue an error message and exit.
246 * @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
247 */
248 function modAccess($conf,$exitOnError) {
249 if (!t3lib_BEfunc::isModuleSetInTBE_MODULES($conf['name'])) {
250 if ($exitOnError) {
251 t3lib_BEfunc::typo3PrintError ('Fatal Error','This module "'.$conf['name'].'" is not enabled in TBE_MODULES',0);
252 exit;
253 }
254 return false;
255 }
256
257 // Returns true if conf[access] is not set at all or if the user is admin
258 if (!$conf['access'] || $this->isAdmin()) return true;
259
260 // If $conf['access'] is set but not with 'admin' then we return true, if the module is found in the modList
261 if (!strstr($conf['access'],'admin') && $conf['name']) {
262 $acs = $this->check('modules',$conf['name']);
263 }
264 if (!$acs && $exitOnError) {
265 t3lib_BEfunc::typo3PrintError ('Access Error','You don\'t have access to this module.',0);
266 exit;
267 } else return $acs;
268 }
269
270 /**
271 * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
272 * $perms is the 'mask' used to select. Fx. if $perms is 1 then you'll get all pages that a user can actually see!
273 * 2^0 = show (1)
274 * 2^1 = edit (2)
275 * 2^2 = delete (4)
276 * 2^3 = new (8)
277 * If the user is 'admin' " 1=1" is returned (no effect)
278 * 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)
279 * 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.
280 *
281 * @param integer Permission mask to use, see function description
282 * @return string Part of where clause. Prefix " AND " to this.
283 */
284 function getPagePermsClause($perms) {
285 if (is_array($this->user)) {
286 if ($this->isAdmin()) {
287 return ' 1=1';
288 }
289
290 $perms = intval($perms); // Make sure it's integer.
291 $str= ' ('.
292 '(pages.perms_everybody & '.$perms.' = '.$perms.')'. // Everybody
293 'OR(pages.perms_userid = '.$this->user['uid'].' AND pages.perms_user & '.$perms.' = '.$perms.')'; // User
294 if ($this->groupList){$str.='OR(pages.perms_groupid in ('.$this->groupList.') AND pages.perms_group & '.$perms.' = '.$perms.')';} // Group (if any is set)
295 $str.=')';
296 return $str;
297 } else {
298 return ' 1=0';
299 }
300 }
301
302 /**
303 * Returns a combined binary representation of the current users permissions for the page-record, $row.
304 * 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
305 * If the user is admin, 31 is returned (full permissions for all five flags)
306 *
307 * @param array Input page row with all perms_* fields available.
308 * @return integer Bitwise representation of the users permissions in relation to input page row, $row
309 */
310 function calcPerms($row) {
311 if ($this->isAdmin()) {return 31;} // Return 31 for admin users.
312
313 $out=0;
314 if (isset($row['perms_userid']) && isset($row['perms_user']) && isset($row['perms_groupid']) && isset($row['perms_group']) && isset($row['perms_everybody']) && isset($this->groupList)) {
315 if ($this->user['uid']==$row['perms_userid']) {
316 $out|=$row['perms_user'];
317 }
318 if ($this->isMemberOfGroup($row['perms_groupid'])) {
319 $out|=$row['perms_group'];
320 }
321 $out|=$row['perms_everybody'];
322 }
323 return $out;
324 }
325
326 /**
327 * Returns true if the RTE (Rich Text Editor) can be enabled for the user
328 * 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]
329 *
330 * @return boolean
331 */
332 function isRTE() {
333 global $CLIENT;
334 if (
335 t3lib_extMgm::isLoaded('rte') &&
336 $CLIENT['BROWSER']=='msie' &&
337 $CLIENT['SYSTEM']=='win' &&
338 $CLIENT['VERSION']>=5 &&
339 $this->uc['edit_RTE'] &&
340 $GLOBALS['TYPO3_CONF_VARS']['BE']['RTEenabled']
341 ) {
342 return 1;
343 } else {
344 return 0;
345 }
346 }
347
348 /**
349 * Returns true if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
350 * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
351 * If user is admin true is also returned
352 * Please see the document Inside TYPO3 for examples.
353 *
354 * @param string The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules"
355 * @param string String to search for in the groupData-list
356 * @return boolean True if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
357 */
358 function check ($type,$value) {
359 if (isset($this->groupData[$type])) {
360 if ($this->isAdmin() || $this->inList($this->groupData[$type],$value)) {
361 return 1;
362 }
363 }
364 }
365
366 /**
367 * Will check a type of permission against the compiled permission integer, $lCP, and in relation to table, $table
368 *
369 * @param integer $lCP could typically be the "compiled permissions" integer returned by ->calcPerms
370 * @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)
371 * @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)
372 * @return boolean
373 * @access private
374 */
375 function isPSet($lCP,$table,$type='') {
376 if ($this->isAdmin()) return true;
377 if ($table=='pages') {
378 if ($type=='edit') return $lCP & 2;
379 if ($type=='new') return ($lCP & 8) || ($lCP & 16); // Create new page OR pagecontent
380 if ($type=='delete') return $lCP & 4;
381 if ($type=='editcontent') return $lCP & 16;
382 } else {
383 return $lCP & 16;
384 }
385 }
386
387 /**
388 * Returns true if the BE_USER is allowed to *create* shortcuts in the backend modules
389 *
390 * @return boolean
391 */
392 function mayMakeShortcut() {
393 return $this->getTSConfigVal('options.shortcutFrame') && !$this->getTSConfigVal('options.mayNotCreateEditShortcuts');
394 }
395
396
397
398
399
400
401
402
403
404
405 /*************************************
406 *
407 * Miscellaneous functions
408 *
409 *************************************/
410
411 /**
412 * Returns the value/properties of a TS-object as given by $objectString, eg. 'options.dontMountAdminMounts'
413 * Nice (general!) function for returning a part of a TypoScript array!
414 *
415 * @param string Pointer to an "object" in the TypoScript array, fx. 'options.dontMountAdminMounts'
416 * @param array Optional TSconfig array: If array, then this is used and not $this->userTS. If not array, $this->userTS is used.
417 * @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.
418 * @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.
419 */
420 function getTSConfig($objectString,$config='') {
421 if (!is_array($config)) {
422 $config=$this->userTS; // Getting Root-ts if not sent
423 }
424 $TSConf=array();
425 $parts = explode('.',$objectString,2);
426 $key = $parts[0];
427 if (trim($key)) {
428 if (count($parts)>1 && trim($parts[1])) {
429 // Go on, get the next level
430 if (is_array($config[$key.'.'])) $TSConf = $this->getTSConfig($parts[1],$config[$key.'.']);
431 } else {
432 $TSConf['value']=$config[$key];
433 $TSConf['properties']=$config[$key.'.'];
434 }
435 }
436 return $TSConf;
437 }
438
439 /**
440 * Returns the "value" of the $objectString from the BE_USERS "User TSconfig" array
441 *
442 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
443 * @return string The value for that object string (object path)
444 * @see getTSConfig()
445 */
446 function getTSConfigVal($objectString) {
447 $TSConf = $this->getTSConfig($objectString);
448 return $TSConf['value'];
449 }
450
451 /**
452 * Returns the "properties" of the $objectString from the BE_USERS "User TSconfig" array
453 *
454 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
455 * @return array The properties for that object string (object path) - if any
456 * @see getTSConfig()
457 */
458 function getTSConfigProp($objectString) {
459 $TSConf = $this->getTSConfig($objectString);
460 return $TSConf['properties'];
461 }
462
463 /**
464 * Returns true if $item is in $in_list
465 *
466 * @param string Comma list with items, no spaces between items!
467 * @param string The string to find in the list of items
468 * @return string Boolean
469 */
470 function inList($in_list,$item) {
471 return strstr(','.$in_list.',', ','.$item.',');
472 }
473
474 /**
475 * Returns an array with the webmounts.
476 * If no webmounts, and empty array is returned.
477 *
478 * @return array
479 */
480 function returnWebmounts() {
481 return (string)($this->groupData['webmounts'])!='' ? explode(',',$this->groupData['webmounts']) : Array();
482 }
483
484 /**
485 * Returns an array with the filemounts for the user. Each filemount is represented with an array of a "name", "path" and "type".
486 * If no filemounts an empty array is returned.
487 *
488 * @return array
489 */
490 function returnFilemounts() {
491 return $this->groupData['filemounts'];
492 }
493
494
495
496
497
498
499
500
501
502
503
504
505 /*************************************
506 *
507 * Authentication methods
508 *
509 *************************************/
510
511
512 /**
513 * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
514 * This method is called by ->backendCheckLogin() (from extending class t3lib_beuserauth) if the backend user login has verified OK.
515 *
516 * @return void
517 * @access private
518 * @see t3lib_TSparser
519 */
520 function fetchGroupData() {
521 if ($this->user['uid']) {
522
523 // Get lists for the be_user record and set them as default/primary values.
524 $this->dataLists['modList'] = $this->user['userMods']; // Enabled Backend Modules
525 $this->dataLists['webmount_list'] = $this->user['db_mountpoints']; // Database mountpoints
526 $this->dataLists['filemount_list'] = $this->user['file_mountpoints']; // File mountpoints
527
528 // Setting default User TSconfig:
529 $this->TSdataArray[]=$this->addTScomment('From $GLOBALS["TYPO3_CONF_VARS"]["BE"]["defaultUserTSconfig"]:').
530 $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
531
532 // Default TSconfig for admin-users
533 if ($this->isAdmin()) {
534 $this->TSdataArray[]=$this->addTScomment('"admin" user presets:').'
535 admPanel.enable.all = 1
536 setup.default.deleteCmdInClipboard = 1
537 options.shortcutFrame=1
538 ';
539 if (t3lib_extMgm::isLoaded('tt_news')) {
540 $this->TSdataArray[]='
541 // Setting defaults for tt_news author / email...
542 TCAdefaults.tt_news.author = '.$this->user['realName'].'
543 TCAdefaults.tt_news.author_email = '.$this->user['email'].'
544 ';
545 }
546 if (t3lib_extMgm::isLoaded('sys_note')) {
547 $this->TSdataArray[]='
548 // Setting defaults for sys_note author / email...
549 TCAdefaults.sys_note.author = '.$this->user['realName'].'
550 TCAdefaults.sys_note.email = '.$this->user['email'].'
551 ';
552 }
553 }
554
555 // FILE MOUNTS:
556 // Admin users has the base fileadmin dir mounted
557 if ($this->isAdmin() && $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
558 $this->addFileMount($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '', PATH_site.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], 0, '');
559 }
560
561 // If userHomePath is set, we attempt to mount it
562 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
563 // First try and mount with [uid]_[username]
564 $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');
565 if (!$didMount) {
566 // If that failed, try and mount with only [uid]
567 $this->addFileMount($this->user['username'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'].$this->user['uid'].$GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'], 0, 'user');
568 }
569 }
570
571 // BE_GROUPS:
572 // Get the groups...
573 # $grList = t3lib_BEfunc::getSQLselectableList($this->user[$this->usergroup_column],$this->usergroup_table,$this->usergroup_table);
574 $grList = implode(',',t3lib_div::intExplode(',',$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.
575 if ($grList) {
576 // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc. Refer to fetchGroups() function.
577 $this->fetchGroups($grList);
578 }
579
580 // Add the TSconfig for this specific user:
581 $this->TSdataArray[] = $this->addTScomment('USER TSconfig field').$this->user['TSconfig'];
582 // Check include lines.
583 $this->TSdataArray = t3lib_TSparser::checkIncludeLines_array($this->TSdataArray);
584
585 // Parsing the user TSconfig (or getting from cache)
586 $this->userTS_text = implode($this->TSdataArray,chr(10).'[GLOBAL]'.chr(10)); // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
587 $hash = md5('userTS:'.$this->userTS_text);
588 $cachedContent = t3lib_BEfunc::getHash($hash,0);
589 if (isset($cachedContent) && !$this->userTS_dontGetCached) {
590 $this->userTS = unserialize($cachedContent);
591 } else {
592 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
593 $parseObj->parse($this->userTS_text);
594 $this->userTS = $parseObj->setup;
595 t3lib_BEfunc::storeHash($hash,serialize($this->userTS),'BE_USER_TSconfig');
596 // Update UC:
597 $this->userTSUpdated=1;
598 }
599
600 // Processing webmounts
601 if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) { // Admin's always have the root mounted
602 $this->dataLists['webmount_list']='0,'.$this->dataLists['webmount_list'];
603 }
604
605 // Processing filemounts
606 $this->dataLists['filemount_list']=t3lib_div::uniqueList($this->dataLists['filemount_list']);
607 if ($this->dataLists['filemount_list']) {
608 $res = mysql(TYPO3_db,'SELECT * FROM sys_filemounts
609 WHERE NOT deleted
610 AND NOT hidden
611 AND pid=0
612 AND uid IN ('.$this->dataLists['filemount_list'].')'
613 );
614 while ($row=mysql_fetch_assoc($res)) {
615 $this->addFileMount($row['title'], $row['path'], $row['path'], $row['base']?1:0, '');
616 }
617 }
618
619 // The lists are cleaned for duplicates
620 $this->groupData['webmounts'] = t3lib_div::uniqueList($this->dataLists['webmount_list']);
621 $this->groupData['pagetypes_select'] = t3lib_div::uniqueList($this->dataLists['pagetypes_select']);
622 $this->groupData['tables_select'] = t3lib_div::uniqueList($this->dataLists['tables_modify'].','.$this->dataLists['tables_select']);
623 $this->groupData['tables_modify'] = t3lib_div::uniqueList($this->dataLists['tables_modify']);
624 $this->groupData['non_exclude_fields'] = t3lib_div::uniqueList($this->dataLists['non_exclude_fields']);
625 $this->groupData['modules'] = t3lib_div::uniqueList($this->dataLists['modList']);
626
627 // populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
628 $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
629
630 // 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)
631 $this->groupList = implode(',',$this->userGroupsUID);
632 $this->setCachedList($this->groupList);
633 }
634 }
635
636 /**
637 * Fetches the group records, subgroups and fills internal arrays.
638 * Function is called recursively to fetch subgroups
639 *
640 * @param string Commalist of be_groups uid numbers
641 * @param string List of already processed be_groups-uids so the function will not fall into a eternal recursion.
642 * @return void
643 * @access private
644 */
645 function fetchGroups($grList,$idList='') {
646
647 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
648 $lockToDomain_SQL = ' AND (lockToDomain="" OR lockToDomain="'.t3lib_div::getIndpEnv('HTTP_HOST').'")';
649 $res = mysql(TYPO3_db,'SELECT * FROM '.$this->usergroup_table.'
650 WHERE NOT deleted
651 AND NOT hidden
652 AND pid=0
653 AND uid IN ('.$grList.')'.
654 $lockToDomain_SQL);
655
656 // The userGroups array is filled
657 while ($row=mysql_fetch_assoc($res)) {
658 $this->userGroups[$row['uid']]=$row;
659 }
660
661 // Traversing records in the correct order
662 $include_staticArr = t3lib_div::intExplode(',',$grList);
663 reset($include_staticArr);
664 while(list(,$uid)=each($include_staticArr)) { // traversing list
665
666 // Get row:
667 $row=$this->userGroups[$uid];
668 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
669
670 // Include sub groups
671 if (trim($row['subgroup'])) {
672 $theList = implode(t3lib_div::intExplode(',',$row['subgroup']),','); // Make integer list
673 $this->fetchGroups($theList, $idList.','.$uid); // Call recursively, pass along list of already processed groups so they are not recursed again.
674 }
675 // Add the group uid, current list, TSconfig to the internal arrays.
676 $this->includeGroupArray[]=$uid;
677 $this->includeHierarchy[]=$idList;
678 $this->TSdataArray[] = $this->addTScomment('Group "'.$row['title'].'" ['.$row['uid'].'] TSconfig field:').$row['TSconfig'];
679
680 // Mount group database-mounts
681 if (($this->user['options']&1) == 1) { $this->dataLists['webmount_list'].= ','.$row['db_mountpoints']; }
682
683 // Mount group file-mounts
684 if (($this->user['options']&2) == 2) { $this->dataLists['filemount_list'].= ','.$row['file_mountpoints']; }
685
686 // Mount group home-dirs
687 if (($this->user['options']&2) == 2) {
688 // If groupHomePath is set, we attempt to mount it
689 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath']) {
690 $this->addFileMount($row['title'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'].$row['uid'], 0, 'group');
691 }
692 }
693
694 // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields
695 if ($row['inc_access_lists']==1) {
696 $this->dataLists['modList'].= ','.$row['groupMods'];
697 $this->dataLists['tables_select'].= ','.$row['tables_select'];
698 $this->dataLists['tables_modify'].= ','.$row['tables_modify'];
699 $this->dataLists['pagetypes_select'].= ','.$row['pagetypes_select'];
700 $this->dataLists['non_exclude_fields'].= ','.$row['non_exclude_fields'];
701 }
702 // 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.
703 if (!strcmp($idList,'') && !$this->firstMainGroup) {
704 $this->firstMainGroup=$uid;
705 }
706 }
707 }
708
709 }
710
711 /**
712 * Updates the field be_users.usergroup_cached_list if the groupList of the user has changed/is different from the current list.
713 * 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.
714 *
715 * @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.
716 * @return void
717 * @access private
718 */
719 function setCachedList($cList) {
720 if ((string)$cList != (string)$this->user['usergroup_cached_list']) {
721 $query='UPDATE be_users SET usergroup_cached_list="'.addslashes($cList).'" WHERE uid='.intval($this->user['uid']);
722 $res = mysql(TYPO3_db,$query);
723 }
724 }
725
726 /**
727 * Adds a filemount to the users array of filemounts, $this->groupData['filemounts'][hash_key] = Array ('name'=>$name, 'path'=>$path, 'type'=>$type);
728 * Is a part of the authentication proces of the user.
729 * 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!
730 * Paths in the mounted information will always be absolute and have a trailing slash.
731 *
732 * @param string $title will be the (root)name of the filemount in the folder tree
733 * @param string $altTitle will be the (root)name of the filemount IF $title is not true (blank or zero)
734 * @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.
735 * @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.
736 * @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.
737 * @return boolean Returns "1" if the requested filemount was mounted, otherwise no return value.
738 * @access private
739 */
740 function addFileMount($title, $altTitle, $path, $webspace, $type) {
741 // Return false if fileadminDir is not set and we try to mount a relative path
742 if ($webspace && !$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) return false;
743
744 // Trimming and pre-processing
745 $path=trim($path);
746 if ($this->OS=='WIN') { // with WINDOWS convert backslash to slash!!
747 $path=str_replace('\\','/',$path);
748 }
749 // If the path is true and validates as a valid path string:
750 if ($path && t3lib_div::validPathStr($path)) {
751 // these lines remove all slashes and dots before and after the path
752 $path=ereg_replace('^[\/\. ]*','',$path);
753 $path=trim(ereg_replace('[\/\. ]*$','',$path));
754
755
756 if ($path) { // there must be some chars in the path
757 $fdir=PATH_site.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']; // fileadmin dir, absolute
758 if ($webspace) {
759 $path=$fdir.$path; // PATH_site + fileadmin dir is prepended
760 } else {
761 if ($this->OS!='WIN') { // with WINDOWS no prepending!!
762 $path='/'.$path; // root-level is the start...
763 }
764 }
765 $path.='/';
766
767 // We now have a path with slash after and slash before (if unix)
768 if (@is_dir($path) &&
769 (($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'])) || t3lib_div::isFirstPartOfStr($path,$fdir))) {
770 // Alternative title?
771 $name = $title ? $title : $altTitle;
772 // 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.
773 $this->groupData['filemounts'][md5($name.'|'.$path.'|'.$type)] = Array('name'=>$name, 'path'=>$path, 'type'=>$type);
774 // Return true - went well, success!
775 return 1;
776 }
777 }
778 }
779 }
780
781 /**
782 * Creates a TypoScript comment with the string text inside.
783 *
784 * @param string The text to wrap in comment prefixes and delimiters.
785 * @return string TypoScript comment with the string text inside.
786 */
787 function addTScomment($str) {
788 $delimiter = '# ***********************************************';
789
790 $out = $delimiter.chr(10);
791 $lines = t3lib_div::trimExplode(chr(10),$str);
792 foreach($lines as $v) {
793 $out.= '# '.$v.chr(10);
794 }
795 $out.= $delimiter.chr(10);
796 return $out;
797 }
798
799
800
801
802
803
804
805
806
807
808
809
810 /************************************
811 *
812 * Logging
813 *
814 ************************************/
815
816
817 /**
818 * Writes an entry in the logfile
819 * ... Still missing documentation for syntax etc...
820 *
821 * @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
822 * @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 !!)
823 * @param integer $error: flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
824 * @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
825 * @param string $details: Default text that follows the message
826 * @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...
827 * @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.)
828 * @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.)
829 * @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.)
830 * @param integer $event_pid: The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
831 * @param string $NEWid: NEWid string
832 * @return void
833 */
834 function writelog($type,$action,$error,$details_nr,$details,$data,$tablename='',$recuid='',$recpid='',$event_pid=-1,$NEWid='') {
835 $userid = $this->user['uid'];
836 $tstamp = $GLOBALS['EXEC_TIME'];
837 if (TYPO3_db) {
838 $fields_values=array();
839 $fields_values['userid']=intval($userid);
840 $fields_values['type']=intval($type);
841 $fields_values['action']=intval($action);
842 $fields_values['error']=intval($error);
843 $fields_values['details_nr']=intval($details_nr);
844 $fields_values['details']=$details;
845 $fields_values['log_data']=serialize($data);
846 $fields_values['tablename']=$tablename;
847 $fields_values['recuid']=intval($recuid);
848 $fields_values['recpid']=intval($recpid);
849 $fields_values['IP']=t3lib_div::getIndpEnv('REMOTE_ADDR');
850 $fields_values['tstamp']=$tstamp;
851 $fields_values['event_pid']=intval($event_pid);
852 $fields_values['NEWid']=$NEWid;
853
854 $query = t3lib_BEfunc::DBcompileInsert('sys_log',$fields_values,1);
855
856 mysql(TYPO3_db,$query);
857 return mysql_insert_id();
858 }
859 }
860
861 /**
862 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
863 * 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.
864 *
865 * @param string Email address
866 * @param integer Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
867 * @param integer Max allowed failures before a warning mail is sent
868 * @return void
869 * @access private
870 */
871 function checkLogFailures($email, $secondsBack=3600, $max=3) {
872 if ($email) {
873
874 // get last flag set in the log for sending
875 $theTimeBack = time()-$secondsBack;
876 $query = 'SELECT tstamp FROM sys_log
877 WHERE type=255
878 AND action=4
879 AND tstamp>'.intval($theTimeBack).'
880 ORDER BY tstamp DESC LIMIT 1';
881 $res = mysql(TYPO3_db,$query);
882 if ($testRow = mysql_fetch_assoc($res)) {
883 $theTimeBack = $testRow['tstamp'];
884 }
885
886 // Check for more than $max number of error failures with the last period.
887 $query = 'SELECT * FROM sys_log
888 WHERE type=255
889 AND action=3
890 AND error!=0
891 AND tstamp>'.$theTimeBack.'
892 ORDER BY tstamp';
893 $res = mysql(TYPO3_db,$query);
894 if (mysql_num_rows($res) > $max) {
895 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
896 $subject = 'TYPO3 Login Failure Warning (at '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'].')';
897 $email_body = '
898 There has been numerous attempts ('.mysql_num_rows($res).') to login at the TYPO3
899 site "'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'].'" ('.t3lib_div::getIndpEnv('HTTP_HOST').').
900
901 This is a dump of the failures:
902
903 ';
904 while($testRows=mysql_fetch_assoc($res)) {
905 $theData = unserialize($testRows['log_data']);
906 $email_body.=date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' H:i',$testRows['tstamp']).': '.sprintf($testRows['details'],''.$theData[0],''.$theData[1],''.$theData[2]);
907 $email_body.=chr(10);
908 }
909 mail( $email,
910 $subject,
911 $email_body,
912 'From: TYPO3 Login WARNING<>'
913 );
914 $this->writelog(255,4,0,3,'Failure warning (%s failures within %s seconds) sent by email to %s',Array(mysql_num_rows($res),$secondsBack,$email)); // Logout written to log
915 }
916 }
917 }
918 }
919
920
921
922 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']) {
923 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']);
924 }
925 ?>