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