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