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