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