[BUGFIX] Moving files in filelist renames file to "1"
[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 every time (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 possible 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(
413 'The regular expression for the cookie domain (' . $cookieDomain . ') contains errors. The session is not shared across sub-domains.',
414 'Core',
415 t3lib_div::SYSLOG_SEVERITY_ERROR
416 );
417 } elseif ($matchCnt) {
418 $result = $match[0];
419 }
420 } else {
421 $result = $cookieDomain;
422 }
423 }
424
425 return $result;
426 }
427
428 /**
429 * Get the value of a specified cookie.
430 *
431 * Uses HTTP_COOKIE, if available, to avoid a IE8 bug where multiple
432 * cookies with the same name might be returned if the user accessed
433 * the site without "www." first and switched to "www." later:
434 * Cookie: fe_typo_user=AAA; fe_typo_user=BBB
435 * In this case PHP will set _COOKIE as the first cookie, when we
436 * would need the last one (which is what this function then returns).
437 *
438 * @param string $cookieName The cookie ID
439 * @return string The value stored in the cookie
440 */
441 protected function getCookie($cookieName) {
442 if (isset($_SERVER['HTTP_COOKIE'])) {
443 $cookies = t3lib_div::trimExplode(';', $_SERVER['HTTP_COOKIE']);
444 foreach ($cookies as $cookie) {
445 list ($name, $value) = t3lib_div::trimExplode('=', $cookie);
446 if (strcmp(trim($name), $cookieName) == 0) {
447 // Use the last one
448 $cookieValue = urldecode($value);
449 }
450 }
451 } else {
452 // Fallback if there is no HTTP_COOKIE, use original method:
453 $cookieValue = isset($_COOKIE[$cookieName]) ? stripslashes($_COOKIE[$cookieName]) : '';
454 }
455 return $cookieValue;
456 }
457
458 /**
459 * Determine whether a session cookie needs to be set (lifetime=0)
460 *
461 * @return boolean
462 * @internal
463 */
464 function isSetSessionCookie() {
465 return ($this->newSessionID || $this->forceSetCookie) && $this->lifetime == 0;
466 }
467
468 /**
469 * Determine whether a non-session cookie needs to be set (lifetime>0)
470 *
471 * @return boolean
472 * @internal
473 */
474 function isRefreshTimeBasedCookie() {
475 return $this->lifetime > 0;
476 }
477
478 /**
479 * Checks if a submission of username and password is present or use other authentication by auth services
480 *
481 * @return void
482 * @internal
483 */
484 function checkAuthentication() {
485
486 // No user for now - will be searched by service below
487 $tempuserArr = array();
488 $tempuser = FALSE;
489
490 // User is not authenticated by default
491 $authenticated = FALSE;
492
493 // User want to login with passed login data (name/password)
494 $activeLogin = FALSE;
495
496 // Indicates if an active authentication failed (not auto login)
497 $this->loginFailure = FALSE;
498
499 if ($this->writeDevLog) {
500 t3lib_div::devLog('Login type: ' . $this->loginType, 't3lib_userAuth');
501 }
502
503 // The info array provide additional information for auth services
504 $authInfo = $this->getAuthInfoArray();
505
506 // Get Login/Logout data submitted by a form or params
507 $loginData = $this->getLoginFormData();
508
509 if ($this->writeDevLog) {
510 t3lib_div::devLog('Login data: ' . t3lib_div::arrayToLogString($loginData), 't3lib_userAuth');
511 }
512
513 // Active logout (eg. with "logout" button)
514 if ($loginData['status'] == 'logout') {
515 if ($this->writeStdLog) {
516 // $type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid
517 $this->writelog(255, 2, 0, 2, 'User %s logged out', array($this->user['username']), '', 0, 0);
518 } // Logout written to log
519 if ($this->writeDevLog) {
520 t3lib_div::devLog('User logged out. Id: ' . $this->id, 't3lib_userAuth', -1);
521 }
522
523 $this->logoff();
524 }
525
526 // Active login (eg. with login form)
527 if ($loginData['status'] == 'login') {
528 $activeLogin = TRUE;
529
530 if ($this->writeDevLog) {
531 t3lib_div::devLog('Active login (eg. with login form)', 't3lib_userAuth');
532 }
533
534 // check referer for submitted login values
535 if ($this->formfield_status && $loginData['uident'] && $loginData['uname']) {
536 $httpHost = t3lib_div::getIndpEnv('TYPO3_HOST_ONLY');
537 if (!$this->getMethodEnabled && ($httpHost != $authInfo['refInfo']['host'] && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer'])) {
538 throw new RuntimeException(
539 'TYPO3 Fatal Error: Error: This host address ("' . $httpHost . '") and the referer host ("' . $authInfo['refInfo']['host'] . '") mismatches!<br />
540 It\'s possible that the environment variable HTTP_REFERER is not passed to the script because of a proxy.<br />
541 The site administrator can disable this check in the "All Configuration" section of the Install Tool (flag: TYPO3_CONF_VARS[SYS][doNotCheckReferer]).',
542 1270853930
543 );
544 }
545
546 // Delete old user session if any
547 $this->logoff();
548 }
549
550 // Refuse login for _CLI users, if not processing a CLI request type
551 // (although we shouldn't be here in case of a CLI request type)
552 if ((strtoupper(substr($loginData['uname'], 0, 5)) == '_CLI_') && !(TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)) {
553 throw new RuntimeException(
554 'TYPO3 Fatal Error: You have tried to login using a CLI user. Access prohibited!',
555 1270853931
556 );
557 }
558 }
559
560 // The following code makes auto-login possible (if configured). No submitted data needed
561
562 // Determine whether we need to skip session update.
563 // This is used mainly for checking session timeout without
564 // refreshing the session itself while checking.
565 if (t3lib_div::_GP('skipSessionUpdate')) {
566 $skipSessionUpdate = TRUE;
567 } else {
568 $skipSessionUpdate = FALSE;
569 }
570
571 // Re-read user session
572 $authInfo['userSession'] = $this->fetchUserSession($skipSessionUpdate);
573 $haveSession = is_array($authInfo['userSession']) ? TRUE : FALSE;
574
575 if ($this->writeDevLog) {
576 if ($haveSession) {
577 t3lib_div::devLog('User session found: ' . t3lib_div::arrayToLogString($authInfo['userSession'], array($this->userid_column, $this->username_column)), 't3lib_userAuth', 0);
578 }
579 if (is_array($this->svConfig['setup'])) {
580 t3lib_div::devLog('SV setup: ' . t3lib_div::arrayToLogString($this->svConfig['setup']), 't3lib_userAuth', 0);
581 }
582 }
583
584 // Fetch user if ...
585 if ($activeLogin
586 || (!$haveSession && $this->svConfig['setup'][$this->loginType . '_fetchUserIfNoSession'])
587 || $this->svConfig['setup'][$this->loginType . '_alwaysFetchUser']) {
588
589 // Use 'auth' service to find the user
590 // First found user will be used
591 $serviceChain = '';
592 $subType = 'getUser' . $this->loginType;
593 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
594 $serviceChain .= ',' . $serviceObj->getServiceKey();
595 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
596 if ($row = $serviceObj->getUser()) {
597 $tempuserArr[] = $row;
598
599 if ($this->writeDevLog) {
600 t3lib_div::devLog('User found: ' . t3lib_div::arrayToLogString($row, array($this->userid_column, $this->username_column)), 't3lib_userAuth', 0);
601 }
602
603 // User found, just stop to search for more if not configured to go on
604 if (!$this->svConfig['setup'][$this->loginType . '_fetchAllUsers']) {
605 break;
606 }
607 }
608 unset($serviceObj);
609 }
610 unset($serviceObj);
611
612 if ($this->writeDevLog && $this->svConfig['setup'][$this->loginType . '_alwaysFetchUser']) {
613 t3lib_div::devLog($this->loginType . '_alwaysFetchUser option is enabled', 't3lib_userAuth');
614 }
615 if ($this->writeDevLog && $serviceChain) {
616 t3lib_div::devLog($subType . ' auth services called: ' . $serviceChain, 't3lib_userAuth');
617 }
618 if ($this->writeDevLog && !count($tempuserArr)) {
619 t3lib_div::devLog('No user found by services', 't3lib_userAuth');
620 }
621 if ($this->writeDevLog && count($tempuserArr)) {
622 t3lib_div::devLog(count($tempuserArr) . ' user records found by services', 't3lib_userAuth');
623 }
624 }
625
626 // If no new user was set we use the already found user session
627 if (!count($tempuserArr) && $haveSession) {
628 $tempuserArr[] = $authInfo['userSession'];
629 $tempuser = $authInfo['userSession'];
630 // User is authenticated because we found a user session
631 $authenticated = TRUE;
632
633 if ($this->writeDevLog) {
634 t3lib_div::devLog('User session used: ' . t3lib_div::arrayToLogString($authInfo['userSession'], array($this->userid_column, $this->username_column)), 't3lib_userAuth');
635 }
636 }
637
638 // Re-auth user when 'auth'-service option is set
639 if ($this->svConfig['setup'][$this->loginType . '_alwaysAuthUser']) {
640 $authenticated = FALSE;
641 if ($this->writeDevLog) {
642 t3lib_div::devLog('alwaysAuthUser option is enabled', 't3lib_userAuth');
643 }
644 }
645
646 // Authenticate the user if needed
647 if (count($tempuserArr) && !$authenticated) {
648
649 foreach ($tempuserArr as $tempuser) {
650
651 // Use 'auth' service to authenticate the user
652 // If one service returns FALSE then authentication failed
653 // a service might return 100 which means there's no reason to stop but the user can't be authenticated by that service
654
655 if ($this->writeDevLog) {
656 t3lib_div::devLog('Auth user: ' . t3lib_div::arrayToLogString($tempuser), 't3lib_userAuth');
657 }
658
659 $serviceChain = '';
660 $subType = 'authUser' . $this->loginType;
661 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
662 $serviceChain .= ',' . $serviceObj->getServiceKey();
663 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
664 if (($ret = $serviceObj->authUser($tempuser)) > 0) {
665
666 // If the service returns >=200 then no more checking is needed - useful for IP checking without password
667 if (intval($ret) >= 200) {
668 $authenticated = TRUE;
669 break;
670 } elseif (intval($ret) >= 100) {
671 // Just go on. User is still not authenticated but there's no reason to stop now.
672 } else {
673 $authenticated = TRUE;
674 }
675
676 } else {
677 $authenticated = FALSE;
678 break;
679 }
680 unset($serviceObj);
681 }
682 unset($serviceObj);
683
684 if ($this->writeDevLog && $serviceChain) {
685 t3lib_div::devLog($subType . ' auth services called: ' . $serviceChain, 't3lib_userAuth');
686 }
687
688 if ($authenticated) {
689 // Leave foreach() because a user is authenticated
690 break;
691 }
692 }
693 }
694
695 // If user is authenticated a valid user is in $tempuser
696 if ($authenticated) {
697 // Reset failure flag
698 $this->loginFailure = FALSE;
699
700 // Insert session record if needed:
701 if (!($haveSession && (
702 $tempuser['ses_id'] == $this->id || // check if the tempuser has the current session id
703 $tempuser['uid'] == $authInfo['userSession']['ses_userid'] // check if the tempuser has the uid of the fetched session user
704 ))) {
705 $this->createUserSession($tempuser);
706
707 // The login session is started.
708 $this->loginSessionStarted = TRUE;
709 }
710
711 // User logged in - write that to the log!
712 if ($this->writeStdLog && $activeLogin) {
713 $this->writelog(255, 1, 0, 1,
714 'User %s logged in from %s (%s)',
715 array($tempuser[$this->username_column], t3lib_div::getIndpEnv('REMOTE_ADDR'), t3lib_div::getIndpEnv('REMOTE_HOST')),
716 '', '', '', -1, '', $tempuser['uid']
717 );
718 }
719
720 if ($this->writeDevLog && $activeLogin) {
721 t3lib_div::devLog('User ' . $tempuser[$this->username_column] . ' logged in from ' . t3lib_div::getIndpEnv('REMOTE_ADDR') . ' (' . t3lib_div::getIndpEnv('REMOTE_HOST') . ')', 't3lib_userAuth', -1);
722 }
723 if ($this->writeDevLog && !$activeLogin) {
724 t3lib_div::devLog('User ' . $tempuser[$this->username_column] . ' authenticated from ' . t3lib_div::getIndpEnv('REMOTE_ADDR') . ' (' . t3lib_div::getIndpEnv('REMOTE_HOST') . ')', 't3lib_userAuth', -1);
725 }
726
727 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] == 3 && $this->user_table == 'be_users') {
728 $requestStr = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'), strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir));
729 $backendScript = t3lib_BEfunc::getBackendScript();
730 if ($requestStr == $backendScript && t3lib_div::getIndpEnv('TYPO3_SSL')) {
731 list(, $url) = explode('://', t3lib_div::getIndpEnv('TYPO3_SITE_URL'), 2);
732 list($server, $address) = explode('/', $url, 2);
733 if (intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'])) {
734 $sslPortSuffix = ':' . intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']);
735 // strip port from server
736 $server = str_replace($sslPortSuffix, '', $server);
737 }
738 t3lib_utility_Http::redirect('http://' . $server . '/' . $address . TYPO3_mainDir . $backendScript);
739 }
740 }
741
742 } elseif ($activeLogin || count($tempuserArr)) {
743 $this->loginFailure = TRUE;
744
745 if ($this->writeDevLog && !count($tempuserArr) && $activeLogin) {
746 t3lib_div::devLog('Login failed: ' . t3lib_div::arrayToLogString($loginData), 't3lib_userAuth', 2);
747 }
748 if ($this->writeDevLog && count($tempuserArr)) {
749 t3lib_div::devLog('Login failed: ' . t3lib_div::arrayToLogString($tempuser, array($this->userid_column, $this->username_column)), 't3lib_userAuth', 2);
750 }
751 }
752
753 // If there were a login failure, check to see if a warning email should be sent:
754 if ($this->loginFailure && $activeLogin) {
755 if ($this->writeDevLog) {
756 t3lib_div::devLog('Call checkLogFailures: ' . t3lib_div::arrayToLogString(array('warningEmail' => $this->warningEmail, 'warningPeriod' => $this->warningPeriod, 'warningMax' => $this->warningMax,)), 't3lib_userAuth', -1);
757 }
758
759 $this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax);
760 }
761 }
762
763 /**
764 * Creates a new session ID.
765 *
766 * @return string The new session ID
767 */
768 public function createSessionId() {
769 return t3lib_div::getRandomHexString($this->hash_length);
770 }
771
772 /*************************
773 *
774 * User Sessions
775 *
776 *************************/
777
778 /**
779 * Creates a user session record.
780 *
781 * @param array $tempuser User data array
782 * @return void
783 */
784 function createUserSession($tempuser) {
785
786 if ($this->writeDevLog) {
787 t3lib_div::devLog('Create session ses_id = ' . $this->id, 't3lib_userAuth');
788 }
789
790 // Delete session entry first
791 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
792 $this->session_table,
793 'ses_id = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table) . '
794 AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
795 );
796
797 // Re-create session entry
798 $insertFields = $this->getNewSessionRecord($tempuser);
799 $GLOBALS['TYPO3_DB']->exec_INSERTquery($this->session_table, $insertFields);
800
801 // Updating lastLogin_column carrying information about last login.
802 if ($this->lastLogin_column) {
803 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
804 $this->user_table,
805 $this->userid_column . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tempuser[$this->userid_column], $this->user_table),
806 array($this->lastLogin_column => $GLOBALS['EXEC_TIME'])
807 );
808 }
809 }
810
811 /**
812 * Returns a new session record for the current user for insertion into the DB.
813 * This function is mainly there as a wrapper for inheriting classes to override it.
814 *
815 * @param array $tempuser
816 * @return array User session record
817 */
818 function getNewSessionRecord($tempuser) {
819 return array(
820 'ses_id' => $this->id,
821 'ses_name' => $this->name,
822 'ses_iplock' => $tempuser['disableIPlock'] ? '[DISABLED]' : $this->ipLockClause_remoteIPNumber($this->lockIP),
823 'ses_hashlock' => $this->hashLockClause_getHashInt(),
824 'ses_userid' => $tempuser[$this->userid_column],
825 'ses_tstamp' => $GLOBALS['EXEC_TIME']
826 );
827 }
828
829 /**
830 * Read the user session from db.
831 *
832 * @param boolean $skipSessionUpdate
833 * @return array User session data
834 */
835 function fetchUserSession($skipSessionUpdate = FALSE) {
836
837 $user = '';
838
839 if ($this->writeDevLog) {
840 t3lib_div::devLog('Fetch session ses_id = ' . $this->id, 't3lib_userAuth');
841 }
842
843 // Fetch the user session from the DB
844 $statement = $this->fetchUserSessionFromDB();
845 $user = FALSE;
846 if ($statement) {
847 $statement->execute();
848 $user = $statement->fetch();
849 $statement->free();
850 }
851
852 if ($statement && $user) {
853 // A user was found
854 if (t3lib_Utility_Math::canBeInterpretedAsInteger($this->auth_timeout_field)) {
855 // Get timeout from object
856 $timeout = intval($this->auth_timeout_field);
857 } else {
858 // Get timeout-time from usertable
859 $timeout = intval($user[$this->auth_timeout_field]);
860 }
861 // If timeout > 0 (TRUE) and currenttime has not exceeded the latest sessions-time plus the timeout in seconds then accept user
862 // 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...
863 if ($timeout > 0 && ($GLOBALS['EXEC_TIME'] < ($user['ses_tstamp'] + $timeout))) {
864 if (!$skipSessionUpdate) {
865 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
866 $this->session_table,
867 'ses_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table) . '
868 AND ses_name=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table),
869 array('ses_tstamp' => $GLOBALS['EXEC_TIME'])
870 );
871 // Make sure that the timestamp is also updated in the array
872 $user['ses_tstamp'] = $GLOBALS['EXEC_TIME'];
873 }
874
875 } else {
876 // Delete any user set...
877 $this->logoff();
878 }
879 } else {
880 // Delete any user set...
881 $this->logoff();
882 }
883 return $user;
884 }
885
886 /**
887 * Log out current user!
888 * Removes the current session record, sets the internal ->user array to a blank string; Thereby the current user (if any) is effectively logged out!
889 *
890 * @return void
891 */
892 function logoff() {
893 if ($this->writeDevLog) {
894 t3lib_div::devLog('logoff: ses_id = ' . $this->id, 't3lib_userAuth');
895 }
896
897 // Release the locked records
898 t3lib_BEfunc::lockRecords();
899
900 // Hook for pre-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
901 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'])) {
902 $_params = array();
903 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'] as $_funcRef) {
904 if ($_funcRef) {
905 t3lib_div::callUserFunction($_funcRef, $_params, $this);
906 }
907 }
908 }
909
910 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
911 $this->session_table,
912 'ses_id = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table) . '
913 AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
914 );
915
916 $this->user = '';
917
918 // Hook for post-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
919 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'])) {
920 $_params = array();
921 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'] as $_funcRef) {
922 if ($_funcRef) {
923 t3lib_div::callUserFunction($_funcRef, $_params, $this);
924 }
925 }
926 }
927 }
928
929 /**
930 * Determine whether there's an according session record to a given session_id
931 * in the database. Don't care if session record is still valid or not.
932 *
933 * @param integer $id Claimed Session ID
934 * @return boolean Returns TRUE if a corresponding session was found in the database
935 */
936 function isExistingSessionRecord($id) {
937 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery(
938 'COUNT(*)',
939 $this->session_table,
940 'ses_id = :ses_id'
941 );
942 $statement->execute(array(':ses_id' => $id));
943 $row = $statement->fetch(t3lib_db_PreparedStatement::FETCH_NUM);
944 $statement->free();
945
946 return (($row[0] ? TRUE : FALSE));
947 }
948
949 /*************************
950 *
951 * SQL Functions
952 *
953 *************************/
954
955 /**
956 * The session_id is used to find user in the database.
957 * Two tables are joined: The session-table with user_id of the session and the usertable with its primary key
958 * if the client is flash (e.g. from a flash application inside TYPO3 that does a server request)
959 * then don't evaluate with the hashLockClause, as the client/browser is included in this hash
960 * and thus, the flash request would be rejected
961 *
962 * @return t3lib_db_PreparedStatement
963 * @access private
964 */
965 protected function fetchUserSessionFromDB() {
966 $statement = NULL;
967 $ipLockClause = $this->ipLockClause();
968
969 if ($GLOBALS['CLIENT']['BROWSER'] == 'flash') {
970 // If on the flash client, the veri code is valid, then the user session is fetched
971 // from the DB without the hashLock clause
972 if (t3lib_div::_GP('vC') == $this->veriCode()) {
973 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery(
974 '*',
975 $this->session_table . ',' . $this->user_table,
976 $this->session_table . '.ses_id = :ses_id
977 AND ' . $this->session_table . '.ses_name = :ses_name
978 AND ' . $this->session_table . '.ses_userid = ' . $this->user_table . '.' . $this->userid_column . '
979 ' . $ipLockClause['where'] . '
980 ' . $this->user_where_clause()
981 );
982 $statement->bindValues(array(
983 ':ses_id' => $this->id,
984 ':ses_name' => $this->name,
985 ));
986 $statement->bindValues($ipLockClause['parameters']);
987 }
988 } else {
989 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery(
990 '*',
991 $this->session_table . ',' . $this->user_table,
992 $this->session_table . '.ses_id = :ses_id
993 AND ' . $this->session_table . '.ses_name = :ses_name
994 AND ' . $this->session_table . '.ses_userid = ' . $this->user_table . '.' . $this->userid_column . '
995 ' . $ipLockClause['where'] . '
996 ' . $this->hashLockClause() . '
997 ' . $this->user_where_clause()
998 );
999 $statement->bindValues(array(
1000 ':ses_id' => $this->id,
1001 ':ses_name' => $this->name,
1002 ));
1003 $statement->bindValues($ipLockClause['parameters']);
1004 }
1005 return $statement;
1006 }
1007
1008 /**
1009 * This returns the where-clause needed to select the user with respect flags like deleted, hidden, starttime, endtime
1010 *
1011 * @return string
1012 * @access private
1013 */
1014 protected function user_where_clause() {
1015 return (($this->enablecolumns['rootLevel']) ? 'AND ' . $this->user_table . '.pid=0 ' : '') .
1016 (($this->enablecolumns['disabled']) ? ' AND ' . $this->user_table . '.' . $this->enablecolumns['disabled'] . '=0' : '') .
1017 (($this->enablecolumns['deleted']) ? ' AND ' . $this->user_table . '.' . $this->enablecolumns['deleted'] . '=0' : '') .
1018 (($this->enablecolumns['starttime']) ? ' AND (' . $this->user_table . '.' . $this->enablecolumns['starttime'] . '<=' . $GLOBALS['EXEC_TIME'] . ')' : '') .
1019 (($this->enablecolumns['endtime']) ? ' AND (' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '=0 OR ' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '>' . $GLOBALS['EXEC_TIME'] . ')' : '');
1020 }
1021
1022 /**
1023 * This returns the where prepared statement-clause needed to lock a user to the IP address
1024 *
1025 * @return array
1026 * @access private
1027 */
1028 protected function ipLockClause() {
1029 $statementClause = array(
1030 'where' => '',
1031 'parameters' => array(),
1032 );
1033 if ($this->lockIP) {
1034 $statementClause['where'] = 'AND (
1035 ' . $this->session_table . '.ses_iplock = :ses_iplock
1036 OR ' . $this->session_table . '.ses_iplock=\'[DISABLED]\'
1037 )';
1038 $statementClause['parameters'] = array(
1039 ':ses_iplock' => $this->ipLockClause_remoteIPNumber($this->lockIP),
1040 );
1041 }
1042 return $statementClause;
1043 }
1044
1045 /**
1046 * Returns the IP address to lock to.
1047 * The IP address may be partial based on $parts.
1048 *
1049 * @param integer $parts 1-4: Indicates how many parts of the IP address to return. 4 means all, 1 means only first number.
1050 * @return string (Partial) IP address for REMOTE_ADDR
1051 * @access private
1052 */
1053 protected function ipLockClause_remoteIPNumber($parts) {
1054 $IP = t3lib_div::getIndpEnv('REMOTE_ADDR');
1055
1056 if ($parts >= 4) {
1057 return $IP;
1058 } else {
1059 $parts = t3lib_utility_Math::forceIntegerInRange($parts, 1, 3);
1060 $IPparts = explode('.', $IP);
1061 for ($a = 4; $a > $parts; $a--) {
1062 unset($IPparts[$a - 1]);
1063 }
1064 return implode('.', $IPparts);
1065 }
1066 }
1067
1068 /**
1069 * VeriCode returns 10 first chars of a md5 hash of the session cookie AND the encryptionKey from TYPO3_CONF_VARS.
1070 * 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...
1071 *
1072 * @return string
1073 */
1074 public function veriCode() {
1075 return substr(md5($this->id . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, 10);
1076 }
1077
1078 /**
1079 * This returns the where-clause needed to lock a user to a hash integer
1080 *
1081 * @return string
1082 * @access private
1083 */
1084 protected function hashLockClause() {
1085 $wherePart = 'AND ' . $this->session_table . '.ses_hashlock=' . intval($this->hashLockClause_getHashInt());
1086 return $wherePart;
1087 }
1088
1089 /**
1090 * Creates hash integer to lock user to. Depends on configured keywords
1091 *
1092 * @return integer Hash integer
1093 * @access private
1094 */
1095 protected function hashLockClause_getHashInt() {
1096 $hashStr = '';
1097
1098 if (t3lib_div::inList($this->lockHashKeyWords, 'useragent')) {
1099 $hashStr .= ':' . t3lib_div::getIndpEnv('HTTP_USER_AGENT');
1100 }
1101
1102 return t3lib_div::md5int($hashStr);
1103 }
1104
1105 /*************************
1106 *
1107 * Session and Configuration Handling
1108 *
1109 *************************/
1110
1111 /**
1112 * This writes $variable to the user-record. This is a way of providing session-data.
1113 * You can fetch the data again through $this->uc in this class!
1114 * If $variable is not an array, $this->uc is saved!
1115 *
1116 * @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
1117 * @return void
1118 */
1119 function writeUC($variable = '') {
1120 if (is_array($this->user) && $this->user[$this->userid_column]) {
1121 if (!is_array($variable)) {
1122 $variable = $this->uc;
1123 }
1124
1125 if ($this->writeDevLog) {
1126 t3lib_div::devLog('writeUC: ' . $this->userid_column . '=' . intval($this->user[$this->userid_column]), 't3lib_userAuth');
1127 }
1128 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->user_table, $this->userid_column . '=' . intval($this->user[$this->userid_column]), array('uc' => serialize($variable)));
1129 }
1130 }
1131
1132 /**
1133 * 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
1134 *
1135 * @param mixed $theUC If an array, then set as ->uc, otherwise load from user record
1136 * @return void
1137 */
1138 function unpack_uc($theUC = '') {
1139 if (!$theUC) {
1140 $theUC = unserialize($this->user['uc']);
1141 }
1142 if (is_array($theUC)) {
1143 $this->uc = $theUC;
1144 }
1145 }
1146
1147 /**
1148 * Stores data for a module.
1149 * 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.
1150 *
1151 * @param string $module Is the name of the module ($MCONF['name'])
1152 * @param mixed $data Is the data you want to store for that module (array, string, ...)
1153 * @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.
1154 * @return void
1155 */
1156 function pushModuleData($module, $data, $noSave = 0) {
1157 $this->uc['moduleData'][$module] = $data;
1158 $this->uc['moduleSessionID'][$module] = $this->id;
1159 if (!$noSave) {
1160 $this->writeUC();
1161 }
1162 }
1163
1164 /**
1165 * Gets module data for a module (from a loaded ->uc array)
1166 *
1167 * @param string $module Is the name of the module ($MCONF['name'])
1168 * @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).
1169 * @return mixed The module data if available: $this->uc['moduleData'][$module];
1170 */
1171 function getModuleData($module, $type = '') {
1172 if ($type != 'ses' || $this->uc['moduleSessionID'][$module] == $this->id) {
1173 return $this->uc['moduleData'][$module];
1174 }
1175 }
1176
1177 /**
1178 * Returns the session data stored for $key.
1179 * The data will last only for this login session since it is stored in the session table.
1180 *
1181 * @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.
1182 * @return mixed
1183 */
1184 function getSessionData($key) {
1185 $sesDat = unserialize($this->user['ses_data']);
1186 return $sesDat[$key];
1187 }
1188
1189 /**
1190 * Sets the session data ($data) for $key and writes all session data (from ->user['ses_data']) to the database.
1191 * The data will last only for this login session since it is stored in the session table.
1192 *
1193 * @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.
1194 * @param mixed $data The variable to store in index $key
1195 * @return void
1196 */
1197 function setAndSaveSessionData($key, $data) {
1198 $sesDat = unserialize($this->user['ses_data']);
1199 $sesDat[$key] = $data;
1200 $this->user['ses_data'] = serialize($sesDat);
1201
1202 if ($this->writeDevLog) {
1203 t3lib_div::devLog('setAndSaveSessionData: ses_id = ' . $this->user['ses_id'], 't3lib_userAuth');
1204 }
1205 $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']));
1206 }
1207
1208 /*************************
1209 *
1210 * Misc
1211 *
1212 *************************/
1213
1214 /**
1215 * Returns an info array with Login/Logout data submitted by a form or params
1216 *
1217 * @return array
1218 * @internal
1219 */
1220 function getLoginFormData() {
1221 $loginData = array();
1222 if ($this->getMethodEnabled) {
1223 $loginData['status'] = t3lib_div::_GP($this->formfield_status);
1224 $loginData['uname'] = t3lib_div::_GP($this->formfield_uname);
1225 $loginData['uident'] = t3lib_div::_GP($this->formfield_uident);
1226 $loginData['chalvalue'] = t3lib_div::_GP($this->formfield_chalvalue);
1227 } else {
1228 $loginData['status'] = t3lib_div::_POST($this->formfield_status);
1229 $loginData['uname'] = t3lib_div::_POST($this->formfield_uname);
1230 $loginData['uident'] = t3lib_div::_POST($this->formfield_uident);
1231 $loginData['chalvalue'] = t3lib_div::_POST($this->formfield_chalvalue);
1232 }
1233 // Only process the login data if a login is requested
1234 if ($loginData['status'] === 'login') {
1235 $loginData = $this->processLoginData($loginData);
1236 }
1237
1238 return $loginData;
1239 }
1240
1241 /**
1242 * Processes Login data submitted by a form or params depending on the
1243 * passwordTransmissionStrategy
1244 *
1245 * @param array $loginData Login data array
1246 * @param string $passwordTransmissionStrategy Alternative passwordTransmissionStrategy. Used when authentication services wants to override the default.
1247 * @return array
1248 * @internal
1249 */
1250 function processLoginData($loginData, $passwordTransmissionStrategy = '') {
1251 $passwordTransmissionStrategy = $passwordTransmissionStrategy ? $passwordTransmissionStrategy : ($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['loginSecurityLevel'] ? trim($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['loginSecurityLevel']) : $this->security_level);
1252
1253 if ($this->writeDevLog) {
1254 t3lib_div::devLog('Login data before processing: ' . t3lib_div::arrayToLogString($loginData), 't3lib_userAuth');
1255 }
1256
1257 $serviceChain = '';
1258 $subType = 'processLoginData' . $this->loginType;
1259 $authInfo = $this->getAuthInfoArray();
1260 $isLoginDataProcessed = FALSE;
1261 $processedLoginData = $loginData;
1262 while (is_object($serviceObject = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
1263 $serviceChain .= ',' . $serviceObject->getServiceKey();
1264 $serviceObject->initAuth($subType, $loginData, $authInfo, $this);
1265
1266 $serviceResult = $serviceObject->processLoginData($processedLoginData, $passwordTransmissionStrategy);
1267
1268 if (!empty($serviceResult)) {
1269 $isLoginDataProcessed = TRUE;
1270
1271 // If the service returns >=200 then no more processing is needed
1272 if (intval($serviceResult) >= 200) {
1273 unset($serviceObject);
1274 break;
1275 }
1276 }
1277 unset($serviceObject);
1278 }
1279
1280 if ($isLoginDataProcessed) {
1281 $loginData = $processedLoginData;
1282 if ($this->writeDevLog) {
1283 t3lib_div::devLog('Processed login data: '.t3lib_div::arrayToLogString($processedLoginData), 't3lib_userAuth');
1284 }
1285 }
1286
1287 return $loginData;
1288 }
1289
1290 /**
1291 * Returns an info array which provides additional information for auth services
1292 *
1293 * @return array
1294 * @internal
1295 */
1296 function getAuthInfoArray() {
1297 $authInfo = array();
1298 $authInfo['loginType'] = $this->loginType;
1299 $authInfo['refInfo'] = parse_url(t3lib_div::getIndpEnv('HTTP_REFERER'));
1300 $authInfo['HTTP_HOST'] = t3lib_div::getIndpEnv('HTTP_HOST');
1301 $authInfo['REMOTE_ADDR'] = t3lib_div::getIndpEnv('REMOTE_ADDR');
1302 $authInfo['REMOTE_HOST'] = t3lib_div::getIndpEnv('REMOTE_HOST');
1303 /** @deprecated the usage of $authInfo['security_level'] is deprecated since 4.7 */
1304 $authInfo['security_level'] = $this->security_level;
1305 $authInfo['showHiddenRecords'] = $this->showHiddenRecords;
1306 // Can be overidden in localconf by SVCONF:
1307 $authInfo['db_user']['table'] = $this->user_table;
1308 $authInfo['db_user']['userid_column'] = $this->userid_column;
1309 $authInfo['db_user']['username_column'] = $this->username_column;
1310 $authInfo['db_user']['userident_column'] = $this->userident_column;
1311 $authInfo['db_user']['usergroup_column'] = $this->usergroup_column;
1312 $authInfo['db_user']['enable_clause'] = $this->user_where_clause();
1313 $authInfo['db_user']['checkPidList'] = $this->checkPid ? $this->checkPid_value : '';
1314 $authInfo['db_user']['check_pid_clause'] = $this->checkPid ? ' AND pid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($authInfo['db_user']['checkPidList']) . ')' : '';
1315 $authInfo['db_groups']['table'] = $this->usergroup_table;
1316 return $authInfo;
1317 }
1318
1319 /**
1320 * Check the login data with the user record data for builtin login methods
1321 *
1322 * @param array $user User data array
1323 * @param array $loginData Login data array
1324 * @param string $passwordCompareStrategy Alternative passwordCompareStrategy. Used when authentication services wants to override the default.
1325 * @return boolean TRUE if login data matched
1326 */
1327 function compareUident($user, $loginData, $passwordCompareStrategy = '') {
1328
1329 $OK = FALSE;
1330 $passwordCompareStrategy = $passwordCompareStrategy ? $passwordCompareStrategy : $this->security_level;
1331
1332 switch ($passwordCompareStrategy) {
1333 case 'superchallenged': // If superchallenged the password in the database ($user[$this->userident_column]) must be a md5-hash of the original password.
1334 case 'challenged':
1335
1336 // Check challenge stored in cookie:
1337 if ($this->challengeStoredInCookie) {
1338 session_start();
1339 if ($_SESSION['login_challenge'] !== $loginData['chalvalue']) {
1340 if ($this->writeDevLog) {
1341 t3lib_div::devLog('PHP Session stored challenge "' . $_SESSION['login_challenge'] . '" and submitted challenge "' . $loginData['chalvalue'] . '" did not match, so authentication failed!', 't3lib_userAuth', 2);
1342 }
1343 $this->logoff();
1344 return FALSE;
1345 }
1346 }
1347
1348 if ((string) $loginData['uident_' . $passwordCompareStrategy] === (string) md5($user[$this->username_column] . ':' . $user[$this->userident_column] . ':' . $loginData['chalvalue'])) {
1349 $OK = TRUE;
1350 }
1351 break;
1352 default: // normal
1353 if ((string) $loginData['uident_text'] === (string) $user[$this->userident_column]) {
1354 $OK = TRUE;
1355 }
1356 break;
1357 }
1358
1359 return $OK;
1360 }
1361
1362 /**
1363 * Garbage collector, removing old expired sessions.
1364 *
1365 * @return void
1366 * @internal
1367 */
1368 function gc() {
1369 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
1370 $this->session_table,
1371 'ses_tstamp < ' . intval($GLOBALS['EXEC_TIME'] - ($this->gc_time)) .
1372 ' AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
1373 );
1374 }
1375
1376 /**
1377 * DUMMY: Writes to log database table (in some extension classes)
1378 *
1379 * @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
1380 * @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 !!)
1381 * @param integer $error flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1382 * @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
1383 * @param string $details Default text that follows the message
1384 * @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...
1385 * @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.)
1386 * @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.)
1387 * @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.)
1388 * @return void
1389 * @see t3lib_beUserAuth::writelog()
1390 */
1391 function writelog($type, $action, $error, $details_nr, $details, $data, $tablename, $recuid, $recpid) {
1392 }
1393
1394 /**
1395 * DUMMY: Check login failures (in some extension classes)
1396 *
1397 * @param string $email Email address
1398 * @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
1399 * @param integer $maxFailures Max allowed failures before a warning mail is sent
1400 * @return void
1401 * @ignore
1402 */
1403 function checkLogFailures($email, $secondsBack, $maxFailures) {
1404 }
1405
1406 /**
1407 * Raw initialization of the be_user with uid=$uid
1408 * This will circumvent all login procedures and select a be_users record from the
1409 * database and set the content of ->user to the record selected.
1410 * Thus the BE_USER object will appear like if a user was authenticated - however without
1411 * a session id and the fields from the session table of course.
1412 * Will check the users for disabled, start/endtime, etc. ($this->user_where_clause())
1413 *
1414 * @param integer $uid The UID of the backend user to set in ->user
1415 * @return void
1416 * @internal
1417 * @see SC_mod_tools_be_user_index::compareUsers(), SC_mod_user_setup_index::simulateUser(), freesite_admin::startCreate()
1418 */
1419 function setBeUserByUid($uid) {
1420 $this->user = $this->getRawUserByUid($uid);
1421 }
1422
1423 /**
1424 * Raw initialization of the be_user with username=$name
1425 *
1426 * @param string $name The username to look up.
1427 * @return void
1428 * @see t3lib_userAuth::setBeUserByUid()
1429 * @internal
1430 */
1431 function setBeUserByName($name) {
1432 $this->user = $this->getRawUserByName($name);
1433 }
1434
1435 /**
1436 * Fetching raw user record with uid=$uid
1437 *
1438 * @param integer $uid The UID of the backend user to set in ->user
1439 * @return array user record or FALSE
1440 * @internal
1441 */
1442 function getRawUserByUid($uid) {
1443 $user = FALSE;
1444 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'uid=' . intval($uid) . ' ' . $this->user_where_clause());
1445 if ($dbres) {
1446 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1447 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1448 }
1449 return $user;
1450 }
1451
1452 /**
1453 * Fetching raw user record with username=$name
1454 *
1455 * @param string $name The username to look up.
1456 * @return array user record or FALSE
1457 * @see t3lib_userAuth::getUserByUid()
1458 * @internal
1459 */
1460 function getRawUserByName($name) {
1461 $user = FALSE;
1462 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'username=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($name, $this->user_table) . ' ' . $this->user_where_clause());
1463 if ($dbres) {
1464 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1465 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1466 }
1467 return $user;
1468 }
1469
1470 /*************************
1471 *
1472 * Create/update user - EXPERIMENTAL
1473 *
1474 *************************/
1475
1476 /**
1477 * Get a user from DB by username
1478 * provided for usage from services
1479 *
1480 * @param array $dbUser User db table definition: $this->db_user
1481 * @param string $username user name
1482 * @param string $extraWhere Additional WHERE clause: " AND ...
1483 * @return mixed User array or FALSE
1484 */
1485 function fetchUserRecord($dbUser, $username, $extraWhere = '') {
1486 $user = FALSE;
1487
1488 $usernameClause = $username ? ($dbUser['username_column'] . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($username, $dbUser['table'])) : '';
1489
1490 if ($username || $extraWhere) {
1491
1492 // Look up the user by the username and/or extraWhere:
1493 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1494 '*',
1495 $dbUser['table'],
1496 $usernameClause .
1497 $dbUser['check_pid_clause'] .
1498 $dbUser['enable_clause'] .
1499 $extraWhere
1500 );
1501
1502 if ($dbres) {
1503 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1504 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1505 }
1506 }
1507 return $user;
1508 }
1509 }
1510
1511 ?>