Fixed bug #4367: Reset recs with clear_all should reset as array, not as string ...
[Packages/TYPO3.CMS.git] / typo3 / sysext / cms / tslib / class.tslib_feuserauth.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2008 Kasper Skaarhoj (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 Skaarhoj
33 *
34 * @author Kasper Skaarhoj <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 Skaarhoj <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_include = ''; // this is the name of the include-file containing the login form. If not set, login CAN be anonymous. If set login IS needed.
104
105 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.
106
107 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.
108 var $sendNoCacheHeaders = 0;
109 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
110 var $getMethodEnabled = 1; // Login may be supplied by url.
111
112 var $usergroup_column = 'usergroup';
113 var $usergroup_table = 'fe_groups';
114 var $groupData = Array(
115 'title' =>Array(),
116 'uid' =>Array(),
117 'pid' =>Array()
118 );
119 var $TSdataArray=array(); // Used to accumulate the TSconfig data of the user
120 var $userTS = array();
121 var $userTSUpdated=0;
122 var $showHiddenRecords=0;
123
124 // Session and user data:
125 /*
126 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.
127 '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)
128 'Reserved' keys are:
129 - 'recs': Array: Used to 'register' records, eg in a shopping basket. Structure: [recs][tablename][record_uid]=number
130 - sys: Reserved for TypoScript standard code.
131 */
132 var $sesData = Array();
133 var $sesData_change = 0;
134 var $userData_change = 0;
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 parent::start();
150 }
151
152 /**
153 * Returns a new session record for the current user for insertion into the DB.
154 *
155 * @return array user session record
156 */
157 function getNewSessionRecord($tempuser) {
158 $insertFields = parent::getNewSessionRecord($tempuser);
159 $insertFields['ses_permanent'] = $this->is_permanent;
160
161 return $insertFields;
162 }
163
164 /**
165 * Determine whether a session cookie needs to be set (lifetime=0)
166 *
167 * @return boolean
168 * @internal
169 */
170 function isSetSessionCookie() {
171 $retVal = ($this->newSessionID || $this->forceSetCookie) && ($this->lifetime==0 || !$this->user['ses_permanent']);
172 return $retVal;
173 }
174
175 /**
176 * Determine whether a non-session cookie needs to be set (lifetime>0)
177 *
178 * @return boolean
179 * @internal
180 */
181 function isRefreshTimeBasedCookie() {
182 return $this->lifetime > 0 && $this->user['ses_permanent'];
183 }
184
185 /**
186 * Returns an info array with Login/Logout data submitted by a form or params
187 *
188 * @return array
189 * @see t3lib_userAuth::getLoginFormData()
190 */
191 function getLoginFormData() {
192 $loginData = parent::getLoginFormData();
193 if($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 0 || $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 1) {
194 if ($this->getMethodEnabled) {
195 $isPermanent = t3lib_div::_GP($this->formfield_permanent);
196 } else {
197 $isPermanent = t3lib_div::_POST($this->formfield_permanent);
198 }
199 if(strlen($isPermanent) != 1) {
200 $isPermanent = $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'];
201 } elseif(!$isPermanent) {
202 $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
203 }
204 $isPermanent = $isPermanent?1:0;
205 } elseif($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 2) {
206 $isPermanent = 1;
207 } else {
208 $isPermanent = 0;
209 }
210 $loginData['permanent'] = $isPermanent;
211 $this->is_permanent = $isPermanent;
212
213 return $loginData;
214 }
215
216 /**
217 * Will select all fe_groups records that the current fe_user is member of - and which groups are also allowed in the current domain.
218 * It also accumulates the TSconfig for the fe_user/fe_groups in ->TSdataArray
219 *
220 * @return integer Returns the number of usergroups for the frontend users (if the internal user record exists and the usergroup field contains a value)
221 */
222 function fetchGroupData() {
223 $this->TSdataArray = array();
224 $this->userTS = array();
225 $this->userTSUpdated = 0;
226 $this->groupData = Array(
227 'title' => Array(),
228 'uid' => Array(),
229 'pid' => Array()
230 );
231
232 // Setting default configuration:
233 $this->TSdataArray[]=$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultUserTSconfig'];
234
235 // get the info data for auth services
236 $authInfo = $this->getAuthInfoArray();
237
238 if ($this->writeDevLog) {
239 if (is_array($this->user)) {
240 t3lib_div::devLog('Get usergroups for user: '.t3lib_div::arrayToLogString($this->user, array($this->userid_column,$this->username_column)), 'tslib_feUserAuth');
241 } else {
242 t3lib_div::devLog('Get usergroups for "anonymous" user', 'tslib_feUserAuth');
243 }
244 }
245
246 $groupDataArr = array();
247
248 // use 'auth' service to find the groups for the user
249 $serviceChain='';
250 $subType = 'getGroups'.$this->loginType;
251 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
252 $serviceChain.=','.$serviceObj->getServiceKey();
253 $serviceObj->initAuth($subType, array(), $authInfo, $this);
254
255 $groupData = $serviceObj->getGroups($this->user, $groupDataArr);
256 if (is_array($groupData) && count($groupData)) {
257 $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.
258 }
259 unset($serviceObj);
260 }
261 if ($this->writeDevLog AND $serviceChain) t3lib_div::devLog($subType.' auth services called: '.$serviceChain, 'tslib_feUserAuth');
262 if ($this->writeDevLog AND !count($groupDataArr)) t3lib_div::devLog('No usergroups found by services', 'tslib_feUserAuth');
263 if ($this->writeDevLog AND count($groupDataArr)) t3lib_div::devLog(count($groupDataArr).' usergroup records found by services', 'tslib_feUserAuth');
264
265
266 // use 'auth' service to check the usergroups if they are really valid
267 foreach ($groupDataArr as $groupData) {
268 // by default a group is valid
269 $validGroup = TRUE;
270
271 $serviceChain='';
272 $subType = 'authGroups'.$this->loginType;
273 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
274 $serviceChain.=','.$serviceObj->getServiceKey();
275 $serviceObj->initAuth($subType, array(), $authInfo, $this);
276
277 if (!$serviceObj->authGroup($this->user, $groupData)) {
278 $validGroup = FALSE;
279 if ($this->writeDevLog) t3lib_div::devLog($subType.' auth service did not auth group: '.t3lib_div::arrayToLogString($groupData, 'uid,title'), 'tslib_feUserAuth', 2);
280
281 break;
282 }
283 unset($serviceObj);
284 }
285 unset($serviceObj);
286
287 if ($validGroup) {
288 $this->groupData['title'][$groupData['uid']]=$groupData['title'];
289 $this->groupData['uid'][$groupData['uid']]=$groupData['uid'];
290 $this->groupData['pid'][$groupData['uid']]=$groupData['pid'];
291 $this->groupData['TSconfig'][$groupData['uid']]=$groupData['TSconfig'];
292 }
293 }
294
295 if (count($this->groupData) && count($this->groupData['TSconfig'])) {
296 // TSconfig: collect it in the order it was collected
297 foreach($this->groupData['TSconfig'] as $TSdata) {
298 $this->TSdataArray[]=$TSdata;
299 }
300
301 $this->TSdataArray[]=$this->user['TSconfig'];
302
303 // Sort information
304 ksort($this->groupData['title']);
305 ksort($this->groupData['uid']);
306 ksort($this->groupData['pid']);
307 }
308
309 return count($this->groupData['uid']) ? count($this->groupData['uid']) : 0;
310 }
311
312 /**
313 * Returns the parsed TSconfig for the fe_user
314 * 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
315 *
316 * @return array TSconfig array for the fe_user
317 */
318 function getUserTSconf() {
319 if (!$this->userTSUpdated) {
320 // Parsing the user TS (or getting from cache)
321 $this->TSdataArray = t3lib_TSparser::checkIncludeLines_array($this->TSdataArray);
322 $userTS = implode(chr(10).'[GLOBAL]'.chr(10),$this->TSdataArray);
323 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
324 $parseObj->parse($userTS);
325 $this->userTS = $parseObj->setup;
326
327 $this->userTSUpdated=1;
328 }
329 return $this->userTS;
330 }
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348 /*****************************************
349 *
350 * Session data management functions
351 *
352 ****************************************/
353
354 /**
355 * Fetches the session data for the user (from the fe_session_data table) based on the ->id of the current user-session.
356 * The session data is restored to $this->sesData
357 * 1/100 calls will also do a garbage collection.
358 *
359 * @return void
360 * @access private
361 * @see storeSessionData()
362 */
363 function fetchSessionData() {
364 // Gets SesData if any AND if not already selected by session fixation check in ->isExistingSessionRecord()
365 if ($this->id && !count($this->sesData)) {
366 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'fe_session_data', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, 'fe_session_data'));
367 if ($sesDataRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres)) {
368 $this->sesData = unserialize($sesDataRow['content']);
369 }
370 }
371 // delete old data:
372 if ((rand()%100) <= 1) { // a possibility of 1 % for garbage collection.
373 $GLOBALS['TYPO3_DB']->exec_DELETEquery('fe_session_data', 'tstamp < '.intval(time()-3600*24)); // all data older than 24 hours are deleted.
374 }
375 }
376
377 /**
378 * Will write UC and session data.
379 * If the flag $this->userData_change has been set, the function ->writeUC is called (which will save persistent user session data)
380 * 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)
381 *
382 * @return void
383 * @see fetchSessionData(), getKey(), setKey()
384 */
385 function storeSessionData() {
386 // Saves UC and SesData if changed.
387 if ($this->userData_change) {
388 $this->writeUC('');
389 }
390 if ($this->sesData_change) {
391 if ($this->id) {
392 $insertFields = array (
393 'hash' => $this->id,
394 'content' => serialize($this->sesData),
395 'tstamp' => time()
396 );
397 $GLOBALS['TYPO3_DB']->exec_DELETEquery('fe_session_data', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, 'fe_session_data'));
398 $GLOBALS['TYPO3_DB']->exec_INSERTquery('fe_session_data', $insertFields);
399 }
400 }
401 }
402
403 /**
404 * 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)
405 *
406 * @param string Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
407 * @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.
408 * @return mixed Returns whatever value there was in the array for the key, $key
409 * @see setKey()
410 */
411 function getKey($type,$key) {
412 if ($key) {
413 switch($type) {
414 case 'user':
415 return $this->uc[$key];
416 break;
417 case 'ses':
418 return $this->sesData[$key];
419 break;
420 }
421 }
422 }
423
424 /**
425 * Saves session data, either persistent or bound to current session cookie. Please see getKey() for more details.
426 * 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.
427 * 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.
428 * 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.
429 *
430 * @param string Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
431 * @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.
432 * @param mixed The data value to store in $key
433 * @return void
434 * @see setKey(), storeSessionData(), record_registration()
435 */
436 function setKey($type,$key,$data) {
437 if ($key) {
438 switch($type) {
439 case 'user':
440 if ($this->user['uid']) {
441 $this->uc[$key]=$data;
442 $this->userData_change=1;
443 }
444 break;
445 case 'ses':
446 $this->sesData[$key]=$data;
447 $this->sesData_change=1;
448 break;
449 }
450 }
451 }
452
453 /**
454 * Registration of records/"shopping basket" in session data
455 * This will take the input array, $recs, and merge into the current "recs" array found in the session data.
456 * If a change in the recs storage happens (which it probably does) the function setKey() is called in order to store the array again.
457 *
458 * @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).
459 * @param integer The maximum size of stored session data. If zero, no limit is applied and even confirmation of cookie session is discarded.
460 * @return void
461 */
462 function record_registration($recs,$maxSizeOfSessionData=0) {
463
464 // Storing value ONLY if there is a confirmed cookie set (->cookieID), otherwise a shellscript could easily be spamming the fe_sessions table with bogus content and thus bloat the database
465 if (!$maxSizeOfSessionData || $this->cookieId===$this->id) {
466 if ($recs['clear_all']) {
467 $this->setKey('ses', 'recs', array());
468 }
469 $change=0;
470 $recs_array=$this->getKey('ses','recs');
471 reset($recs);
472 while(list($table,$data)=each($recs)) {
473 if (is_array($data)) {
474 reset($data);
475 while(list($rec_id,$value)=each($data)) {
476 if ($value != $recs_array[$table][$rec_id]) {
477 $recs_array[$table][$rec_id] = $value;
478 $change=1;
479 }
480 }
481 }
482 }
483 if ($change && (!$maxSizeOfSessionData || strlen(serialize($recs_array))<$maxSizeOfSessionData)) {
484 $this->setKey('ses','recs',$recs_array);
485 }
486 }
487 }
488
489 /**
490 * Determine whether there's an according session record to a given session_id
491 * in the database. Don't care if session record is still valid or not.
492 *
493 * This calls the parent function but additionally tries to look up the session ID in the "fe_session_data" table.
494 *
495 * @param integer Claimed Session ID
496 * @return boolean Returns true if a corresponding session was found in the database
497 */
498 function isExistingSessionRecord($id) {
499 // Perform check in parent function
500 $count = parent::isExistingSessionRecord($id);
501
502 // Check if there are any fe_session_data records for the session ID the client claims to have
503 if ($count == false) {
504 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
505 'content',
506 'fe_session_data',
507 'hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($id, 'fe_session_data')
508 );
509 if ($dbres !== false) {
510 if ($sesDataRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres)) {
511 $count = true;
512 $this->sesData = unserialize($sesDataRow['content']);
513 }
514 }
515 }
516
517 // @deprecated: Check for commerce basket records. The following lines should be removed once a fixed commerce version is released.
518 // 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.
519 if ($count == false && t3lib_extMgm::isLoaded('commerce')) {
520 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
521 '*',
522 'tx_commerce_baskets',
523 'sid=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($id, 'tx_commerce_baskets')
524 );
525 if ($dbres !== false) {
526 if ($sesDataRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres)) {
527 $count = true;
528 }
529 }
530 }
531
532 return $count;
533 }
534 }
535
536
537 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['tslib/class.tslib_feuserauth.php']) {
538 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['tslib/class.tslib_feuserauth.php']);
539 }
540
541 ?>