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