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