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