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