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