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