TYPO3 API  SVNRelease
class.t3lib_userauth.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 a base class for authentication of users in TYPO3, both frontend and backend.
00029  *
00030  * $Id: class.t3lib_userauth.php 10664 2011-02-28 19:37:41Z lolli $
00031  * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
00032  *
00033  * @author  Kasper Skårhøj <kasperYYYY@typo3.com>
00034  * @author  René Fritz <r.fritz@colorcube.de>
00035  */
00036 /**
00037  * [CLASS/FUNCTION INDEX of SCRIPT]
00038  *
00039  *
00040  *
00041  *  111: class t3lib_userAuth
00042  *  195:     function start()
00043  *  329:     function checkAuthentication()
00044  *
00045  *            SECTION: User Sessions
00046  *  569:     function createUserSession ($tempuser)
00047  *  606:     function fetchUserSession()
00048  *  657:     function logoff()
00049  *
00050  *            SECTION: SQL Functions
00051  *  713:     function user_where_clause()
00052  *  727:     function ipLockClause()
00053  *  745:     function ipLockClause_remoteIPNumber($parts)
00054  *  766:     function hashLockClause()
00055  *  777:     function hashLockClause_getHashInt()
00056  *
00057  *            SECTION: Session and Configuration Handling
00058  *  809:     function writeUC($variable='')
00059  *  824:     function unpack_uc($theUC='')
00060  *  840:     function pushModuleData($module,$data,$noSave=0)
00061  *  853:     function getModuleData($module,$type='')
00062  *  866:     function getSessionData($key)
00063  *  879:     function setAndSaveSessionData($key,$data)
00064  *
00065  *            SECTION: Misc
00066  *  912:     function getLoginFormData()
00067  *  939:     function processLoginData($loginData, $security_level='')
00068  *  981:     function getAuthInfoArray()
00069  * 1011:     function compareUident($user, $loginData, $security_level='')
00070  * 1050:     function gc()
00071  * 1064:     function redirect()
00072  * 1086:     function writelog($type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid)
00073  * 1095:     function checkLogFailures()
00074  * 1108:     function setBeUserByUid($uid)
00075  * 1120:     function setBeUserByName($name)
00076  * 1131:     function getRawUserByUid($uid)
00077  * 1149:     function getRawUserByName($name)
00078  *
00079  *            SECTION: Create/update user - EXPERIMENTAL
00080  * 1188:     function fetchUserRecord($dbUser, $username, $extraWhere='' )
00081  *
00082  * TOTAL FUNCTIONS: 29
00083  * (This index is automatically created/updated by the extension "extdeveval")
00084  *
00085  */
00086 
00087 
00088 require_once(t3lib_extMgm::extPath('sv') . 'class.tx_sv_authbase.php');
00089 
00090 
00091 /**
00092  * Authentication of users in TYPO3
00093  *
00094  * This class is used to authenticate a login user.
00095  * The class is used by both the frontend and backend. In both cases this class is a parent class to beuserauth and feuserauth
00096  *
00097  * See Inside TYPO3 for more information about the API of the class and internal variables.
00098  *
00099  * @author  Kasper Skårhøj <kasperYYYY@typo3.com>
00100  * @author  René Fritz <r.fritz@colorcube.de>
00101  * @package TYPO3
00102  * @subpackage t3lib
00103  */
00104 class t3lib_userAuth {
00105     var $global_database = ''; // Which global database to connect to
00106     var $session_table = ''; // Table to use for session data.
00107     var $name = ''; // Session/Cookie name
00108     var $get_name = ''; // Session/GET-var name
00109 
00110     var $user_table = ''; // Table in database with userdata
00111     var $username_column = ''; // Column for login-name
00112     var $userident_column = ''; // Column for password
00113     var $userid_column = ''; // Column for user-id
00114     var $lastLogin_column = '';
00115 
00116     var $enablecolumns = array(
00117         'rootLevel' => '', // Boolean: If true, 'AND pid=0' will be a part of the query...
00118         'disabled' => '',
00119         'starttime' => '',
00120         'endtime' => '',
00121         'deleted' => ''
00122     );
00123 
00124     var $formfield_uname = ''; // formfield with login-name
00125     var $formfield_uident = ''; // formfield with password
00126     var $formfield_chalvalue = ''; // formfield with a unique value which is used to encrypt the password and username
00127     var $formfield_status = ''; // formfield with status: *'login', 'logout'. If empty login is not verified.
00128     var $security_level = 'normal'; // sets the level of security. *'normal' = clear-text. 'challenged' = hashed password/username from form in $formfield_uident. 'superchallenged' = hashed password hashed again with username.
00129 
00130     var $auth_timeout_field = 0; // Server session lifetime. If > 0: session-timeout in seconds. If false or <0: no timeout. If string: The string is a fieldname from the usertable where the timeout can be found.
00131     var $lifetime = 0; // Client session lifetime. 0 = Session-cookies. If session-cookies, the browser will stop the session when the browser is closed. Otherwise this specifies the lifetime of a cookie that keeps the session.
00132     var $gc_time = 0; // GarbageCollection. Purge all server session data older than $gc_time seconds. 0 = default to $this->timeout or use 86400 seconds (1 day) if $this->lifetime is 0
00133     var $gc_probability = 1; // Possibility (in percent) for GarbageCollection to be run.
00134     var $writeStdLog = FALSE; // Decides if the writelog() function is called at login and logout
00135     var $writeAttemptLog = FALSE; // If the writelog() functions is called if a login-attempt has be tried without success
00136     var $sendNoCacheHeaders = TRUE; // If this is set, headers is sent to assure, caching is NOT done
00137     var $getFallBack = FALSE; // If this is set, authentication is also accepted by the $_GET. Notice that the identification is NOT 128bit MD5 hash but reduced. This is done in order to minimize the size for mobile-devices, such as WAP-phones
00138     var $hash_length = 32; // The ident-hash is normally 32 characters and should be! But if you are making sites for WAP-devices og other lowbandwidth stuff, you may shorten the length. Never let this value drop below 6. A length of 6 would give you more than 16 mio possibilities.
00139     var $getMethodEnabled = FALSE; // Setting this flag true lets user-authetication happen from GET_VARS if POST_VARS are not set. Thus you may supply username/password from the URL.
00140     var $lockIP = 4; // If set, will lock the session to the users IP address (all four numbers. Reducing to 1-3 means that only first, second or third part of the IP address is used).
00141     var $lockHashKeyWords = 'useragent'; // Keyword list (commalist with no spaces!): "useragent". Each keyword indicates some information that can be included in a integer hash made to lock down usersessions. Configurable through $TYPO3_CONF_VARS[TYPO3_MODE]['lockHashKeyWords']
00142 
00143     var $warningEmail = ''; // warning -emailaddress:
00144     var $warningPeriod = 3600; // Period back in time (in seconds) in which number of failed logins are collected
00145     var $warningMax = 3; // The maximum accepted number of warnings before an email is sent
00146     var $checkPid = TRUE; // If set, the user-record must $checkPid_value as pid
00147     var $checkPid_value = 0; // The pid, the user-record must have as page-id
00148 
00149         // Internals
00150     var $id; // Internal: Will contain session_id (MD5-hash)
00151     var $cookieId; // Internal: Will contain the session_id gotten from cookie or GET method. This is used in statistics as a reliable cookie (one which is known to come from $_COOKIE).
00152     var $loginFailure = FALSE; // Indicates if an authentication was started but failed
00153     var $loginSessionStarted = FALSE; // Will be set to true if the login session is actually written during auth-check.
00154 
00155     var $user; // Internal: Will contain user- AND session-data from database (joined tables)
00156     var $get_URL_ID = ''; // Internal: Will will be set to the url--ready (eg. '&login=ab7ef8d...') GET-auth-var if getFallBack is true. Should be inserted in links!
00157 
00158     var $newSessionID = FALSE; // Will be set to true if a new session ID was created
00159     var $forceSetCookie = FALSE; // Will force the session cookie to be set everytime (lifetime must be 0)
00160     var $dontSetCookie = FALSE; // Will prevent the setting of the session cookie (takes precedence over forceSetCookie)
00161     var $challengeStoredInCookie = FALSE; // If set, the challenge value will be stored in a session as well so the server can check that is was not forged.
00162     var $loginType = ''; // Login type, used for services.
00163 
00164     var $svConfig = array(); // "auth" services configuration array from $TYPO3_CONF_VARS['SVCONF']['auth']
00165     var $writeDevLog = FALSE; // write messages into the devlog?
00166 
00167 
00168     /**
00169      * Starts a user session
00170      * Typical configurations will:
00171      * a) check if session cookie was set and if not, set one,
00172      * b) check if a password/username was sent and if so, try to authenticate the user
00173      * c) Lookup a session attached to a user and check timeout etc.
00174      * d) Garbage collection, setting of no-cache headers.
00175      * If a user is authenticated the database record of the user (array) will be set in the ->user internal variable.
00176      *
00177      * @return  void
00178      */
00179     function start() {
00180         global $TYPO3_CONF_VARS;
00181 
00182             // backend or frontend login - used for auth services
00183         $this->loginType = ($this->name == 'fe_typo_user') ? 'FE' : 'BE';
00184 
00185             // set level to normal if not already set
00186         if (!$this->security_level) {
00187                 // Notice: cannot use TYPO3_MODE here because BE user can be logged in and operate inside FE!
00188             $this->security_level = trim($TYPO3_CONF_VARS[$this->loginType]['loginSecurityLevel']);
00189             if (!$this->security_level) {
00190                 $this->security_level = 'normal';
00191             }
00192         }
00193 
00194             // enable dev logging if set
00195         if ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['writeDevLog']) {
00196             $this->writeDevLog = TRUE;
00197         }
00198         if ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['writeDevLog' . $this->loginType]) {
00199             $this->writeDevLog = TRUE;
00200         }
00201         if (TYPO3_DLOG) {
00202             $this->writeDevLog = TRUE;
00203         }
00204 
00205         if ($this->writeDevLog) {
00206             t3lib_div::devLog('## Beginning of auth logging.', 't3lib_userAuth');
00207         }
00208 
00209             // Init vars.
00210         $mode = '';
00211         $this->newSessionID = FALSE;
00212             // $id is set to ses_id if cookie is present. Else set to false, which will start a new session
00213         $id = $this->getCookie($this->name);
00214         $this->svConfig = $TYPO3_CONF_VARS['SVCONF']['auth'];
00215 
00216             // if we have a flash client, take the ID from the GP
00217         if (!$id && $GLOBALS['CLIENT']['BROWSER'] == 'flash') {
00218             $id = t3lib_div::_GP($this->name);
00219         }
00220 
00221             // If fallback to get mode....
00222         if (!$id && $this->getFallBack && $this->get_name) {
00223             $id = isset($_GET[$this->get_name]) ? t3lib_div::_GET($this->get_name) : '';
00224             if (strlen($id) != $this->hash_length) {
00225                 $id = '';
00226             }
00227             $mode = 'get';
00228         }
00229         $this->cookieId = $id;
00230 
00231             // If new session or client tries to fix session...
00232         if (!$id || !$this->isExistingSessionRecord($id)) {
00233                 // New random session-$id is made
00234             $id = $this->createSessionId();
00235                 // New session
00236             $this->newSessionID = TRUE;
00237         }
00238 
00239             // Internal var 'id' is set
00240         $this->id = $id;
00241 
00242             // If fallback to get mode....
00243         if ($mode == 'get' && $this->getFallBack && $this->get_name) {
00244             $this->get_URL_ID = '&' . $this->get_name . '=' . $id;
00245         }
00246 
00247             // Set session hashKey lock keywords from configuration; currently only 'useragent' can be used.
00248         $this->lockHashKeyWords = $TYPO3_CONF_VARS[$this->loginType]['lockHashKeyWords'];
00249 
00250             // Make certain that NO user is set initially
00251         $this->user = '';
00252 
00253             // Check to see if anyone has submitted login-information and if so register the user with the session. $this->user[uid] may be used to write log...
00254         $this->checkAuthentication();
00255 
00256             // Make certain that NO user is set initially. ->check_authentication may have set a session-record which will provide us with a user record in the next section:
00257         unset($this->user);
00258 
00259             // determine whether we need to skip session update.
00260             // This is used mainly for checking session timeout without
00261             // refreshing the session itself while checking.
00262         if (t3lib_div::_GP('skipSessionUpdate')) {
00263             $skipSessionUpdate = TRUE;
00264         } else {
00265             $skipSessionUpdate = FALSE;
00266         }
00267 
00268             // re-read user session
00269         $this->user = $this->fetchUserSession($skipSessionUpdate);
00270 
00271         if ($this->writeDevLog && is_array($this->user)) {
00272             t3lib_div::devLog('User session finally read: ' . t3lib_div::arrayToLogString($this->user, array($this->userid_column, $this->username_column)), 't3lib_userAuth', -1);
00273         }
00274         if ($this->writeDevLog && !is_array($this->user)) {
00275             t3lib_div::devLog('No user session found.', 't3lib_userAuth', 2);
00276         }
00277 
00278             // Setting cookies
00279         if (!$this->dontSetCookie) {
00280             $this->setSessionCookie();
00281         }
00282 
00283             // Hook for alternative ways of filling the $this->user array (is used by the "timtaw" extension)
00284         if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'])) {
00285             foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'] as $funcName) {
00286                 $_params = array(
00287                     'pObj' => &$this,
00288                 );
00289                 t3lib_div::callUserFunction($funcName, $_params, $this);
00290             }
00291         }
00292 
00293             // Set all posible headers that could ensure that the script is not cached on the client-side
00294         if ($this->sendNoCacheHeaders) {
00295             header('Expires: 0');
00296             header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
00297             header('Cache-Control: no-cache, must-revalidate');
00298             header('Pragma: no-cache');
00299         }
00300 
00301             // Set $this->gc_time if not explicitely specified
00302         if ($this->gc_time == 0) {
00303             $this->gc_time = ($this->auth_timeout_field == 0 ? 86400 : $this->auth_timeout_field); // Default to 1 day if $this->auth_timeout_field is 0
00304         }
00305 
00306             // If we're lucky we'll get to clean up old sessions....
00307         if ((rand() % 100) <= $this->gc_probability) {
00308             $this->gc();
00309         }
00310 
00311     }
00312 
00313     /**
00314      * Sets the session cookie for the current disposal.
00315      *
00316      * @return  void
00317      */
00318     protected function setSessionCookie() {
00319         $isSetSessionCookie = $this->isSetSessionCookie();
00320         $isRefreshTimeBasedCookie = $this->isRefreshTimeBasedCookie();
00321 
00322         if ($isSetSessionCookie || $isRefreshTimeBasedCookie) {
00323             $settings = $GLOBALS['TYPO3_CONF_VARS']['SYS'];
00324 
00325                 // Get the domain to be used for the cookie (if any):
00326             $cookieDomain = $this->getCookieDomain();
00327                 // If no cookie domain is set, use the base path:
00328             $cookiePath = ($cookieDomain ? '/' : t3lib_div::getIndpEnv('TYPO3_SITE_PATH'));
00329                 // If the cookie lifetime is set, use it:
00330             $cookieExpire = ($isRefreshTimeBasedCookie ? $GLOBALS['EXEC_TIME'] + $this->lifetime : 0);
00331                 // Use the secure option when the current request is served by a secure connection:
00332             $cookieSecure = (bool) $settings['cookieSecure'] && t3lib_div::getIndpEnv('TYPO3_SSL');
00333                 // Deliver cookies only via HTTP and prevent possible XSS by JavaScript:
00334             $cookieHttpOnly = (bool) $settings['cookieHttpOnly'];
00335 
00336                 // Do not set cookie if cookieSecure is set to "1" (force HTTPS) and no secure channel is used:
00337             if ((int) $settings['cookieSecure'] !== 1 || t3lib_div::getIndpEnv('TYPO3_SSL')) {
00338                 setcookie(
00339                     $this->name,
00340                     $this->id,
00341                     $cookieExpire,
00342                     $cookiePath,
00343                     $cookieDomain,
00344                     $cookieSecure,
00345                     $cookieHttpOnly
00346                 );
00347             } else {
00348                 throw new t3lib_exception(
00349                     'Cookie was not set since HTTPS was forced in $TYPO3_CONF_VARS[SYS][cookieSecure].',
00350                     1254325546
00351                 );
00352             }
00353 
00354             if ($this->writeDevLog) {
00355                 $devLogMessage = ($isRefreshTimeBasedCookie ? 'Updated Cookie: ' : 'Set Cookie: ') . $this->id;
00356                 t3lib_div::devLog($devLogMessage . ($cookieDomain ? ', ' . $cookieDomain : ''), 't3lib_userAuth');
00357             }
00358         }
00359     }
00360 
00361     /**
00362      * Gets the domain to be used on setting cookies.
00363      * The information is taken from the value in $TYPO3_CONF_VARS[SYS][cookieDomain].
00364      *
00365      * @return  string      The domain to be used on setting cookies
00366      */
00367     protected function getCookieDomain() {
00368         $result = '';
00369         $cookieDomain = $GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieDomain'];
00370             // If a specific cookie domain is defined for a given TYPO3_MODE,
00371             // use that domain
00372         if (!empty($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['cookieDomain'])) {
00373             $cookieDomain = $GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['cookieDomain'];
00374         }
00375 
00376         if ($cookieDomain) {
00377             if ($cookieDomain{0} == '/') {
00378                 $match = array();
00379                 $matchCnt = @preg_match($cookieDomain, t3lib_div::getIndpEnv('TYPO3_HOST_ONLY'), $match);
00380                 if ($matchCnt === FALSE) {
00381                     t3lib_div::sysLog('The regular expression for the cookie domain (' . $cookieDomain . ') contains errors. The session is not shared across sub-domains.', 'Core', 3);
00382                 } elseif ($matchCnt) {
00383                     $result = $match[0];
00384                 }
00385             } else {
00386                 $result = $cookieDomain;
00387             }
00388         }
00389 
00390         return $result;
00391     }
00392 
00393     /**
00394      * Get the value of a specified cookie.
00395      *
00396      * Uses HTTP_COOKIE, if available, to avoid a IE8 bug where multiple
00397      * cookies with the same name might be returned if the user accessed
00398      * the site without "www." first and switched to "www." later:
00399      *   Cookie: fe_typo_user=AAA; fe_typo_user=BBB
00400      * In this case PHP will set _COOKIE as the first cookie, when we
00401      * would need the last one (which is what this function then returns).
00402      *
00403      * @param   string      The cookie ID
00404      * @return  string      The value stored in the cookie
00405      */
00406     protected function getCookie($cookieName) {
00407         if (isset($_SERVER['HTTP_COOKIE'])) {
00408             $cookies = t3lib_div::trimExplode(';', $_SERVER['HTTP_COOKIE']);
00409             foreach ($cookies as $cookie) {
00410                 list ($name, $value) = t3lib_div::trimExplode('=', $cookie);
00411                 if (strcmp(trim($name), $cookieName) == 0) {
00412                         // Use the last one
00413                     $cookieValue = urldecode($value);
00414                 }
00415             }
00416         } else {
00417                 // Fallback if there is no HTTP_COOKIE, use original method:
00418             $cookieValue = isset($_COOKIE[$cookieName]) ? stripslashes($_COOKIE[$cookieName]) : '';
00419         }
00420         return $cookieValue;
00421     }
00422 
00423     /**
00424      * Determine whether a session cookie needs to be set (lifetime=0)
00425      *
00426      * @return  boolean
00427      * @internal
00428      */
00429     function isSetSessionCookie() {
00430         return ($this->newSessionID || $this->forceSetCookie) && $this->lifetime == 0;
00431     }
00432 
00433     /**
00434      * Determine whether a non-session cookie needs to be set (lifetime>0)
00435      *
00436      * @return  boolean
00437      * @internal
00438      */
00439     function isRefreshTimeBasedCookie() {
00440         return $this->lifetime > 0;
00441     }
00442 
00443     /**
00444      * Checks if a submission of username and password is present or use other authentication by auth services
00445      *
00446      * @return  void
00447      * @internal
00448      */
00449     function checkAuthentication() {
00450 
00451             // No user for now - will be searched by service below
00452         $tempuserArr = array();
00453         $tempuser = FALSE;
00454 
00455             // User is not authenticated by default
00456         $authenticated = FALSE;
00457 
00458             // User want to login with passed login data (name/password)
00459         $activeLogin = FALSE;
00460 
00461             // Indicates if an active authentication failed (not auto login)
00462         $this->loginFailure = FALSE;
00463 
00464         if ($this->writeDevLog) {
00465             t3lib_div::devLog('Login type: ' . $this->loginType, 't3lib_userAuth');
00466         }
00467 
00468             // The info array provide additional information for auth services
00469         $authInfo = $this->getAuthInfoArray();
00470 
00471             // Get Login/Logout data submitted by a form or params
00472         $loginData = $this->getLoginFormData();
00473 
00474         if ($this->writeDevLog) {
00475             t3lib_div::devLog('Login data: ' . t3lib_div::arrayToLogString($loginData), 't3lib_userAuth');
00476         }
00477 
00478 
00479             // active logout (eg. with "logout" button)
00480         if ($loginData['status'] == 'logout') {
00481             if ($this->writeStdLog) {
00482                     // $type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid
00483                 $this->writelog(255, 2, 0, 2, 'User %s logged out', array($this->user['username']), '', 0, 0);
00484             } // Logout written to log
00485             if ($this->writeDevLog) {
00486                 t3lib_div::devLog('User logged out. Id: ' . $this->id, 't3lib_userAuth', -1);
00487             }
00488 
00489             $this->logoff();
00490         }
00491 
00492             // active login (eg. with login form)
00493         if ($loginData['status'] == 'login') {
00494             $activeLogin = TRUE;
00495 
00496             if ($this->writeDevLog) {
00497                 t3lib_div::devLog('Active login (eg. with login form)', 't3lib_userAuth');
00498             }
00499 
00500                 // check referer for submitted login values
00501             if ($this->formfield_status && $loginData['uident'] && $loginData['uname']) {
00502                 $httpHost = t3lib_div::getIndpEnv('TYPO3_HOST_ONLY');
00503                 if (!$this->getMethodEnabled && ($httpHost != $authInfo['refInfo']['host'] && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer'])) {
00504                     throw new RuntimeException(
00505                         'TYPO3 Fatal Error: Error: This host address ("' . $httpHost . '") and the referer host ("' . $authInfo['refInfo']['host'] . '") mismatches!<br />
00506                         It\'s possible that the environment variable HTTP_REFERER is not passed to the script because of a proxy.<br />
00507                         The site administrator can disable this check in the "All Configuration" section of the Install Tool (flag: TYPO3_CONF_VARS[SYS][doNotCheckReferer]).',
00508                         1270853930
00509                     );
00510                 }
00511 
00512                     // delete old user session if any
00513                 $this->logoff();
00514             }
00515 
00516                 // Refuse login for _CLI users, if not processing a CLI request type
00517                 // (although we shouldn't be here in case of a CLI request type)
00518             if ((strtoupper(substr($loginData['uname'], 0, 5)) == '_CLI_') && !(TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)) {
00519                 throw new RuntimeException(
00520                     'TYPO3 Fatal Error: You have tried to login using a CLI user. Access prohibited!',
00521                     1270853931
00522                 );
00523             }
00524         }
00525 
00526 
00527             // the following code makes auto-login possible (if configured). No submitted data needed
00528 
00529             // determine whether we need to skip session update.
00530             // This is used mainly for checking session timeout without
00531             // refreshing the session itself while checking.
00532         if (t3lib_div::_GP('skipSessionUpdate')) {
00533             $skipSessionUpdate = TRUE;
00534         } else {
00535             $skipSessionUpdate = FALSE;
00536         }
00537 
00538             // re-read user session
00539         $authInfo['userSession'] = $this->fetchUserSession($skipSessionUpdate);
00540         $haveSession = is_array($authInfo['userSession']) ? TRUE : FALSE;
00541 
00542         if ($this->writeDevLog) {
00543             if ($haveSession) {
00544                 t3lib_div::devLog('User session found: ' . t3lib_div::arrayToLogString($authInfo['userSession'], array($this->userid_column, $this->username_column)), 't3lib_userAuth', 0);
00545             }
00546             if (is_array($this->svConfig['setup'])) {
00547                 t3lib_div::devLog('SV setup: ' . t3lib_div::arrayToLogString($this->svConfig['setup']), 't3lib_userAuth', 0);
00548             }
00549         }
00550 
00551             // fetch user if ...
00552         if ($activeLogin
00553             || (!$haveSession && $this->svConfig['setup'][$this->loginType . '_fetchUserIfNoSession'])
00554             || $this->svConfig['setup'][$this->loginType . '_alwaysFetchUser']) {
00555 
00556                 // use 'auth' service to find the user
00557                 // first found user will be used
00558             $serviceChain = '';
00559             $subType = 'getUser' . $this->loginType;
00560             while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
00561                 $serviceChain .= ',' . $serviceObj->getServiceKey();
00562                 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
00563                 if ($row = $serviceObj->getUser()) {
00564                     $tempuserArr[] = $row;
00565 
00566                     if ($this->writeDevLog) {
00567                         t3lib_div::devLog('User found: ' . t3lib_div::arrayToLogString($row, array($this->userid_column, $this->username_column)), 't3lib_userAuth', 0);
00568                     }
00569 
00570                         // user found, just stop to search for more if not configured to go on
00571                     if (!$this->svConfig['setup'][$this->loginType . '_fetchAllUsers']) {
00572                         break;
00573                     }
00574                 }
00575                 unset($serviceObj);
00576             }
00577             unset($serviceObj);
00578 
00579             if ($this->writeDevLog && $this->svConfig['setup'][$this->loginType . '_alwaysFetchUser']) {
00580                 t3lib_div::devLog($this->loginType . '_alwaysFetchUser option is enabled', 't3lib_userAuth');
00581             }
00582             if ($this->writeDevLog && $serviceChain) {
00583                 t3lib_div::devLog($subType . ' auth services called: ' . $serviceChain, 't3lib_userAuth');
00584             }
00585             if ($this->writeDevLog && !count($tempuserArr)) {
00586                 t3lib_div::devLog('No user found by services', 't3lib_userAuth');
00587             }
00588             if ($this->writeDevLog && count($tempuserArr)) {
00589                 t3lib_div::devLog(count($tempuserArr) . ' user records found by services', 't3lib_userAuth');
00590             }
00591         }
00592 
00593 
00594             // If no new user was set we use the already found user session
00595         if (!count($tempuserArr) && $haveSession) {
00596             $tempuserArr[] = $authInfo['userSession'];
00597             $tempuser = $authInfo['userSession'];
00598                 // User is authenticated because we found a user session
00599             $authenticated = TRUE;
00600 
00601             if ($this->writeDevLog) {
00602                 t3lib_div::devLog('User session used: ' . t3lib_div::arrayToLogString($authInfo['userSession'], array($this->userid_column, $this->username_column)), 't3lib_userAuth');
00603             }
00604         }
00605 
00606 
00607             // Re-auth user when 'auth'-service option is set
00608         if ($this->svConfig['setup'][$this->loginType . '_alwaysAuthUser']) {
00609             $authenticated = FALSE;
00610             if ($this->writeDevLog) {
00611                 t3lib_div::devLog('alwaysAuthUser option is enabled', 't3lib_userAuth');
00612             }
00613         }
00614 
00615 
00616             // Authenticate the user if needed
00617         if (count($tempuserArr) && !$authenticated) {
00618 
00619             foreach ($tempuserArr as $tempuser) {
00620 
00621                     // use 'auth' service to authenticate the user
00622                     // if one service returns FALSE then authentication failed
00623                     // a service might return 100 which means there's no reason to stop but the user can't be authenticated by that service
00624 
00625                 if ($this->writeDevLog) {
00626                     t3lib_div::devLog('Auth user: ' . t3lib_div::arrayToLogString($tempuser), 't3lib_userAuth');
00627                 }
00628 
00629                 $serviceChain = '';
00630                 $subType = 'authUser' . $this->loginType;
00631                 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
00632                     $serviceChain .= ',' . $serviceObj->getServiceKey();
00633                     $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
00634                     if (($ret = $serviceObj->authUser($tempuser)) > 0) {
00635 
00636                             // if the service returns >=200 then no more checking is needed - useful for IP checking without password
00637                         if (intval($ret) >= 200) {
00638                             $authenticated = TRUE;
00639                             break;
00640                         } elseif (intval($ret) >= 100) {
00641                             // Just go on. User is still not authenticated but there's no reason to stop now.
00642                         } else {
00643                             $authenticated = TRUE;
00644                         }
00645 
00646                     } else {
00647                         $authenticated = FALSE;
00648                         break;
00649                     }
00650                     unset($serviceObj);
00651                 }
00652                 unset($serviceObj);
00653 
00654                 if ($this->writeDevLog && $serviceChain) {
00655                     t3lib_div::devLog($subType . ' auth services called: ' . $serviceChain, 't3lib_userAuth');
00656                 }
00657 
00658                 if ($authenticated) {
00659                         // leave foreach() because a user is authenticated
00660                     break;
00661                 }
00662             }
00663         }
00664 
00665             // If user is authenticated a valid user is in $tempuser
00666         if ($authenticated) {
00667                 // reset failure flag
00668             $this->loginFailure = FALSE;
00669 
00670                 // Insert session record if needed:
00671             if (!($haveSession && (
00672                     $tempuser['ses_id'] == $this->id || // check if the tempuser has the current session id
00673                     $tempuser['uid'] == $authInfo['userSession']['ses_userid'] // check if the tempuser has the uid of the fetched session user
00674             ))) {
00675                 $this->createUserSession($tempuser);
00676 
00677                     // The login session is started.
00678                 $this->loginSessionStarted = TRUE;
00679             }
00680 
00681                 // User logged in - write that to the log!
00682             if ($this->writeStdLog && $activeLogin) {
00683                 $this->writelog(255, 1, 0, 1,
00684                                 'User %s logged in from %s (%s)',
00685                                 array($tempuser[$this->username_column], t3lib_div::getIndpEnv('REMOTE_ADDR'), t3lib_div::getIndpEnv('REMOTE_HOST')),
00686                                 '', '', '', -1, '', $tempuser['uid']
00687                 );
00688             }
00689 
00690             if ($this->writeDevLog && $activeLogin) {
00691                 t3lib_div::devLog('User ' . $tempuser[$this->username_column] . ' logged in from ' . t3lib_div::getIndpEnv('REMOTE_ADDR') . ' (' . t3lib_div::getIndpEnv('REMOTE_HOST') . ')', 't3lib_userAuth', -1);
00692             }
00693             if ($this->writeDevLog && !$activeLogin) {
00694                 t3lib_div::devLog('User ' . $tempuser[$this->username_column] . ' authenticated from ' . t3lib_div::getIndpEnv('REMOTE_ADDR') . ' (' . t3lib_div::getIndpEnv('REMOTE_HOST') . ')', 't3lib_userAuth', -1);
00695             }
00696 
00697             if ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] == 3 && $this->user_table == 'be_users') {
00698                 $requestStr = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'), strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir));
00699                 $backendScript = t3lib_BEfunc::getBackendScript();
00700                 if ($requestStr == $backendScript && t3lib_div::getIndpEnv('TYPO3_SSL')) {
00701                     list(, $url) = explode('://', t3lib_div::getIndpEnv('TYPO3_SITE_URL'), 2);
00702                     list($server, $address) = explode('/', $url, 2);
00703                     if (intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'])) {
00704                         $sslPortSuffix = ':' . intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']);
00705                         $server = str_replace($sslPortSuffix, '', $server); // strip port from server
00706                     }
00707                     t3lib_utility_Http::redirect('http://' . $server . '/' . $address . TYPO3_mainDir . $backendScript);
00708                 }
00709             }
00710 
00711         } elseif ($activeLogin || count($tempuserArr)) {
00712             $this->loginFailure = TRUE;
00713 
00714             if ($this->writeDevLog && !count($tempuserArr) && $activeLogin) {
00715                 t3lib_div::devLog('Login failed: ' . t3lib_div::arrayToLogString($loginData), 't3lib_userAuth', 2);
00716             }
00717             if ($this->writeDevLog && count($tempuserArr)) {
00718                 t3lib_div::devLog('Login failed: ' . t3lib_div::arrayToLogString($tempuser, array($this->userid_column, $this->username_column)), 't3lib_userAuth', 2);
00719             }
00720         }
00721 
00722 
00723             // If there were a login failure, check to see if a warning email should be sent:
00724         if ($this->loginFailure && $activeLogin) {
00725             if ($this->writeDevLog) {
00726                 t3lib_div::devLog('Call checkLogFailures: ' . t3lib_div::arrayToLogString(array('warningEmail' => $this->warningEmail, 'warningPeriod' => $this->warningPeriod, 'warningMax' => $this->warningMax,)), 't3lib_userAuth', -1);
00727             }
00728 
00729             $this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax);
00730         }
00731     }
00732 
00733     /**
00734      * Creates a new session ID.
00735      *
00736      * @return  string      The new session ID
00737      */
00738     public function createSessionId() {
00739         return t3lib_div::getRandomHexString($this->hash_length);
00740     }
00741 
00742 
00743     /*************************
00744      *
00745      * User Sessions
00746      *
00747      *************************/
00748 
00749 
00750     /**
00751      * Creates a user session record.
00752      *
00753      * @param   array       user data array
00754      * @return  void
00755      */
00756     function createUserSession($tempuser) {
00757 
00758         if ($this->writeDevLog) {
00759             t3lib_div::devLog('Create session ses_id = ' . $this->id, 't3lib_userAuth');
00760         }
00761 
00762             // delete session entry first
00763         $GLOBALS['TYPO3_DB']->exec_DELETEquery(
00764             $this->session_table,
00765             'ses_id = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table) . '
00766                         AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
00767         );
00768 
00769             // re-create session entry
00770         $insertFields = $this->getNewSessionRecord($tempuser);
00771         $GLOBALS['TYPO3_DB']->exec_INSERTquery($this->session_table, $insertFields);
00772 
00773             // Updating lastLogin_column carrying information about last login.
00774         if ($this->lastLogin_column) {
00775             $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
00776                 $this->user_table,
00777                 $this->userid_column . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tempuser[$this->userid_column], $this->user_table),
00778                 array($this->lastLogin_column => $GLOBALS['EXEC_TIME'])
00779             );
00780         }
00781     }
00782 
00783     /**
00784      * Returns a new session record for the current user for insertion into the DB.
00785      * This function is mainly there as a wrapper for inheriting classes to override it.
00786      *
00787      * @return  array       user session record
00788      */
00789     function getNewSessionRecord($tempuser) {
00790         return array(
00791             'ses_id' => $this->id,
00792             'ses_name' => $this->name,
00793             'ses_iplock' => $tempuser['disableIPlock'] ? '[DISABLED]' : $this->ipLockClause_remoteIPNumber($this->lockIP),
00794             'ses_hashlock' => $this->hashLockClause_getHashInt(),
00795             'ses_userid' => $tempuser[$this->userid_column],
00796             'ses_tstamp' => $GLOBALS['EXEC_TIME']
00797         );
00798     }
00799 
00800     /**
00801      * Read the user session from db.
00802      *
00803      * @return  array       user session data
00804      */
00805     function fetchUserSession($skipSessionUpdate = FALSE) {
00806 
00807         $user = '';
00808 
00809         if ($this->writeDevLog) {
00810             t3lib_div::devLog('Fetch session ses_id = ' . $this->id, 't3lib_userAuth');
00811         }
00812 
00813             // fetch the user session from the DB
00814         $statement = $this->fetchUserSessionFromDB();
00815         $user = FALSE;
00816         if ($statement) {
00817             $statement->execute();
00818             $user = $statement->fetch();
00819             $statement->free();
00820         }
00821 
00822         if ($statement && $user) {
00823                 // A user was found
00824             if (is_string($this->auth_timeout_field)) {
00825                 $timeout = intval($user[$this->auth_timeout_field]); // Get timeout-time from usertable
00826             } else {
00827                 $timeout = intval($this->auth_timeout_field); // Get timeout from object
00828             }
00829                 // If timeout > 0 (true) and currenttime has not exceeded the latest sessions-time plus the timeout in seconds then accept user
00830                 // Option later on: We could check that last update was at least x seconds ago in order not to update twice in a row if one script redirects to another...
00831             if ($timeout > 0 && ($GLOBALS['EXEC_TIME'] < ($user['ses_tstamp'] + $timeout))) {
00832                 if (!$skipSessionUpdate) {
00833                     $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
00834                         $this->session_table,
00835                         'ses_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table) . '
00836                                                 AND ses_name=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table),
00837                         array('ses_tstamp' => $GLOBALS['EXEC_TIME'])
00838                     );
00839                     $user['ses_tstamp'] = $GLOBALS['EXEC_TIME']; // Make sure that the timestamp is also updated in the array
00840                 }
00841 
00842             } else {
00843                 $this->logoff(); // delete any user set...
00844             }
00845         } else {
00846             $this->logoff(); // delete any user set...
00847         }
00848         return $user;
00849     }
00850 
00851     /**
00852      * Log out current user!
00853      * Removes the current session record, sets the internal ->user array to a blank string; Thereby the current user (if any) is effectively logged out!
00854      *
00855      * @return  void
00856      */
00857     function logoff() {
00858         if ($this->writeDevLog) {
00859             t3lib_div::devLog('logoff: ses_id = ' . $this->id, 't3lib_userAuth');
00860         }
00861 
00862             // Hook for pre-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
00863         if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'])) {
00864             $_params = array();
00865             foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'] as $_funcRef) {
00866                 if ($_funcRef) {
00867                     t3lib_div::callUserFunction($_funcRef, $_params, $this);
00868                 }
00869             }
00870         }
00871 
00872         $GLOBALS['TYPO3_DB']->exec_DELETEquery(
00873             $this->session_table,
00874             'ses_id = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table) . '
00875                         AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
00876         );
00877 
00878         $this->user = '';
00879 
00880             // Hook for post-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
00881         if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'])) {
00882             $_params = array();
00883             foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'] as $_funcRef) {
00884                 if ($_funcRef) {
00885                     t3lib_div::callUserFunction($_funcRef, $_params, $this);
00886                 }
00887             }
00888         }
00889     }
00890 
00891     /**
00892      * Determine whether there's an according session record to a given session_id
00893      * in the database. Don't care if session record is still valid or not.
00894      *
00895      * @param   integer     Claimed Session ID
00896      * @return  boolean     Returns true if a corresponding session was found in the database
00897      */
00898     function isExistingSessionRecord($id) {
00899         $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery(
00900             'COUNT(*)',
00901             $this->session_table,
00902             'ses_id = :ses_id'
00903         );
00904         $statement->execute(array(':ses_id' => $id));
00905         $row = $statement->fetch(t3lib_db_PreparedStatement::FETCH_NUM);
00906         $statement->free();
00907 
00908         return (($row[0] ? TRUE : FALSE));
00909     }
00910 
00911 
00912     /*************************
00913      *
00914      * SQL Functions
00915      *
00916      *************************/
00917 
00918     /**
00919      * The session_id is used to find user in the database.
00920      * Two tables are joined: The session-table with user_id of the session and the usertable with its primary key
00921      * if the client is flash (e.g. from a flash application inside TYPO3 that does a server request)
00922      * then don't evaluate with the hashLockClause, as the client/browser is included in this hash
00923      * and thus, the flash request would be rejected
00924      *
00925      * @return t3lib_db_PreparedStatement
00926      * @access private
00927      */
00928     protected function fetchUserSessionFromDB() {
00929         $statement = NULL;
00930         $ipLockClause = $this->ipLockClause();
00931 
00932         if ($GLOBALS['CLIENT']['BROWSER'] == 'flash') {
00933                 // if on the flash client, the veri code is valid, then the user session is fetched
00934                 // from the DB without the hashLock clause
00935             if (t3lib_div::_GP('vC') == $this->veriCode()) {
00936                 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery(
00937                     '*',
00938                     $this->session_table . ',' . $this->user_table,
00939                     $this->session_table . '.ses_id = :ses_id
00940                         AND ' . $this->session_table . '.ses_name = :ses_name
00941                         AND ' . $this->session_table . '.ses_userid = ' . $this->user_table . '.' . $this->userid_column . '
00942                         ' . $ipLockClause['where'] . '
00943                         ' . $this->user_where_clause()
00944                 );
00945                 $statement->bindValues(array(
00946                                             ':ses_id' => $this->id,
00947                                             ':ses_name' => $this->name,
00948                                        ));
00949                 $statement->bindValues($ipLockClause['parameters']);
00950             }
00951         } else {
00952             $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery(
00953                 '*',
00954                 $this->session_table . ',' . $this->user_table,
00955                 $this->session_table . '.ses_id = :ses_id
00956                     AND ' . $this->session_table . '.ses_name = :ses_name
00957                     AND ' . $this->session_table . '.ses_userid = ' . $this->user_table . '.' . $this->userid_column . '
00958                     ' . $ipLockClause['where'] . '
00959                     ' . $this->hashLockClause() . '
00960                     ' . $this->user_where_clause()
00961             );
00962             $statement->bindValues(array(
00963                                         ':ses_id' => $this->id,
00964                                         ':ses_name' => $this->name,
00965                                    ));
00966             $statement->bindValues($ipLockClause['parameters']);
00967         }
00968         return $statement;
00969     }
00970 
00971 
00972     /**
00973      * This returns the where-clause needed to select the user with respect flags like deleted, hidden, starttime, endtime
00974      *
00975      * @return  string
00976      * @access private
00977      */
00978     protected function user_where_clause() {
00979         return (($this->enablecolumns['rootLevel']) ? 'AND ' . $this->user_table . '.pid=0 ' : '') .
00980                (($this->enablecolumns['disabled']) ? ' AND ' . $this->user_table . '.' . $this->enablecolumns['disabled'] . '=0' : '') .
00981                (($this->enablecolumns['deleted']) ? ' AND ' . $this->user_table . '.' . $this->enablecolumns['deleted'] . '=0' : '') .
00982                (($this->enablecolumns['starttime']) ? ' AND (' . $this->user_table . '.' . $this->enablecolumns['starttime'] . '<=' . $GLOBALS['EXEC_TIME'] . ')' : '') .
00983                (($this->enablecolumns['endtime']) ? ' AND (' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '=0 OR ' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '>' . $GLOBALS['EXEC_TIME'] . ')' : '');
00984     }
00985 
00986     /**
00987      * This returns the where prepared statement-clause needed to lock a user to the IP address
00988      *
00989      * @return array
00990      * @access private
00991      */
00992     protected function ipLockClause() {
00993         $statementClause = array(
00994             'where' => '',
00995             'parameters' => array(),
00996         );
00997         if ($this->lockIP) {
00998             $statementClause['where'] = 'AND (
00999                 ' . $this->session_table . '.ses_iplock = :ses_iplock
01000                 OR ' . $this->session_table . '.ses_iplock=\'[DISABLED]\'
01001                 )';
01002             $statementClause['parameters'] = array(
01003                 ':ses_iplock' => $this->ipLockClause_remoteIPNumber($this->lockIP),
01004             );
01005         }
01006         return $statementClause;
01007     }
01008 
01009     /**
01010      * Returns the IP address to lock to.
01011      * The IP address may be partial based on $parts.
01012      *
01013      * @param   integer     1-4: Indicates how many parts of the IP address to return. 4 means all, 1 means only first number.
01014      * @return  string      (Partial) IP address for REMOTE_ADDR
01015      * @access private
01016      */
01017     protected function ipLockClause_remoteIPNumber($parts) {
01018         $IP = t3lib_div::getIndpEnv('REMOTE_ADDR');
01019 
01020         if ($parts >= 4) {
01021             return $IP;
01022         } else {
01023             $parts = t3lib_div::intInRange($parts, 1, 3);
01024             $IPparts = explode('.', $IP);
01025             for ($a = 4; $a > $parts; $a--) {
01026                 unset($IPparts[$a - 1]);
01027             }
01028             return implode('.', $IPparts);
01029         }
01030     }
01031 
01032     /**
01033      * VeriCode returns 10 first chars of a md5 hash of the session cookie AND the encryptionKey from TYPO3_CONF_VARS.
01034      * This code is used as an alternative verification when the JavaScript interface executes cmd's to tce_db.php from eg. MSIE 5.0 because the proper referer is not passed with this browser...
01035      *
01036      * @return  string
01037      */
01038     public function veriCode() {
01039         return substr(md5($this->id . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, 10);
01040     }
01041 
01042     /**
01043      * This returns the where-clause needed to lock a user to a hash integer
01044      *
01045      * @return  string
01046      * @access private
01047      */
01048     protected function hashLockClause() {
01049         $wherePart = 'AND ' . $this->session_table . '.ses_hashlock=' . intval($this->hashLockClause_getHashInt());
01050         return $wherePart;
01051     }
01052 
01053     /**
01054      * Creates hash integer to lock user to. Depends on configured keywords
01055      *
01056      * @return  integer     Hash integer
01057      * @access private
01058      */
01059     protected function hashLockClause_getHashInt() {
01060         $hashStr = '';
01061 
01062         if (t3lib_div::inList($this->lockHashKeyWords, 'useragent')) {
01063             $hashStr .= ':' . t3lib_div::getIndpEnv('HTTP_USER_AGENT');
01064         }
01065 
01066         return t3lib_div::md5int($hashStr);
01067     }
01068 
01069 
01070     /*************************
01071      *
01072      * Session and Configuration Handling
01073      *
01074      *************************/
01075 
01076     /**
01077      * This writes $variable to the user-record. This is a way of providing session-data.
01078      * You can fetch the data again through $this->uc in this class!
01079      * If $variable is not an array, $this->uc is saved!
01080      *
01081      * @param   array       An array you want to store for the user as session data. If $variable is not supplied (is blank string), the internal variable, ->uc, is stored by default
01082      * @return  void
01083      */
01084     function writeUC($variable = '') {
01085         if (is_array($this->user) && $this->user[$this->userid_column]) {
01086             if (!is_array($variable)) {
01087                 $variable = $this->uc;
01088             }
01089 
01090             if ($this->writeDevLog) {
01091                 t3lib_div::devLog('writeUC: ' . $this->userid_column . '=' . intval($this->user[$this->userid_column]), 't3lib_userAuth');
01092             }
01093             $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->user_table, $this->userid_column . '=' . intval($this->user[$this->userid_column]), array('uc' => serialize($variable)));
01094         }
01095     }
01096 
01097     /**
01098      * Sets $theUC as the internal variable ->uc IF $theUC is an array. If $theUC is false, the 'uc' content from the ->user array will be unserialized and restored in ->uc
01099      *
01100      * @param   mixed       If an array, then set as ->uc, otherwise load from user record
01101      * @return  void
01102      */
01103     function unpack_uc($theUC = '') {
01104         if (!$theUC) {
01105             $theUC = unserialize($this->user['uc']);
01106         }
01107         if (is_array($theUC)) {
01108             $this->uc = $theUC;
01109         }
01110     }
01111 
01112     /**
01113      * Stores data for a module.
01114      * The data is stored with the session id so you can even check upon retrieval if the module data is from a previous session or from the current session.
01115      *
01116      * @param   string      $module is the name of the module ($MCONF['name'])
01117      * @param   mixed       $data is the data you want to store for that module (array, string, ...)
01118      * @param   boolean     If $noSave is set, then the ->uc array (which carries all kinds of user data) is NOT written immediately, but must be written by some subsequent call.
01119      * @return  void
01120      */
01121     function pushModuleData($module, $data, $noSave = 0) {
01122         $this->uc['moduleData'][$module] = $data;
01123         $this->uc['moduleSessionID'][$module] = $this->id;
01124         if (!$noSave) {
01125             $this->writeUC();
01126         }
01127     }
01128 
01129     /**
01130      * Gets module data for a module (from a loaded ->uc array)
01131      *
01132      * @param   string      $module is the name of the module ($MCONF['name'])
01133      * @param   string      If $type = 'ses' then module data is returned only if it was stored in the current session, otherwise data from a previous session will be returned (if available).
01134      * @return  mixed       The module data if available: $this->uc['moduleData'][$module];
01135      */
01136     function getModuleData($module, $type = '') {
01137         if ($type != 'ses' || $this->uc['moduleSessionID'][$module] == $this->id) {
01138             return $this->uc['moduleData'][$module];
01139         }
01140     }
01141 
01142     /**
01143      * Returns the session data stored for $key.
01144      * The data will last only for this login session since it is stored in the session table.
01145      *
01146      * @param   string      Pointer to an associative key in the session data array which is stored serialized in the field "ses_data" of the session table.
01147      * @return  mixed
01148      */
01149     function getSessionData($key) {
01150         $sesDat = unserialize($this->user['ses_data']);
01151         return $sesDat[$key];
01152     }
01153 
01154     /**
01155      * Sets the session data ($data) for $key and writes all session data (from ->user['ses_data']) to the database.
01156      * The data will last only for this login session since it is stored in the session table.
01157      *
01158      * @param   string      Pointer to an associative key in the session data array which is stored serialized in the field "ses_data" of the session table.
01159      * @param   mixed       The variable to store in index $key
01160      * @return  void
01161      */
01162     function setAndSaveSessionData($key, $data) {
01163         $sesDat = unserialize($this->user['ses_data']);
01164         $sesDat[$key] = $data;
01165         $this->user['ses_data'] = serialize($sesDat);
01166 
01167         if ($this->writeDevLog) {
01168             t3lib_div::devLog('setAndSaveSessionData: ses_id = ' . $this->user['ses_id'], 't3lib_userAuth');
01169         }
01170         $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->session_table, 'ses_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->user['ses_id'], $this->session_table), array('ses_data' => $this->user['ses_data']));
01171     }
01172 
01173 
01174     /*************************
01175      *
01176      * Misc
01177      *
01178      *************************/
01179 
01180     /**
01181      * Returns an info array with Login/Logout data submitted by a form or params
01182      *
01183      * @return  array
01184      * @internal
01185      */
01186     function getLoginFormData() {
01187         $loginData = array();
01188         if ($this->getMethodEnabled) {
01189             $loginData['status'] = t3lib_div::_GP($this->formfield_status);
01190             $loginData['uname'] = t3lib_div::_GP($this->formfield_uname);
01191             $loginData['uident'] = t3lib_div::_GP($this->formfield_uident);
01192             $loginData['chalvalue'] = t3lib_div::_GP($this->formfield_chalvalue);
01193         } else {
01194             $loginData['status'] = t3lib_div::_POST($this->formfield_status);
01195             $loginData['uname'] = t3lib_div::_POST($this->formfield_uname);
01196             $loginData['uident'] = t3lib_div::_POST($this->formfield_uident);
01197             $loginData['chalvalue'] = t3lib_div::_POST($this->formfield_chalvalue);
01198         }
01199         $loginData = $this->processLoginData($loginData);
01200 
01201         return $loginData;
01202     }
01203 
01204     /**
01205      * Processes Login data submitted by a form or params depending on the
01206      * security_level
01207      *
01208      * @param   array       login data array
01209      * @param   string      Alternative security_level. Used when authentication services wants to override the default.
01210      * @return  array       processed login data array
01211      * @internal
01212      */
01213     function processLoginData($loginData, $security_level = '') {
01214         global $TYPO3_CONF_VARS;
01215 
01216         $loginSecurityLevel = $security_level ? $security_level : ($TYPO3_CONF_VARS[$this->loginType]['loginSecurityLevel'] ? $TYPO3_CONF_VARS[$this->loginType]['loginSecurityLevel'] : $this->security_level);
01217 
01218             // Processing data according to the state it was submitted in.
01219             // ($loginSecurityLevel should reflect the security level used on the data being submitted in the login form)
01220         if ($loginSecurityLevel == 'normal') {
01221             $loginData['uident_text'] = $loginData['uident'];
01222             $loginData['uident_challenged'] = (string) md5($loginData['uname'] . ':' . $loginData['uident'] . ':' . $loginData['chalvalue']);
01223             $loginData['uident_superchallenged'] = (string) md5($loginData['uname'] . ':' . (md5($loginData['uident'])) . ':' . $loginData['chalvalue']);
01224         } elseif ($loginSecurityLevel == 'challenged') {
01225             $loginData['uident_text'] = '';
01226             $loginData['uident_challenged'] = $loginData['uident'];
01227             $loginData['uident_superchallenged'] = '';
01228         } elseif ($loginSecurityLevel == 'superchallenged') {
01229             $loginData['uident_text'] = '';
01230             $loginData['uident_challenged'] = '';
01231             $loginData['uident_superchallenged'] = $loginData['uident'];
01232         }
01233 
01234             // The password "uident" is set based on the internal security setting of TYPO3
01235             // Example:
01236             // $this->security_level for the backend must be "superchallenged" because passwords are stored as md5-hashes in the be_users table
01237             // $this->security_level for the frontend must be "normal" or "challenged" because passwords are stored as clear-text in the fe_users tables
01238         if ($this->security_level == 'normal') {
01239             $loginData['uident'] = $loginData['uident_text'];
01240         } elseif ($this->security_level == 'challenged') {
01241             $loginData['uident'] = $loginData['uident_challenged'];
01242         } elseif ($this->security_level == 'superchallenged') {
01243             $loginData['uident'] = $loginData['uident_superchallenged'];
01244         }
01245 
01246         return $loginData;
01247     }
01248 
01249     /**
01250      * Returns an info array which provides additional information for auth services
01251      *
01252      * @return  array
01253      * @internal
01254      */
01255     function getAuthInfoArray() {
01256         $authInfo = array();
01257         $authInfo['loginType'] = $this->loginType;
01258         $authInfo['refInfo'] = parse_url(t3lib_div::getIndpEnv('HTTP_REFERER'));
01259         $authInfo['HTTP_HOST'] = t3lib_div::getIndpEnv('HTTP_HOST');
01260         $authInfo['REMOTE_ADDR'] = t3lib_div::getIndpEnv('REMOTE_ADDR');
01261         $authInfo['REMOTE_HOST'] = t3lib_div::getIndpEnv('REMOTE_HOST');
01262         $authInfo['security_level'] = $this->security_level;
01263         $authInfo['showHiddenRecords'] = $this->showHiddenRecords;
01264             // can be overidden in localconf by SVCONF:
01265         $authInfo['db_user']['table'] = $this->user_table;
01266         $authInfo['db_user']['userid_column'] = $this->userid_column;
01267         $authInfo['db_user']['username_column'] = $this->username_column;
01268         $authInfo['db_user']['userident_column'] = $this->userident_column;
01269         $authInfo['db_user']['usergroup_column'] = $this->usergroup_column;
01270         $authInfo['db_user']['enable_clause'] = $this->user_where_clause();
01271         $authInfo['db_user']['checkPidList'] = $this->checkPid ? $this->checkPid_value : '';
01272         $authInfo['db_user']['check_pid_clause'] = $this->checkPid ? ' AND pid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($authInfo['db_user']['checkPidList']) . ')' : '';
01273         $authInfo['db_groups']['table'] = $this->usergroup_table;
01274         return $authInfo;
01275     }
01276 
01277     /**
01278      * Check the login data with the user record data for builtin login methods
01279      *
01280      * @param   array       user data array
01281      * @param   array       login data array
01282      * @param   string      Alternative security_level. Used when authentication services wants to override the default.
01283      * @return  boolean     true if login data matched
01284      */
01285     function compareUident($user, $loginData, $security_level = '') {
01286 
01287         $OK = FALSE;
01288         $security_level = $security_level ? $security_level : $this->security_level;
01289 
01290         switch ($security_level) {
01291             case 'superchallenged': // If superchallenged the password in the database ($user[$this->userident_column]) must be a md5-hash of the original password.
01292             case 'challenged':
01293 
01294                     // Check challenge stored in cookie:
01295                 if ($this->challengeStoredInCookie) {
01296                     session_start();
01297                     if ($_SESSION['login_challenge'] !== $loginData['chalvalue']) {
01298                         if ($this->writeDevLog) {
01299                             t3lib_div::devLog('PHP Session stored challenge "' . $_SESSION['login_challenge'] . '" and submitted challenge "' . $loginData['chalvalue'] . '" did not match, so authentication failed!', 't3lib_userAuth', 2);
01300                         }
01301                         $this->logoff();
01302                         return FALSE;
01303                     }
01304                 }
01305 
01306                 if ((string) $loginData['uident'] === (string) md5($user[$this->username_column] . ':' . $user[$this->userident_column] . ':' . $loginData['chalvalue'])) {
01307                     $OK = TRUE;
01308                 }
01309             break;
01310             default: // normal
01311                 if ((string) $loginData['uident'] === (string) $user[$this->userident_column]) {
01312                     $OK = TRUE;
01313                 }
01314             break;
01315         }
01316 
01317         return $OK;
01318     }
01319 
01320     /**
01321      * Garbage collector, removing old expired sessions.
01322      *
01323      * @return  void
01324      * @internal
01325      */
01326     function gc() {
01327         $GLOBALS['TYPO3_DB']->exec_DELETEquery(
01328             $this->session_table,
01329             'ses_tstamp < ' . intval($GLOBALS['EXEC_TIME'] - ($this->gc_time)) .
01330             ' AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
01331         );
01332     }
01333 
01334     /**
01335      * DUMMY: Writes to log database table (in some extension classes)
01336      *
01337      * @param   integer     $type: denotes which module that has submitted the entry. This is the current list:  1=tce_db; 2=tce_file; 3=system (eg. sys_history save); 4=modules; 254=Personal settings changed; 255=login / out action: 1=login, 2=logout, 3=failed login (+ errorcode 3), 4=failure_warning_email sent
01338      * @param   integer     $action: denotes which specific operation that wrote the entry (eg. 'delete', 'upload', 'update' and so on...). Specific for each $type. Also used to trigger update of the interface. (see the log-module for the meaning of each number !!)
01339      * @param   integer     $error: flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
01340      * @param   integer     $details_nr: The message number. Specific for each $type and $action. in the future this will make it possible to translate errormessages to other languages
01341      * @param   string      $details: Default text that follows the message
01342      * @param   array       $data: Data that follows the log. Might be used to carry special information. If an array the first 5 entries (0-4) will be sprintf'ed the details-text...
01343      * @param   string      $tablename: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
01344      * @param   integer     $recuid: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
01345      * @param   integer     $recpid: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
01346      * @return  void
01347      * @see t3lib_userauthgroup::writelog()
01348      */
01349     function writelog($type, $action, $error, $details_nr, $details, $data, $tablename, $recuid, $recpid) {
01350     }
01351 
01352     /**
01353      * DUMMY: Check login failures (in some extension classes)
01354      *
01355      * @return  void
01356      * @ignore
01357      */
01358     function checkLogFailures() {
01359     }
01360 
01361     /**
01362      * Raw initialization of the be_user with uid=$uid
01363      * This will circumvent all login procedures and select a be_users record from the database and set the content of ->user to the record selected. Thus the BE_USER object will appear like if a user was authenticated - however without a session id and the fields from the session table of course.
01364      * Will check the users for disabled, start/endtime, etc. ($this->user_where_clause())
01365      *
01366      * @param   integer     The UID of the backend user to set in ->user
01367      * @return  void
01368      * @internal
01369      * @see SC_mod_tools_be_user_index::compareUsers(), SC_mod_user_setup_index::simulateUser(), freesite_admin::startCreate()
01370      */
01371     function setBeUserByUid($uid) {
01372         $this->user = $this->getRawUserByUid($uid);
01373     }
01374 
01375     /**
01376      * Raw initialization of the be_user with username=$name
01377      *
01378      * @param   string      The username to look up.
01379      * @return  void
01380      * @see t3lib_userAuth::setBeUserByUid()
01381      * @internal
01382      */
01383     function setBeUserByName($name) {
01384         $this->user = $this->getRawUserByName($name);
01385     }
01386 
01387     /**
01388      * Fetching raw user record with uid=$uid
01389      *
01390      * @param   integer     The UID of the backend user to set in ->user
01391      * @return  array       user record or FALSE
01392      * @internal
01393      */
01394     function getRawUserByUid($uid) {
01395         $user = FALSE;
01396         $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'uid=' . intval($uid) . ' ' . $this->user_where_clause());
01397         if ($dbres) {
01398             $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
01399             $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
01400         }
01401         return $user;
01402     }
01403 
01404     /**
01405      * Fetching raw user record with username=$name
01406      *
01407      * @param   string      The username to look up.
01408      * @return  array       user record or FALSE
01409      * @see t3lib_userAuth::getUserByUid()
01410      * @internal
01411      */
01412     function getRawUserByName($name) {
01413         $user = FALSE;
01414         $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'username=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($name, $this->user_table) . ' ' . $this->user_where_clause());
01415         if ($dbres) {
01416             $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
01417             $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
01418         }
01419         return $user;
01420     }
01421 
01422 
01423     /*************************
01424      *
01425      * Create/update user - EXPERIMENTAL
01426      *
01427      *************************/
01428 
01429     /**
01430      * Get a user from DB by username
01431      * provided for usage from services
01432      *
01433      * @param   array       User db table definition: $this->db_user
01434      * @param   string      user name
01435      * @param   string      additional WHERE clause: " AND ...
01436      * @return  mixed       user array or FALSE
01437      */
01438     function fetchUserRecord($dbUser, $username, $extraWhere = '') {
01439         $user = FALSE;
01440 
01441         $usernameClause = $username ? ($dbUser['username_column'] . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($username, $dbUser['table'])) : '';
01442 
01443         if ($username || $extraWhere) {
01444 
01445                 // Look up the user by the username and/or extraWhere:
01446             $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
01447                 '*',
01448                 $dbUser['table'],
01449                 $usernameClause .
01450                 $dbUser['check_pid_clause'] .
01451                 $dbUser['enable_clause'] .
01452                 $extraWhere
01453             );
01454 
01455             if ($dbres) {
01456                 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
01457                 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
01458             }
01459         }
01460         return $user;
01461     }
01462 }
01463 
01464 
01465 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauth.php'])) {
01466     include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauth.php']);
01467 }
01468 
01469 ?>