Fixed bug #17665: Remove deprecated method redirect() from t3lib_userAuth
[Packages/TYPO3.CMS.git] / typo3 / sysext / cms / tslib / class.tslib_feuserauth.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Front End session user. Login and session data
29 * Included from index_ts.php
30 *
31 * $Id$
32 * Revised for TYPO3 3.6 June/2003 by Kasper Skårhøj
33 *
34 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
35 * @author René Fritz <r.fritz@colorcube.de>
36 */
37 /**
38 * [CLASS/FUNCTION INDEX of SCRIPT]
39 *
40 *
41 *
42 * 79: class tslib_feUserAuth extends t3lib_userAuth
43 * 143: function fetchGroupData()
44 * 233: function getUserTSconf()
45 *
46 * SECTION: Session data management functions
47 * 278: function fetchSessionData()
48 * 300: function storeSessionData()
49 * 326: function getKey($type,$key)
50 * 351: function setKey($type,$key,$data)
51 * 377: function record_registration($recs,$maxSizeOfSessionData=0)
52 *
53 * TOTAL FUNCTIONS: 7
54 * (This index is automatically created/updated by the extension "extdeveval")
55 *
56 */
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 /**
72 * Extension class for Front End User Authentication.
73 *
74 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
75 * @author René Fritz <r.fritz@colorcube.de>
76 * @package TYPO3
77 * @subpackage tslib
78 */
79 class tslib_feUserAuth extends t3lib_userAuth {
80 var $session_table = 'fe_sessions'; // Table to use for session data.
81 var $name = 'fe_typo_user'; // Session/Cookie name
82 var $get_name = 'ftu'; // Session/GET-var name
83
84 var $user_table = 'fe_users'; // Table in database with userdata
85 var $username_column = 'username'; // Column for login-name
86 var $userident_column = 'password'; // Column for password
87 var $userid_column = 'uid'; // Column for user-id
88 var $lastLogin_column = 'lastlogin';
89
90 var $enablecolumns = Array (
91 'deleted' => 'deleted',
92 'disabled' => 'disable',
93 'starttime' => 'starttime',
94 'endtime' => 'endtime'
95 );
96 var $formfield_uname = 'user'; // formfield with login-name
97 var $formfield_uident = 'pass'; // formfield with password
98 var $formfield_chalvalue = 'challenge'; // formfield with a unique value which is used to encrypt the password and username
99 var $formfield_status = 'logintype'; // formfield with status: *'login', 'logout'
100 var $formfield_permanent = 'permalogin'; // formfield with 0 or 1 // 1 = permanent login enabled // 0 = session is valid for a browser session only
101 var $security_level = ''; // sets the level of security. *'normal' = clear-text. 'challenged' = hashed password/username from form in $formfield_uident. 'superchallenged' = hashed password hashed again with username.
102
103 var $auth_timeout_field = 6000; // Server session lifetime. If > 0: session-timeout in seconds. If false or <0: no timeout. If string: The string is a fieldname from the usertable where the timeout can be found.
104
105 var $lifetime = 0; // Client session lifetime. 0 = Session-cookies. If session-cookies, the browser will stop the session when the browser is closed. Otherwise this specifies the lifetime of a cookie that keeps the session.
106 protected $sessionDataLifetime = 86400; // Lifetime of session data in seconds.
107 var $sendNoCacheHeaders = 0;
108 var $getFallBack = 1; // If this is set, authentication is also accepted by the _GET. Notice that the identification is NOT 128bit MD5 hash but reduced. This is done in order to minimize the size for mobile-devices, such as WAP-phones
109 var $getMethodEnabled = 1; // Login may be supplied by url.
110
111 var $usergroup_column = 'usergroup';
112 var $usergroup_table = 'fe_groups';
113 var $groupData = Array(
114 'title' =>Array(),
115 'uid' =>Array(),
116 'pid' =>Array()
117 );
118 var $TSdataArray=array(); // Used to accumulate the TSconfig data of the user
119 var $userTS = array();
120 var $userTSUpdated=0;
121 var $showHiddenRecords=0;
122
123 // Session and user data:
124 /*
125 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.
126 '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)
127 'Reserved' keys are:
128 - 'recs': Array: Used to 'register' records, eg in a shopping basket. Structure: [recs][tablename][record_uid]=number
129 - sys: Reserved for TypoScript standard code.
130 */
131 var $sesData = Array();
132 var $sesData_change = 0;
133 var $userData_change = 0;
134 protected $sessionDataTimestamp;
135
136
137 /**
138 * Starts a user session
139 *
140 * @return void
141 * @see t3lib_userAuth::start()
142 */
143 function start() {
144 if (intval($this->auth_timeout_field)>0 && intval($this->auth_timeout_field) < $this->lifetime) {
145 // If server session timeout is non-zero but less than client session timeout: Copy this value instead.
146 $this->auth_timeout_field = $this->lifetime;
147 }
148
149 $this->sessionDataLifetime = intval($GLOBALS['TYPO3_CONF_VARS']['FE']['sessionDataLifetime']);
150 if ($this->sessionDataLifetime <= 0) {
151 $this->sessionDataLifetime = 86400;
152 }
153
154 parent::start();
155 }
156
157 /**
158 * Returns a new session record for the current user for insertion into the DB.
159 *
160 * @return array user session record
161 */
162 function getNewSessionRecord($tempuser) {
163 $insertFields = parent::getNewSessionRecord($tempuser);
164 $insertFields['ses_permanent'] = $this->is_permanent;
165
166 return $insertFields;
167 }
168
169 /**
170 * Determine whether a session cookie needs to be set (lifetime=0)
171 *
172 * @return boolean
173 * @internal
174 */
175 function isSetSessionCookie() {
176 $retVal = ($this->newSessionID || $this->forceSetCookie) && ($this->lifetime==0 || !$this->user['ses_permanent']);
177 return $retVal;
178 }
179
180 /**
181 * Determine whether a non-session cookie needs to be set (lifetime>0)
182 *
183 * @return boolean
184 * @internal
185 */
186 function isRefreshTimeBasedCookie() {
187 return $this->lifetime > 0 && $this->user['ses_permanent'];
188 }
189
190 /**
191 * Returns an info array with Login/Logout data submitted by a form or params
192 *
193 * @return array
194 * @see t3lib_userAuth::getLoginFormData()
195 */
196 function getLoginFormData() {
197 $loginData = parent::getLoginFormData();
198 if($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 0 || $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 1) {
199 if ($this->getMethodEnabled) {
200 $isPermanent = t3lib_div::_GP($this->formfield_permanent);
201 } else {
202 $isPermanent = t3lib_div::_POST($this->formfield_permanent);
203 }
204 if(strlen($isPermanent) != 1) {
205 $isPermanent = $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'];
206 } elseif(!$isPermanent) {
207 $this->forceSetCookie = true; // To make sure the user gets a session cookie and doesn't keep a possibly existing time based cookie, we need to force seeting the session cookie here
208 }
209 $isPermanent = $isPermanent?1:0;
210 } elseif($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 2) {
211 $isPermanent = 1;
212 } else {
213 $isPermanent = 0;
214 }
215 $loginData['permanent'] = $isPermanent;
216 $this->is_permanent = $isPermanent;
217
218 return $loginData;
219 }
220
221 /**
222 * Will select all fe_groups records that the current fe_user is member of - and which groups are also allowed in the current domain.
223 * It also accumulates the TSconfig for the fe_user/fe_groups in ->TSdataArray
224 *
225 * @return integer Returns the number of usergroups for the frontend users (if the internal user record exists and the usergroup field contains a value)
226 */
227 function fetchGroupData() {
228 $this->TSdataArray = array();
229 $this->userTS = array();
230 $this->userTSUpdated = 0;
231 $this->groupData = Array(
232 'title' => Array(),
233 'uid' => Array(),
234 'pid' => Array()
235 );
236
237 // Setting default configuration:
238 $this->TSdataArray[]=$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultUserTSconfig'];
239
240 // get the info data for auth services
241 $authInfo = $this->getAuthInfoArray();
242
243 if ($this->writeDevLog) {
244 if (is_array($this->user)) {
245 t3lib_div::devLog('Get usergroups for user: '.t3lib_div::arrayToLogString($this->user, array($this->userid_column,$this->username_column)), 'tslib_feUserAuth');
246 } else {
247 t3lib_div::devLog('Get usergroups for "anonymous" user', 'tslib_feUserAuth');
248 }
249 }
250
251 $groupDataArr = array();
252
253 // use 'auth' service to find the groups for the user
254 $serviceChain='';
255 $subType = 'getGroups'.$this->loginType;
256 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
257 $serviceChain.=','.$serviceObj->getServiceKey();
258 $serviceObj->initAuth($subType, array(), $authInfo, $this);
259
260 $groupData = $serviceObj->getGroups($this->user, $groupDataArr);
261 if (is_array($groupData) && count($groupData)) {
262 $groupDataArr = t3lib_div::array_merge($groupDataArr, $groupData); // Keys in $groupData should be unique ids of the groups (like "uid") so this function will override groups.
263 }
264 unset($serviceObj);
265 }
266 if ($this->writeDevLog AND $serviceChain) t3lib_div::devLog($subType.' auth services called: '.$serviceChain, 'tslib_feUserAuth');
267 if ($this->writeDevLog AND !count($groupDataArr)) t3lib_div::devLog('No usergroups found by services', 'tslib_feUserAuth');
268 if ($this->writeDevLog AND count($groupDataArr)) t3lib_div::devLog(count($groupDataArr).' usergroup records found by services', 'tslib_feUserAuth');
269
270
271 // use 'auth' service to check the usergroups if they are really valid
272 foreach ($groupDataArr as $groupData) {
273 // by default a group is valid
274 $validGroup = TRUE;
275
276 $serviceChain='';
277 $subType = 'authGroups'.$this->loginType;
278 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
279 $serviceChain.=','.$serviceObj->getServiceKey();
280 $serviceObj->initAuth($subType, array(), $authInfo, $this);
281
282 if (!$serviceObj->authGroup($this->user, $groupData)) {
283 $validGroup = FALSE;
284 if ($this->writeDevLog) t3lib_div::devLog($subType.' auth service did not auth group: '.t3lib_div::arrayToLogString($groupData, 'uid,title'), 'tslib_feUserAuth', 2);
285
286 break;
287 }
288 unset($serviceObj);
289 }
290 unset($serviceObj);
291
292 if ($validGroup) {
293 $this->groupData['title'][$groupData['uid']]=$groupData['title'];
294 $this->groupData['uid'][$groupData['uid']]=$groupData['uid'];
295 $this->groupData['pid'][$groupData['uid']]=$groupData['pid'];
296 $this->groupData['TSconfig'][$groupData['uid']]=$groupData['TSconfig'];
297 }
298 }
299
300 if (count($this->groupData) && count($this->groupData['TSconfig'])) {
301 // TSconfig: collect it in the order it was collected
302 foreach($this->groupData['TSconfig'] as $TSdata) {
303 $this->TSdataArray[]=$TSdata;
304 }
305
306 $this->TSdataArray[]=$this->user['TSconfig'];
307
308 // Sort information
309 ksort($this->groupData['title']);
310 ksort($this->groupData['uid']);
311 ksort($this->groupData['pid']);
312 }
313
314 return count($this->groupData['uid']) ? count($this->groupData['uid']) : 0;
315 }
316
317 /**
318 * Returns the parsed TSconfig for the fe_user
319 * 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
320 *
321 * @return array TSconfig array for the fe_user
322 */
323 function getUserTSconf() {
324 if (!$this->userTSUpdated) {
325 // Parsing the user TS (or getting from cache)
326 $this->TSdataArray = t3lib_TSparser::checkIncludeLines_array($this->TSdataArray);
327 $userTS = implode(LF.'[GLOBAL]'.LF,$this->TSdataArray);
328 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
329 $parseObj->parse($userTS);
330 $this->userTS = $parseObj->setup;
331
332 $this->userTSUpdated=1;
333 }
334 return $this->userTS;
335 }
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353 /*****************************************
354 *
355 * Session data management functions
356 *
357 ****************************************/
358
359 /**
360 * Fetches the session data for the user (from the fe_session_data table) based on the ->id of the current user-session.
361 * The session data is restored to $this->sesData
362 * 1/100 calls will also do a garbage collection.
363 *
364 * @return void
365 * @access private
366 * @see storeSessionData()
367 */
368 function fetchSessionData() {
369 // Gets SesData if any AND if not already selected by session fixation check in ->isExistingSessionRecord()
370 if ($this->id && !count($this->sesData)) {
371 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery(
372 '*',
373 'fe_session_data',
374 'hash = :hash'
375 );
376 $statement->execute(array(':hash' => $this->id));
377 if (($sesDataRow = $statement->fetch()) !== FALSE) {
378 $this->sesData = unserialize($sesDataRow['content']);
379 $this->sessionDataTimestamp = $sesDataRow['tstamp'];
380 }
381 $statement->free();
382 }
383 }
384
385 /**
386 * Will write UC and session data.
387 * If the flag $this->userData_change has been set, the function ->writeUC is called (which will save persistent user session data)
388 * If the flag $this->sesData_change has been set, the fe_session_data table is updated with the content of $this->sesData (deleting any old record, inserting new)
389 *
390 * @return void
391 * @see fetchSessionData(), getKey(), setKey()
392 */
393 function storeSessionData() {
394 // Saves UC and SesData if changed.
395 if ($this->userData_change) {
396 $this->writeUC('');
397 }
398 if ($this->sesData_change) {
399 if ($this->id) {
400 $insertFields = array (
401 'hash' => $this->id,
402 'content' => serialize($this->sesData),
403 'tstamp' => $GLOBALS['EXEC_TIME'],
404 );
405 $this->removeSessionData();
406 $GLOBALS['TYPO3_DB']->exec_INSERTquery('fe_session_data', $insertFields);
407 }
408 }
409 }
410
411 /**
412 * Removes data of the current session.
413 *
414 * @return void
415 */
416 public function removeSessionData() {
417 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
418 'fe_session_data',
419 'hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, 'fe_session_data')
420 );
421 }
422
423 /**
424 * Executes the garbage collection of session data and session.
425 * The lifetime of session data is defined by $TYPO3_CONF_VARS['FE']['sessionDataLifetime'].
426 *
427 * @return void
428 */
429 public function gc() {
430 $timeoutTimeStamp = intval($GLOBALS['EXEC_TIME'] - $this->sessionDataLifetime);
431 $GLOBALS['TYPO3_DB']->exec_DELETEquery('fe_session_data', 'tstamp < ' . $timeoutTimeStamp);
432
433 parent::gc();
434 }
435
436 /**
437 * 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)
438 *
439 * @param string Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
440 * @param string 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.
441 * @return mixed Returns whatever value there was in the array for the key, $key
442 * @see setKey()
443 */
444 function getKey($type,$key) {
445 if ($key) {
446 switch($type) {
447 case 'user':
448 return $this->uc[$key];
449 break;
450 case 'ses':
451 return $this->sesData[$key];
452 break;
453 }
454 }
455 }
456
457 /**
458 * Saves session data, either persistent or bound to current session cookie. Please see getKey() for more details.
459 * 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.
460 * 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.
461 * 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.
462 *
463 * @param string Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
464 * @param string 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.
465 * @param mixed The data value to store in $key
466 * @return void
467 * @see setKey(), storeSessionData(), record_registration()
468 */
469 function setKey($type,$key,$data) {
470 if ($key) {
471 switch($type) {
472 case 'user':
473 if ($this->user['uid']) {
474 $this->uc[$key]=$data;
475 $this->userData_change=1;
476 }
477 break;
478 case 'ses':
479 $this->sesData[$key]=$data;
480 $this->sesData_change=1;
481 break;
482 }
483 }
484 }
485
486 /**
487 * Returns the session data stored for $key.
488 * The data will last only for this login session since it is stored in the session table.
489 *
490 * @param string $key
491 * @return mixed
492 */
493 public function getSessionData($key) {
494 return $this->getKey('ses', $key);
495 }
496
497 /**
498 * Saves the tokens so that they can be used by a later incarnation of this class.
499 *
500 * @param string $key
501 * @param mixed $data
502 * @return void
503 */
504 public function setAndSaveSessionData($key, $data) {
505 $this->setKey('ses', $key, $data);
506 $this->storeSessionData();
507 }
508
509
510
511 /**
512 * Registration of records/"shopping basket" in session data
513 * This will take the input array, $recs, and merge into the current "recs" array found in the session data.
514 * If a change in the recs storage happens (which it probably does) the function setKey() is called in order to store the array again.
515 *
516 * @param array The data array to merge into/override the current recs values. The $recs array is constructed as [table]][uid] = scalar-value (eg. string/integer).
517 * @param integer The maximum size of stored session data. If zero, no limit is applied and even confirmation of cookie session is discarded.
518 * @return void
519 */
520 function record_registration($recs,$maxSizeOfSessionData=0) {
521
522 // Storing value ONLY if there is a confirmed cookie set (->cookieID),
523 // otherwise a shellscript could easily be spamming the fe_sessions table
524 // with bogus content and thus bloat the database
525 if (!$maxSizeOfSessionData || $this->cookieId) {
526 if ($recs['clear_all']) {
527 $this->setKey('ses', 'recs', array());
528 }
529 $change=0;
530 $recs_array=$this->getKey('ses','recs');
531 foreach ($recs as $table => $data) {
532 if (is_array($data)) {
533 foreach ($data as $rec_id => $value) {
534 if ($value != $recs_array[$table][$rec_id]) {
535 $recs_array[$table][$rec_id] = $value;
536 $change=1;
537 }
538 }
539 }
540 }
541 if ($change && (!$maxSizeOfSessionData || strlen(serialize($recs_array))<$maxSizeOfSessionData)) {
542 $this->setKey('ses','recs',$recs_array);
543 }
544 }
545 }
546
547 /**
548 * Determine whether there's an according session record to a given session_id
549 * in the database. Don't care if session record is still valid or not.
550 *
551 * This calls the parent function but additionally tries to look up the session ID in the "fe_session_data" table.
552 *
553 * @param integer Claimed Session ID
554 * @return boolean Returns true if a corresponding session was found in the database
555 */
556 function isExistingSessionRecord($id) {
557 // Perform check in parent function
558 $count = parent::isExistingSessionRecord($id);
559
560 // Check if there are any fe_session_data records for the session ID the client claims to have
561 if ($count == false) {
562 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery(
563 'content',
564 'fe_session_data',
565 'hash = :hash'
566 );
567 $res = $statement->execute(array(':hash' => $id));
568 if ($res !== FALSE) {
569 if ($sesDataRow = $statement->fetch()) {
570 $count = true;
571 $this->sesData = unserialize($sesDataRow['content']);
572 }
573 $statement->free();
574 }
575 }
576
577 // @deprecated: Check for commerce basket records. The following lines should be removed once a fixed commerce version is released.
578 // Extensions like commerce which have their own session table should just put some small bit of data into fe_session_data using $GLOBALS['TSFE']->fe_user->setKey('ses', ...) to make the session stable.
579 if ($count == false && t3lib_extMgm::isLoaded('commerce')) {
580 t3lib_div::deprecationLog("EXT:commerce specific code in tslib_feuserauth::isExistingSessionRecord() is deprecated. Will be removed in 4.6");
581
582 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
583 '*',
584 'tx_commerce_baskets',
585 'sid=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($id, 'tx_commerce_baskets')
586 );
587 if ($dbres !== false) {
588 if ($sesDataRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres)) {
589 $count = true;
590 }
591 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
592 }
593 }
594
595 return $count;
596 }
597 }
598
599
600 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['tslib/class.tslib_feuserauth.php'])) {
601 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['tslib/class.tslib_feuserauth.php']);
602 }
603
604 ?>