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