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