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