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