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