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