[TASK] Remove @author lines
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Authentication / FrontendUserAuthentication.php
1 <?php
2 namespace TYPO3\CMS\Frontend\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\Authentication\AbstractUserAuthentication;
18 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Extension class for Front End User Authentication.
23 */
24 class FrontendUserAuthentication extends AbstractUserAuthentication {
25
26 /**
27 * form field with 0 or 1
28 * 1 = permanent login enabled
29 * 0 = session is valid for a browser session only
30 * @var string
31 */
32 public $formfield_permanent = 'permalogin';
33
34 /**
35 * Lifetime of session data in seconds.
36 * @var int
37 */
38 protected $sessionDataLifetime = 86400;
39
40 /**
41 * @var string
42 */
43 public $usergroup_column = 'usergroup';
44
45 /**
46 * @var string
47 */
48 public $usergroup_table = 'fe_groups';
49
50 /**
51 * @var array
52 */
53 public $groupData = array(
54 'title' => array(),
55 'uid' => array(),
56 'pid' => array()
57 );
58
59 /**
60 * Used to accumulate the TSconfig data of the user
61 * @var array
62 */
63 public $TSdataArray = array();
64
65 /**
66 * @var array
67 */
68 public $userTS = array();
69
70 /**
71 * @var bool
72 */
73 public $userTSUpdated = FALSE;
74
75 /**
76 * Session and user data:
77 * There are two types of data that can be stored: UserData and Session-Data.
78 * Userdata is for the login-user, and session-data for anyone viewing the pages.
79 * 'Keys' are keys in the internal data array of the data.
80 * When you get or set a key in one of the data-spaces (user or session) you decide the type of the variable (not object though)
81 * 'Reserved' keys are:
82 * - 'recs': Array: Used to 'register' records, eg in a shopping basket. Structure: [recs][tablename][record_uid]=number
83 * - sys: Reserved for TypoScript standard code.
84 *
85 * @var array
86 */
87 public $sesData = array();
88
89 /**
90 * @var bool
91 */
92 public $sesData_change = FALSE;
93
94 /**
95 * @var bool
96 */
97 public $userData_change = FALSE;
98
99 /**
100 * @var bool
101 */
102 public $is_permanent;
103
104 /**
105 * @var int|NULL
106 */
107 protected $sessionDataTimestamp = NULL;
108
109 /**
110 * @var bool
111 */
112 protected $loginHidden = FALSE;
113
114 /**
115 * Default constructor.
116 */
117 public function __construct() {
118 parent::__construct();
119
120 // Disable cookie by default, will be activated if saveSessionData() is called,
121 // a user is logging-in or an existing session is found
122 $this->dontSetCookie = TRUE;
123
124 $this->session_table = 'fe_sessions';
125 $this->name = self::getCookieName();
126 $this->get_name = 'ftu';
127 $this->loginType = 'FE';
128 $this->user_table = 'fe_users';
129 $this->username_column = 'username';
130 $this->userident_column = 'password';
131 $this->userid_column = 'uid';
132 $this->lastLogin_column = 'lastlogin';
133 $this->enablecolumns = array(
134 'deleted' => 'deleted',
135 'disabled' => 'disable',
136 'starttime' => 'starttime',
137 'endtime' => 'endtime'
138 );
139 $this->formfield_uname = 'user';
140 $this->formfield_uident = 'pass';
141 $this->formfield_status = 'logintype';
142 $this->auth_timeout_field = 6000;
143 $this->sendNoCacheHeaders = FALSE;
144 $this->getFallBack = TRUE;
145 $this->getMethodEnabled = TRUE;
146 }
147
148 /**
149 * Returns the configured cookie name
150 *
151 * @return string
152 */
153 static public function getCookieName() {
154 $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['FE']['cookieName']);
155 if (empty($configuredCookieName)) {
156 $configuredCookieName = 'fe_typo_user';
157 }
158 return $configuredCookieName;
159 }
160
161 /**
162 * Starts a user session
163 *
164 * @return void
165 * @see AbstractUserAuthentication::start()
166 */
167 public function start() {
168 if ((int)$this->auth_timeout_field > 0 && (int)$this->auth_timeout_field < $this->lifetime) {
169 // If server session timeout is non-zero but less than client session timeout: Copy this value instead.
170 $this->auth_timeout_field = $this->lifetime;
171 }
172 $this->sessionDataLifetime = (int)$GLOBALS['TYPO3_CONF_VARS']['FE']['sessionDataLifetime'];
173 if ($this->sessionDataLifetime <= 0) {
174 $this->sessionDataLifetime = 86400;
175 }
176 parent::start();
177 }
178
179 /**
180 * Returns a new session record for the current user for insertion into the DB.
181 *
182 * @param array $tempuser
183 * @return array User session record
184 */
185 public function getNewSessionRecord($tempuser) {
186 $insertFields = parent::getNewSessionRecord($tempuser);
187 $insertFields['ses_permanent'] = $this->is_permanent;
188 return $insertFields;
189 }
190
191 /**
192 * Determine whether a session cookie needs to be set (lifetime=0)
193 *
194 * @return bool
195 * @internal
196 */
197 public function isSetSessionCookie() {
198 return ($this->newSessionID || $this->forceSetCookie)
199 && ($this->lifetime == 0 || !isset($this->user['ses_permanent']) || !$this->user['ses_permanent']);
200 }
201
202 /**
203 * Determine whether a non-session cookie needs to be set (lifetime>0)
204 *
205 * @return bool
206 * @internal
207 */
208 public function isRefreshTimeBasedCookie() {
209 return $this->lifetime > 0 && isset($this->user['ses_permanent']) && $this->user['ses_permanent'];
210 }
211
212 /**
213 * Returns an info array with Login/Logout data submitted by a form or params
214 *
215 * @return array
216 * @see AbstractUserAuthentication::getLoginFormData()
217 */
218 public function getLoginFormData() {
219 $loginData = parent::getLoginFormData();
220 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 0 || $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 1) {
221 if ($this->getMethodEnabled) {
222 $isPermanent = GeneralUtility::_GP($this->formfield_permanent);
223 } else {
224 $isPermanent = GeneralUtility::_POST($this->formfield_permanent);
225 }
226 if (strlen($isPermanent) != 1) {
227 $isPermanent = $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'];
228 } elseif (!$isPermanent) {
229 // To make sure the user gets a session cookie and doesn't keep a possibly existing time based cookie,
230 // we need to force setting the session cookie here
231 $this->forceSetCookie = TRUE;
232 }
233 $isPermanent = $isPermanent ? 1 : 0;
234 } elseif ($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 2) {
235 $isPermanent = 1;
236 } else {
237 $isPermanent = 0;
238 }
239 $loginData['permanent'] = $isPermanent;
240 $this->is_permanent = $isPermanent;
241 return $loginData;
242 }
243
244 /**
245 * Creates a user session record and returns its values.
246 * However, as the FE user cookie is normally not set, this has to be done
247 * before the parent class is doing the rest.
248 *
249 * @param array $tempuser User data array
250 * @return array The session data for the newly created session.
251 */
252 public function createUserSession($tempuser) {
253 // At this point we do not know if we need to set a session or a "permanant" cookie
254 // So we force the cookie to be set after authentication took place, which will
255 // then call setSessionCookie(), which will set a cookie with correct settings.
256 $this->dontSetCookie = FALSE;
257 return parent::createUserSession($tempuser);
258 }
259
260 /**
261 * Will select all fe_groups records that the current fe_user is member of
262 * and which groups are also allowed in the current domain.
263 * It also accumulates the TSconfig for the fe_user/fe_groups in ->TSdataArray
264 *
265 * @return int Returns the number of usergroups for the frontend users (if the internal user record exists and the usergroup field contains a value)
266 */
267 public function fetchGroupData() {
268 $this->TSdataArray = array();
269 $this->userTS = array();
270 $this->userTSUpdated = FALSE;
271 $this->groupData = array(
272 'title' => array(),
273 'uid' => array(),
274 'pid' => array()
275 );
276 // Setting default configuration:
277 $this->TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultUserTSconfig'];
278 // Get the info data for auth services
279 $authInfo = $this->getAuthInfoArray();
280 if ($this->writeDevLog) {
281 if (is_array($this->user)) {
282 GeneralUtility::devLog('Get usergroups for user: ' . GeneralUtility::arrayToLogString($this->user, array($this->userid_column, $this->username_column)), __CLASS__);
283 } else {
284 GeneralUtility::devLog('Get usergroups for "anonymous" user', __CLASS__);
285 }
286 }
287 $groupDataArr = array();
288 // Use 'auth' service to find the groups for the user
289 $serviceChain = '';
290 $subType = 'getGroups' . $this->loginType;
291 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
292 $serviceChain .= ',' . $serviceObj->getServiceKey();
293 $serviceObj->initAuth($subType, array(), $authInfo, $this);
294 $groupData = $serviceObj->getGroups($this->user, $groupDataArr);
295 if (is_array($groupData) && !empty($groupData)) {
296 // Keys in $groupData should be unique ids of the groups (like "uid") so this function will override groups.
297 $groupDataArr = $groupData + $groupDataArr;
298 }
299 unset($serviceObj);
300 }
301 if ($this->writeDevLog && $serviceChain) {
302 GeneralUtility::devLog($subType . ' auth services called: ' . $serviceChain, __CLASS__);
303 }
304 if ($this->writeDevLog && empty($groupDataArr)) {
305 GeneralUtility::devLog('No usergroups found by services', __CLASS__);
306 }
307 if ($this->writeDevLog && !empty($groupDataArr)) {
308 GeneralUtility::devLog(count($groupDataArr) . ' usergroup records found by services', __CLASS__);
309 }
310 // Use 'auth' service to check the usergroups if they are really valid
311 foreach ($groupDataArr as $groupData) {
312 // By default a group is valid
313 $validGroup = TRUE;
314 $serviceChain = '';
315 $subType = 'authGroups' . $this->loginType;
316 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
317 $serviceChain .= ',' . $serviceObj->getServiceKey();
318 $serviceObj->initAuth($subType, array(), $authInfo, $this);
319 if (!$serviceObj->authGroup($this->user, $groupData)) {
320 $validGroup = FALSE;
321 if ($this->writeDevLog) {
322 GeneralUtility::devLog($subType . ' auth service did not auth group: ' . GeneralUtility::arrayToLogString($groupData, 'uid,title'), __CLASS__, 2);
323 }
324 break;
325 }
326 unset($serviceObj);
327 }
328 unset($serviceObj);
329 if ($validGroup) {
330 $this->groupData['title'][$groupData['uid']] = $groupData['title'];
331 $this->groupData['uid'][$groupData['uid']] = $groupData['uid'];
332 $this->groupData['pid'][$groupData['uid']] = $groupData['pid'];
333 $this->groupData['TSconfig'][$groupData['uid']] = $groupData['TSconfig'];
334 }
335 }
336 if (!empty($this->groupData) && !empty($this->groupData['TSconfig'])) {
337 // TSconfig: collect it in the order it was collected
338 foreach ($this->groupData['TSconfig'] as $TSdata) {
339 $this->TSdataArray[] = $TSdata;
340 }
341 $this->TSdataArray[] = $this->user['TSconfig'];
342 // Sort information
343 ksort($this->groupData['title']);
344 ksort($this->groupData['uid']);
345 ksort($this->groupData['pid']);
346 }
347 return !empty($this->groupData['uid']) ? count($this->groupData['uid']) : 0;
348 }
349
350 /**
351 * Returns the parsed TSconfig for the fe_user
352 * The TSconfig will be cached in $this->userTS.
353 *
354 * @return array TSconfig array for the fe_user
355 */
356 public function getUserTSconf() {
357 if (!$this->userTSUpdated) {
358 // Parsing the user TS (or getting from cache)
359 $this->TSdataArray = TypoScriptParser::checkIncludeLines_array($this->TSdataArray);
360 $userTS = implode(LF . '[GLOBAL]' . LF, $this->TSdataArray);
361 $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
362 $parseObj->parse($userTS);
363 $this->userTS = $parseObj->setup;
364 $this->userTSUpdated = TRUE;
365 }
366 return $this->userTS;
367 }
368
369 /*****************************************
370 *
371 * Session data management functions
372 *
373 ****************************************/
374 /**
375 * Fetches the session data for the user (from the fe_session_data table) based on the ->id of the current user-session.
376 * The session data is restored to $this->sesData
377 * 1/100 calls will also do a garbage collection.
378 *
379 * @return void
380 * @access private
381 * @see storeSessionData()
382 */
383 public function fetchSessionData() {
384 // Gets SesData if any AND if not already selected by session fixation check in ->isExistingSessionRecord()
385 if ($this->id && empty($this->sesData)) {
386 $statement = $this->db->prepare_SELECTquery('*', 'fe_session_data', 'hash = :hash');
387 $statement->execute(array(':hash' => $this->id));
388 if (($sesDataRow = $statement->fetch()) !== FALSE) {
389 $this->sesData = unserialize($sesDataRow['content']);
390 $this->sessionDataTimestamp = $sesDataRow['tstamp'];
391 }
392 $statement->free();
393 }
394 }
395
396 /**
397 * Will write UC and session data.
398 * If the flag $this->userData_change has been set, the function ->writeUC is called (which will save persistent user session data)
399 * If the flag $this->sesData_change has been set, the fe_session_data table is updated with the content of $this->sesData
400 * If the $this->sessionDataTimestamp is NULL there was no session record yet, so we need to insert it into the database
401 *
402 * @return void
403 * @see fetchSessionData(), getKey(), setKey()
404 */
405 public function storeSessionData() {
406 // Saves UC and SesData if changed.
407 if ($this->userData_change) {
408 $this->writeUC('');
409 }
410 if ($this->sesData_change && $this->id) {
411 if (empty($this->sesData)) {
412 // Remove session-data
413 $this->removeSessionData();
414 // Remove cookie if not logged in as the session data is removed as well
415 if (empty($this->user['uid']) && !$this->loginHidden && $this->isCookieSet()) {
416 $this->removeCookie($this->name);
417 }
418 } elseif ($this->sessionDataTimestamp === NULL) {
419 // Write new session-data
420 $insertFields = array(
421 'hash' => $this->id,
422 'content' => serialize($this->sesData),
423 'tstamp' => $GLOBALS['EXEC_TIME']
424 );
425 $this->sessionDataTimestamp = $GLOBALS['EXEC_TIME'];
426 $this->db->exec_INSERTquery('fe_session_data', $insertFields);
427 // Now set the cookie (= fix the session)
428 $this->setSessionCookie();
429 } else {
430 // Update session data
431 $updateFields = array(
432 'content' => serialize($this->sesData),
433 'tstamp' => $GLOBALS['EXEC_TIME']
434 );
435 $this->sessionDataTimestamp = $GLOBALS['EXEC_TIME'];
436 $this->db->exec_UPDATEquery('fe_session_data', 'hash=' . $this->db->fullQuoteStr($this->id, 'fe_session_data'), $updateFields);
437 }
438 }
439 }
440
441 /**
442 * Removes data of the current session.
443 *
444 * @return void
445 */
446 public function removeSessionData() {
447 $this->sessionDataTimestamp = NULL;
448 $this->db->exec_DELETEquery('fe_session_data', 'hash=' . $this->db->fullQuoteStr($this->id, 'fe_session_data'));
449 }
450
451 /**
452 * Log out current user!
453 * Removes the current session record, sets the internal ->user array to a blank string
454 * Thereby the current user (if any) is effectively logged out!
455 * Additionally the cookie is removed
456 *
457 * @return void
458 */
459 public function logoff() {
460 parent::logoff();
461 // Remove the cookie on log-off, but only if we do not have an anonymous session
462 if (!$this->isExistingSessionRecord($this->id) && $this->isCookieSet()) {
463 $this->removeCookie($this->name);
464 }
465 }
466
467 /**
468 * Regenerate the id, take seperate session data table into account
469 * and set cookie again
470 */
471 protected function regenerateSessionId() {
472 $oldSessionId = $this->id;
473 parent::regenerateSessionId();
474 // Update session data with new ID
475 $this->db->exec_UPDATEquery(
476 'fe_session_data',
477 'hash=' . $this->db->fullQuoteStr($oldSessionId, 'fe_session_data'),
478 array('hash' => $this->id)
479 );
480
481 // We force the cookie to be set later in the authentication process
482 $this->dontSetCookie = FALSE;
483 }
484
485 /**
486 * Executes the garbage collection of session data and session.
487 * The lifetime of session data is defined by $TYPO3_CONF_VARS['FE']['sessionDataLifetime'].
488 *
489 * @return void
490 */
491 public function gc() {
492 $timeoutTimeStamp = (int)($GLOBALS['EXEC_TIME'] - $this->sessionDataLifetime);
493 $this->db->exec_DELETEquery('fe_session_data', 'tstamp < ' . $timeoutTimeStamp);
494 parent::gc();
495 }
496
497 /**
498 * Returns session data for the fe_user; Either persistent data following the fe_users uid/profile (requires login)
499 * or current-session based (not available when browse is closed, but does not require login)
500 *
501 * @param string $type Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
502 * @param string $key Key from the data array to return; The session data (in either case) is an array ($this->uc / $this->sesData) and this value determines which key to return the value for.
503 * @return mixed Returns whatever value there was in the array for the key, $key
504 * @see setKey()
505 */
506 public function getKey($type, $key) {
507 if (!$key) {
508 return NULL;
509 }
510 $value = NULL;
511 switch ($type) {
512 case 'user':
513 $value = $this->uc[$key];
514 break;
515 case 'ses':
516 $value = $this->sesData[$key];
517 break;
518 }
519 return $value;
520 }
521
522 /**
523 * Saves session data, either persistent or bound to current session cookie. Please see getKey() for more details.
524 * When a value is set the flags $this->userData_change or $this->sesData_change will be set so that the final call to ->storeSessionData() will know if a change has occurred and needs to be saved to the database.
525 * Notice: The key "recs" is already used by the function record_registration() which stores table/uid=value pairs in that key. This is used for the shopping basket among other things.
526 * Notice: Simply calling this function will not save the data to the database! The actual saving is done in storeSessionData() which is called as some of the last things in index_ts.php. So if you exit before this point, nothing gets saved of course! And the solution is to call $GLOBALS['TSFE']->storeSessionData(); before you exit.
527 *
528 * @param string $type Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
529 * @param string $key Key from the data array to store incoming data in; The session data (in either case) is an array ($this->uc / $this->sesData) and this value determines in which key the $data value will be stored.
530 * @param mixed $data The data value to store in $key
531 * @return void
532 * @see setKey(), storeSessionData(), record_registration()
533 */
534 public function setKey($type, $key, $data) {
535 if (!$key) {
536 return;
537 }
538 switch ($type) {
539 case 'user':
540 if ($this->user['uid']) {
541 if ($data === NULL) {
542 unset($this->uc[$key]);
543 } else {
544 $this->uc[$key] = $data;
545 }
546 $this->userData_change = TRUE;
547 }
548 break;
549 case 'ses':
550 if ($data === NULL) {
551 unset($this->sesData[$key]);
552 } else {
553 $this->sesData[$key] = $data;
554 }
555 $this->sesData_change = TRUE;
556 break;
557 }
558 }
559
560 /**
561 * Returns the session data stored for $key.
562 * The data will last only for this login session since it is stored in the session table.
563 *
564 * @param string $key
565 * @return mixed
566 */
567 public function getSessionData($key) {
568 return $this->getKey('ses', $key);
569 }
570
571 /**
572 * Saves the tokens so that they can be used by a later incarnation of this class.
573 *
574 * @param string $key
575 * @param mixed $data
576 * @return void
577 */
578 public function setAndSaveSessionData($key, $data) {
579 $this->setKey('ses', $key, $data);
580 $this->storeSessionData();
581 }
582
583 /**
584 * Registration of records/"shopping basket" in session data
585 * This will take the input array, $recs, and merge into the current "recs" array found in the session data.
586 * If a change in the recs storage happens (which it probably does) the function setKey() is called in order to store the array again.
587 *
588 * @param array $recs The data array to merge into/override the current recs values. The $recs array is constructed as [table]][uid] = scalar-value (eg. string/integer).
589 * @param int $maxSizeOfSessionData The maximum size of stored session data. If zero, no limit is applied and even confirmation of cookie session is discarded.
590 * @return void
591 */
592 public function record_registration($recs, $maxSizeOfSessionData = 0) {
593 // Storing value ONLY if there is a confirmed cookie set,
594 // otherwise a shellscript could easily be spamming the fe_sessions table
595 // with bogus content and thus bloat the database
596 if (!$maxSizeOfSessionData || $this->isCookieSet()) {
597 if ($recs['clear_all']) {
598 $this->setKey('ses', 'recs', array());
599 }
600 $change = 0;
601 $recs_array = $this->getKey('ses', 'recs');
602 foreach ($recs as $table => $data) {
603 if (is_array($data)) {
604 foreach ($data as $rec_id => $value) {
605 if ($value != $recs_array[$table][$rec_id]) {
606 $recs_array[$table][$rec_id] = $value;
607 $change = 1;
608 }
609 }
610 }
611 }
612 if ($change && (!$maxSizeOfSessionData || strlen(serialize($recs_array)) < $maxSizeOfSessionData)) {
613 $this->setKey('ses', 'recs', $recs_array);
614 }
615 }
616 }
617
618 /**
619 * Determine whether there's an according session record to a given session_id
620 * in the database. Don't care if session record is still valid or not.
621 *
622 * This calls the parent function but additionally tries to look up the session ID in the "fe_session_data" table.
623 *
624 * @param int $id Claimed Session ID
625 * @return bool Returns TRUE if a corresponding session was found in the database
626 */
627 public function isExistingSessionRecord($id) {
628 // Perform check in parent function
629 $count = parent::isExistingSessionRecord($id);
630 // Check if there are any fe_session_data records for the session ID the client claims to have
631 if ($count == FALSE) {
632 $statement = $this->db->prepare_SELECTquery('content,tstamp', 'fe_session_data', 'hash = :hash');
633 $res = $statement->execute(array(':hash' => $id));
634 if ($res !== FALSE) {
635 if ($sesDataRow = $statement->fetch()) {
636 $count = TRUE;
637 $this->sesData = unserialize($sesDataRow['content']);
638 $this->sessionDataTimestamp = $sesDataRow['tstamp'];
639 }
640 $statement->free();
641 }
642 }
643 return $count;
644 }
645
646 /**
647 * Hide the current login
648 *
649 * This is used by the fe_login_mode feature for pages.
650 * A current login is unset, but we remember that there has been one.
651 *
652 * @return void
653 */
654 public function hideActiveLogin() {
655 $this->user = NULL;
656 $this->loginHidden = TRUE;
657 }
658
659 }