git-svn-id: https://svn.typo3.org/TYPO3v4/Core/branches/TYPO3_4-2@4784 709f56b5-9817...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_userauth.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2008 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains a base class for authentication of users in TYPO3, both frontend and backend.
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
34 * @author René Fritz <r.fritz@colorcube.de>
35 */
36 /**
37 * [CLASS/FUNCTION INDEX of SCRIPT]
38 *
39 *
40 *
41 * 111: class t3lib_userAuth
42 * 195: function start()
43 * 329: function checkAuthentication()
44 *
45 * SECTION: User Sessions
46 * 569: function createUserSession ($tempuser)
47 * 606: function fetchUserSession()
48 * 657: function logoff()
49 *
50 * SECTION: SQL Functions
51 * 713: function user_where_clause()
52 * 727: function ipLockClause()
53 * 745: function ipLockClause_remoteIPNumber($parts)
54 * 766: function hashLockClause()
55 * 777: function hashLockClause_getHashInt()
56 *
57 * SECTION: Session and Configuration Handling
58 * 809: function writeUC($variable='')
59 * 824: function unpack_uc($theUC='')
60 * 840: function pushModuleData($module,$data,$noSave=0)
61 * 853: function getModuleData($module,$type='')
62 * 866: function getSessionData($key)
63 * 879: function setAndSaveSessionData($key,$data)
64 *
65 * SECTION: Misc
66 * 912: function getLoginFormData()
67 * 939: function processLoginData($loginData, $security_level='')
68 * 981: function getAuthInfoArray()
69 * 1011: function compareUident($user, $loginData, $security_level='')
70 * 1050: function gc()
71 * 1064: function redirect()
72 * 1086: function writelog($type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid)
73 * 1095: function checkLogFailures()
74 * 1108: function setBeUserByUid($uid)
75 * 1120: function setBeUserByName($name)
76 * 1131: function getRawUserByUid($uid)
77 * 1149: function getRawUserByName($name)
78 *
79 * SECTION: Create/update user - EXPERIMENTAL
80 * 1188: function fetchUserRecord($dbUser, $username, $extraWhere='' )
81 *
82 * TOTAL FUNCTIONS: 29
83 * (This index is automatically created/updated by the extension "extdeveval")
84 *
85 */
86
87
88 require_once(t3lib_extMgm::extPath('sv').'class.tx_sv_authbase.php');
89
90
91
92
93
94
95
96
97
98 /**
99 * Authentication of users in TYPO3
100 *
101 * This class is used to authenticate a login user.
102 * The class is used by both the frontend and backend. In both cases this class is a parent class to beuserauth and feuserauth
103 *
104 * See Inside TYPO3 for more information about the API of the class and internal variables.
105 *
106 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
107 * @author René Fritz <r.fritz@colorcube.de>
108 * @package TYPO3
109 * @subpackage t3lib
110 */
111 class t3lib_userAuth {
112 var $global_database = ''; // Which global database to connect to
113 var $session_table = ''; // Table to use for session data.
114 var $name = ''; // Session/Cookie name
115 var $get_name = ''; // Session/GET-var name
116
117 var $user_table = ''; // Table in database with userdata
118 var $username_column = ''; // Column for login-name
119 var $userident_column = ''; // Column for password
120 var $userid_column = ''; // Column for user-id
121 var $lastLogin_column = '';
122
123 var $enablecolumns = Array (
124 'rootLevel' => '', // Boolean: If true, 'AND pid=0' will be a part of the query...
125 'disabled' => '',
126 'starttime' => '',
127 'endtime' => '',
128 'deleted' => ''
129 );
130
131 var $formfield_uname = ''; // formfield with login-name
132 var $formfield_uident = ''; // formfield with password
133 var $formfield_chalvalue = ''; // formfield with a unique value which is used to encrypt the password and username
134 var $formfield_status = ''; // formfield with status: *'login', 'logout'. If empty login is not verified.
135 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.
136
137 var $auth_include = ''; // this is the name of the include-file containing the login form. If not set, login CAN be anonymous. If set login IS needed.
138
139 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.
140 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.
141 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
142 var $gc_probability = 1; // Possibility (in percent) for GarbageCollection to be run.
143 var $writeStdLog = FALSE; // Decides if the writelog() function is called at login and logout
144 var $writeAttemptLog = FALSE; // If the writelog() functions is called if a login-attempt has be tried without success
145 var $sendNoCacheHeaders = TRUE; // If this is set, headers is sent to assure, caching is NOT done
146 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
147 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.
148 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.
149 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).
150 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.
151
152 var $warningEmail = ''; // warning -emailaddress:
153 var $warningPeriod = 3600; // Period back in time (in seconds) in which number of failed logins are collected
154 var $warningMax = 3; // The maximum accepted number of warnings before an email is sent
155 var $checkPid = TRUE; // If set, the user-record must $checkPid_value as pid
156 var $checkPid_value=0; // The pid, the user-record must have as page-id
157
158 // Internals
159 var $id; // Internal: Will contain session_id (MD5-hash)
160 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).
161 var $loginFailure = FALSE; // Indicates if an authentication was started but failed
162 var $loginSessionStarted = FALSE; // Will be set to true if the login session is actually written during auth-check.
163
164 var $user; // Internal: Will contain user- AND session-data from database (joined tables)
165 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!
166
167 var $newSessionID = FALSE; // Will be set to true if a new session ID was created
168 var $forceSetCookie = FALSE; // Will force the session cookie to be set everytime (lifetime must be 0)
169 var $dontSetCookie = FALSE; // Will prevent the setting of the session cookie (takes precedence over forceSetCookie)
170 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.
171 var $loginType = ''; // Login type, used for services.
172
173 var $svConfig = array(); // "auth" services configuration array from $TYPO3_CONF_VARS['SVCONF']['auth']
174 var $writeDevLog = FALSE; // write messages into the devlog?
175
176
177
178
179
180
181
182
183
184 /**
185 * Starts a user session
186 * Typical configurations will:
187 * a) check if session cookie was set and if not, set one,
188 * b) check if a password/username was sent and if so, try to authenticate the user
189 * c) Lookup a session attached to a user and check timeout etc.
190 * d) Garbage collection, setting of no-cache headers.
191 * If a user is authenticated the database record of the user (array) will be set in the ->user internal variable.
192 *
193 * @return void
194 */
195 function start() {
196 global $TYPO3_CONF_VARS;
197
198 // backend or frontend login - used for auth services
199 $this->loginType = ($this->name=='fe_typo_user') ? 'FE' : 'BE';
200
201 // set level to normal if not already set
202 $this->security_level = $this->security_level ? $this->security_level : 'normal';
203
204 // enable dev logging if set
205 if ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['writeDevLog']) $this->writeDevLog = TRUE;
206 if ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['writeDevLog'.$this->loginType]) $this->writeDevLog = TRUE;
207 if (TYPO3_DLOG) $this->writeDevLog = TRUE;
208
209 if ($this->writeDevLog) t3lib_div::devLog('## Beginning of auth logging.', 't3lib_userAuth');
210
211 // Init vars.
212 $mode = '';
213 $this->newSessionID = FALSE;
214 // $id is set to ses_id if cookie is present. Else set to false, which will start a new session
215 $id = isset($_COOKIE[$this->name]) ? stripslashes($_COOKIE[$this->name]) : '';
216 $this->hash_length = t3lib_div::intInRange($this->hash_length,6,32);
217 $this->svConfig = $TYPO3_CONF_VARS['SVCONF']['auth'];
218
219
220 // If fallback to get mode....
221 if (!$id && $this->getFallBack && $this->get_name) {
222 $id = isset($_GET[$this->get_name]) ? t3lib_div::_GET($this->get_name) : '';
223 if (strlen($id)!=$this->hash_length) $id='';
224 $mode='get';
225 }
226 $this->cookieId = $id;
227
228 // If new session or client tries to fix session...
229 if (!$id || !$this->isExistingSessionRecord($id)) {
230 // New random session-$id is made
231 $id = substr(md5(uniqid('').getmypid()),0,$this->hash_length);
232 // New session
233 $this->newSessionID = TRUE;
234 }
235
236 // Internal var 'id' is set
237 $this->id = $id;
238
239 // If fallback to get mode....
240 if ($mode=='get' && $this->getFallBack && $this->get_name) {
241 $this->get_URL_ID = '&'.$this->get_name.'='.$id;
242 }
243 // Make certain that NO user is set initially
244 $this->user = '';
245
246 // 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...
247 $this->checkAuthentication();
248
249 // 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:
250 unset($this->user);
251
252 // re-read user session
253 $this->user = $this->fetchUserSession();
254
255 if ($this->writeDevLog && is_array($this->user)) t3lib_div::devLog('User session finally read: '.t3lib_div::arrayToLogString($this->user, array($this->userid_column,$this->username_column)), 't3lib_userAuth', -1);
256 if ($this->writeDevLog && !is_array($this->user)) t3lib_div::devLog('No user session found.', 't3lib_userAuth', 2);
257
258 // Setting cookies
259 if ($TYPO3_CONF_VARS['SYS']['cookieDomain']) {
260 if ($TYPO3_CONF_VARS['SYS']['cookieDomain']{0} == '/') {
261 $matchCnt = @preg_match($TYPO3_CONF_VARS['SYS']['cookieDomain'], t3lib_div::getIndpEnv('TYPO3_HOST_ONLY'), $match);
262 if ($matchCnt === FALSE) {
263 t3lib_div::sysLog('The regular expression of $TYPO3_CONF_VARS[SYS][cookieDomain] contains errors. The session is not shared across sub-domains.', 'Core', 3);
264 } elseif ($matchCnt) {
265 $cookieDomain = $match[0];
266 }
267 } else {
268 $cookieDomain = $TYPO3_CONF_VARS['SYS']['cookieDomain'];
269 }
270 }
271
272 // If new session and the cookie is a sessioncookie, we need to set it only once!
273 if ($this->isSetSessionCookie()) {
274 if (!$this->dontSetCookie) {
275 if ($cookieDomain) {
276 SetCookie($this->name, $id, 0, '/', $cookieDomain);
277 } else {
278 SetCookie($this->name, $id, 0, '/');
279 }
280 if ($this->writeDevLog) t3lib_div::devLog('Set new Cookie: '.$id.($cookieDomain ? ', '.$cookieDomain : ''), 't3lib_userAuth');
281 }
282 }
283
284 // If it is NOT a session-cookie, we need to refresh it.
285 if ($this->isRefreshTimeBasedCookie()) {
286 if (!$this->dontSetCookie) {
287 if ($cookieDomain) {
288 SetCookie($this->name, $id, time()+$this->lifetime, '/', $cookieDomain);
289 } else {
290 SetCookie($this->name, $id, time()+$this->lifetime, '/');
291 }
292 if ($this->writeDevLog) t3lib_div::devLog('Update Cookie: '.$id.($cookieDomain ? ', '.$cookieDomain : ''), 't3lib_userAuth');
293 }
294 }
295
296 // Hook for alternative ways of filling the $this->user array (is used by the "timtaw" extension)
297 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'])) {
298 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'] as $funcName) {
299 $_params = array(
300 'pObj' => &$this,
301 );
302 t3lib_div::callUserFunction($funcName,$_params,$this);
303 }
304 }
305
306 // If any redirection (inclusion of file) then it will happen in this function
307 $this->redirect();
308
309 // Set all posible headers that could ensure that the script is not cached on the client-side
310 if ($this->sendNoCacheHeaders) {
311 header('Expires: 0');
312 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
313 header('Cache-Control: no-cache, must-revalidate');
314 header('Pragma: no-cache');
315 }
316
317 // Set $this->gc_time if not explicitely specified
318 if ($this->gc_time==0) {
319 $this->gc_time = ($this->auth_timeout_field==0 ? 86400 : $this->auth_timeout_field); // Default to 1 day if $this->auth_timeout_field is 0
320 }
321
322 // If we're lucky we'll get to clean up old sessions....
323 if ((rand()%100) <= $this->gc_probability) {
324 $this->gc();
325 }
326 }
327
328 /**
329 * Determine whether a session cookie needs to be set (lifetime=0)
330 *
331 * @return boolean
332 * @internal
333 */
334 function isSetSessionCookie() {
335 return ($this->newSessionID || $this->forceSetCookie) && $this->lifetime==0;
336 }
337
338 /**
339 * Determine whether a non-session cookie needs to be set (lifetime>0)
340 *
341 * @return boolean
342 * @internal
343 */
344 function isRefreshTimeBasedCookie() {
345 return $this->lifetime > 0;
346 }
347
348 /**
349 * Checks if a submission of username and password is present or use other authentication by auth services
350 *
351 * @return void
352 * @internal
353 */
354 function checkAuthentication() {
355
356 // No user for now - will be searched by service below
357 $tempuserArr = array();
358 $tempuser = FALSE;
359
360 // User is not authenticated by default
361 $authenticated = FALSE;
362
363 // User want to login with passed login data (name/password)
364 $activeLogin = FALSE;
365
366 // Indicates if an active authentication failed (not auto login)
367 $this->loginFailure = FALSE;
368
369 if ($this->writeDevLog) t3lib_div::devLog('Login type: '.$this->loginType, 't3lib_userAuth');
370
371 // The info array provide additional information for auth services
372 $authInfo = $this->getAuthInfoArray();
373
374 // Get Login/Logout data submitted by a form or params
375 $loginData = $this->getLoginFormData();
376
377 if ($this->writeDevLog) t3lib_div::devLog('Login data: '.t3lib_div::arrayToLogString($loginData), 't3lib_userAuth');
378
379
380 // active logout (eg. with "logout" button)
381 if ($loginData['status']=='logout') {
382 if ($this->writeStdLog) $this->writelog(255,2,0,2,'User %s logged out',Array($this->user['username'])); // Logout written to log
383 if ($this->writeDevLog) t3lib_div::devLog('User logged out. Id: '.$this->id, 't3lib_userAuth', -1);
384
385 $this->logoff();
386 }
387
388 // active login (eg. with login form)
389 if ($loginData['status']=='login') {
390 $activeLogin = TRUE;
391
392 if ($this->writeDevLog) t3lib_div::devLog('Active login (eg. with login form)', 't3lib_userAuth');
393
394 // check referer for submitted login values
395 if ($this->formfield_status && $loginData['uident'] && $loginData['uname']) {
396 $httpHost = t3lib_div::getIndpEnv('TYPO3_HOST_ONLY');
397 if (!$this->getMethodEnabled && ($httpHost!=$authInfo['refInfo']['host'] && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer'])) {
398 die('Error: This host address ("'.$httpHost.'") and the referer host ("'.$authInfo['refInfo']['host'].'") mismatches!<br />
399 It\'s possible that the environment variable HTTP_REFERER is not passed to the script because of a proxy.<br />
400 The site administrator can disable this check in the "All Configuration" section of the Install Tool (flag: TYPO3_CONF_VARS[SYS][doNotCheckReferer]).');
401 }
402
403 // delete old user session if any
404 $this->logoff();
405 }
406
407 // Refuse login for _CLI users (used by commandline scripts)
408 if ((strtoupper(substr($loginData['uname'],0,5))=='_CLI_') && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) { // although TYPO3_cliMode should never be set when using active login...
409 die('Error: You have tried to login using a CLI user. Access prohibited!');
410 }
411 }
412
413
414 // the following code makes auto-login possible (if configured). No submitted data needed
415
416 // re-read user session
417 $authInfo['userSession'] = $this->fetchUserSession();
418 $haveSession = is_array($authInfo['userSession']) ? TRUE : FALSE;
419
420 if ($this->writeDevLog) {
421 if ($haveSession) {
422 t3lib_div::devLog('User session found: '.t3lib_div::arrayToLogString($authInfo['userSession'], array($this->userid_column,$this->username_column)), 't3lib_userAuth', 0);
423 }
424 if (is_array($this->svConfig['setup'])) {
425 t3lib_div::devLog('SV setup: '.t3lib_div::arrayToLogString($this->svConfig['setup']), 't3lib_userAuth', 0);
426 }
427 }
428
429 // fetch user if ...
430 if ($activeLogin
431 || (!$haveSession && $this->svConfig['setup'][$this->loginType.'_fetchUserIfNoSession'])
432 || $this->svConfig['setup'][$this->loginType.'_alwaysFetchUser']) {
433
434 // use 'auth' service to find the user
435 // first found user will be used
436 $serviceChain = '';
437 $subType = 'getUser'.$this->loginType;
438 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
439 $serviceChain.=','.$serviceObj->getServiceKey();
440 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
441 if ($row=$serviceObj->getUser()) {
442 $tempuserArr[] = $row;
443
444 if ($this->writeDevLog) t3lib_div::devLog('User found: '.t3lib_div::arrayToLogString($row, array($this->userid_column,$this->username_column)), 't3lib_userAuth', 0);
445
446 // user found, just stop to search for more if not configured to go on
447 if(!$this->svConfig['setup'][$this->loginType.'_fetchAllUsers']) {
448 break;
449 }
450 }
451 unset($serviceObj);
452 }
453 unset($serviceObj);
454
455 if ($this->writeDevLog && $this->svConfig['setup'][$this->loginType.'_alwaysFetchUser']) t3lib_div::devLog($this->loginType.'_alwaysFetchUser option is enabled', 't3lib_userAuth');
456 if ($this->writeDevLog && $serviceChain) t3lib_div::devLog($subType.' auth services called: '.$serviceChain, 't3lib_userAuth');
457 if ($this->writeDevLog && !count($tempuserArr)) t3lib_div::devLog('No user found by services', 't3lib_userAuth');
458 if ($this->writeDevLog && count($tempuserArr)) t3lib_div::devLog(count($tempuserArr).' user records found by services', 't3lib_userAuth');
459 }
460
461
462 // If no new user was set we use the already found user session
463 if (!count($tempuserArr) && $haveSession) {
464 $tempuserArr[] = $authInfo['userSession'];
465 $tempuser = $authInfo['userSession'];
466 // User is authenticated because we found a user session
467 $authenticated = TRUE;
468
469 if ($this->writeDevLog) t3lib_div::devLog('User session used: '.t3lib_div::arrayToLogString($authInfo['userSession'], array($this->userid_column,$this->username_column)), 't3lib_userAuth');
470 }
471
472
473 // Re-auth user when 'auth'-service option is set
474 if ($this->svConfig['setup'][$this->loginType.'_alwaysAuthUser']) {
475 $authenticated = FALSE;
476 if ($this->writeDevLog) t3lib_div::devLog('alwaysAuthUser option is enabled', 't3lib_userAuth');
477 }
478
479
480 // Authenticate the user if needed
481 if (count($tempuserArr) && !$authenticated) {
482
483 foreach ($tempuserArr as $tempuser) {
484
485 // use 'auth' service to authenticate the user
486 // if one service returns FALSE then authentication failed
487 // a service might return 100 which means there's no reason to stop but the user can't be authenticated by that service
488
489 if ($this->writeDevLog) t3lib_div::devLog('Auth user: '.t3lib_div::arrayToLogString($tempuser), 't3lib_userAuth');
490
491 $serviceChain='';
492 $subType = 'authUser'.$this->loginType;
493 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
494 $serviceChain.=','.$serviceObj->getServiceKey();
495 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
496 if (($ret=$serviceObj->authUser($tempuser)) > 0) {
497
498 // if the service returns >=200 then no more checking is needed - useful for IP checking without password
499 if (intval($ret) >= 200) {
500 $authenticated = TRUE;
501 break;
502 } elseif (intval($ret) >= 100) {
503 // Just go on. User is still not authenticated but there's no reason to stop now.
504 } else {
505 $authenticated = TRUE;
506 }
507
508 } else {
509 $authenticated = FALSE;
510 break;
511 }
512 unset($serviceObj);
513 }
514 unset($serviceObj);
515
516 if ($this->writeDevLog && $serviceChain) t3lib_div::devLog($subType.' auth services called: '.$serviceChain, 't3lib_userAuth');
517
518 if ($authenticated) {
519 // leave foreach() because a user is authenticated
520 break;
521 }
522 }
523 }
524
525 // If user is authenticated a valid user is in $tempuser
526 if ($authenticated) {
527 // reset failure flag
528 $this->loginFailure = FALSE;
529
530
531 // Insert session record if needed:
532 if (!($haveSession && (
533 $tempuser['ses_id']==$this->id || // check if the tempuser has the current session id
534 $tempuser['uid']==$authInfo['userSession']['ses_userid'] // check if the tempuser has the uid of the fetched session user
535 ))) {
536 $this->createUserSession($tempuser);
537
538 // The login session is started.
539 $this->loginSessionStarted = TRUE;
540 }
541
542 // User logged in - write that to the log!
543 if ($this->writeStdLog && $activeLogin) {
544 $this->writelog(255,1,0,1,
545 'User %s logged in from %s (%s)',
546 Array($tempuser[$this->username_column], t3lib_div::getIndpEnv('REMOTE_ADDR'), t3lib_div::getIndpEnv('REMOTE_HOST')),
547 '','','',-1,'',$tempuser['uid']
548 );
549 }
550
551 if ($this->writeDevLog && $activeLogin) t3lib_div::devLog('User '.$tempuser[$this->username_column].' logged in from '.t3lib_div::getIndpEnv('REMOTE_ADDR').' ('.t3lib_div::getIndpEnv('REMOTE_HOST').')', 't3lib_userAuth', -1);
552 if ($this->writeDevLog && !$activeLogin) t3lib_div::devLog('User '.$tempuser[$this->username_column].' authenticated from '.t3lib_div::getIndpEnv('REMOTE_ADDR').' ('.t3lib_div::getIndpEnv('REMOTE_HOST').')', 't3lib_userAuth', -1);
553
554 if($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] == 3 && $this->user_table == 'be_users') {
555 $requestStr = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'), strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL').TYPO3_mainDir));
556 $backendScript = t3lib_BEfunc::getBackendScript();
557 if($requestStr == $backendScript && t3lib_div::getIndpEnv('TYPO3_SSL')) {
558 list(,$url) = explode('://',t3lib_div::getIndpEnv('TYPO3_SITE_URL'),2);
559 list($server,$address) = explode('/',$url,2);
560 if (intval($TYPO3_CONF_VARS['BE']['lockSSLPort'])) {
561 $sslPortSuffix = ':'.intval($TYPO3_CONF_VARS['BE']['lockSSLPort']);
562 $server = str_replace($sslPortSuffix,'',$server); // strip port from server
563 }
564 header('Location: http://'.$server.'/'.$address.TYPO3_mainDir.$backendScript);
565 exit;
566 }
567 }
568
569 } elseif ($activeLogin || count($tempuserArr)) {
570 $this->loginFailure = TRUE;
571
572 if ($this->writeDevLog && !count($tempuserArr) && $activeLogin) t3lib_div::devLog('Login failed: '.t3lib_div::arrayToLogString($loginData), 't3lib_userAuth', 2);
573 if ($this->writeDevLog && count($tempuserArr)) t3lib_div::devLog('Login failed: '.t3lib_div::arrayToLogString($tempuser, array($this->userid_column,$this->username_column)), 't3lib_userAuth', 2);
574 }
575
576
577 // If there were a login failure, check to see if a warning email should be sent:
578 if ($this->loginFailure && $activeLogin) {
579 if ($this->writeDevLog) t3lib_div::devLog('Call checkLogFailures: '.t3lib_div::arrayToLogString(array('warningEmail'=>$this->warningEmail,'warningPeriod'=>$this->warningPeriod,'warningMax'=>$this->warningMax,)), 't3lib_userAuth', -1);
580
581 $this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax);
582 }
583 }
584
585
586
587
588
589
590
591
592
593
594
595
596 /*************************
597 *
598 * User Sessions
599 *
600 *************************/
601
602
603 /**
604 * Creates a user session record.
605 *
606 * @param array user data array
607 * @return void
608 */
609 function createUserSession ($tempuser) {
610
611 if ($this->writeDevLog) t3lib_div::devLog('Create session ses_id = '.$this->id, 't3lib_userAuth');
612
613 // delete session entry first
614 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
615 $this->session_table,
616 'ses_id = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
617 AND ses_name = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
618 );
619
620 // re-create session entry
621 $insertFields = $this->getNewSessionRecord($tempuser);
622 $GLOBALS['TYPO3_DB']->exec_INSERTquery($this->session_table, $insertFields);
623
624 // Updating lastLogin_column carrying information about last login.
625 if ($this->lastLogin_column) {
626 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
627 $this->user_table,
628 $this->userid_column.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($tempuser[$this->userid_column], $this->user_table),
629 array($this->lastLogin_column => $GLOBALS['EXEC_TIME'])
630 );
631 }
632 }
633
634 /**
635 * Returns a new session record for the current user for insertion into the DB.
636 * This function is mainly there as a wrapper for inheriting classes to override it.
637 *
638 * @return array user session record
639 */
640 function getNewSessionRecord($tempuser) {
641 return array(
642 'ses_id' => $this->id,
643 'ses_name' => $this->name,
644 'ses_iplock' => $tempuser['disableIPlock'] ? '[DISABLED]' : $this->ipLockClause_remoteIPNumber($this->lockIP),
645 'ses_hashlock' => $this->hashLockClause_getHashInt(),
646 'ses_userid' => $tempuser[$this->userid_column],
647 'ses_tstamp' => $GLOBALS['EXEC_TIME']
648 );
649 }
650
651 /**
652 * Read the user session from db.
653 *
654 * @return array user session data
655 */
656 function fetchUserSession() {
657
658 $user = '';
659
660 if ($this->writeDevLog) t3lib_div::devLog('Fetch session ses_id = '.$this->id, 't3lib_userAuth');
661
662 // The session_id is used to find user in the database. Two tables are joined: The session-table with user_id of the session and the usertable with its primary key
663 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
664 '*',
665 $this->session_table.','.$this->user_table,
666 $this->session_table.'.ses_id = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
667 AND '.$this->session_table.'.ses_name = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table).'
668 AND '.$this->session_table.'.ses_userid = '.$this->user_table.'.'.$this->userid_column.'
669 '.$this->ipLockClause().'
670 '.$this->hashLockClause().'
671 '.$this->user_where_clause()
672 );
673
674
675 if ($user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres)) {
676 // A user was found
677 if (is_string($this->auth_timeout_field)) {
678 $timeout = intval($user[$this->auth_timeout_field]); // Get timeout-time from usertable
679 } else {
680 $timeout = intval($this->auth_timeout_field); // Get timeout from object
681 }
682 // If timeout > 0 (true) and currenttime has not exceeded the latest sessions-time plus the timeout in seconds then accept user
683 // 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...
684 if ($timeout>0 && ($GLOBALS['EXEC_TIME'] < ($user['ses_tstamp']+$timeout))) {
685 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
686 $this->session_table,
687 'ses_id='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
688 AND ses_name='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table),
689 array('ses_tstamp' => $GLOBALS['EXEC_TIME'])
690 );
691 $user['ses_tstamp'] = $GLOBALS['EXEC_TIME']; // Make sure that the timestamp is also updated in the array
692 } else {
693 $this->logoff(); // delete any user set...
694 }
695 } else {
696 $this->logoff(); // delete any user set...
697 }
698 return $user;
699 }
700
701 /**
702 * Log out current user!
703 * Removes the current session record, sets the internal ->user array to a blank string; Thereby the current user (if any) is effectively logged out!
704 *
705 * @return void
706 */
707 function logoff() {
708 if ($this->writeDevLog) t3lib_div::devLog('logoff: ses_id = '.$this->id, 't3lib_userAuth');
709
710 // Hook for pre-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
711 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'])) {
712 $_params = array();
713 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'] as $_funcRef) {
714 if ($_funcRef) {
715 t3lib_div::callUserFunction($_funcRef,$_params,$this);
716 }
717 }
718 }
719
720 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
721 $this->session_table,
722 'ses_id = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
723 AND ses_name = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
724 );
725
726 $this->user = '';
727
728 // Hook for post-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
729 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'])) {
730 $_params = array();
731 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'] as $_funcRef) {
732 if ($_funcRef) {
733 t3lib_div::callUserFunction($_funcRef,$_params,$this);
734 }
735 }
736 }
737 }
738
739 /**
740 * Determine whether there's an according session record to a given session_id
741 * in the database. Don't care if session record is still valid or not.
742 *
743 * @return boolean
744 */
745 function isExistingSessionRecord($id) {
746 $count = false;
747 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
748 'COUNT(ses_id)',
749 $this->session_table,
750 'ses_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($id, $this->session_table)
751 );
752 if ($dbres !== false) {
753 list($count) = $GLOBALS['TYPO3_DB']->sql_fetch_row($dbres);
754 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
755 }
756 return (($count ? true : false));
757 }
758
759
760
761
762
763
764
765
766
767
768
769
770
771 /*************************
772 *
773 * SQL Functions
774 *
775 *************************/
776
777 /**
778 * This returns the where-clause needed to select the user with respect flags like deleted, hidden, starttime, endtime
779 *
780 * @return string
781 * @access private
782 */
783 function user_where_clause() {
784 return (($this->enablecolumns['rootLevel']) ? 'AND '.$this->user_table.'.pid=0 ' : '').
785 (($this->enablecolumns['disabled']) ? ' AND '.$this->user_table.'.'.$this->enablecolumns['disabled'].'=0' : '').
786 (($this->enablecolumns['deleted']) ? ' AND '.$this->user_table.'.'.$this->enablecolumns['deleted'].'=0' : '').
787 (($this->enablecolumns['starttime']) ? ' AND ('.$this->user_table.'.'.$this->enablecolumns['starttime'].'<='.time().')' : '').
788 (($this->enablecolumns['endtime']) ? ' AND ('.$this->user_table.'.'.$this->enablecolumns['endtime'].'=0 OR '.$this->user_table.'.'.$this->enablecolumns['endtime'].'>'.time().')' : '');
789 }
790
791 /**
792 * This returns the where-clause needed to lock a user to the IP address
793 *
794 * @return string
795 * @access private
796 */
797 function ipLockClause() {
798 if ($this->lockIP) {
799 $wherePart = 'AND (
800 '.$this->session_table.'.ses_iplock='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->ipLockClause_remoteIPNumber($this->lockIP),$this->session_table).'
801 OR '.$this->session_table.'.ses_iplock=\'[DISABLED]\'
802 )';
803 return $wherePart;
804 }
805 }
806
807 /**
808 * Returns the IP address to lock to.
809 * The IP address may be partial based on $parts.
810 *
811 * @param integer 1-4: Indicates how many parts of the IP address to return. 4 means all, 1 means only first number.
812 * @return string (Partial) IP address for REMOTE_ADDR
813 * @access private
814 */
815 function ipLockClause_remoteIPNumber($parts) {
816 $IP = t3lib_div::getIndpEnv('REMOTE_ADDR');
817
818 if ($parts>=4) {
819 return $IP;
820 } else {
821 $parts = t3lib_div::intInRange($parts,1,3);
822 $IPparts = explode('.',$IP);
823 for($a=4;$a>$parts;$a--) {
824 unset($IPparts[$a-1]);
825 }
826 return implode('.',$IPparts);
827 }
828 }
829
830 /**
831 * This returns the where-clause needed to lock a user to a hash integer
832 *
833 * @return string
834 * @access private
835 */
836 function hashLockClause() {
837 $wherePart = 'AND '.$this->session_table.'.ses_hashlock='.intval($this->hashLockClause_getHashInt());
838 return $wherePart;
839 }
840
841 /**
842 * Creates hash integer to lock user to. Depends on configured keywords
843 *
844 * @return integer Hash integer
845 * @access private
846 */
847 function hashLockClause_getHashInt() {
848 $hashStr = '';
849
850 if (t3lib_div::inList($this->lockHashKeyWords,'useragent')) $hashStr.=':'.t3lib_div::getIndpEnv('HTTP_USER_AGENT');
851
852 return t3lib_div::md5int($hashStr);
853 }
854
855
856
857
858
859
860
861
862
863
864
865 /*************************
866 *
867 * Session and Configuration Handling
868 *
869 *************************/
870
871 /**
872 * This writes $variable to the user-record. This is a way of providing session-data.
873 * You can fetch the data again through $this->uc in this class!
874 * If $variable is not an array, $this->uc is saved!
875 *
876 * @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
877 * @return void
878 */
879 function writeUC($variable='') {
880 if (is_array($this->user) && $this->user[$this->userid_column]) {
881 if (!is_array($variable)) { $variable = $this->uc; }
882
883 if ($this->writeDevLog) t3lib_div::devLog('writeUC: '.$this->userid_column.'='.intval($this->user[$this->userid_column]), 't3lib_userAuth');
884 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->user_table, $this->userid_column.'='.intval($this->user[$this->userid_column]), array('uc' => serialize($variable)));
885 }
886 }
887
888 /**
889 * 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
890 *
891 * @param mixed If an array, then set as ->uc, otherwise load from user record
892 * @return void
893 */
894 function unpack_uc($theUC='') {
895 if (!$theUC) $theUC=unserialize($this->user['uc']);
896 if (is_array($theUC)) {
897 $this->uc=$theUC;
898 }
899 }
900
901 /**
902 * Stores data for a module.
903 * 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.
904 *
905 * @param string $module is the name of the module ($MCONF['name'])
906 * @param mixed $data is the data you want to store for that module (array, string, ...)
907 * @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.
908 * @return void
909 */
910 function pushModuleData($module,$data,$noSave=0) {
911 $this->uc['moduleData'][$module] = $data;
912 $this->uc['moduleSessionID'][$module] = $this->id;
913 if (!$noSave) $this->writeUC();
914 }
915
916 /**
917 * Gets module data for a module (from a loaded ->uc array)
918 *
919 * @param string $module is the name of the module ($MCONF['name'])
920 * @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).
921 * @return mixed The module data if available: $this->uc['moduleData'][$module];
922 */
923 function getModuleData($module,$type='') {
924 if ($type!='ses' || $this->uc['moduleSessionID'][$module]==$this->id) {
925 return $this->uc['moduleData'][$module];
926 }
927 }
928
929 /**
930 * Returns the session data stored for $key.
931 * The data will last only for this login session since it is stored in the session table.
932 *
933 * @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.
934 * @return mixed
935 */
936 function getSessionData($key) {
937 $sesDat = unserialize($this->user['ses_data']);
938 return $sesDat[$key];
939 }
940
941 /**
942 * Sets the session data ($data) for $key and writes all session data (from ->user['ses_data']) to the database.
943 * The data will last only for this login session since it is stored in the session table.
944 *
945 * @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.
946 * @param mixed The variable to store in index $key
947 * @return void
948 */
949 function setAndSaveSessionData($key,$data) {
950 $sesDat = unserialize($this->user['ses_data']);
951 $sesDat[$key] = $data;
952 $this->user['ses_data'] = serialize($sesDat);
953
954 if ($this->writeDevLog) t3lib_div::devLog('setAndSaveSessionData: ses_id = '.$this->user['ses_id'], 't3lib_userAuth');
955 $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']));
956 }
957
958
959
960
961
962
963
964
965
966
967
968
969
970 /*************************
971 *
972 * Misc
973 *
974 *************************/
975
976 /**
977 * Returns an info array with Login/Logout data submitted by a form or params
978 *
979 * @return array
980 * @internal
981 */
982 function getLoginFormData() {
983 $loginData=array();
984 if ($this->getMethodEnabled) {
985 $loginData['status'] = t3lib_div::_GP($this->formfield_status);
986 $loginData['uname'] = t3lib_div::_GP($this->formfield_uname);
987 $loginData['uident'] = t3lib_div::_GP($this->formfield_uident);
988 $loginData['chalvalue'] = t3lib_div::_GP($this->formfield_chalvalue);
989 } else {
990 $loginData['status'] = t3lib_div::_POST($this->formfield_status);
991 $loginData['uname'] = t3lib_div::_POST($this->formfield_uname);
992 $loginData['uident'] = t3lib_div::_POST($this->formfield_uident);
993 $loginData['chalvalue'] = t3lib_div::_POST($this->formfield_chalvalue);
994 }
995 $loginData = $this->processLoginData($loginData);
996
997 return $loginData;
998 }
999
1000 /**
1001 * Processes Login data submitted by a form or params depending on the
1002 * security_level
1003 *
1004 * @param array login data array
1005 * @param string Alternative security_level. Used when authentication services wants to override the default.
1006 * @return array processed login data array
1007 * @internal
1008 */
1009 function processLoginData($loginData, $security_level='') {
1010 global $TYPO3_CONF_VARS;
1011
1012 $loginSecurityLevel = $security_level ? $security_level : ($TYPO3_CONF_VARS[$this->loginType]['loginSecurityLevel'] ? $TYPO3_CONF_VARS[$this->loginType]['loginSecurityLevel'] : $this->security_level);
1013
1014 // Processing data according to the state it was submitted in.
1015 // ($loginSecurityLevel should reflect the security level used on the data being submitted in the login form)
1016 if ($loginSecurityLevel=='normal') {
1017 $loginData['uident_text'] = $loginData['uident'];
1018 $loginData['uident_challenged'] = (string)md5($loginData['uname'].':'.$loginData['uident'].':'.$loginData['chalvalue']);
1019 $loginData['uident_superchallenged'] = (string)md5($loginData['uname'].':'.(md5($loginData['uident'])).':'.$loginData['chalvalue']);
1020 } elseif ($loginSecurityLevel=='challenged') {
1021 $loginData['uident_text'] = '';
1022 $loginData['uident_challenged'] = $loginData['uident'];
1023 $loginData['uident_superchallenged'] = '';
1024 } elseif ($loginSecurityLevel=='superchallenged') {
1025 $loginData['uident_text'] = '';
1026 $loginData['uident_challenged'] = '';
1027 $loginData['uident_superchallenged'] = $loginData['uident'];
1028 }
1029
1030 // The password "uident" is set based on the internal security setting of TYPO3
1031 // Example:
1032 // $this->security_level for the backend must be "superchallenged" because passwords are stored as md5-hashes in the be_users table
1033 // $this->security_level for the frontend must be "normal" or "challenged" because passwords are stored as clear-text in the fe_users tables
1034 if ($this->security_level=='normal') {
1035 $loginData['uident'] = $loginData['uident_text'];
1036 } elseif ($this->security_level=='challenged') {
1037 $loginData['uident'] = $loginData['uident_challenged'];
1038 } elseif ($this->security_level=='superchallenged') {
1039 $loginData['uident'] = $loginData['uident_superchallenged'];
1040 }
1041
1042 return $loginData;
1043 }
1044
1045 /**
1046 * Returns an info array which provides additional information for auth services
1047 *
1048 * @return array
1049 * @internal
1050 */
1051 function getAuthInfoArray() {
1052 $authInfo = array();
1053 $authInfo['loginType'] = $this->loginType;
1054 $authInfo['refInfo'] = parse_url(t3lib_div::getIndpEnv('HTTP_REFERER'));
1055 $authInfo['HTTP_HOST'] = t3lib_div::getIndpEnv('HTTP_HOST');
1056 $authInfo['REMOTE_ADDR'] = t3lib_div::getIndpEnv('REMOTE_ADDR');
1057 $authInfo['REMOTE_HOST'] = t3lib_div::getIndpEnv('REMOTE_HOST');
1058 $authInfo['security_level'] = $this->security_level;
1059 $authInfo['showHiddenRecords'] = $this->showHiddenRecords;
1060 // can be overidden in localconf by SVCONF:
1061 $authInfo['db_user']['table'] = $this->user_table;
1062 $authInfo['db_user']['userid_column'] = $this->userid_column;
1063 $authInfo['db_user']['username_column'] = $this->username_column;
1064 $authInfo['db_user']['userident_column'] = $this->userident_column;
1065 $authInfo['db_user']['usergroup_column'] = $this->usergroup_column;
1066 $authInfo['db_user']['enable_clause'] = $this->user_where_clause();
1067 $authInfo['db_user']['checkPidList'] = $this->checkPid ? $this->checkPid_value : '';
1068 $authInfo['db_user']['check_pid_clause'] = $this->checkPid ? ' AND pid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($authInfo['db_user']['checkPidList']).')' : '';
1069 $authInfo['db_groups']['table'] = $this->usergroup_table;
1070 return $authInfo;
1071 }
1072
1073 /**
1074 * Check the login data with the user record data for builtin login methods
1075 *
1076 * @param array user data array
1077 * @param array login data array
1078 * @param string Alternative security_level. Used when authentication services wants to override the default.
1079 * @return boolean true if login data matched
1080 */
1081 function compareUident($user, $loginData, $security_level='') {
1082
1083 $OK = FALSE;
1084 $security_level = $security_level ? $security_level : $this->security_level;
1085
1086 switch ($security_level) {
1087 case 'superchallenged': // If superchallenged the password in the database ($user[$this->userident_column]) must be a md5-hash of the original password.
1088 case 'challenged':
1089
1090 // Check challenge stored in cookie:
1091 if ($this->challengeStoredInCookie) {
1092 session_start();
1093 if ($_SESSION['login_challenge'] !== $loginData['chalvalue']) {
1094 if ($this->writeDevLog) t3lib_div::devLog('PHP Session stored challenge "'.$_SESSION['login_challenge'].'" and submitted challenge "'.$loginData['chalvalue'].'" did not match, so authentication failed!', 't3lib_userAuth', 2);
1095 $this->logoff();
1096 return FALSE;
1097 }
1098 }
1099
1100 if ((string)$loginData['uident'] === (string)md5($user[$this->username_column].':'.$user[$this->userident_column].':'.$loginData['chalvalue'])) {
1101 $OK = TRUE;
1102 }
1103 break;
1104 default: // normal
1105 if ((string)$loginData['uident'] === (string)$user[$this->userident_column]) {
1106 $OK = TRUE;
1107 }
1108 break;
1109 }
1110
1111 return $OK;
1112 }
1113
1114 /**
1115 * Garbage collector, removing old expired sessions.
1116 *
1117 * @return void
1118 * @internal
1119 */
1120 function gc() {
1121 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
1122 $this->session_table,
1123 'ses_tstamp < '.intval(time()-($this->gc_time)).'
1124 AND ses_name = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
1125 );
1126 }
1127
1128 /**
1129 * Redirect to somewhere. Obsolete, deprecated etc.
1130 *
1131 * @return void
1132 * @ignore
1133 */
1134 function redirect() {
1135 if (!$this->userid && $this->auth_url) { // if no userid AND an include-document for login is given
1136 include ($this->auth_include);
1137 exit;
1138 }
1139 }
1140
1141 /**
1142 * DUMMY: Writes to log database table (in some extension classes)
1143 *
1144 * @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
1145 * @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 !!)
1146 * @param integer $error: flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1147 * @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
1148 * @param string $details: Default text that follows the message
1149 * @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...
1150 * @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.)
1151 * @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.)
1152 * @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.)
1153 * @return void
1154 * @see t3lib_userauthgroup::writelog()
1155 */
1156 function writelog($type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid) {
1157 }
1158
1159 /**
1160 * DUMMY: Check login failures (in some extension classes)
1161 *
1162 * @return void
1163 * @ignore
1164 */
1165 function checkLogFailures() {
1166 }
1167
1168 /**
1169 * Raw initialization of the be_user with uid=$uid
1170 * 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.
1171 * Will check the users for disabled, start/endtime, etc. ($this->user_where_clause())
1172 *
1173 * @param integer The UID of the backend user to set in ->user
1174 * @return void
1175 * @internal
1176 * @see SC_mod_tools_be_user_index::compareUsers(), SC_mod_user_setup_index::simulateUser(), freesite_admin::startCreate()
1177 */
1178 function setBeUserByUid($uid) {
1179 $this->user = $this->getRawUserByUid($uid);
1180 }
1181
1182 /**
1183 * Raw initialization of the be_user with username=$name
1184 *
1185 * @param string The username to look up.
1186 * @return void
1187 * @see t3lib_userAuth::setBeUserByUid()
1188 * @internal
1189 */
1190 function setBeUserByName($name) {
1191 $this->user = $this->getRawUserByName($name);
1192 }
1193
1194 /**
1195 * Fetching raw user record with uid=$uid
1196 *
1197 * @param integer The UID of the backend user to set in ->user
1198 * @return array user record or FALSE
1199 * @internal
1200 */
1201 function getRawUserByUid($uid) {
1202 $user = FALSE;
1203 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'uid='.intval($uid).' '.$this->user_where_clause());
1204 if ($dbres) {
1205 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1206 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1207 }
1208 return $user;
1209 }
1210
1211 /**
1212 * Fetching raw user record with username=$name
1213 *
1214 * @param string The username to look up.
1215 * @return array user record or FALSE
1216 * @see t3lib_userAuth::getUserByUid()
1217 * @internal
1218 */
1219 function getRawUserByName($name) {
1220 $user = FALSE;
1221 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'username='.$GLOBALS['TYPO3_DB']->fullQuoteStr($name, $this->user_table).' '.$this->user_where_clause());
1222 if ($dbres) {
1223 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1224 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1225 }
1226 return $user;
1227 }
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243 /*************************
1244 *
1245 * Create/update user - EXPERIMENTAL
1246 *
1247 *************************/
1248
1249 /**
1250 * Get a user from DB by username
1251 * provided for usage from services
1252 *
1253 * @param array User db table definition: $this->db_user
1254 * @param string user name
1255 * @param string additional WHERE clause: " AND ...
1256 * @return mixed user array or FALSE
1257 */
1258 function fetchUserRecord($dbUser, $username, $extraWhere='' ) {
1259 $user = FALSE;
1260
1261 $usernameClause = $username ? ($dbUser['username_column'].'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($username, $dbUser['table'])) : '';
1262
1263 if ($username || $extraWhere) {
1264
1265 // Look up the user by the username and/or extraWhere:
1266 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1267 '*',
1268 $dbUser['table'],
1269 $usernameClause.
1270 $dbUser['check_pid_clause'].
1271 $dbUser['enable_clause'].
1272 $extraWhere
1273 );
1274
1275 if ($dbres) {
1276 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1277 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1278 }
1279 }
1280 return $user;
1281 }
1282 }
1283
1284
1285
1286 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauth.php']) {
1287 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauth.php']);
1288 }
1289 ?>