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