TYPO3 API  SVNRelease
class.t3lib_userauthgroup.php
Go to the documentation of this file.
00001 <?php
00002 /***************************************************************
00003  *  Copyright notice
00004  *
00005  *  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
00006  *  All rights reserved
00007  *
00008  *  This script is part of the TYPO3 project. The TYPO3 project is
00009  *  free software; you can redistribute it and/or modify
00010  *  it under the terms of the GNU General Public License as published by
00011  *  the Free Software Foundation; either version 2 of the License, or
00012  *  (at your option) any later version.
00013  *
00014  *  The GNU General Public License can be found at
00015  *  http://www.gnu.org/copyleft/gpl.html.
00016  *  A copy is found in the textfile GPL.txt and important notices to the license
00017  *  from the author is found in LICENSE.txt distributed with these scripts.
00018  *
00019  *
00020  *  This script is distributed in the hope that it will be useful,
00021  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023  *  GNU General Public License for more details.
00024  *
00025  *  This copyright notice MUST APPEAR in all copies of the script!
00026  ***************************************************************/
00027 /**
00028  * Contains an extension class specifically for authentication/initialization of backend users in TYPO3
00029  *
00030  * $Id: class.t3lib_userauthgroup.php 10478 2011-02-17 11:08:43Z ohader $
00031  * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
00032  *
00033  * @author  Kasper Skårhøj <kasperYYYY@typo3.com>
00034  */
00035 /**
00036  * [CLASS/FUNCTION INDEX of SCRIPT]
00037  *
00038  *
00039  *
00040  *  135: class t3lib_userAuthGroup extends t3lib_userAuth
00041  *
00042  *            SECTION: Permission checking functions:
00043  *  199:     function isAdmin()
00044  *  211:     function isMemberOfGroup($groupId)
00045  *  233:     function doesUserHaveAccess($row,$perms)
00046  *  250:     function isInWebMount($id,$readPerms='',$exitOnError=0)
00047  *  277:     function modAccess($conf,$exitOnError)
00048  *  328:     function getPagePermsClause($perms)
00049  *  367:     function calcPerms($row)
00050  *  405:     function isRTE()
00051  *  439:     function check($type,$value)
00052  *  456:     function checkAuthMode($table,$field,$value,$authMode)
00053  *  522:     function checkLanguageAccess($langValue)
00054  *  544:     function recordEditAccessInternals($table,$idOrRow,$newRecord=FALSE)
00055  *  619:     function isPSet($lCP,$table,$type='')
00056  *  636:     function mayMakeShortcut()
00057  *  650:     function workspaceCannotEditRecord($table,$recData)
00058  *  689:     function workspaceCannotEditOfflineVersion($table,$recData)
00059  *  712:     function workspaceAllowLiveRecordsInPID($pid, $table)
00060  *  733:     function workspaceCreateNewRecord($pid, $table)
00061  *  752:     function workspaceAllowAutoCreation($table,$id,$recpid)
00062  *  772:     function workspaceCheckStageForCurrent($stage)
00063  *  795:     function workspacePublishAccess($wsid)
00064  *  823:     function workspaceSwapAccess()
00065  *  835:     function workspaceVersioningTypeAccess($type)
00066  *  866:     function workspaceVersioningTypeGetClosest($type)
00067  *
00068  *            SECTION: Miscellaneous functions
00069  *  909:     function getTSConfig($objectString,$config='')
00070  *  935:     function getTSConfigVal($objectString)
00071  *  947:     function getTSConfigProp($objectString)
00072  *  959:     function inList($in_list,$item)
00073  *  970:     function returnWebmounts()
00074  *  980:     function returnFilemounts()
00075  *  997:     function jsConfirmation($bitmask)
00076  *
00077  *            SECTION: Authentication methods
00078  * 1035:     function fetchGroupData()
00079  * 1168:     function fetchGroups($grList,$idList='')
00080  * 1266:     function setCachedList($cList)
00081  * 1286:     function addFileMount($title, $altTitle, $path, $webspace, $type)
00082  * 1333:     function addTScomment($str)
00083  *
00084  *            SECTION: Workspaces
00085  * 1369:     function workspaceInit()
00086  * 1412:     function checkWorkspace($wsRec,$fields='uid,title,adminusers,members,reviewers,publish_access,stagechg_notification')
00087  * 1487:     function checkWorkspaceCurrent()
00088  * 1500:     function setWorkspace($workspaceId)
00089  * 1528:     function setWorkspacePreview($previewState)
00090  * 1538:     function getDefaultWorkspace()
00091  *
00092  *            SECTION: Logging
00093  * 1589:     function writelog($type,$action,$error,$details_nr,$details,$data,$tablename='',$recuid='',$recpid='',$event_pid=-1,$NEWid='',$userId=0)
00094  * 1621:     function simplelog($message, $extKey='', $error=0)
00095  * 1642:     function checkLogFailures($email, $secondsBack=3600, $max=3)
00096  *
00097  * TOTAL FUNCTIONS: 45
00098  * (This index is automatically created/updated by the extension "extdeveval")
00099  *
00100  */
00101 
00102 
00103 /**
00104  * Extension to class.t3lib_userauth.php; Authentication of users in TYPO3 Backend
00105  *
00106  * Actually this class is extended again by t3lib_beuserauth which is the actual backend user class that will be instantiated.
00107  * 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.
00108  *
00109  * @author  Kasper Skårhøj <kasperYYYY@typo3.com>
00110  * @package TYPO3
00111  * @subpackage t3lib
00112  */
00113 class t3lib_userAuthGroup extends t3lib_userAuth {
00114     var $usergroup_column = 'usergroup'; // Should be set to the usergroup-column (id-list) in the user-record
00115     var $usergroup_table = 'be_groups'; // The name of the group-table
00116 
00117         // internal
00118     var $groupData = array( // This array holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
00119         'filemounts' => array() // Filemounts are loaded here
00120     );
00121     var $workspace = -99; // User workspace. -99 is ERROR (none available), -1 is offline, 0 is online, >0 is custom workspaces.
00122     var $workspaceRec = array(); // Custom workspace record if any
00123 
00124     var $userGroups = array(); // This array will hold the groups that the user is a member of
00125     var $userGroupsUID = array(); // This array holds the uid's of the groups in the listed order
00126     var $groupList = ''; // This is $this->userGroupsUID imploded to a comma list... Will correspond to the 'usergroup_cached_list'
00127     var $dataLists = array( // Used internally to accumulate data for the user-group. DONT USE THIS EXTERNALLY! Use $this->groupData instead
00128         'webmount_list' => '',
00129         'filemount_list' => '',
00130         'fileoper_perms' => 0,
00131         'modList' => '',
00132         'tables_select' => '',
00133         'tables_modify' => '',
00134         'pagetypes_select' => '',
00135         'non_exclude_fields' => '',
00136         'explicit_allowdeny' => '',
00137         'allowed_languages' => '',
00138         'workspace_perms' => '',
00139         'custom_options' => '',
00140     );
00141     var $includeHierarchy = array(); // For debugging/display of order in which subgroups are included.
00142     var $includeGroupArray = array(); // List of group_id's in the order they are processed.
00143 
00144     var $OS = ''; // Set to 'WIN', if windows
00145     var $TSdataArray = array(); // Used to accumulate the TSconfig data of the user
00146     var $userTS_text = ''; // Contains the non-parsed user TSconfig
00147     var $userTS = array(); // Contains the parsed user TSconfig
00148     var $userTSUpdated = 0; // Set internally if the user TSconfig was parsed and needs to be cached.
00149     var $userTS_dontGetCached = 0; // Set this from outside if you want the user TSconfig to ALWAYS be parsed and not fetched from cache.
00150 
00151     var $RTE_errors = array(); // RTE availability errors collected.
00152     var $errorMsg = ''; // Contains last error message
00153 
00154     var $checkWorkspaceCurrent_cache = NULL; // Cache for checkWorkspaceCurrent()
00155 
00156 
00157     /************************************
00158      *
00159      * Permission checking functions:
00160      *
00161      ************************************/
00162 
00163     /**
00164      * Returns true if user is admin
00165      * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
00166      *
00167      * @return  boolean
00168      */
00169     function isAdmin() {
00170         return (($this->user['admin'] & 1) == 1);
00171     }
00172 
00173     /**
00174      * Returns true if the current user is a member of group $groupId
00175      * $groupId must be set. $this->groupList must contain groups
00176      * Will return true also if the user is a member of a group through subgroups.
00177      *
00178      * @param   integer     Group ID to look for in $this->groupList
00179      * @return  boolean
00180      */
00181     function isMemberOfGroup($groupId) {
00182         $groupId = intval($groupId);
00183         if ($this->groupList && $groupId) {
00184             return $this->inList($this->groupList, $groupId);
00185         }
00186     }
00187 
00188     /**
00189      * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
00190      *
00191      * Bits for permissions, see $perms variable:
00192      *
00193      *       1 - Show:  See/Copy page and the pagecontent.
00194      *       16- Edit pagecontent: Change/Add/Delete/Move pagecontent.
00195      *       2- Edit page: Change/Move the page, eg. change title, startdate, hidden.
00196      *       4- Delete page: Delete the page and pagecontent.
00197      *       8- New pages: Create new pages under the page.
00198      *
00199      * @param   array       $row is the pagerow for which the permissions is checked
00200      * @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.
00201      * @return  boolean     True or False upon evaluation
00202      */
00203     function doesUserHaveAccess($row, $perms) {
00204         $userPerms = $this->calcPerms($row);
00205         return ($userPerms & $perms) == $perms;
00206     }
00207 
00208     /**
00209      * Checks if the page id, $id, is found within the webmounts set up for the user.
00210      * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
00211      * 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.
00212      * 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
00213      * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
00214      *
00215      * @param   integer     Page ID to check
00216      * @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!)
00217      * @param   boolean     If set, then the function will exit with an error message.
00218      * @return  integer     The page UID of a page in the rootline that matched a mount point
00219      */
00220     function isInWebMount($id, $readPerms = '', $exitOnError = 0) {
00221         if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['lockBeUserToDBmounts'] || $this->isAdmin()) {
00222             return 1;
00223         }
00224         $id = intval($id);
00225 
00226             // Check if input id is an offline version page in which case we will map id to the online version:
00227         $checkRec = t3lib_beFUnc::getRecord('pages', $id, 'pid,t3ver_oid');
00228         if ($checkRec['pid'] == -1) {
00229             $id = intval($checkRec['t3ver_oid']);
00230         }
00231 
00232         if (!$readPerms) {
00233             $readPerms = $this->getPagePermsClause(1);
00234         }
00235         if ($id > 0) {
00236             $wM = $this->returnWebmounts();
00237             $rL = t3lib_BEfunc::BEgetRootLine($id, ' AND ' . $readPerms);
00238 
00239             foreach ($rL as $v) {
00240                 if ($v['uid'] && in_array($v['uid'], $wM)) {
00241                     return $v['uid'];
00242                 }
00243             }
00244         }
00245         if ($exitOnError) {
00246             throw new RuntimeException('Access Error: This page is not within your DB-mounts');
00247         }
00248     }
00249 
00250     /**
00251      * Checks access to a backend module with the $MCONF passed as first argument
00252      *
00253      * @param   array       $MCONF array of a backend module!
00254      * @param   boolean     If set, an array will issue an error message and exit.
00255      * @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
00256      */
00257     function modAccess($conf, $exitOnError) {
00258         if (!t3lib_BEfunc::isModuleSetInTBE_MODULES($conf['name'])) {
00259             if ($exitOnError) {
00260                 throw new RuntimeException('Fatal Error: This module "' . $conf['name'] . '" is not enabled in TBE_MODULES');
00261             }
00262             return FALSE;
00263         }
00264 
00265             // Workspaces check:
00266         if ($conf['workspaces']) {
00267             if (($this->workspace === 0 && t3lib_div::inList($conf['workspaces'], 'online')) ||
00268                 ($this->workspace === -1 && t3lib_div::inList($conf['workspaces'], 'offline')) ||
00269                 ($this->workspace > 0 && t3lib_div::inList($conf['workspaces'], 'custom'))) {
00270                 // ok, go on...
00271             } else {
00272                 if ($exitOnError) {
00273                     throw new RuntimeException('Workspace Error: This module "' . $conf['name'] . '" is not available under the current workspace');
00274                 }
00275                 return FALSE;
00276             }
00277         }
00278 
00279             // Returns true if conf[access] is not set at all or if the user is admin
00280         if (!$conf['access'] || $this->isAdmin()) {
00281             return TRUE;
00282         }
00283 
00284             // If $conf['access'] is set but not with 'admin' then we return true, if the module is found in the modList
00285         if (!strstr($conf['access'], 'admin') && $conf['name']) {
00286             $acs = $this->check('modules', $conf['name']);
00287         }
00288         if (!$acs && $exitOnError) {
00289             throw new RuntimeException('Access Error: You don\'t have access to this module.');
00290         } else {
00291             return $acs;
00292         }
00293     }
00294 
00295     /**
00296      * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
00297      * $perms is the "mask" used to select. Fx. if $perms is 1 then you'll get all pages that a user can actually see!
00298      *        2^0 = show (1)
00299      *       2^1 = edit (2)
00300      *       2^2 = delete (4)
00301      *       2^3 = new (8)
00302      * If the user is 'admin' " 1=1" is returned (no effect)
00303      * 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)
00304      * 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.
00305      *
00306      * @param   integer     Permission mask to use, see function description
00307      * @return  string      Part of where clause. Prefix " AND " to this.
00308      */
00309     function getPagePermsClause($perms) {
00310         global $TYPO3_CONF_VARS;
00311         if (is_array($this->user)) {
00312             if ($this->isAdmin()) {
00313                 return ' 1=1';
00314             }
00315 
00316             $perms = intval($perms); // Make sure it's integer.
00317             $str = ' (' .
00318                    '(pages.perms_everybody & ' . $perms . ' = ' . $perms . ')' . // Everybody
00319                    ' OR (pages.perms_userid = ' . $this->user['uid'] . ' AND pages.perms_user & ' . $perms . ' = ' . $perms . ')'; // User
00320             if ($this->groupList) {
00321                 $str .= ' OR (pages.perms_groupid in (' . $this->groupList . ') AND pages.perms_group & ' . $perms . ' = ' . $perms . ')'; // Group (if any is set)
00322             }
00323             $str .= ')';
00324 
00325                 // ****************
00326                 // getPagePermsClause-HOOK
00327                 // ****************
00328             if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'])) {
00329 
00330                 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'] as $_funcRef) {
00331                     $_params = array('currentClause' => $str, 'perms' => $perms);
00332                     $str = t3lib_div::callUserFunction($_funcRef, $_params, $this);
00333                 }
00334             }
00335 
00336             return $str;
00337         } else {
00338             return ' 1=0';
00339         }
00340     }
00341 
00342     /**
00343      * Returns a combined binary representation of the current users permissions for the page-record, $row.
00344      * 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
00345      * If the user is admin, 31 is returned (full permissions for all five flags)
00346      *
00347      * @param   array       Input page row with all perms_* fields available.
00348      * @return  integer     Bitwise representation of the users permissions in relation to input page row, $row
00349      */
00350     function calcPerms($row) {
00351         global $TYPO3_CONF_VARS;
00352         if ($this->isAdmin()) {
00353             return 31;
00354         } // Return 31 for admin users.
00355 
00356         $out = 0;
00357         if (isset($row['perms_userid']) && isset($row['perms_user']) && isset($row['perms_groupid']) && isset($row['perms_group']) && isset($row['perms_everybody']) && isset($this->groupList)) {
00358             if ($this->user['uid'] == $row['perms_userid']) {
00359                 $out |= $row['perms_user'];
00360             }
00361             if ($this->isMemberOfGroup($row['perms_groupid'])) {
00362                 $out |= $row['perms_group'];
00363             }
00364             $out |= $row['perms_everybody'];
00365         }
00366 
00367             // ****************
00368             // CALCPERMS hook
00369             // ****************
00370         if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'])) {
00371             foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'] as $_funcRef) {
00372                 $_params = array(
00373                     'row' => $row,
00374                     'outputPermissions' => $out
00375                 );
00376                 $out = t3lib_div::callUserFunction($_funcRef, $_params, $this);
00377             }
00378         }
00379 
00380         return $out;
00381     }
00382 
00383     /**
00384      * Returns true if the RTE (Rich Text Editor) can be enabled for the user
00385      * 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]
00386      * The reasons for a FALSE return can be found in $this->RTE_errors
00387      *
00388      * @return  boolean
00389      */
00390     function isRTE() {
00391         global $CLIENT;
00392 
00393             // Start:
00394         $this->RTE_errors = array();
00395         if (!$this->uc['edit_RTE']) {
00396             $this->RTE_errors[] = 'RTE is not enabled for user!';
00397         }
00398         if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['RTEenabled']) {
00399             $this->RTE_errors[] = 'RTE is not enabled in $TYPO3_CONF_VARS["BE"]["RTEenabled"]';
00400         }
00401 
00402 
00403             // Acquire RTE object:
00404         $RTE = t3lib_BEfunc::RTEgetObj();
00405         if (!is_object($RTE)) {
00406             $this->RTE_errors = array_merge($this->RTE_errors, $RTE);
00407         }
00408 
00409         if (!count($this->RTE_errors)) {
00410             return TRUE;
00411         } else {
00412             return FALSE;
00413         }
00414     }
00415 
00416     /**
00417      * Returns true if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
00418      * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
00419      * If user is admin true is also returned
00420      * Please see the document Inside TYPO3 for examples.
00421      *
00422      * @param   string      The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules"
00423      * @param   string      String to search for in the groupData-list
00424      * @return  boolean     True if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
00425      */
00426     function check($type, $value) {
00427         if (isset($this->groupData[$type])) {
00428             if ($this->isAdmin() || $this->inList($this->groupData[$type], $value)) {
00429                 return TRUE;
00430             }
00431         }
00432         return FALSE;
00433     }
00434 
00435     /**
00436      * Checking the authMode of a select field with authMode set
00437      *
00438      * @param   string      Table name
00439      * @param   string      Field name (must be configured in TCA and of type "select" with authMode set!)
00440      * @param   string      Value to evaluation (single value, must not contain any of the chars ":,|")
00441      * @param   string      Auth mode keyword (explicitAllow, explicitDeny, individual)
00442      * @return  boolean     True or false whether access is granted or not.
00443      */
00444     function checkAuthMode($table, $field, $value, $authMode) {
00445         global $TCA;
00446 
00447             // Admin users can do anything:
00448         if ($this->isAdmin()) {
00449             return TRUE;
00450         }
00451 
00452             // Allow all blank values:
00453         if (!strcmp($value, '')) {
00454             return TRUE;
00455         }
00456 
00457             // Certain characters are not allowed in the value
00458         if (preg_match('/[:|,]/', $value)) {
00459             return FALSE;
00460         }
00461 
00462             // Initialize:
00463         $testValue = $table . ':' . $field . ':' . $value;
00464         $out = TRUE;
00465 
00466             // Checking value:
00467         switch ((string) $authMode) {
00468             case 'explicitAllow':
00469                 if (!$this->inList($this->groupData['explicit_allowdeny'], $testValue . ':ALLOW')) {
00470                     $out = FALSE;
00471                 }
00472             break;
00473             case 'explicitDeny':
00474                 if ($this->inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
00475                     $out = FALSE;
00476                 }
00477             break;
00478             case 'individual':
00479                 t3lib_div::loadTCA($table);
00480                 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field])) {
00481                     $items = $TCA[$table]['columns'][$field]['config']['items'];
00482                     if (is_array($items)) {
00483                         foreach ($items as $iCfg) {
00484                             if (!strcmp($iCfg[1], $value) && $iCfg[4]) {
00485                                 switch ((string) $iCfg[4]) {
00486                                     case 'EXPL_ALLOW':
00487                                         if (!$this->inList($this->groupData['explicit_allowdeny'], $testValue . ':ALLOW')) {
00488                                             $out = FALSE;
00489                                         }
00490                                     break;
00491                                     case 'EXPL_DENY':
00492                                         if ($this->inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
00493                                             $out = FALSE;
00494                                         }
00495                                     break;
00496                                 }
00497                             break;
00498                             }
00499                         }
00500                     }
00501                 }
00502             break;
00503         }
00504 
00505         return $out;
00506     }
00507 
00508     /**
00509      * Checking if a language value (-1, 0 and >0 for sys_language records) is allowed to be edited by the user.
00510      *
00511      * @param   integer     Language value to evaluate
00512      * @return  boolean     Returns true if the language value is allowed, otherwise false.
00513      */
00514     function checkLanguageAccess($langValue) {
00515         if (strcmp(trim($this->groupData['allowed_languages']), '')) { // The users language list must be non-blank - otherwise all languages are allowed.
00516             $langValue = intval($langValue);
00517             if ($langValue != -1 && !$this->check('allowed_languages', $langValue)) { // Language must either be explicitly allowed OR the lang Value be "-1" (all languages)
00518                 return FALSE;
00519             }
00520         }
00521         return TRUE;
00522     }
00523 
00524     /**
00525      * Check if user has access to all existing localizations for a certain record
00526      *
00527      * @param string     the table
00528      * @param array  the current record
00529      * @return boolean
00530      */
00531     function checkFullLanguagesAccess($table, $record) {
00532         $recordLocalizationAccess = $this->checkLanguageAccess(0);
00533         if ($recordLocalizationAccess
00534             && (
00535                         t3lib_BEfunc::isTableLocalizable($table)
00536                         || isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])
00537                 )
00538         ) {
00539 
00540             if (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])) {
00541                 $l10nTable = $GLOBALS['TCA'][$table]['ctrl']['transForeignTable'];
00542                 $pointerField = $GLOBALS['TCA'][$l10nTable]['ctrl']['transOrigPointerField'];
00543                 $pointerValue = $record['uid'];
00544             } else {
00545                 $l10nTable = $table;
00546                 $pointerField = $GLOBALS['TCA'][$l10nTable]['ctrl']['transOrigPointerField'];
00547                 $pointerValue = $record[$pointerField] > 0 ? $record[$pointerField] : $record['uid'];
00548             }
00549 
00550             $recordLocalizations = t3lib_BEfunc::getRecordsByField(
00551                 $l10nTable,
00552                 $pointerField,
00553                 $pointerValue,
00554                 '',
00555                 '',
00556                 '',
00557                 '1'
00558             );
00559 
00560             if (is_array($recordLocalizations)) {
00561                 foreach ($recordLocalizations as $localization) {
00562                     $recordLocalizationAccess = $recordLocalizationAccess
00563                                                 && $this->checkLanguageAccess($localization[$GLOBALS['TCA'][$l10nTable]['ctrl']['languageField']]);
00564                     if (!$recordLocalizationAccess) {
00565                         break;
00566                     }
00567                 }
00568             }
00569 
00570         }
00571         return $recordLocalizationAccess;
00572     }
00573 
00574     /**
00575      * Checking if a user has editing access to a record from a $TCA table.
00576      * 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.
00577      * For instance languages settings, authMode selector boxes are evaluated (and maybe more in the future).
00578      * It will check for workspace dependent access.
00579      * The function takes an ID (integer) or row (array) as second argument.
00580      *
00581      * @param   string      Table name
00582      * @param   mixed       If integer, then this is the ID of the record. If Array this just represents fields in the record.
00583      * @param   boolean     Set, if testing a new (non-existing) record array. Will disable certain checks that doesn't make much sense in that context.
00584      * @param   boolean     Set, if testing a deleted record array.
00585      * @param   boolean     Set, whenever access to all translations of the record is required
00586      * @return  boolean     True if OK, otherwise false
00587      */
00588     function recordEditAccessInternals($table, $idOrRow, $newRecord = FALSE, $deletedRecord = FALSE, $checkFullLanguageAccess = FALSE) {
00589         global $TCA;
00590 
00591         if (isset($TCA[$table])) {
00592             t3lib_div::loadTCA($table);
00593 
00594                 // Always return true for Admin users.
00595             if ($this->isAdmin()) {
00596                 return TRUE;
00597             }
00598 
00599                 // Fetching the record if the $idOrRow variable was not an array on input:
00600             if (!is_array($idOrRow)) {
00601                 if ($deletedRecord) {
00602                     $idOrRow = t3lib_BEfunc::getRecord($table, $idOrRow, '*', '', FALSE);
00603                 } else {
00604                     $idOrRow = t3lib_BEfunc::getRecord($table, $idOrRow);
00605                 }
00606                 if (!is_array($idOrRow)) {
00607                     $this->errorMsg = 'ERROR: Record could not be fetched.';
00608                     return FALSE;
00609                 }
00610             }
00611 
00612                 // Checking languages:
00613             if ($TCA[$table]['ctrl']['languageField']) {
00614                 if (isset($idOrRow[$TCA[$table]['ctrl']['languageField']])) { // Language field must be found in input row - otherwise it does not make sense.
00615                     if (!$this->checkLanguageAccess($idOrRow[$TCA[$table]['ctrl']['languageField']])) {
00616                         $this->errorMsg = 'ERROR: Language was not allowed.';
00617                         return FALSE;
00618                     } elseif ($checkFullLanguageAccess && $idOrRow[$TCA[$table]['ctrl']['languageField']] == 0 && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
00619                         $this->errorMsg = 'ERROR: Related/affected language was not allowed.';
00620                         return FALSE;
00621                     }
00622                 } else {
00623                     $this->errorMsg = 'ERROR: The "languageField" field named "' . $TCA[$table]['ctrl']['languageField'] . '" was not found in testing record!';
00624                     return FALSE;
00625                 }
00626             } elseif (isset($TCA[$table]['ctrl']['transForeignTable']) && $checkFullLanguageAccess && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
00627                 return FALSE;
00628             }
00629 
00630                 // Checking authMode fields:
00631             if (is_array($TCA[$table]['columns'])) {
00632                 foreach ($TCA[$table]['columns'] as $fieldName => $fieldValue) {
00633                     if (isset($idOrRow[$fieldName])) {
00634                         if ($fieldValue['config']['type'] == 'select' && $fieldValue['config']['authMode'] && !strcmp($fieldValue['config']['authMode_enforce'], 'strict')) {
00635                             if (!$this->checkAuthMode($table, $fieldName, $idOrRow[$fieldName], $fieldValue['config']['authMode'])) {
00636                                 $this->errorMsg = 'ERROR: authMode "' . $fieldValue['config']['authMode'] . '" failed for field "' . $fieldName . '" with value "' . $idOrRow[$fieldName] . '" evaluated';
00637                                 return FALSE;
00638                             }
00639                         }
00640                     }
00641                 }
00642             }
00643 
00644                 // Checking "editlock" feature (doesn't apply to new records)
00645             if (!$newRecord && $TCA[$table]['ctrl']['editlock']) {
00646                 if (isset($idOrRow[$TCA[$table]['ctrl']['editlock']])) {
00647                     if ($idOrRow[$TCA[$table]['ctrl']['editlock']]) {
00648                         $this->errorMsg = 'ERROR: Record was locked for editing. Only admin users can change this state.';
00649                         return FALSE;
00650                     }
00651                 } else {
00652                     $this->errorMsg = 'ERROR: The "editLock" field named "' . $TCA[$table]['ctrl']['editlock'] . '" was not found in testing record!';
00653                     return FALSE;
00654                 }
00655             }
00656 
00657                 // Checking record permissions
00658                 // THIS is where we can include a check for "perms_" fields for other records than pages...
00659 
00660                 // Process any hooks
00661             if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'])) {
00662                 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'] as $funcRef) {
00663                     $params = array(
00664                         'table' => $table,
00665                         'idOrRow' => $idOrRow,
00666                         'newRecord' => $newRecord
00667                     );
00668                     if (!t3lib_div::callUserFunction($funcRef, $params, $this)) {
00669                         return FALSE;
00670                     }
00671                 }
00672             }
00673 
00674                 // Finally, return true if all is well.
00675             return TRUE;
00676         }
00677     }
00678 
00679     /**
00680      * Checks a type of permission against the compiled permission integer, $compiledPermissions, and in relation to table, $tableName
00681      *
00682      * @param   integer     $compiledPermissions could typically be the "compiled permissions" integer returned by ->calcPerms
00683      * @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)
00684      * @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)
00685      * @return  boolean
00686      * @access public (used by typo3/alt_clickmenu.php)
00687      */
00688     public function isPSet($compiledPermissions, $tableName, $actionType = '') {
00689         if ($this->isAdmin()) {
00690             $result = TRUE;
00691         }
00692         elseif ($tableName == 'pages') {
00693             switch ($actionType) {
00694                 case 'edit':
00695                     $result = ($compiledPermissions & 2) !== 0;
00696                 break;
00697                 case 'new':
00698                         // Create new page OR page content
00699                     $result = ($compiledPermissions & (8 + 16)) !== 0;
00700                 break;
00701                 case 'delete':
00702                     $result = ($compiledPermissions & 4) !== 0;
00703                 break;
00704                 case 'editcontent':
00705                     $result = ($compiledPermissions & 16) !== 0;
00706                 break;
00707                 default:
00708                     $result = FALSE;
00709             }
00710         } else {
00711             $result = ($compiledPermissions & 16) !== 0;
00712         }
00713         return $result;
00714     }
00715 
00716     /**
00717      * Returns true if the BE_USER is allowed to *create* shortcuts in the backend modules
00718      *
00719      * @return  boolean
00720      */
00721     function mayMakeShortcut() {
00722             // "Shortcuts" have been renamed to "Bookmarks"
00723             // @deprecated remove shortcuts code in TYPO3 4.7
00724         return ($this->getTSConfigVal('options.enableShortcuts')
00725                 || $this->getTSConfigVal('options.enableBookmarks'))
00726                && (!$this->getTSConfigVal('options.mayNotCreateEditShortcuts')
00727                    && !$this->getTSConfigVal('options.mayNotCreateEditBookmarks'));
00728     }
00729 
00730     /**
00731      * Checking if editing of an existing record is allowed in current workspace if that is offline.
00732      * Rules for editing in offline mode:
00733      *       - record supports versioning and is an offline version from workspace and has the corrent stage
00734      *       - 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
00735      *
00736      * @param   string      Table of record
00737      * @param   array       Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
00738      * @return  string      String error code, telling the failure state. FALSE=All ok
00739      */
00740     function workspaceCannotEditRecord($table, $recData) {
00741 
00742         if ($this->workspace !== 0) { // Only test offline spaces:
00743 
00744             if (!is_array($recData)) {
00745                 $recData = t3lib_BEfunc::getRecord($table, $recData, 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : ''));
00746             }
00747 
00748             if (is_array($recData)) {
00749                 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.
00750                     if (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) { // No versioning, basic error, inconsistency even! Such records should not have a pid of -1!
00751                         return 'Versioning disabled for table';
00752                     } elseif ((int) $recData['t3ver_wsid'] !== $this->workspace) { // So does workspace match?
00753                         return 'Workspace ID of record didn\'t match current workspace';
00754                     } else { // So what about the stage of the version, does that allow editing for this user?
00755                         return $this->workspaceCheckStageForCurrent($recData['t3ver_stage']) ? FALSE : 'Record stage "' . $recData['t3ver_stage'] . '" and users access level did not allow for editing';
00756                     }
00757                 } else { // We are testing a "live" record:
00758                     if ($res = $this->workspaceAllowLiveRecordsInPID($recData['pid'], $table)) { // For "Live" records, check that PID for table allows editing
00759                         // Live records are OK in this branch, but what about the stage of branch point, if any:
00760                         return $res > 0 ? FALSE : 'Stage for versioning root point and users access level did not allow for editing'; // OK
00761                     } else { // If not offline and not in versionized branch, output error:
00762                         return 'Online record was not in versionized branch!';
00763                     }
00764                 }
00765             } else {
00766                 return 'No record';
00767             }
00768         } else {
00769             return FALSE; // OK because workspace is 0
00770         }
00771     }
00772 
00773     /**
00774      * Evaluates if a user is allowed to edit the offline version
00775      *
00776      * @param   string      Table of record
00777      * @param   array       Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
00778      * @return  string      String error code, telling the failure state. FALSE=All ok
00779      * @see workspaceCannotEditRecord()
00780      */
00781     function workspaceCannotEditOfflineVersion($table, $recData) {
00782         if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
00783 
00784             if (!is_array($recData)) {
00785                 $recData = t3lib_BEfunc::getRecord($table, $recData, 'uid,pid,t3ver_wsid,t3ver_stage');
00786             }
00787             if (is_array($recData)) {
00788                 if ((int) $recData['pid'] === -1) {
00789                     return $this->workspaceCannotEditRecord($table, $recData);
00790                 } else {
00791                     return 'Not an offline version';
00792                 }
00793             } else {
00794                 return 'No record';
00795             }
00796         } else {
00797             return 'Table does not support versioning.';
00798         }
00799     }
00800 
00801     /**
00802      * Check if "live" records from $table may be created or edited in this PID.
00803      * If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
00804      * 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!
00805      *
00806      * @param   integer     PID value to check for.
00807      * @param   string      Table name
00808      * @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.
00809      */
00810     function workspaceAllowLiveRecordsInPID($pid, $table) {
00811 
00812             // Always for Live workspace AND if live-edit is enabled and tables are completely without versioning it is ok as well.
00813         if ($this->workspace === 0 || ($this->workspaceRec['live_edit'] && !$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) || $GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']) {
00814             return 2; // OK to create for this table.
00815         } 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.
00816                 // Now, check what the stage of that "page" or "branch" version type is:
00817             $stage = t3lib_BEfunc::isPidInVersionizedBranch($pid, $table, TRUE);
00818             return $this->workspaceCheckStageForCurrent($stage) ? 1 : -1;
00819         } else {
00820             return FALSE; // If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
00821         }
00822     }
00823 
00824     /**
00825      * Evaluates if a record from $table can be created in $pid
00826      *
00827      * @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!
00828      * @param   string      Table name
00829      * @return  boolean     TRUE if OK.
00830      */
00831     function workspaceCreateNewRecord($pid, $table) {
00832         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
00833             if ($res < 0) {
00834                 return FALSE; // Stage for versioning root point and users access level did not allow for editing
00835             }
00836         } elseif (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) { // So, if no live records were allowed, we have to create a new version of this record:
00837             return FALSE;
00838         }
00839         return TRUE;
00840     }
00841 
00842     /**
00843      * Evaluates if auto creation of a version of a record is allowed.
00844      *
00845      * @param   string      Table of the record
00846      * @param   integer     UID of record
00847      * @param   integer     PID of record
00848      * @return  boolean     TRUE if ok.
00849      */
00850     function workspaceAllowAutoCreation($table, $id, $recpid) {
00851             // 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.
00852         if ($this->workspace !== 0 // Only in draft workspaces
00853             && !$this->workspaceRec['disable_autocreate'] // Auto-creation must not be disabled.
00854             && $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] // Table must be versionizable
00855             && $recpid >= 0 // The PID of the record must NOT be -1 or less (would indicate that it already was a version!)
00856             && !t3lib_BEfunc::getWorkspaceVersionOfRecord($this->workspace, $table, $id, 'uid') // There must be no existing version of this record in workspace.
00857             && !t3lib_BEfunc::isPidInVersionizedBranch($recpid, $table)) { // PID must NOT be in a versionized branch either
00858             return TRUE;
00859         } else if ($this->workspaceRec['disable_autocreate']) {
00860             t3lib_div::deprecationLog('Usage of disable_autocreate feature is deprecated since 4.5.');
00861         }
00862     }
00863 
00864     /**
00865      * Checks if an element stage allows access for the user in the current workspace
00866      * In workspaces 0 (Live) and -1 (Default draft) access is always granted for any stage.
00867      * Admins are always allowed.
00868      * An option for custom workspaces allows members to also edit when the stage is "Review"
00869      *
00870      * @param   integer     Stage id from an element: -1,0 = editing, 1 = reviewer, >1 = owner
00871      * @return  boolean     TRUE if user is allowed access
00872      */
00873     function workspaceCheckStageForCurrent($stage) {
00874         $stage = intval($stage);
00875         if ($this->isAdmin()) {
00876             return TRUE;
00877         }
00878 
00879         if ($this->workspace > 0 && t3lib_extMgm::isLoaded('workspaces')) {
00880             $stat = $this->checkWorkspaceCurrent();
00881 
00882                 // Check if custom staging is activated
00883             $workspaceRec = t3lib_BEfunc::getRecord('sys_workspace', $stat['uid']);
00884             if ($workspaceRec['custom_stages'] > 0 && $stage !== 0 && $stage !== '-10') {
00885 
00886                     // Get custom stage record
00887                 $workspaceStageRec = t3lib_BEfunc::getRecord('sys_workspace_stage', $stage);
00888                     // Check if the user is responsible for the current stage
00889                 if ((t3lib_div::inList($workspaceStageRec['responsible_persons'], 'be_users_' . $this->user['uid'])
00890                      && $stat['_ACCESS'] === 'member')
00891                     || $stat['_ACCESS'] === 'owner') {
00892                     return TRUE;
00893                 }
00894 
00895                     // Check if the user is in a group which is responsible for the current stage
00896                 foreach ($this->userGroupsUID as $groupUid) {
00897                     if ((t3lib_div::inList($workspaceStageRec['responsible_persons'], 'be_groups_' . $groupUid)
00898                          && $stat['_ACCESS'] === 'member')
00899                         || $stat['_ACCESS'] === 'owner') {
00900                         return TRUE;
00901                     }
00902                 }
00903                 // only owner is allowed to change records which are "ready to publish"
00904             } elseif ($stage == '-10' || $stage == '-20') {
00905                 if ($stat['_ACCESS'] === 'owner') {
00906                     return TRUE;
00907                 } else {
00908                     return FALSE;
00909                 }
00910             } else {
00911                 $memberStageLimit = $this->workspaceRec['review_stage_edit'] ? 1 : 0;
00912                 if (($stage <= $memberStageLimit && $stat['_ACCESS'] === 'member')
00913                     || ($stage <= 1 && $stat['_ACCESS'] === 'reviewer')
00914                     || $stat['_ACCESS'] === 'owner') {
00915                     return TRUE;
00916                 }
00917             }
00918         } else {
00919             return TRUE;
00920         } // Always OK for live and draft workspaces.
00921     }
00922 
00923     /**
00924      * Returns TRUE if the user has access to publish content from the workspace ID given.
00925      * Admin-users are always granted access to do this
00926      * If the workspace ID is 0 (live) all users have access also
00927      * If -1 (draft workspace) TRUE is returned if the user has access to the Live workspace
00928      * For custom workspaces it depends on whether the user is owner OR like with draft workspace if the user has access to Live workspace.
00929      *
00930      * @param   integer     Workspace UID; -1,0,1+
00931      * @return  boolean     Returns TRUE if the user has access to publish content from the workspace ID given.
00932      */
00933     function workspacePublishAccess($wsid) {
00934         if ($this->isAdmin()) {
00935             return TRUE;
00936         }
00937 
00938             // If no access to workspace, of course you cannot publish!
00939         $retVal = FALSE;
00940 
00941         $wsAccess = $this->checkWorkspace($wsid);
00942         if ($wsAccess) {
00943             switch ($wsAccess['uid']) {
00944                 case 0: // Live workspace
00945                     $retVal = TRUE; // If access to Live workspace, no problem.
00946                 break;
00947                 case -1: // Default draft workspace
00948                     $retVal = $this->checkWorkspace(0) ? TRUE : FALSE; // If access to Live workspace, no problem.
00949                 break;
00950                 default: // Custom workspace
00951                     $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.
00952                 break;
00953             }
00954         }
00955         return $retVal;
00956     }
00957 
00958     /**
00959      * Workspace swap-mode access?
00960      *
00961      * @return  boolean     Returns TRUE if records can be swapped in the current workspace, otherwise false
00962      */
00963     function workspaceSwapAccess() {
00964         if ($this->workspace > 0 && (int) $this->workspaceRec['swap_modes'] === 2) {
00965             return FALSE;
00966         } else {
00967             return TRUE;
00968         }
00969     }
00970 
00971     /**
00972      * Workspace Versioning type access. Check wether the requsted type of versioning (element/page/branch) is allowd in current workspace
00973      *   (element/pages/branches type of versioning can/could be set on custom workspaces on filed "vtype")
00974      *
00975      * @todo workspacecleanup: this seems mostly obsolete and should be removed
00976      * @param   integer     Versioning type to evaluation: -1, 0, >1
00977      *                      0 = page (deprecated)
00978      *                      -1 = element
00979      *                      >1 = branch (deprecated), indicating the "nesting" level
00980      * @return  boolean     TRUE if OK
00981      */
00982     function workspaceVersioningTypeAccess($type) {
00983         $retVal = FALSE;
00984 
00985         $type = t3lib_div::intInRange($type, -1);
00986 
00987             // Check if only element versioning is allowed:
00988         if ($GLOBALS['TYPO3_CONF_VARS']['BE']['elementVersioningOnly'] && $type != -1) {
00989             return FALSE;
00990         }
00991 
00992         if ($this->workspace > 0 && !$this->isAdmin()) {
00993             $stat = $this->checkWorkspaceCurrent();
00994             if ($stat['_ACCESS'] !== 'owner') {
00995 
00996                 switch ((int) $type) {
00997                     case -1:
00998                         $retVal = $this->workspaceRec['vtypes'] & 1 ? FALSE : TRUE;
00999                     break;
01000                     case 0:
01001                         $retVal = $this->workspaceRec['vtypes'] & 2 ? FALSE : TRUE;
01002                     break;
01003                     default:
01004                         $retVal = $this->workspaceRec['vtypes'] & 4 ? FALSE : TRUE;
01005                     break;
01006                 }
01007             } else {
01008                 $retVal = TRUE;
01009             }
01010         } else {
01011             $retVal = TRUE;
01012         }
01013 
01014         return $retVal;
01015     }
01016 
01017     /**
01018      * Finding "closest" versioning type, used for creation of new records.
01019      *
01020      * @see workspaceVersioningTypeAccess() for hints on $type
01021      * @param   integer     Versioning type to evaluation: -1, 0, >1
01022      * @return  integer     Returning versioning type
01023      */
01024     function workspaceVersioningTypeGetClosest($type) {
01025         $type = t3lib_div::intInRange($type, -1);
01026 
01027         if ($this->workspace > 0) {
01028             switch ((int) $type) {
01029                 case -1:
01030                     $type = -1;
01031                 break;
01032                 case 0:
01033                     $type = $this->workspaceVersioningTypeAccess($type) ? $type : -1;
01034                 break;
01035                 default:
01036                     $type = $this->workspaceVersioningTypeAccess($type) ? $type : ($this->workspaceVersioningTypeAccess(0) ? 0 : -1);
01037                 break;
01038             }
01039         }
01040         return $type;
01041     }
01042 
01043 
01044     /*************************************
01045      *
01046      * Miscellaneous functions
01047      *
01048      *************************************/
01049 
01050     /**
01051      * Returns the value/properties of a TS-object as given by $objectString, eg. 'options.dontMountAdminMounts'
01052      * Nice (general!) function for returning a part of a TypoScript array!
01053      *
01054      * @param   string      Pointer to an "object" in the TypoScript array, fx. 'options.dontMountAdminMounts'
01055      * @param   array       Optional TSconfig array: If array, then this is used and not $this->userTS. If not array, $this->userTS is used.
01056      * @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.
01057      * @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.
01058      */
01059     function getTSConfig($objectString, $config = '') {
01060         if (!is_array($config)) {
01061             $config = $this->userTS; // Getting Root-ts if not sent
01062         }
01063         $TSConf = array();
01064         $parts = explode('.', $objectString, 2);
01065         $key = $parts[0];
01066         if (trim($key)) {
01067             if (count($parts) > 1 && trim($parts[1])) {
01068                     // Go on, get the next level
01069                 if (is_array($config[$key . '.'])) {
01070                     $TSConf = $this->getTSConfig($parts[1], $config[$key . '.']);
01071                 }
01072             } else {
01073                 $TSConf['value'] = $config[$key];
01074                 $TSConf['properties'] = $config[$key . '.'];
01075             }
01076         }
01077         return $TSConf;
01078     }
01079 
01080     /**
01081      * Returns the "value" of the $objectString from the BE_USERS "User TSconfig" array
01082      *
01083      * @param   string      Object string, eg. "somestring.someproperty.somesubproperty"
01084      * @return  string      The value for that object string (object path)
01085      * @see getTSConfig()
01086      */
01087     function getTSConfigVal($objectString) {
01088         $TSConf = $this->getTSConfig($objectString);
01089         return $TSConf['value'];
01090     }
01091 
01092     /**
01093      * Returns the "properties" of the $objectString from the BE_USERS "User TSconfig" array
01094      *
01095      * @param   string      Object string, eg. "somestring.someproperty.somesubproperty"
01096      * @return  array       The properties for that object string (object path) - if any
01097      * @see getTSConfig()
01098      */
01099     function getTSConfigProp($objectString) {
01100         $TSConf = $this->getTSConfig($objectString);
01101         return $TSConf['properties'];
01102     }
01103 
01104     /**
01105      * Returns true if $item is in $in_list
01106      *
01107      * @param   string      Comma list with items, no spaces between items!
01108      * @param   string      The string to find in the list of items
01109      * @return  string      Boolean
01110      */
01111     function inList($in_list, $item) {
01112         return strstr(',' . $in_list . ',', ',' . $item . ',');
01113     }
01114 
01115     /**
01116      * Returns an array with the webmounts.
01117      * If no webmounts, and empty array is returned.
01118      * 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.
01119      *
01120      * @return  array
01121      */
01122     function returnWebmounts() {
01123         return (string) ($this->groupData['webmounts']) != '' ? explode(',', $this->groupData['webmounts']) : array();
01124     }
01125 
01126     /**
01127      * Returns an array with the filemounts for the user. Each filemount is represented with an array of a "name", "path" and "type".
01128      * If no filemounts an empty array is returned.
01129      *
01130      * @return  array
01131      */
01132     function returnFilemounts() {
01133         return $this->groupData['filemounts'];
01134     }
01135 
01136     /**
01137      * Returns an integer bitmask that represents the permissions for file operations.
01138      * Permissions of the user and groups the user is a member of were combined by a logical OR.
01139      *
01140      * Meaning of each bit:
01141      *   1 - Files: Upload,Copy,Move,Delete,Rename
01142      *   2 - Files: Unzip
01143      *   4 - Directory: Move,Delete,Rename,New
01144      *   8 - Directory: Copy
01145      *   16 - Directory: Delete recursively (rm -Rf)
01146      *
01147      * @return  integer     File operation permission bitmask
01148      */
01149     public function getFileoperationPermissions() {
01150         if ($this->isAdmin()) {
01151             return 31;
01152         } else {
01153             return $this->groupData['fileoper_perms'];
01154         }
01155     }
01156 
01157     /**
01158      * Returns true or false, depending if an alert popup (a javascript confirmation) should be shown
01159      * call like $GLOBALS['BE_USER']->jsConfirmation($BITMASK)
01160      *
01161      *  1 - typeChange
01162      *  2 - copy/move/paste
01163      *  4 - delete
01164      *  8 - frontend editing
01165      *  128 - other (not used yet)
01166      *
01167      * @param   integer   Bitmask
01168      * @return  boolean     true if the confirmation should be shown
01169      */
01170     function jsConfirmation($bitmask) {
01171         $alertPopup = $GLOBALS['BE_USER']->getTSConfig('options.alertPopups');
01172         if (empty($alertPopup['value'])) {
01173             $alertPopup = 255; // default: show all warnings
01174         } else {
01175             $alertPopup = (int) $alertPopup['value'];
01176         }
01177         if (($alertPopup & $bitmask) == $bitmask) { // show confirmation
01178             return 1;
01179         } else { // don't show confirmation
01180             return 0;
01181         }
01182     }
01183 
01184 
01185     /*************************************
01186      *
01187      * Authentication methods
01188      *
01189      *************************************/
01190 
01191 
01192     /**
01193      * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
01194      * This method is called by ->backendCheckLogin() (from extending class t3lib_beuserauth) if the backend user login has verified OK.
01195      * Generally this is required initialization of a backend user.
01196      *
01197      * @return  void
01198      * @access private
01199      * @see t3lib_TSparser
01200      */
01201     function fetchGroupData() {
01202         if ($this->user['uid']) {
01203 
01204                 // Get lists for the be_user record and set them as default/primary values.
01205             $this->dataLists['modList'] = $this->user['userMods']; // Enabled Backend Modules
01206             $this->dataLists['allowed_languages'] = $this->user['allowed_languages']; // Add Allowed Languages
01207             $this->dataLists['workspace_perms'] = $this->user['workspace_perms']; // Set user value for workspace permissions.
01208             $this->dataLists['webmount_list'] = $this->user['db_mountpoints']; // Database mountpoints
01209             $this->dataLists['filemount_list'] = $this->user['file_mountpoints']; // File mountpoints
01210             $this->dataLists['fileoper_perms'] = (int) $this->user['fileoper_perms']; // Fileoperation permissions
01211 
01212                 // Setting default User TSconfig:
01213             $this->TSdataArray[] = $this->addTScomment('From $GLOBALS["TYPO3_CONF_VARS"]["BE"]["defaultUserTSconfig"]:') .
01214                                    $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
01215 
01216                 // Default TSconfig for admin-users
01217             if ($this->isAdmin()) {
01218                 $this->TSdataArray[] = $this->addTScomment('"admin" user presets:') . '
01219                     admPanel.enable.all = 1
01220                 ';
01221                 if (t3lib_extMgm::isLoaded('sys_note')) {
01222                     $this->TSdataArray[] = '
01223                             // Setting defaults for sys_note author / email...
01224                         TCAdefaults.sys_note.author = ' . $this->user['realName'] . '
01225                         TCAdefaults.sys_note.email = ' . $this->user['email'] . '
01226                     ';
01227                 }
01228             }
01229 
01230                 // FILE MOUNTS:
01231                 // Admin users has the base fileadmin dir mounted
01232             if ($this->isAdmin() && $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
01233                 $this->addFileMount($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '', PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], 0, '');
01234             }
01235 
01236                 // If userHomePath is set, we attempt to mount it
01237             if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
01238                     // First try and mount with [uid]_[username]
01239                 $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');
01240                 if (!$didMount) {
01241                         // If that failed, try and mount with only [uid]
01242                     $this->addFileMount($this->user['username'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'] . $this->user['uid'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'], 0, 'user');
01243                 }
01244             }
01245 
01246                 // BE_GROUPS:
01247                 // Get the groups...
01248             #           $grList = t3lib_BEfunc::getSQLselectableList($this->user[$this->usergroup_column],$this->usergroup_table,$this->usergroup_table);
01249             $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.
01250             if ($grList) {
01251                     // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc. Refer to fetchGroups() function.
01252                 $this->fetchGroups($grList);
01253             }
01254 
01255                 // Add the TSconfig for this specific user:
01256             $this->TSdataArray[] = $this->addTScomment('USER TSconfig field') . $this->user['TSconfig'];
01257                 // Check include lines.
01258             $this->TSdataArray = t3lib_TSparser::checkIncludeLines_array($this->TSdataArray);
01259 
01260             $this->userTS_text = implode(LF . '[GLOBAL]' . LF, $this->TSdataArray); // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
01261 
01262             if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions'] && !$this->userTS_dontGetCached) {
01263                     // Perform TS-Config parsing with condition matching
01264                 $parseObj = t3lib_div::makeInstance('t3lib_TSparser_TSconfig');
01265                 $res = $parseObj->parseTSconfig($this->userTS_text, 'userTS');
01266                 if ($res) {
01267                     $this->userTS = $res['TSconfig'];
01268                     $this->userTSUpdated = ($res['cached'] ? 0 : 1);
01269                 }
01270             } else {
01271                     // Parsing the user TSconfig (or getting from cache)
01272                 $hash = md5('userTS:' . $this->userTS_text);
01273                 $cachedContent = t3lib_BEfunc::getHash($hash);
01274                 if (isset($cachedContent) && !$this->userTS_dontGetCached) {
01275                     $this->userTS = unserialize($cachedContent);
01276                 } else {
01277                     $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
01278                     $parseObj->parse($this->userTS_text);
01279                     $this->userTS = $parseObj->setup;
01280                     t3lib_BEfunc::storeHash($hash, serialize($this->userTS), 'BE_USER_TSconfig');
01281                         // Update UC:
01282                     $this->userTSUpdated = 1;
01283                 }
01284             }
01285 
01286                 // Processing webmounts
01287             if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) { // Admin's always have the root mounted
01288                 $this->dataLists['webmount_list'] = '0,' . $this->dataLists['webmount_list'];
01289             }
01290 
01291                 // Processing filemounts
01292             t3lib_div::loadTCA('sys_filemounts');
01293             $orderBy = $GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'] ? $GLOBALS['TYPO3_DB']->stripOrderBy($GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby']) : 'sorting';
01294             $this->dataLists['filemount_list'] = t3lib_div::uniqueList($this->dataLists['filemount_list']);
01295             if ($this->dataLists['filemount_list']) {
01296                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_filemounts', 'deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $this->dataLists['filemount_list'] . ')', '', $orderBy);
01297                 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
01298                     $this->addFileMount($row['title'], $row['path'], $row['path'], $row['base'] ? 1 : 0, '');
01299                 }
01300             }
01301 
01302                 // The lists are cleaned for duplicates
01303             $this->groupData['webmounts'] = t3lib_div::uniqueList($this->dataLists['webmount_list']);
01304             $this->groupData['pagetypes_select'] = t3lib_div::uniqueList($this->dataLists['pagetypes_select']);
01305             $this->groupData['tables_select'] = t3lib_div::uniqueList($this->dataLists['tables_modify'] . ',' . $this->dataLists['tables_select']);
01306             $this->groupData['tables_modify'] = t3lib_div::uniqueList($this->dataLists['tables_modify']);
01307             $this->groupData['non_exclude_fields'] = t3lib_div::uniqueList($this->dataLists['non_exclude_fields']);
01308             $this->groupData['explicit_allowdeny'] = t3lib_div::uniqueList($this->dataLists['explicit_allowdeny']);
01309             $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->dataLists['allowed_languages']);
01310             $this->groupData['custom_options'] = t3lib_div::uniqueList($this->dataLists['custom_options']);
01311             $this->groupData['modules'] = t3lib_div::uniqueList($this->dataLists['modList']);
01312             $this->groupData['fileoper_perms'] = $this->dataLists['fileoper_perms'];
01313             $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
01314 
01315                 // populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
01316             $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
01317 
01318                 // 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)
01319             $this->groupList = implode(',', $this->userGroupsUID);
01320             $this->setCachedList($this->groupList);
01321 
01322                 // Checking read access to webmounts:
01323             if (trim($this->groupData['webmounts']) !== '') {
01324                 $webmounts = explode(',', $this->groupData['webmounts']); // Explode mounts
01325                 $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
01326                 foreach ($webmounts as $idx => $mountPointUid) {
01327                     if ($mountPointUid > 0 && !isset($MProws[$mountPointUid])) { // If the mount ID is NOT found among selected pages, unset it:
01328                         unset($webmounts[$idx]);
01329                     }
01330                 }
01331                 $this->groupData['webmounts'] = implode(',', $webmounts); // Implode mounts in the end.
01332             }
01333 
01334                 // Setting up workspace situation (after webmounts are processed!):
01335             $this->workspaceInit();
01336         }
01337     }
01338 
01339     /**
01340      * Fetches the group records, subgroups and fills internal arrays.
01341      * Function is called recursively to fetch subgroups
01342      *
01343      * @param   string      Commalist of be_groups uid numbers
01344      * @param   string      List of already processed be_groups-uids so the function will not fall into a eternal recursion.
01345      * @return  void
01346      * @access private
01347      */
01348     function fetchGroups($grList, $idList = '') {
01349         global $TYPO3_CONF_VARS;
01350 
01351             // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
01352         $lockToDomain_SQL = ' AND (lockToDomain=\'\' OR lockToDomain IS NULL OR lockToDomain=\'' . t3lib_div::getIndpEnv('HTTP_HOST') . '\')';
01353         $whereSQL = 'deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $grList . ')' . $lockToDomain_SQL;
01354 
01355             // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
01356         if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'])) {
01357             foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] as $classRef) {
01358                 $hookObj = t3lib_div::getUserObj($classRef);
01359                 if (method_exists($hookObj, 'fetchGroupQuery_processQuery')) {
01360                     $whereSQL = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, $whereSQL);
01361                 }
01362             }
01363         }
01364 
01365         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->usergroup_table, $whereSQL);
01366 
01367             // The userGroups array is filled
01368         while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
01369             $this->userGroups[$row['uid']] = $row;
01370         }
01371 
01372             // Traversing records in the correct order
01373         $include_staticArr = t3lib_div::intExplode(',', $grList);
01374             // traversing list
01375         foreach ($include_staticArr as $key => $uid) {
01376 
01377                 // Get row:
01378             $row = $this->userGroups[$uid];
01379             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
01380 
01381                     // Include sub groups
01382                 if (trim($row['subgroup'])) {
01383                     $theList = implode(',', t3lib_div::intExplode(',', $row['subgroup'])); // Make integer list
01384                     $this->fetchGroups($theList, $idList . ',' . $uid); // Call recursively, pass along list of already processed groups so they are not recursed again.
01385                 }
01386                     // Add the group uid, current list, TSconfig to the internal arrays.
01387                 $this->includeGroupArray[] = $uid;
01388                 $this->includeHierarchy[] = $idList;
01389                 $this->TSdataArray[] = $this->addTScomment('Group "' . $row['title'] . '" [' . $row['uid'] . '] TSconfig field:') . $row['TSconfig'];
01390 
01391                     // Mount group database-mounts
01392                 if (($this->user['options'] & 1) == 1) {
01393                     $this->dataLists['webmount_list'] .= ',' . $row['db_mountpoints'];
01394                 }
01395 
01396                     // Mount group file-mounts
01397                 if (($this->user['options'] & 2) == 2) {
01398                     $this->dataLists['filemount_list'] .= ',' . $row['file_mountpoints'];
01399                 }
01400 
01401                     // Mount group home-dirs
01402                 if (($this->user['options'] & 2) == 2) {
01403                         // If groupHomePath is set, we attempt to mount it
01404                     if ($GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath']) {
01405                         $this->addFileMount($row['title'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'] . $row['uid'], 0, 'group');
01406                     }
01407                 }
01408 
01409                     // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
01410                 if ($row['inc_access_lists'] == 1) {
01411                     $this->dataLists['modList'] .= ',' . $row['groupMods'];
01412                     $this->dataLists['tables_select'] .= ',' . $row['tables_select'];
01413                     $this->dataLists['tables_modify'] .= ',' . $row['tables_modify'];
01414                     $this->dataLists['pagetypes_select'] .= ',' . $row['pagetypes_select'];
01415                     $this->dataLists['non_exclude_fields'] .= ',' . $row['non_exclude_fields'];
01416                     $this->dataLists['explicit_allowdeny'] .= ',' . $row['explicit_allowdeny'];
01417                     $this->dataLists['allowed_languages'] .= ',' . $row['allowed_languages'];
01418                     $this->dataLists['custom_options'] .= ',' . $row['custom_options'];
01419                 }
01420 
01421                     // Setting fileoperation permissions
01422                 $this->dataLists['fileoper_perms'] |= (int) $row['fileoper_perms'];
01423 
01424                     // Setting workspace permissions:
01425                 $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
01426 
01427                     // 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.
01428                 if (!strcmp($idList, '') && !$this->firstMainGroup) {
01429                     $this->firstMainGroup = $uid;
01430                 }
01431             }
01432         }
01433 
01434             // ****************
01435             // HOOK: fetchGroups_postProcessing
01436             // ****************
01437         if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'])) {
01438             foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] as $_funcRef) {
01439                 $_params = array();
01440                 t3lib_div::callUserFunction($_funcRef, $_params, $this);
01441             }
01442         }
01443     }
01444 
01445     /**
01446      * Updates the field be_users.usergroup_cached_list if the groupList of the user has changed/is different from the current list.
01447      * 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.
01448      *
01449      * @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.
01450      * @return  void
01451      * @access private
01452      */
01453     function setCachedList($cList) {
01454         if ((string) $cList != (string) $this->user['usergroup_cached_list']) {
01455             $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('usergroup_cached_list' => $cList));
01456         }
01457     }
01458 
01459     /**
01460      * Adds a filemount to the users array of filemounts, $this->groupData['filemounts'][hash_key] = Array ('name'=>$name, 'path'=>$path, 'type'=>$type);
01461      * Is a part of the authentication proces of the user.
01462      * 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!
01463      * Paths in the mounted information will always be absolute and have a trailing slash.
01464      *
01465      * @param   string      $title will be the (root)name of the filemount in the folder tree
01466      * @param   string      $altTitle will be the (root)name of the filemount IF $title is not true (blank or zero)
01467      * @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.
01468      * @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.
01469      * @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.
01470      * @return  boolean     Returns "1" if the requested filemount was mounted, otherwise no return value.
01471      * @access private
01472      */
01473     function addFileMount($title, $altTitle, $path, $webspace, $type) {
01474             // Return false if fileadminDir is not set and we try to mount a relative path
01475         if ($webspace && !$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
01476             return FALSE;
01477         }
01478 
01479             // Trimming and pre-processing
01480         $path = trim($path);
01481         if ($this->OS == 'WIN') { // with WINDOWS convert backslash to slash!!
01482             $path = str_replace('\\', '/', $path);
01483         }
01484             // If the path is true and validates as a valid path string:
01485         if ($path && t3lib_div::validPathStr($path)) {
01486                 // normalize path: remove leading '/' and './', and trailing '/' and '/.'
01487             $path = trim($path);
01488             $path = preg_replace('#^\.?/|/\.?$#', '', $path);
01489 
01490             if ($path) { // there must be some chars in the path
01491                 $fdir = PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']; // fileadmin dir, absolute
01492                 if ($webspace) {
01493                     $path = $fdir . $path; // PATH_site + fileadmin dir is prepended
01494                 } else {
01495                     if ($this->OS != 'WIN') { // with WINDOWS no prepending!!
01496                         $path = '/' . $path; // root-level is the start...
01497                     }
01498                 }
01499                 $path .= '/';
01500 
01501                     // We now have a path with slash after and slash before (if unix)
01502                 if (@is_dir($path) &&
01503                      (($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'])) || t3lib_div::isFirstPartOfStr($path, $fdir))) {
01504                         // Alternative title?
01505                     $name = $title ? $title : $altTitle;
01506                         // 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.
01507                     $this->groupData['filemounts'][md5($name . '|' . $path . '|' . $type)] = array('name' => $name, 'path' => $path, 'type' => $type);
01508                         // Return true - went well, success!
01509                     return 1;
01510                 }
01511             }
01512         }
01513     }
01514 
01515     /**
01516      * Creates a TypoScript comment with the string text inside.
01517      *
01518      * @param   string      The text to wrap in comment prefixes and delimiters.
01519      * @return  string      TypoScript comment with the string text inside.
01520      */
01521     function addTScomment($str) {
01522         $delimiter = '# ***********************************************';
01523 
01524         $out = $delimiter . LF;
01525         $lines = t3lib_div::trimExplode(LF, $str);
01526         foreach ($lines as $v) {
01527             $out .= '# ' . $v . LF;
01528         }
01529         $out .= $delimiter . LF;
01530         return $out;
01531     }
01532 
01533 
01534     /************************************
01535      *
01536      * Workspaces
01537      *
01538      ************************************/
01539 
01540     /**
01541      * Initializing workspace.
01542      * Called from within this function, see fetchGroupData()
01543      *
01544      * @return  void
01545      * @see fetchGroupData()
01546      */
01547     function workspaceInit() {
01548 
01549             // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
01550         $this->setWorkspace($this->user['workspace_id']);
01551 
01552             // Limiting the DB mountpoints if there any selected in the workspace record
01553         $dbMountpoints = trim($this->workspaceRec['db_mountpoints']);
01554         if ($this->workspace > 0 && $dbMountpoints != '') {
01555             $filteredDbMountpoints = array();
01556             $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.
01557 
01558                 // Traverse mount points of the
01559             $dbMountpoints = t3lib_div::intExplode(',', $dbMountpoints);
01560             foreach ($dbMountpoints as $mpId) {
01561                 if ($this->isInWebMount($mpId, $readPerms)) {
01562                     $filteredDbMountpoints[] = $mpId;
01563                 }
01564             }
01565 
01566                 // Re-insert webmounts:
01567             $filteredDbMountpoints = array_unique($filteredDbMountpoints);
01568             $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
01569         }
01570 
01571             // Filtering the file mountpoints
01572             // if there some selected in the workspace record
01573         if ($this->workspace !== 0) {
01574             $usersFileMounts = $this->groupData['filemounts'];
01575             $this->groupData['filemounts'] = array();
01576         }
01577         $fileMountpoints = trim($this->workspaceRec['file_mountpoints']);
01578         if ($this->workspace > 0) {
01579 
01580                 // no custom filemounts that should serve as filter or user is admin
01581                 // so all user mountpoints are re-applied
01582             if ($this->isAdmin() || $fileMountpoints === '') {
01583                 $this->groupData['filemounts'] = $usersFileMounts;
01584             } else {
01585                     // Fetching all filemounts from the workspace
01586                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
01587                     '*',
01588                     'sys_filemounts',
01589                     'deleted = 0 AND hidden = 0 AND pid = 0 AND uid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($fileMountpoints) . ')'
01590                 );
01591 
01592                 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
01593                         // add every filemount of this workspace record
01594                     $this->addFileMount($row['title'], $row['path'], $row['path'], ($row['base'] ? 1 : 0), '');
01595 
01596                         // get the added entry, and check if it was in the users' original filemounts
01597                         // if not, remove it from the new filemount list again
01598                         // see self::addFileMount
01599                     end($this->groupData['filemounts']);
01600                     $md5hash = key($this->groupData['filemounts']);
01601                     if (!array_key_exists($md5hash, $usersFileMounts)) {
01602                         unset($this->groupData['filemounts'][$md5hash]);
01603                     }
01604                 }
01605             }
01606         }
01607 
01608         if ($allowed_languages = $this->getTSConfigVal('options.workspaces.allowed_languages.' . $this->workspace)) {
01609             $this->groupData['allowed_languages'] = $allowed_languages;
01610             $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->groupData['allowed_languages']);
01611         }
01612     }
01613 
01614     /**
01615      * Checking if a workspace is allowed for backend user
01616      *
01617      * @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)
01618      * @param   string      List of fields to select. Default fields are: uid,title,adminusers,members,reviewers,publish_access,stagechg_notification
01619      * @return  array       TRUE if access. Output will also show how access was granted. Admin users will have a true output regardless of input.
01620      */
01621     function checkWorkspace($wsRec, $fields = 'uid,title,adminusers,members,reviewers,publish_access,stagechg_notification') {
01622         $retVal = FALSE;
01623 
01624             // Show draft workspace only if it's enabled in version extension
01625         if (t3lib_extMgm::isLoaded('version')) {
01626             $versionExtConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['version']);
01627             if (!$versionExtConf['showDraftWorkspace']) {
01628                 if (!is_array($wsRec)) {
01629                     if ((string) $wsRec === '-1') {
01630                         return FALSE;
01631                     }
01632                 } else {
01633                     if ((string) $wsRec['uid'] === '-1') {
01634                         return FALSE;
01635                     }
01636                 }
01637             }
01638         }
01639 
01640             // If not array, look up workspace record:
01641         if (!is_array($wsRec)) {
01642             switch ((string) $wsRec) {
01643                 case '0':
01644                 case '-1':
01645                     $wsRec = array('uid' => $wsRec);
01646                 break;
01647                 default:
01648                     if (t3lib_extMgm::isLoaded('workspaces')) {
01649                         $wsRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
01650                             $fields,
01651                             'sys_workspace',
01652                             'pid=0 AND uid=' . intval($wsRec) .
01653                             t3lib_BEfunc::deleteClause('sys_workspace'),
01654                             '',
01655                             'title'
01656                         );
01657                     }
01658                 break;
01659             }
01660         }
01661 
01662             // If wsRec is set to an array, evaluate it:
01663         if (is_array($wsRec)) {
01664             if ($this->isAdmin()) {
01665                 return array_merge($wsRec, array('_ACCESS' => 'admin'));
01666             } else {
01667 
01668                 switch ((string) $wsRec['uid']) {
01669                     case '0':
01670                         $retVal = ($this->groupData['workspace_perms'] & 1) ? array_merge($wsRec, array('_ACCESS' => 'online')) : FALSE;
01671                     break;
01672                     case '-1':
01673                         $retVal = ($this->groupData['workspace_perms'] & 2) ? array_merge($wsRec, array('_ACCESS' => 'offline')) : FALSE;
01674                     break;
01675                     default:
01676                             // Checking if the guy is admin:
01677                         if (t3lib_div::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
01678                             return array_merge($wsRec, array('_ACCESS' => 'owner'));
01679                         }
01680                             // Checking if he is owner through a user group of his:
01681                         foreach ($this->userGroupsUID as $groupUid) {
01682                             if (t3lib_div::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
01683                                 return array_merge($wsRec, array('_ACCESS' => 'owner'));
01684                             }
01685                         }
01686                             // Checking if he is reviewer user:
01687                         if (t3lib_div::inList($wsRec['reviewers'], 'be_users_' . $this->user['uid'])) {
01688                             return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
01689                         }
01690                             // Checking if he is reviewer through a user group of his:
01691                         foreach ($this->userGroupsUID as $groupUid) {
01692                             if (t3lib_div::inList($wsRec['reviewers'], 'be_groups_' . $groupUid)) {
01693                                 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
01694                             }
01695                         }
01696                             // Checking if he is member as user:
01697                         if (t3lib_div::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
01698                             return array_merge($wsRec, array('_ACCESS' => 'member'));
01699                         }
01700                             // Checking if he is member through a user group of his:
01701                         foreach ($this->userGroupsUID as $groupUid) {
01702                             if (t3lib_div::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
01703                                 return array_merge($wsRec, array('_ACCESS' => 'member'));
01704                             }
01705                         }
01706                     break;
01707                 }
01708             }
01709         }
01710 
01711         return $retVal;
01712     }
01713 
01714     /**
01715      * 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.
01716      *
01717      * @return  array       See checkWorkspace()
01718      * @see checkWorkspace()
01719      */
01720     function checkWorkspaceCurrent() {
01721         if (!isset($this->checkWorkspaceCurrent_cache)) {
01722             $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
01723         }
01724         return $this->checkWorkspaceCurrent_cache;
01725     }
01726 
01727     /**
01728      * Setting workspace ID
01729      *
01730      * @param   integer     ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
01731      * @return  void
01732      */
01733     function setWorkspace($workspaceId) {
01734 
01735             // Check workspace validity and if not found, revert to default workspace.
01736         if ($this->workspaceRec = $this->checkWorkspace($workspaceId, '*')) {
01737                 // Set workspace ID internally
01738             $this->workspace = (int) $workspaceId;
01739         } else {
01740             $this->workspace = (int) $this->getDefaultWorkspace();
01741             $this->workspaceRec = $this->checkWorkspace($this->workspace, '*');
01742         }
01743 
01744             // Unset access cache:
01745         unset($this->checkWorkspaceCurrent_cache);
01746 
01747             // If ID is different from the stored one, change it:
01748         if (strcmp($this->workspace, $this->user['workspace_id'])) {
01749             $this->user['workspace_id'] = $this->workspace;
01750             $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('workspace_id' => $this->user['workspace_id']));
01751             $this->simplelog('User changed workspace to "' . $this->workspace . '"');
01752         }
01753     }
01754 
01755     /**
01756      * Setting workspace preview state for user:
01757      *
01758      * @param   boolean     State of user preview.
01759      * @return  void
01760      */
01761     function setWorkspacePreview($previewState) {
01762         $this->user['workspace_preview'] = $previewState;
01763         $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('workspace_preview' => $this->user['workspace_preview']));
01764     }
01765 
01766     /**
01767      * Return default workspace ID for user
01768      *
01769      * @return  integer     Default workspace id. If no workspace is available it will be "-99"
01770      */
01771     function getDefaultWorkspace() {
01772 
01773         if ($this->checkWorkspace(0)) { // Check online
01774             return 0;
01775         } elseif ($this->checkWorkspace(-1)) { // Check offline
01776             return -1;
01777         } elseif (t3lib_extMgm::isLoaded('workspaces')) { // Traverse custom workspaces:
01778             $workspaces = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,title,adminusers,members,reviewers', 'sys_workspace', 'pid=0' . t3lib_BEfunc::deleteClause('sys_workspace'), '', 'title');
01779             foreach ($workspaces as $rec) {
01780                 if ($this->checkWorkspace($rec)) {
01781                     return $rec['uid'];
01782                 }
01783             }
01784         }
01785         return -99;
01786     }
01787 
01788 
01789     /************************************
01790      *
01791      * Logging
01792      *
01793      ************************************/
01794 
01795     /**
01796      * Writes an entry in the logfile/table
01797      * Documentation in "TYPO3 Core API"
01798      *
01799      * @param   integer     Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
01800      * @param   integer     Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
01801      * @param   integer     Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
01802      * @param   integer     The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
01803      * @param   string      Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
01804      * @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
01805      * @param   string      Table name. Special field used by tce_main.php.
01806      * @param   integer     Record UID. Special field used by tce_main.php.
01807      * @param   integer     Record PID. Special field used by tce_main.php. OBSOLETE
01808      * @param   integer     The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
01809      * @param   string      Special field used by tce_main.php. NEWid string of newly created records.
01810      * @param   integer     Alternative Backend User ID (used for logging login actions where this is not yet known).
01811      * @return  integer     Log entry ID.
01812      */
01813     function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0) {
01814 
01815         $fields_values = array(
01816             'userid' => $userId ? $userId : intval($this->user['uid']),
01817             'type' => intval($type),
01818             'action' => intval($action),
01819             'error' => intval($error),
01820             'details_nr' => intval($details_nr),
01821             'details' => $details,
01822             'log_data' => serialize($data),
01823             'tablename' => $tablename,
01824             'recuid' => intval($recuid),
01825             #           'recpid' => intval($recpid),
01826             'IP' => t3lib_div::getIndpEnv('REMOTE_ADDR'),
01827             'tstamp' => $GLOBALS['EXEC_TIME'],
01828             'event_pid' => intval($event_pid),
01829             'NEWid' => $NEWid,
01830             'workspace' => $this->workspace
01831         );
01832 
01833         $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_log', $fields_values);
01834         return $GLOBALS['TYPO3_DB']->sql_insert_id();
01835     }
01836 
01837     /**
01838      * Simple logging function
01839      *
01840      * @param   string      Log message
01841      * @param   string      Option extension key / module name
01842      * @param   integer     Error level. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
01843      * @return  integer     Log entry UID
01844      */
01845     function simplelog($message, $extKey = '', $error = 0) {
01846         return $this->writelog(
01847             4,
01848             0,
01849             $error,
01850             0,
01851             ($extKey ? '[' . $extKey . '] ' : '') . $message,
01852             array()
01853         );
01854     }
01855 
01856     /**
01857      * Sends a warning to $email if there has been a certain amount of failed logins during a period.
01858      * 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.
01859      *
01860      * @param   string      Email address
01861      * @param   integer     Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
01862      * @param   integer     Max allowed failures before a warning mail is sent
01863      * @return  void
01864      * @access private
01865      */
01866     function checkLogFailures($email, $secondsBack = 3600, $max = 3) {
01867 
01868         if ($email) {
01869 
01870                 // get last flag set in the log for sending
01871             $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
01872             $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
01873                 'tstamp',
01874                 'sys_log',
01875                 'type=255 AND action=4 AND tstamp>' . intval($theTimeBack),
01876                 '',
01877                 'tstamp DESC',
01878                 '1'
01879             );
01880             if ($testRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
01881                 $theTimeBack = $testRow['tstamp'];
01882             }
01883 
01884                 // Check for more than $max number of error failures with the last period.
01885             $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
01886                 '*',
01887                 'sys_log',
01888                 'type=255 AND action=3 AND error!=0 AND tstamp>' . intval($theTimeBack),
01889                 '',
01890                 'tstamp'
01891             );
01892             if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) > $max) {
01893                     // OK, so there were more than the max allowed number of login failures - so we will send an email then.
01894                 $subject = 'TYPO3 Login Failure Warning (at ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . ')';
01895                 $email_body = 'There have been some attempts (' . $GLOBALS['TYPO3_DB']->sql_num_rows($res) . ') to login at the TYPO3
01896 site "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '" (' . t3lib_div::getIndpEnv('HTTP_HOST') . ').
01897 
01898 This is a dump of the failures:
01899 
01900 ';
01901                 while ($testRows = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
01902                     $theData = unserialize($testRows['log_data']);
01903                     $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]);
01904                     $email_body .= LF;
01905                 }
01906                 $from = t3lib_utility_Mail::getSystemFrom();
01907                 /** @var $mail t3lib_mail_Message */
01908                 $mail = t3lib_div::makeInstance('t3lib_mail_Message');
01909                 $mail->setTo($email)
01910                         ->setFrom($from)
01911                         ->setSubject($subject)
01912                         ->setBody($email_body);
01913                 $mail->send();
01914                 $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
01915             }
01916         }
01917     }
01918 }
01919 
01920 
01921 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php'])) {
01922     include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']);
01923 }
01924 
01925 ?>