2 /***************************************************************
5 * (c) 1999-2010 Kasper Skårhøj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Contains an extension class specifically for authentication/initialization of backend users in TYPO3
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
33 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
36 * [CLASS/FUNCTION INDEX of SCRIPT]
40 * 135: class t3lib_userAuthGroup extends t3lib_userAuth
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)
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)
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)
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()
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)
98 * (This index is automatically created/updated by the extension "extdeveval")
124 * Extension to class.t3lib_userauth.php; Authentication of users in TYPO3 Backend
126 * Actually this class is extended again by t3lib_beuserauth which is the actual backend user class that will be instantiated.
127 * 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.
129 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
133 class t3lib_userAuthGroup
extends t3lib_userAuth
{
134 var $usergroup_column = 'usergroup'; // Should be set to the usergroup-column (id-list) in the user-record
135 var $usergroup_table = 'be_groups'; // The name of the group-table
138 var $groupData = Array( // This array holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
139 'filemounts' => Array() // Filemounts are loaded here
141 var $workspace = -99; // User workspace. -99 is ERROR (none available), -1 is offline, 0 is online, >0 is custom workspaces.
142 var $workspaceRec = array(); // Custom workspace record if any
144 var $userGroups = Array(); // This array will hold the groups that the user is a member of
145 var $userGroupsUID = Array(); // This array holds the uid's of the groups in the listed order
146 var $groupList =''; // This is $this->userGroupsUID imploded to a comma list... Will correspond to the 'usergroup_cached_list'
147 var $dataLists=array( // Used internally to accumulate data for the user-group. DONT USE THIS EXTERNALLY! Use $this->groupData instead
149 'filemount_list'=>'',
150 'fileoper_perms' => 0,
154 'pagetypes_select'=>'',
155 'non_exclude_fields'=>'',
156 'explicit_allowdeny'=>'',
157 'allowed_languages' => '',
158 'workspace_perms' => '',
159 'custom_options' => '',
161 var $includeHierarchy=array(); // For debugging/display of order in which subgroups are included.
162 var $includeGroupArray=array(); // List of group_id's in the order they are processed.
164 var $OS=''; // Set to 'WIN', if windows
165 var $TSdataArray=array(); // Used to accumulate the TSconfig data of the user
166 var $userTS_text = ''; // Contains the non-parsed user TSconfig
167 var $userTS = array(); // Contains the parsed user TSconfig
168 var $userTSUpdated=0; // Set internally if the user TSconfig was parsed and needs to be cached.
169 var $userTS_dontGetCached=0; // Set this from outside if you want the user TSconfig to ALWAYS be parsed and not fetched from cache.
171 var $RTE_errors = array(); // RTE availability errors collected.
172 var $errorMsg = ''; // Contains last error message
174 var $checkWorkspaceCurrent_cache=NULL; // Cache for checkWorkspaceCurrent()
186 /************************************
188 * Permission checking functions:
190 ************************************/
193 * Returns true if user is admin
194 * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
199 return (($this->user
['admin']&1) ==1);
203 * Returns true if the current user is a member of group $groupId
204 * $groupId must be set. $this->groupList must contain groups
205 * Will return true also if the user is a member of a group through subgroups.
207 * @param integer Group ID to look for in $this->groupList
210 function isMemberOfGroup($groupId) {
211 $groupId = intval($groupId);
212 if ($this->groupList
&& $groupId) {
213 return $this->inList($this->groupList
, $groupId);
218 * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
220 * Bits for permissions, see $perms variable:
222 * 1 - Show: See/Copy page and the pagecontent.
223 * 16- Edit pagecontent: Change/Add/Delete/Move pagecontent.
224 * 2- Edit page: Change/Move the page, eg. change title, startdate, hidden.
225 * 4- Delete page: Delete the page and pagecontent.
226 * 8- New pages: Create new pages under the page.
228 * @param array $row is the pagerow for which the permissions is checked
229 * @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.
230 * @return boolean True or False upon evaluation
232 function doesUserHaveAccess($row,$perms) {
233 $userPerms = $this->calcPerms($row);
234 return ($userPerms & $perms)==$perms;
238 * Checks if the page id, $id, is found within the webmounts set up for the user.
239 * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
240 * 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.
241 * 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
242 * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
244 * @param integer Page ID to check
245 * @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!)
246 * @param boolean If set, then the function will exit with an error message.
247 * @return integer The page UID of a page in the rootline that matched a mount point
249 function isInWebMount($id,$readPerms='',$exitOnError=0) {
250 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['lockBeUserToDBmounts'] ||
$this->isAdmin()) return 1;
253 // Check if input id is an offline version page in which case we will map id to the online version:
254 $checkRec = t3lib_beFUnc
::getRecord('pages',$id,'pid,t3ver_oid');
255 if ($checkRec['pid']==-1) {
256 $id = intval($checkRec['t3ver_oid']);
259 if (!$readPerms) $readPerms = $this->getPagePermsClause(1);
261 $wM = $this->returnWebmounts();
262 $rL = t3lib_BEfunc
::BEgetRootLine($id,' AND '.$readPerms);
265 if ($v['uid'] && in_array($v['uid'],$wM)) {
271 throw new RuntimeException('Access Error: This page is not within your DB-mounts');
276 * Checks access to a backend module with the $MCONF passed as first argument
278 * @param array $MCONF array of a backend module!
279 * @param boolean If set, an array will issue an error message and exit.
280 * @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
282 function modAccess($conf,$exitOnError) {
283 if (!t3lib_BEfunc
::isModuleSetInTBE_MODULES($conf['name'])) {
285 throw new RuntimeException('Fatal Error: This module "'.$conf['name'].'" is not enabled in TBE_MODULES');
291 if ($conf['workspaces']) {
292 if (($this->workspace
===0 && t3lib_div
::inList($conf['workspaces'],'online')) ||
293 ($this->workspace
===-1 && t3lib_div
::inList($conf['workspaces'],'offline')) ||
294 ($this->workspace
>0 && t3lib_div
::inList($conf['workspaces'],'custom'))) {
298 throw new RuntimeException('Workspace Error: This module "'.$conf['name'].'" is not available under the current workspace');
304 // Returns true if conf[access] is not set at all or if the user is admin
305 if (!$conf['access'] ||
$this->isAdmin()) return TRUE;
307 // If $conf['access'] is set but not with 'admin' then we return true, if the module is found in the modList
308 if (!strstr($conf['access'],'admin') && $conf['name']) {
309 $acs = $this->check('modules',$conf['name']);
311 if (!$acs && $exitOnError) {
312 throw new RuntimeException('Access Error: You don\'t have access to this module.');
319 * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
320 * $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 * If the user is 'admin' " 1=1" is returned (no effect)
326 * 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)
327 * 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.
329 * @param integer Permission mask to use, see function description
330 * @return string Part of where clause. Prefix " AND " to this.
332 function getPagePermsClause($perms) {
333 global $TYPO3_CONF_VARS;
334 if (is_array($this->user
)) {
335 if ($this->isAdmin()) {
339 $perms = intval($perms); // Make sure it's integer.
341 '(pages.perms_everybody & '.$perms.' = '.$perms.')'. // Everybody
342 ' OR (pages.perms_userid = '.$this->user
['uid'].' AND pages.perms_user & '.$perms.' = '.$perms.')'; // User
343 if ($this->groupList
) {
344 $str.= ' OR (pages.perms_groupid in ('.$this->groupList
.') AND pages.perms_group & '.$perms.' = '.$perms.')'; // Group (if any is set)
349 // getPagePermsClause-HOOK
351 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'])) {
353 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'] as $_funcRef) {
354 $_params = array('currentClause' => $str, 'perms' => $perms);
355 $str = t3lib_div
::callUserFunction($_funcRef, $_params, $this);
366 * Returns a combined binary representation of the current users permissions for the page-record, $row.
367 * 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
368 * If the user is admin, 31 is returned (full permissions for all five flags)
370 * @param array Input page row with all perms_* fields available.
371 * @return integer Bitwise representation of the users permissions in relation to input page row, $row
373 function calcPerms($row) {
374 global $TYPO3_CONF_VARS;
375 if ($this->isAdmin()) {return 31;} // Return 31 for admin users.
378 if (isset($row['perms_userid']) && isset($row['perms_user']) && isset($row['perms_groupid']) && isset($row['perms_group']) && isset($row['perms_everybody']) && isset($this->groupList
)) {
379 if ($this->user
['uid']==$row['perms_userid']) {
380 $out|
=$row['perms_user'];
382 if ($this->isMemberOfGroup($row['perms_groupid'])) {
383 $out|
=$row['perms_group'];
385 $out|
=$row['perms_everybody'];
391 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'])) {
392 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'] as $_funcRef) {
395 'outputPermissions' => $out
397 $out = t3lib_div
::callUserFunction($_funcRef, $_params, $this);
405 * Returns true if the RTE (Rich Text Editor) can be enabled for the user
406 * 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]
407 * The reasons for a FALSE return can be found in $this->RTE_errors
415 $this->RTE_errors
= array();
416 if (!$this->uc
['edit_RTE'])
417 $this->RTE_errors
[] = 'RTE is not enabled for user!';
418 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['RTEenabled'])
419 $this->RTE_errors
[] = 'RTE is not enabled in $TYPO3_CONF_VARS["BE"]["RTEenabled"]';
422 // Acquire RTE object:
423 $RTE = t3lib_BEfunc
::RTEgetObj();
424 if (!is_object($RTE)) {
425 $this->RTE_errors
= array_merge($this->RTE_errors
, $RTE);
428 if (!count($this->RTE_errors
)) {
436 * Returns true if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
437 * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
438 * If user is admin true is also returned
439 * Please see the document Inside TYPO3 for examples.
441 * @param string The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules"
442 * @param string String to search for in the groupData-list
443 * @return boolean True if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
445 function check($type, $value) {
446 if (isset($this->groupData
[$type])) {
447 if ($this->isAdmin() ||
$this->inList($this->groupData
[$type], $value)) {
455 * Checking the authMode of a select field with authMode set
457 * @param string Table name
458 * @param string Field name (must be configured in TCA and of type "select" with authMode set!)
459 * @param string Value to evaluation (single value, must not contain any of the chars ":,|")
460 * @param string Auth mode keyword (explicitAllow, explicitDeny, individual)
461 * @return boolean True or false whether access is granted or not.
463 function checkAuthMode($table,$field,$value,$authMode) {
466 // Admin users can do anything:
467 if ($this->isAdmin()) return TRUE;
469 // Allow all blank values:
470 if (!strcmp($value,'')) return TRUE;
472 // Certain characters are not allowed in the value
473 if (preg_match('/[:|,]/',$value)) {
478 $testValue = $table.':'.$field.':'.$value;
482 switch((string)$authMode) {
483 case 'explicitAllow':
484 if (!$this->inList($this->groupData
['explicit_allowdeny'],$testValue.':ALLOW')) {
489 if ($this->inList($this->groupData
['explicit_allowdeny'],$testValue.':DENY')) {
494 t3lib_div
::loadTCA($table);
495 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field])) {
496 $items = $TCA[$table]['columns'][$field]['config']['items'];
497 if (is_array($items)) {
498 foreach($items as $iCfg) {
499 if (!strcmp($iCfg[1],$value) && $iCfg[4]) {
500 switch((string)$iCfg[4]) {
502 if (!$this->inList($this->groupData
['explicit_allowdeny'],$testValue.':ALLOW')) {
507 if ($this->inList($this->groupData
['explicit_allowdeny'],$testValue.':DENY')) {
524 * Checking if a language value (-1, 0 and >0 for sys_language records) is allowed to be edited by the user.
526 * @param integer Language value to evaluate
527 * @return boolean Returns true if the language value is allowed, otherwise false.
529 function checkLanguageAccess($langValue) {
530 if (strcmp(trim($this->groupData
['allowed_languages']),'')) { // The users language list must be non-blank - otherwise all languages are allowed.
531 $langValue = intval($langValue);
532 if ($langValue != -1 && !$this->check('allowed_languages',$langValue)) { // Language must either be explicitly allowed OR the lang Value be "-1" (all languages)
540 * Check if user has access to all existing localizations for a certain record
542 * @param string the table
543 * @param array the current record
546 function checkFullLanguagesAccess($table, $record) {
547 $recordLocalizationAccess = $this->checkLanguageAccess(0);
548 if ($recordLocalizationAccess
550 t3lib_BEfunc
::isTableLocalizable($table)
551 ||
isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])
555 if (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])) {
556 $l10nTable = $GLOBALS['TCA'][$table]['ctrl']['transForeignTable'];
557 $pointerField = $GLOBALS['TCA'][$l10nTable]['ctrl']['transOrigPointerField'];
558 $pointerValue = $record['uid'];
561 $pointerField = $GLOBALS['TCA'][$l10nTable]['ctrl']['transOrigPointerField'];
562 $pointerValue = $record[$pointerField] > 0 ?
$record[$pointerField] : $record['uid'];
565 $recordLocalizations = t3lib_BEfunc
::getRecordsByField(
575 if (is_array($recordLocalizations)) {
576 foreach($recordLocalizations as $localization) {
577 $recordLocalizationAccess = $recordLocalizationAccess
578 && $this->checkLanguageAccess($localization[$GLOBALS['TCA'][$l10nTable]['ctrl']['languageField']]);
579 if (!$recordLocalizationAccess) {
586 return $recordLocalizationAccess;
590 * Checking if a user has editing access to a record from a $TCA table.
591 * 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.
592 * For instance languages settings, authMode selector boxes are evaluated (and maybe more in the future).
593 * It will check for workspace dependent access.
594 * The function takes an ID (integer) or row (array) as second argument.
596 * @param string Table name
597 * @param mixed If integer, then this is the ID of the record. If Array this just represents fields in the record.
598 * @param boolean Set, if testing a new (non-existing) record array. Will disable certain checks that doesn't make much sense in that context.
599 * @param boolean Set, if testing a deleted record array.
600 * @param boolean Set, whenever access to all translations of the record is required
601 * @return boolean True if OK, otherwise false
603 function recordEditAccessInternals($table, $idOrRow, $newRecord = FALSE, $deletedRecord = FALSE, $checkFullLanguageAccess = FALSE) {
606 if (isset($TCA[$table])) {
607 t3lib_div
::loadTCA($table);
609 // Always return true for Admin users.
610 if ($this->isAdmin()) return TRUE;
612 // Fetching the record if the $idOrRow variable was not an array on input:
613 if (!is_array($idOrRow)) {
614 if ($deletedRecord) {
615 $idOrRow = t3lib_BEfunc
::getRecord($table, $idOrRow, '*', '', FALSE);
617 $idOrRow = t3lib_BEfunc
::getRecord($table, $idOrRow);
619 if (!is_array($idOrRow)) {
620 $this->errorMsg
= 'ERROR: Record could not be fetched.';
625 // Checking languages:
626 if ($TCA[$table]['ctrl']['languageField']) {
627 if (isset($idOrRow[$TCA[$table]['ctrl']['languageField']])) { // Language field must be found in input row - otherwise it does not make sense.
628 if (!$this->checkLanguageAccess($idOrRow[$TCA[$table]['ctrl']['languageField']])) {
629 $this->errorMsg
= 'ERROR: Language was not allowed.';
631 } elseif ($checkFullLanguageAccess && $idOrRow[$TCA[$table]['ctrl']['languageField']]==0 && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
632 $this->errorMsg
= 'ERROR: Related/affected language was not allowed.';
636 $this->errorMsg
= 'ERROR: The "languageField" field named "'.$TCA[$table]['ctrl']['languageField'].'" was not found in testing record!';
639 } elseif (isset($TCA[$table]['ctrl']['transForeignTable']) && $checkFullLanguageAccess && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
643 // Checking authMode fields:
644 if (is_array($TCA[$table]['columns'])) {
645 foreach ($TCA[$table]['columns'] as $fieldName => $fieldValue) {
646 if (isset($idOrRow[$fieldName])) {
647 if ($fieldValue['config']['type'] == 'select' && $fieldValue['config']['authMode'] && !strcmp($fieldValue['config']['authMode_enforce'], 'strict')) {
648 if (!$this->checkAuthMode($table, $fieldName, $idOrRow[$fieldName], $fieldValue['config']['authMode'])) {
649 $this->errorMsg
= 'ERROR: authMode "' . $fieldValue['config']['authMode'] . '" failed for field "' . $fieldName . '" with value "' . $idOrRow[$fieldName] . '" evaluated';
657 // Checking "editlock" feature (doesn't apply to new records)
658 if (!$newRecord && $TCA[$table]['ctrl']['editlock']) {
659 if (isset($idOrRow[$TCA[$table]['ctrl']['editlock']])) {
660 if ($idOrRow[$TCA[$table]['ctrl']['editlock']]) {
661 $this->errorMsg
= 'ERROR: Record was locked for editing. Only admin users can change this state.';
665 $this->errorMsg
= 'ERROR: The "editLock" field named "'.$TCA[$table]['ctrl']['editlock'].'" was not found in testing record!';
670 // Checking record permissions
671 // THIS is where we can include a check for "perms_" fields for other records than pages...
674 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'])) {
675 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'] as $funcRef) {
678 'idOrRow' => $idOrRow,
679 'newRecord' => $newRecord
681 if (!t3lib_div
::callUserFunction($funcRef, $params, $this)) {
687 // Finally, return true if all is well.
693 * Checks a type of permission against the compiled permission integer, $compiledPermissions, and in relation to table, $tableName
695 * @param integer $compiledPermissions could typically be the "compiled permissions" integer returned by ->calcPerms
696 * @param string $tableName 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)
697 * @param string For $tableName='pages' this can be 'edit' (2), 'new' (8 or 16), 'delete' (4), 'editcontent' (16). For all other tables this is ignored. (16 is used)
699 * @access public (used by typo3/alt_clickmenu.php)
701 public function isPSet($compiledPermissions, $tableName, $actionType = '') {
702 if ($this->isAdmin()) {
705 elseif ($tableName == 'pages') {
706 switch($actionType) {
708 $result = ($compiledPermissions & 2) !== 0;
711 // Create new page OR page content
712 $result = ($compiledPermissions & (8 +
16)) !== 0;
715 $result = ($compiledPermissions & 4) !== 0;
718 $result = ($compiledPermissions & 16) !== 0;
724 $result = ($compiledPermissions & 16) !== 0;
730 * Returns true if the BE_USER is allowed to *create* shortcuts in the backend modules
734 function mayMakeShortcut() {
735 // "Shortcuts" have been renamed to "Bookmarks"
736 // @deprecated remove shortcuts code in TYPO3 4.7
737 return ($this->getTSConfigVal('options.enableShortcuts')
738 ||
$this->getTSConfigVal('options.enableBookmarks'))
739 && (!$this->getTSConfigVal('options.mayNotCreateEditShortcuts')
740 && !$this->getTSConfigVal('options.mayNotCreateEditBookmarks'));
744 * Checking if editing of an existing record is allowed in current workspace if that is offline.
745 * Rules for editing in offline mode:
746 * - record supports versioning and is an offline version from workspace and has the corrent stage
747 * - 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
749 * @param string Table of record
750 * @param array Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
751 * @return string String error code, telling the failure state. FALSE=All ok
753 function workspaceCannotEditRecord($table,$recData) {
755 if ($this->workspace
!==0) { // Only test offline spaces:
757 if (!is_array($recData)) {
758 $recData = t3lib_BEfunc
::getRecord($table,$recData,'pid'.($GLOBALS['TCA'][$table]['ctrl']['versioningWS']?
',t3ver_wsid,t3ver_stage':''));
761 if (is_array($recData)) {
762 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.
763 if (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) { // No versioning, basic error, inconsistency even! Such records should not have a pid of -1!
764 return 'Versioning disabled for table';
765 } elseif ((int)$recData['t3ver_wsid']!==$this->workspace
) { // So does workspace match?
766 return 'Workspace ID of record didn\'t match current workspace';
767 } else { // So what about the stage of the version, does that allow editing for this user?
768 return $this->workspaceCheckStageForCurrent($recData['t3ver_stage']) ?
FALSE : 'Record stage "'.$recData['t3ver_stage'].'" and users access level did not allow for editing';
770 } else { // We are testing a "live" record:
771 if ($res = $this->workspaceAllowLiveRecordsInPID($recData['pid'], $table)) { // For "Live" records, check that PID for table allows editing
772 // Live records are OK in this branch, but what about the stage of branch point, if any:
773 return $res>0 ?
FALSE : 'Stage for versioning root point and users access level did not allow for editing'; // OK
774 } else { // If not offline and not in versionized branch, output error:
775 return 'Online record was not in versionized branch!';
778 } else return 'No record';
780 return FALSE; // OK because workspace is 0
785 * Evaluates if a user is allowed to edit the offline version
787 * @param string Table of record
788 * @param array Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
789 * @return string String error code, telling the failure state. FALSE=All ok
790 * @see workspaceCannotEditRecord()
792 function workspaceCannotEditOfflineVersion($table,$recData) {
793 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
795 if (!is_array($recData)) {
796 $recData = t3lib_BEfunc
::getRecord($table,$recData,'uid,pid,t3ver_wsid,t3ver_stage');
798 if (is_array($recData)) {
799 if ((int)$recData['pid']===-1) {
800 return $this->workspaceCannotEditRecord($table,$recData);
801 } else return 'Not an offline version';
802 } else return 'No record';
803 } else return 'Table does not support versioning.';
807 * Check if "live" records from $table may be created or edited in this PID.
808 * If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
809 * 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!
811 * @param integer PID value to check for.
812 * @param string Table name
813 * @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.
815 function workspaceAllowLiveRecordsInPID($pid, $table) {
817 // Always for Live workspace AND if live-edit is enabled and tables are completely without versioning it is ok as well.
818 if ($this->workspace
===0 ||
($this->workspaceRec
['live_edit'] && !$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) ||
$GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']) {
819 return 2; // OK to create for this table.
820 } 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.
821 // Now, check what the stage of that "page" or "branch" version type is:
822 $stage = t3lib_BEfunc
::isPidInVersionizedBranch($pid, $table, TRUE);
823 return $this->workspaceCheckStageForCurrent($stage) ?
1 : -1;
825 return FALSE; // If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
830 * Evaluates if a record from $table can be created in $pid
832 * @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!
833 * @param string Table name
834 * @return boolean TRUE if OK.
836 function workspaceCreateNewRecord($pid, $table) {
837 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
839 return FALSE; // Stage for versioning root point and users access level did not allow for editing
841 } elseif (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) { // So, if no live records were allowed, we have to create a new version of this record:
848 * Evaluates if auto creation of a version of a record is allowed.
850 * @param string Table of the record
851 * @param integer UID of record
852 * @param integer PID of record
853 * @return boolean TRUE if ok.
855 function workspaceAllowAutoCreation($table,$id,$recpid) {
856 // 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.
857 if ($this->workspace
!==0 // Only in draft workspaces
858 && !$this->workspaceRec
['disable_autocreate'] // Auto-creation must not be disabled.
859 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] // Table must be versionizable
860 && $recpid >= 0 // The PID of the record must NOT be -1 or less (would indicate that it already was a version!)
861 && !t3lib_BEfunc
::getWorkspaceVersionOfRecord($this->workspace
, $table, $id, 'uid') // There must be no existing version of this record in workspace.
862 && !t3lib_BEfunc
::isPidInVersionizedBranch($recpid, $table)) { // PID must NOT be in a versionized branch either
868 * Checks if an element stage allows access for the user in the current workspace
869 * In workspaces 0 (Live) and -1 (Default draft) access is always granted for any stage.
870 * Admins are always allowed.
871 * An option for custom workspaces allows members to also edit when the stage is "Review"
873 * @param integer Stage id from an element: -1,0 = editing, 1 = reviewer, >1 = owner
874 * @return boolean TRUE if user is allowed access
876 function workspaceCheckStageForCurrent($stage) {
877 if ($this->isAdmin()) return TRUE;
879 if ($this->workspace
>0) {
880 $stat = $this->checkWorkspaceCurrent();
882 // Check if custom staging is activated
883 $workspaceRec = t3lib_BEfunc
::getRecord('sys_workspace', $stat['uid']);
884 if ($workspaceRec['custom_stages'] > 0 && $stage !== '0' && $stage !== '-10') {
886 // Get custom stage record
887 $workspaceStageRec = t3lib_BEfunc
::getRecord('sys_workspace_stage', $stage);
888 // Check if the user is responsible for the current stage
889 if ((t3lib_div
::inList($workspaceStageRec['responsible_persons'], 'be_users_' . $this->user
['uid'])
890 && $stat['_ACCESS'] === 'member')
891 ||
$stat['_ACCESS'] === 'owner') {
892 return TRUE; // OK for these criteria
895 // Check if the user is in a group which is responsible for the current stage
896 foreach ($this->userGroupsUID
as $groupUid) {
897 if ((t3lib_div
::inList($workspaceStageRec['responsible_persons'], 'be_groups_' . $groupUid)
898 && $stat['_ACCESS'] === 'member')
899 ||
$stat['_ACCESS'] === 'owner') {
900 return TRUE; // OK for these criteria
904 $memberStageLimit = $this->workspaceRec
['review_stage_edit'] ?
1 : 0;
905 if (($stage <= $memberStageLimit && $stat['_ACCESS'] === 'member')
906 ||
($stage <= 1 && $stat['_ACCESS'] === 'reviewer')
907 ||
$stat['_ACCESS'] === 'owner') {
908 return TRUE; // OK for these criteria
911 } else return TRUE; // Always OK for live and draft workspaces.
915 * Returns TRUE if the user has access to publish content from the workspace ID given.
916 * Admin-users are always granted access to do this
917 * If the workspace ID is 0 (live) all users have access also
918 * If -1 (draft workspace) TRUE is returned if the user has access to the Live workspace
919 * For custom workspaces it depends on whether the user is owner OR like with draft workspace if the user has access to Live workspace.
921 * @param integer Workspace UID; -1,0,1+
922 * @return boolean Returns TRUE if the user has access to publish content from the workspace ID given.
924 function workspacePublishAccess($wsid) {
925 if ($this->isAdmin()) return TRUE;
927 // If no access to workspace, of course you cannot publish!
930 $wsAccess = $this->checkWorkspace($wsid);
932 switch($wsAccess['uid']) {
933 case 0: // Live workspace
934 $retVal = TRUE; // If access to Live workspace, no problem.
936 case -1: // Default draft workspace
937 $retVal = $this->checkWorkspace(0) ?
TRUE : FALSE; // If access to Live workspace, no problem.
939 default: // Custom workspace
940 $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.
948 * Workspace swap-mode access?
950 * @return boolean Returns TRUE if records can be swapped in the current workspace, otherwise false
952 function workspaceSwapAccess() {
953 if ($this->workspace
>0 && (int)$this->workspaceRec
['swap_modes']===2) {
959 * Workspace Versioning type access. Check wether the requsted type of versioning (element/page/branch) is allowd in current workspace
960 * (element/pages/branches type of versioning can/could be set on custom workspaces on filed "vtype")
962 * @todo workspacecleanup: this seems mostly obsolete and should be removed
963 * @param integer Versioning type to evaluation: -1, 0, >1
964 * 0 = page (deprecated)
966 * >1 = branch (deprecated), indicating the "nesting" level
967 * @return boolean TRUE if OK
969 function workspaceVersioningTypeAccess($type) {
972 $type = t3lib_div
::intInRange($type,-1);
974 // Check if only element versioning is allowed:
975 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['elementVersioningOnly'] && $type!=-1) {
979 if ($this->workspace
>0 && !$this->isAdmin()) {
980 $stat = $this->checkWorkspaceCurrent();
981 if ($stat['_ACCESS']!=='owner') {
985 $retVal = $this->workspaceRec
['vtypes']&1 ?
FALSE : TRUE;
988 $retVal = $this->workspaceRec
['vtypes']&2 ?
FALSE : TRUE;
991 $retVal = $this->workspaceRec
['vtypes']&4 ?
FALSE : TRUE;
994 } else $retVal = TRUE;
995 } else $retVal = TRUE;
1001 * Finding "closest" versioning type, used for creation of new records.
1003 * @see workspaceVersioningTypeAccess() for hints on $type
1004 * @param integer Versioning type to evaluation: -1, 0, >1
1005 * @return integer Returning versioning type
1007 function workspaceVersioningTypeGetClosest($type) {
1008 $type = t3lib_div
::intInRange($type,-1);
1010 if ($this->workspace
>0) {
1011 switch((int)$type) {
1016 $type = $this->workspaceVersioningTypeAccess($type) ?
$type : -1;
1019 $type = $this->workspaceVersioningTypeAccess($type) ?
$type : ($this->workspaceVersioningTypeAccess(0) ?
0 : -1);
1035 /*************************************
1037 * Miscellaneous functions
1039 *************************************/
1042 * Returns the value/properties of a TS-object as given by $objectString, eg. 'options.dontMountAdminMounts'
1043 * Nice (general!) function for returning a part of a TypoScript array!
1045 * @param string Pointer to an "object" in the TypoScript array, fx. 'options.dontMountAdminMounts'
1046 * @param array Optional TSconfig array: If array, then this is used and not $this->userTS. If not array, $this->userTS is used.
1047 * @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.
1048 * @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.
1050 function getTSConfig($objectString,$config='') {
1051 if (!is_array($config)) {
1052 $config=$this->userTS
; // Getting Root-ts if not sent
1055 $parts = explode('.',$objectString,2);
1058 if (count($parts)>1 && trim($parts[1])) {
1059 // Go on, get the next level
1060 if (is_array($config[$key.'.'])) $TSConf = $this->getTSConfig($parts[1],$config[$key.'.']);
1062 $TSConf['value']=$config[$key];
1063 $TSConf['properties']=$config[$key.'.'];
1070 * Returns the "value" of the $objectString from the BE_USERS "User TSconfig" array
1072 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
1073 * @return string The value for that object string (object path)
1074 * @see getTSConfig()
1076 function getTSConfigVal($objectString) {
1077 $TSConf = $this->getTSConfig($objectString);
1078 return $TSConf['value'];
1082 * Returns the "properties" of the $objectString from the BE_USERS "User TSconfig" array
1084 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
1085 * @return array The properties for that object string (object path) - if any
1086 * @see getTSConfig()
1088 function getTSConfigProp($objectString) {
1089 $TSConf = $this->getTSConfig($objectString);
1090 return $TSConf['properties'];
1094 * Returns true if $item is in $in_list
1096 * @param string Comma list with items, no spaces between items!
1097 * @param string The string to find in the list of items
1098 * @return string Boolean
1100 function inList($in_list,$item) {
1101 return strstr(','.$in_list.',', ','.$item.',');
1105 * Returns an array with the webmounts.
1106 * If no webmounts, and empty array is returned.
1107 * 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.
1111 function returnWebmounts() {
1112 return (string)($this->groupData
['webmounts'])!='' ?
explode(',',$this->groupData
['webmounts']) : Array();
1116 * Returns an array with the filemounts for the user. Each filemount is represented with an array of a "name", "path" and "type".
1117 * If no filemounts an empty array is returned.
1121 function returnFilemounts() {
1122 return $this->groupData
['filemounts'];
1126 * Returns an integer bitmask that represents the permissions for file operations.
1127 * Permissions of the user and groups the user is a member of were combined by a logical OR.
1129 * Meaning of each bit:
1130 * 1 - Files: Upload,Copy,Move,Delete,Rename
1132 * 4 - Directory: Move,Delete,Rename,New
1133 * 8 - Directory: Copy
1134 * 16 - Directory: Delete recursively (rm -Rf)
1136 * @return integer File operation permission bitmask
1138 public function getFileoperationPermissions() {
1139 if ($this->isAdmin()) {
1142 return $this->groupData
['fileoper_perms'];
1147 * Returns true or false, depending if an alert popup (a javascript confirmation) should be shown
1148 * call like $GLOBALS['BE_USER']->jsConfirmation($BITMASK)
1151 * 2 - copy/move/paste
1153 * 8 - frontend editing
1154 * 128 - other (not used yet)
1156 * @param integer Bitmask
1157 * @return boolean true if the confirmation should be shown
1159 function jsConfirmation($bitmask) {
1160 $alertPopup = $GLOBALS['BE_USER']->getTSConfig('options.alertPopups');
1161 if (empty($alertPopup['value'])) {
1162 $alertPopup = 255; // default: show all warnings
1164 $alertPopup = (int)$alertPopup['value'];
1166 if(($alertPopup&$bitmask) == $bitmask) { // show confirmation
1168 } else { // don't show confirmation
1181 /*************************************
1183 * Authentication methods
1185 *************************************/
1189 * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
1190 * This method is called by ->backendCheckLogin() (from extending class t3lib_beuserauth) if the backend user login has verified OK.
1191 * Generally this is required initialization of a backend user.
1195 * @see t3lib_TSparser
1197 function fetchGroupData() {
1198 if ($this->user
['uid']) {
1200 // Get lists for the be_user record and set them as default/primary values.
1201 $this->dataLists
['modList'] = $this->user
['userMods']; // Enabled Backend Modules
1202 $this->dataLists
['allowed_languages'] = $this->user
['allowed_languages']; // Add Allowed Languages
1203 $this->dataLists
['workspace_perms'] = $this->user
['workspace_perms']; // Set user value for workspace permissions.
1204 $this->dataLists
['webmount_list'] = $this->user
['db_mountpoints']; // Database mountpoints
1205 $this->dataLists
['filemount_list'] = $this->user
['file_mountpoints']; // File mountpoints
1206 $this->dataLists
['fileoper_perms'] = (int)$this->user
['fileoper_perms']; // Fileoperation permissions
1208 // Setting default User TSconfig:
1209 $this->TSdataArray
[]=$this->addTScomment('From $GLOBALS["TYPO3_CONF_VARS"]["BE"]["defaultUserTSconfig"]:').
1210 $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
1212 // Default TSconfig for admin-users
1213 if ($this->isAdmin()) {
1214 $this->TSdataArray
[]=$this->addTScomment('"admin" user presets:').'
1215 admPanel.enable.all = 1
1217 if (t3lib_extMgm
::isLoaded('sys_note')) {
1218 $this->TSdataArray
[]='
1219 // Setting defaults for sys_note author / email...
1220 TCAdefaults.sys_note.author = '.$this->user
['realName'].'
1221 TCAdefaults.sys_note.email = '.$this->user
['email'].'
1227 // Admin users has the base fileadmin dir mounted
1228 if ($this->isAdmin() && $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
1229 $this->addFileMount($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '', PATH_site
.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], 0, '');
1232 // If userHomePath is set, we attempt to mount it
1233 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
1234 // First try and mount with [uid]_[username]
1235 $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');
1237 // If that failed, try and mount with only [uid]
1238 $this->addFileMount($this->user
['username'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'].$this->user
['uid'].$GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'], 0, 'user');
1243 // Get the groups...
1244 # $grList = t3lib_BEfunc::getSQLselectableList($this->user[$this->usergroup_column],$this->usergroup_table,$this->usergroup_table);
1245 $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.
1247 // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc. Refer to fetchGroups() function.
1248 $this->fetchGroups($grList);
1251 // Add the TSconfig for this specific user:
1252 $this->TSdataArray
[] = $this->addTScomment('USER TSconfig field').$this->user
['TSconfig'];
1253 // Check include lines.
1254 $this->TSdataArray
= t3lib_TSparser
::checkIncludeLines_array($this->TSdataArray
);
1256 $this->userTS_text
= implode(LF
.'[GLOBAL]'.LF
,$this->TSdataArray
); // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
1258 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions'] && !$this->userTS_dontGetCached
) {
1259 // Perform TS-Config parsing with condition matching
1260 $parseObj = t3lib_div
::makeInstance('t3lib_TSparser_TSconfig');
1261 $res = $parseObj->parseTSconfig($this->userTS_text
, 'userTS');
1263 $this->userTS
= $res['TSconfig'];
1264 $this->userTSUpdated
= ($res['cached'] ?
0 : 1);
1267 // Parsing the user TSconfig (or getting from cache)
1268 $hash = md5('userTS:' . $this->userTS_text
);
1269 $cachedContent = t3lib_BEfunc
::getHash($hash);
1270 if (isset($cachedContent) && !$this->userTS_dontGetCached
) {
1271 $this->userTS
= unserialize($cachedContent);
1273 $parseObj = t3lib_div
::makeInstance('t3lib_TSparser');
1274 $parseObj->parse($this->userTS_text
);
1275 $this->userTS
= $parseObj->setup
;
1276 t3lib_BEfunc
::storeHash($hash, serialize($this->userTS
), 'BE_USER_TSconfig');
1278 $this->userTSUpdated
=1;
1282 // Processing webmounts
1283 if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) { // Admin's always have the root mounted
1284 $this->dataLists
['webmount_list']='0,'.$this->dataLists
['webmount_list'];
1287 // Processing filemounts
1288 t3lib_div
::loadTCA('sys_filemounts');
1289 $orderBy = $GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'] ?
$GLOBALS['TYPO3_DB']->stripOrderBy($GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby']) : 'sorting';
1290 $this->dataLists
['filemount_list'] = t3lib_div
::uniqueList($this->dataLists
['filemount_list']);
1291 if ($this->dataLists
['filemount_list']) {
1292 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_filemounts', 'deleted=0 AND hidden=0 AND pid=0 AND uid IN ('.$this->dataLists
['filemount_list'].')', '', $orderBy);
1293 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1294 $this->addFileMount($row['title'], $row['path'], $row['path'], $row['base']?
1:0, '');
1298 // The lists are cleaned for duplicates
1299 $this->groupData
['webmounts'] = t3lib_div
::uniqueList($this->dataLists
['webmount_list']);
1300 $this->groupData
['pagetypes_select'] = t3lib_div
::uniqueList($this->dataLists
['pagetypes_select']);
1301 $this->groupData
['tables_select'] = t3lib_div
::uniqueList($this->dataLists
['tables_modify'].','.$this->dataLists
['tables_select']);
1302 $this->groupData
['tables_modify'] = t3lib_div
::uniqueList($this->dataLists
['tables_modify']);
1303 $this->groupData
['non_exclude_fields'] = t3lib_div
::uniqueList($this->dataLists
['non_exclude_fields']);
1304 $this->groupData
['explicit_allowdeny'] = t3lib_div
::uniqueList($this->dataLists
['explicit_allowdeny']);
1305 $this->groupData
['allowed_languages'] = t3lib_div
::uniqueList($this->dataLists
['allowed_languages']);
1306 $this->groupData
['custom_options'] = t3lib_div
::uniqueList($this->dataLists
['custom_options']);
1307 $this->groupData
['modules'] = t3lib_div
::uniqueList($this->dataLists
['modList']);
1308 $this->groupData
['fileoper_perms'] = $this->dataLists
['fileoper_perms'];
1309 $this->groupData
['workspace_perms'] = $this->dataLists
['workspace_perms'];
1311 // populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
1312 $this->userGroupsUID
= array_reverse(array_unique(array_reverse($this->includeGroupArray
)));
1314 // 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)
1315 $this->groupList
= implode(',',$this->userGroupsUID
);
1316 $this->setCachedList($this->groupList
);
1318 // Checking read access to webmounts:
1319 if (trim($this->groupData
['webmounts'])!=='') {
1320 $webmounts = explode(',',$this->groupData
['webmounts']); // Explode mounts
1321 $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
1322 foreach($webmounts as $idx => $mountPointUid) {
1323 if ($mountPointUid>0 && !isset($MProws[$mountPointUid])) { // If the mount ID is NOT found among selected pages, unset it:
1324 unset($webmounts[$idx]);
1327 $this->groupData
['webmounts'] = implode(',',$webmounts); // Implode mounts in the end.
1330 // Setting up workspace situation (after webmounts are processed!):
1331 $this->workspaceInit();
1336 * Fetches the group records, subgroups and fills internal arrays.
1337 * Function is called recursively to fetch subgroups
1339 * @param string Commalist of be_groups uid numbers
1340 * @param string List of already processed be_groups-uids so the function will not fall into a eternal recursion.
1344 function fetchGroups($grList,$idList='') {
1345 global $TYPO3_CONF_VARS;
1347 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
1348 $lockToDomain_SQL = ' AND (lockToDomain=\'\' OR lockToDomain IS NULL OR lockToDomain=\''.t3lib_div
::getIndpEnv('HTTP_HOST').'\')';
1349 $whereSQL = 'deleted=0 AND hidden=0 AND pid=0 AND uid IN ('.$grList.')'.$lockToDomain_SQL;
1351 // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
1352 if (is_array ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'])) {
1353 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] as $classRef) {
1354 $hookObj = t3lib_div
::getUserObj($classRef);
1355 if(method_exists($hookObj,'fetchGroupQuery_processQuery')){
1356 $whereSQL = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, $whereSQL);
1361 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->usergroup_table
, $whereSQL);
1363 // The userGroups array is filled
1364 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1365 $this->userGroups
[$row['uid']] = $row;
1368 // Traversing records in the correct order
1369 $include_staticArr = t3lib_div
::intExplode(',',$grList);
1371 foreach ($include_staticArr as $key => $uid) {
1374 $row=$this->userGroups
[$uid];
1375 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
1377 // Include sub groups
1378 if (trim($row['subgroup'])) {
1379 $theList = implode(',',t3lib_div
::intExplode(',',$row['subgroup'])); // Make integer list
1380 $this->fetchGroups($theList, $idList.','.$uid); // Call recursively, pass along list of already processed groups so they are not recursed again.
1382 // Add the group uid, current list, TSconfig to the internal arrays.
1383 $this->includeGroupArray
[]=$uid;
1384 $this->includeHierarchy
[]=$idList;
1385 $this->TSdataArray
[] = $this->addTScomment('Group "'.$row['title'].'" ['.$row['uid'].'] TSconfig field:').$row['TSconfig'];
1387 // Mount group database-mounts
1388 if (($this->user
['options']&1) == 1) { $this->dataLists
['webmount_list'].= ','.$row['db_mountpoints']; }
1390 // Mount group file-mounts
1391 if (($this->user
['options']&2) == 2) { $this->dataLists
['filemount_list'].= ','.$row['file_mountpoints']; }
1393 // Mount group home-dirs
1394 if (($this->user
['options']&2) == 2) {
1395 // If groupHomePath is set, we attempt to mount it
1396 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath']) {
1397 $this->addFileMount($row['title'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'].$row['uid'], 0, 'group');
1401 // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
1402 if ($row['inc_access_lists']==1) {
1403 $this->dataLists
['modList'].= ','.$row['groupMods'];
1404 $this->dataLists
['tables_select'].= ','.$row['tables_select'];
1405 $this->dataLists
['tables_modify'].= ','.$row['tables_modify'];
1406 $this->dataLists
['pagetypes_select'].= ','.$row['pagetypes_select'];
1407 $this->dataLists
['non_exclude_fields'].= ','.$row['non_exclude_fields'];
1408 $this->dataLists
['explicit_allowdeny'].= ','.$row['explicit_allowdeny'];
1409 $this->dataLists
['allowed_languages'].= ','.$row['allowed_languages'];
1410 $this->dataLists
['custom_options'].= ','.$row['custom_options'];
1413 // Setting fileoperation permissions
1414 $this->dataLists
['fileoper_perms'] |
= (int)$row['fileoper_perms'];
1416 // Setting workspace permissions:
1417 $this->dataLists
['workspace_perms'] |
= $row['workspace_perms'];
1419 // 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.
1420 if (!strcmp($idList,'') && !$this->firstMainGroup
) {
1421 $this->firstMainGroup
=$uid;
1427 // HOOK: fetchGroups_postProcessing
1429 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'])) {
1430 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] as $_funcRef) {
1432 t3lib_div
::callUserFunction($_funcRef, $_params, $this);
1438 * Updates the field be_users.usergroup_cached_list if the groupList of the user has changed/is different from the current list.
1439 * 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.
1441 * @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.
1445 function setCachedList($cList) {
1446 if ((string)$cList != (string)$this->user
['usergroup_cached_list']) {
1447 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid='.intval($this->user
['uid']), array('usergroup_cached_list' => $cList));
1452 * Adds a filemount to the users array of filemounts, $this->groupData['filemounts'][hash_key] = Array ('name'=>$name, 'path'=>$path, 'type'=>$type);
1453 * Is a part of the authentication proces of the user.
1454 * 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!
1455 * Paths in the mounted information will always be absolute and have a trailing slash.
1457 * @param string $title will be the (root)name of the filemount in the folder tree
1458 * @param string $altTitle will be the (root)name of the filemount IF $title is not true (blank or zero)
1459 * @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.
1460 * @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.
1461 * @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.
1462 * @return boolean Returns "1" if the requested filemount was mounted, otherwise no return value.
1465 function addFileMount($title, $altTitle, $path, $webspace, $type) {
1466 // Return false if fileadminDir is not set and we try to mount a relative path
1467 if ($webspace && !$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) return false;
1469 // Trimming and pre-processing
1471 if ($this->OS
=='WIN') { // with WINDOWS convert backslash to slash!!
1472 $path=str_replace('\\','/',$path);
1474 // If the path is true and validates as a valid path string:
1475 if ($path && t3lib_div
::validPathStr($path)) {
1476 // normalize path: remove leading '/' and './', and trailing '/' and '/.'
1478 $path=preg_replace('#^\.?/|/\.?$#','',$path);
1480 if ($path) { // there must be some chars in the path
1481 $fdir=PATH_site
.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']; // fileadmin dir, absolute
1483 $path=$fdir.$path; // PATH_site + fileadmin dir is prepended
1485 if ($this->OS
!='WIN') { // with WINDOWS no prepending!!
1486 $path='/'.$path; // root-level is the start...
1491 // We now have a path with slash after and slash before (if unix)
1492 if (@is_dir
($path) &&
1493 (($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div
::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'])) || t3lib_div
::isFirstPartOfStr($path,$fdir))) {
1494 // Alternative title?
1495 $name = $title ?
$title : $altTitle;
1496 // 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.
1497 $this->groupData
['filemounts'][md5($name.'|'.$path.'|'.$type)] = Array('name'=>$name, 'path'=>$path, 'type'=>$type);
1498 // Return true - went well, success!
1506 * Creates a TypoScript comment with the string text inside.
1508 * @param string The text to wrap in comment prefixes and delimiters.
1509 * @return string TypoScript comment with the string text inside.
1511 function addTScomment($str) {
1512 $delimiter = '# ***********************************************';
1514 $out = $delimiter.LF
;
1515 $lines = t3lib_div
::trimExplode(LF
,$str);
1516 foreach($lines as $v) {
1519 $out.= $delimiter.LF
;
1534 /************************************
1538 ************************************/
1541 * Initializing workspace.
1542 * Called from within this function, see fetchGroupData()
1545 * @see fetchGroupData()
1547 function workspaceInit() {
1549 // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
1550 $this->setWorkspace($this->user
['workspace_id']);
1552 // Limiting the DB mountpoints if there any selected in the workspace record
1553 $dbMountpoints = trim($this->workspaceRec
['db_mountpoints']);
1554 if ($this->workspace
> 0 && $dbMountpoints != '') {
1555 $filteredDbMountpoints = array();
1556 $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.
1558 // Traverse mount points of the
1559 $dbMountpoints = t3lib_div
::intExplode(',', $dbMountpoints);
1560 foreach ($dbMountpoints as $mpId) {
1561 if ($this->isInWebMount($mpId, $readPerms)) {
1562 $filteredDbMountpoints[] = $mpId;
1566 // Re-insert webmounts:
1567 $filteredDbMountpoints = array_unique($filteredDbMountpoints);
1568 $this->groupData
['webmounts'] = implode(',', $filteredDbMountpoints);
1571 // Filtering the file mountpoints
1572 // if there some selected in the workspace record
1573 if ($this->workspace
!== 0) {
1574 $usersFileMounts = $this->groupData
['filemounts'];
1575 $this->groupData
['filemounts'] = array();
1577 $fileMountpoints = trim($this->workspaceRec
['file_mountpoints']);
1578 if ($this->workspace
> 0) {
1580 // no custom filemounts that should serve as filter
1581 // so all user mountpoints are re-applied
1582 if ($fileMountpoints === '') {
1583 $this->groupData
['filemounts'] = $usersFileMounts;
1585 // Fetching all filemounts from the workspace
1586 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1589 'deleted = 0 AND hidden = 0 AND pid = 0 AND uid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($fileMountpoints) . ')'
1592 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1593 // add every filemount of this workspace record
1594 $this->addFileMount($row['title'], $row['path'], $row['path'], ($row['base'] ?
1 : 0), '');
1596 // get the added entry, and check if it was in the users' original filemounts
1597 // if not, remove it from the new filemount list again
1598 // see self::addFileMount
1599 end($this->groupData
['filemounts']);
1600 $md5hash = key($this->groupData
['filemounts']);
1601 if (!array_key_exists($md5hash, $usersFileMounts)) {
1602 unset($this->groupData
['filemounts'][$md5hash]);
1608 if ($allowed_languages = $this->getTSConfigVal('options.workspaces.allowed_languages.'.$this->workspace
)) {
1609 $this->groupData
['allowed_languages'] = $allowed_languages;
1610 $this->groupData
['allowed_languages'] = t3lib_div
::uniqueList($this->groupData
['allowed_languages']);
1615 * Checking if a workspace is allowed for backend user
1617 * @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)
1618 * @param string List of fields to select. Default fields are: uid,title,adminusers,members,reviewers,publish_access,stagechg_notification
1619 * @return array TRUE if access. Output will also show how access was granted. Admin users will have a true output regardless of input.
1621 function checkWorkspace($wsRec,$fields='uid,title,adminusers,members,reviewers,publish_access,stagechg_notification') {
1624 // Show draft workspace only if it's enabled in version extension
1625 if (t3lib_extMgm
::isLoaded('version')) {
1626 $versionExtConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['version']);
1627 if (!$versionExtConf['showDraftWorkspace']) {
1628 if (!is_array($wsRec)) {
1629 if ((string) $wsRec === '-1') {
1633 if ((string) $wsRec['uid'] === '-1') {
1640 // If not array, look up workspace record:
1641 if (!is_array($wsRec)) {
1642 switch((string)$wsRec) {
1645 $wsRec = array('uid' => $wsRec);
1648 list($wsRec) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
1651 'pid=0 AND uid='.intval($wsRec).
1652 t3lib_BEfunc
::deleteClause('sys_workspace'),
1660 // If wsRec is set to an array, evaluate it:
1661 if (is_array($wsRec)) {
1662 if ($this->isAdmin()) {
1663 return array_merge($wsRec,array('_ACCESS' => 'admin'));
1666 switch((string)$wsRec['uid']) {
1668 $retVal = ($this->groupData
['workspace_perms']&1) ?
array_merge($wsRec,array('_ACCESS' => 'online')) : FALSE;
1671 $retVal = ($this->groupData
['workspace_perms']&2) ?
array_merge($wsRec,array('_ACCESS' => 'offline')) : FALSE;
1674 // Checking if the guy is admin:
1675 if (t3lib_div
::inList($wsRec['adminusers'], 'be_users_' . $this->user
['uid'])) {
1676 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1678 // Checking if he is owner through a user group of his:
1679 foreach ($this->userGroupsUID
as $groupUid) {
1680 if (t3lib_div
::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
1681 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1684 // Checking if he is reviewer user:
1685 if (t3lib_div
::inList($wsRec['reviewers'],'be_users_'.$this->user
['uid'])) {
1686 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1688 // Checking if he is reviewer through a user group of his:
1689 foreach($this->userGroupsUID
as $groupUid) {
1690 if (t3lib_div
::inList($wsRec['reviewers'],'be_groups_'.$groupUid)) {
1691 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1694 // Checking if he is member as user:
1695 if (t3lib_div
::inList($wsRec['members'],'be_users_'.$this->user
['uid'])) {
1696 return array_merge($wsRec, array('_ACCESS' => 'member'));
1698 // Checking if he is member through a user group of his:
1699 foreach($this->userGroupsUID
as $groupUid) {
1700 if (t3lib_div
::inList($wsRec['members'],'be_groups_'.$groupUid)) {
1701 return array_merge($wsRec, array('_ACCESS' => 'member'));
1713 * 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.
1715 * @return array See checkWorkspace()
1716 * @see checkWorkspace()
1718 function checkWorkspaceCurrent() {
1719 if (!isset($this->checkWorkspaceCurrent_cache
)) {
1720 $this->checkWorkspaceCurrent_cache
= $this->checkWorkspace($this->workspace
);
1722 return $this->checkWorkspaceCurrent_cache
;
1726 * Setting workspace ID
1728 * @param integer ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
1731 function setWorkspace($workspaceId) {
1733 // Check workspace validity and if not found, revert to default workspace.
1734 if ($this->workspaceRec
= $this->checkWorkspace($workspaceId,'*')) {
1735 // Set workspace ID internally
1736 $this->workspace
= (int)$workspaceId;
1738 $this->workspace
= (int)$this->getDefaultWorkspace();
1739 $this->workspaceRec
= $this->checkWorkspace($this->workspace
,'*');
1742 // Unset access cache:
1743 unset($this->checkWorkspaceCurrent_cache
);
1745 // If ID is different from the stored one, change it:
1746 if (strcmp($this->workspace
, $this->user
['workspace_id'])) {
1747 $this->user
['workspace_id'] = $this->workspace
;
1748 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users','uid='.intval($this->user
['uid']),array('workspace_id' => $this->user
['workspace_id']));
1749 $this->simplelog('User changed workspace to "'.$this->workspace
.'"');
1754 * Setting workspace preview state for user:
1756 * @param boolean State of user preview.
1759 function setWorkspacePreview($previewState) {
1760 $this->user
['workspace_preview'] = $previewState;
1761 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users','uid='.intval($this->user
['uid']),array('workspace_preview' => $this->user
['workspace_preview']));
1765 * Return default workspace ID for user
1767 * @return integer Default workspace id. If no workspace is available it will be "-99"
1769 function getDefaultWorkspace() {
1771 if ($this->checkWorkspace(0)) { // Check online
1773 } elseif ($this->checkWorkspace(-1)) { // Check offline
1775 } else { // Traverse custom workspaces:
1776 $workspaces = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,title,adminusers,members,reviewers','sys_workspace','pid=0'.t3lib_BEfunc
::deleteClause('sys_workspace'),'','title');
1777 foreach($workspaces as $rec) {
1778 if ($this->checkWorkspace($rec)) {
1796 /************************************
1800 ************************************/
1803 * Writes an entry in the logfile/table
1804 * Documentation in "TYPO3 Core API"
1806 * @param integer Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
1807 * @param integer Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
1808 * @param integer Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1809 * @param integer The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
1810 * @param string Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
1811 * @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
1812 * @param string Table name. Special field used by tce_main.php.
1813 * @param integer Record UID. Special field used by tce_main.php.
1814 * @param integer Record PID. Special field used by tce_main.php. OBSOLETE
1815 * @param integer The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
1816 * @param string Special field used by tce_main.php. NEWid string of newly created records.
1817 * @param integer Alternative Backend User ID (used for logging login actions where this is not yet known).
1818 * @return integer Log entry ID.
1820 function writelog($type,$action,$error,$details_nr,$details,$data,$tablename='',$recuid='',$recpid='',$event_pid=-1,$NEWid='',$userId=0) {
1822 $fields_values = Array (
1823 'userid' => $userId ?
$userId : intval($this->user
['uid']),
1824 'type' => intval($type),
1825 'action' => intval($action),
1826 'error' => intval($error),
1827 'details_nr' => intval($details_nr),
1828 'details' => $details,
1829 'log_data' => serialize($data),
1830 'tablename' => $tablename,
1831 'recuid' => intval($recuid),
1832 # 'recpid' => intval($recpid),
1833 'IP' => t3lib_div
::getIndpEnv('REMOTE_ADDR'),
1834 'tstamp' => $GLOBALS['EXEC_TIME'],
1835 'event_pid' => intval($event_pid),
1837 'workspace' => $this->workspace
1840 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_log', $fields_values);
1841 return $GLOBALS['TYPO3_DB']->sql_insert_id();
1845 * Simple logging function
1847 * @param string Log message
1848 * @param string Option extension key / module name
1849 * @param integer Error level. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1850 * @return integer Log entry UID
1852 function simplelog($message, $extKey='', $error=0) {
1853 return $this->writelog(
1858 ($extKey?
'['.$extKey.'] ':'').$message,
1864 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
1865 * 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.
1867 * @param string Email address
1868 * @param integer Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
1869 * @param integer Max allowed failures before a warning mail is sent
1873 function checkLogFailures($email, $secondsBack=3600, $max=3) {
1877 // get last flag set in the log for sending
1878 $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
1879 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1882 'type=255 AND action=4 AND tstamp>'.intval($theTimeBack),
1887 if ($testRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1888 $theTimeBack = $testRow['tstamp'];
1891 // Check for more than $max number of error failures with the last period.
1892 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1895 'type=255 AND action=3 AND error!=0 AND tstamp>'.intval($theTimeBack),
1899 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) > $max) {
1900 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
1901 $subject = 'TYPO3 Login Failure Warning (at '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'].')';
1903 There has been numerous attempts ('.$GLOBALS['TYPO3_DB']->sql_num_rows($res).') to login at the TYPO3
1904 site "'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'].'" ('.t3lib_div
::getIndpEnv('HTTP_HOST').').
1906 This is a dump of the failures:
1909 while($testRows = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1910 $theData = unserialize($testRows['log_data']);
1911 $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]);
1914 t3lib_utility_Mail
::mail($email,
1917 'From: TYPO3 Login WARNING<>'
1919 $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
1927 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']) {
1928 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']);