3 * FusionForge session management
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2001-2002, 2009, Roland Mas
7 * Copyright 2004-2005, GForge, LLC
9 * This file is part of FusionForge.
11 * FusionForge is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published
13 * by the Free Software Foundation; either version 2 of the License,
14 * or (at your option) any later version.
16 * FusionForge is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with FusionForge; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
27 require_once $gfcommon.'include/account.php';
28 require_once $gfcommon.'include/escapingUtils.php';
31 * A User object if user is logged in
33 * @var constant $G_SESSION
40 $session_ser = getStringFromCookie('session_ser');
43 * session_build_session_cookie() - Construct session cookie for the user
45 * @param int User_id of the logged in user
46 * @return cookie value
48 function session_build_session_cookie($user_id) {
49 $session_serial = $user_id.'-*-'.time().'-*-'.getStringFromServer('REMOTE_ADDR').'-*-'.getStringFromServer('HTTP_USER_AGENT');
50 $session_serial_hash = md5($session_serial.$GLOBALS['sys_session_key']);
51 $session_serial_cookie = base64_encode($session_serial).'-*-'.$session_serial_hash;
52 return $session_serial_cookie;
56 * session_get_session_cookie_hash() - Get hash of session cookie
58 * This hash can be used as a key to identify session, e.g. in DB.
60 * @param string Value of the session cookie
63 function session_get_session_cookie_hash($session_cookie) {
64 list ($junk, $hash) = explode('-*-', $session_cookie);
69 * session_check_session_cookie() - Check that session cookie passed from user is ok
71 * @param string Value of the session cookie
72 * @return user_id if cookie is ok, false otherwise
74 function session_check_session_cookie($session_cookie) {
76 list ($session_serial, $hash) = explode('-*-', $session_cookie);
77 $session_serial = base64_decode($session_serial);
78 $new_hash = md5($session_serial.$GLOBALS['sys_session_key']);
80 if ($hash != $new_hash) {
84 list($user_id, $time, $ip, $user_agent) = explode('-*-', $session_serial, 4);
86 if (!session_check_ip($ip, getStringFromServer('REMOTE_ADDR'))) {
89 if (trim($user_agent) != getStringFromServer('HTTP_USER_AGENT')) {
92 if (($GLOBALS['sys_session_expire'] > 0) &&
93 ($time - time() >= $GLOBALS['sys_session_expire'])) {
101 * session_logout() - Log the user off the system.
103 * This function destroys object associated with the current session,
104 * making user "logged out". Deletes both user and session cookies.
109 function session_logout() {
111 // delete both session and username cookies
112 // NB: cookies must be deleted with the same scope parameters they were set with
114 session_cookie('session_ser', '');
119 * session_login_valid() - Log the user to the system.
121 * High-level function for user login. Check credentials, and if they
122 * are valid, open new session.
124 * @param string User name
125 * @param string User password (in clear text)
126 * @param bool Allow login to non-confirmed user account (only for confirmation of the very account)
127 * @return true/false, if false reason is in global $feedback
131 function session_login_valid($loginname, $passwd, $allowpending=0) {
134 if (!$loginname || !$passwd) {
135 $feedback = _('Missing Password Or Users Name');
139 $hook_params = array () ;
140 $hook_params['loginname'] = $loginname ;
141 $hook_params['passwd'] = $passwd ;
142 plugin_hook ("session_before_login", $hook_params) ;
144 return session_login_valid_dbonly ($loginname, $passwd, $allowpending) ;
147 function session_login_valid_dbonly ($loginname, $passwd, $allowpending) {
148 global $feedback,$userstatus;
150 // Try to get the users from the database using user_id and (MD5) user_pw
151 if ($GLOBALS['sys_require_unique_email']) {
152 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE (user_name=$1 OR email=$1) AND user_pw=$2',
156 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1 AND user_pw=$2',
160 if (!$res || db_numrows($res) < 1) {
161 // No user whose MD5 passwd matches the MD5 of the provided passwd
162 // Selecting by user_name/email only
163 if ($GLOBALS['sys_require_unique_email']) {
164 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1 OR email=$1',
165 array ($loginname)) ;
167 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1',
168 array ($loginname)) ;
170 if (!$res || db_numrows($res) < 1) {
171 // No user by that name
172 $feedback=_('Invalid Password Or User Name');
175 // There is a user with the provided user_name/email, but the MD5 passwds do not match
176 // We'll have to try checking the (crypt) unix_pw
177 $usr = db_fetch_array($res);
178 $userstatus = $usr['status'] ;
180 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
181 // Even the (crypt) unix_pw does not patch
182 // This one has clearly typed a bad passwd
183 $feedback=_('Invalid Password Or User Name');
186 // User exists, (crypt) unix_pw matches
187 // Update the (MD5) user_pw and retry authentication
188 // It should work, except for status errors
189 $res = db_query_params ('UPDATE users SET user_pw=$1 WHERE user_id=$2',
192 return session_login_valid_dbonly($loginname, $passwd, $allowpending) ;
195 // If we're here, then the user has typed a password matching the (MD5) user_pw
196 // Let's check whether it also matches the (crypt) unix_pw
197 $usr = db_fetch_array($res);
199 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
200 // The (crypt) unix_pw does not match
201 if ($usr['unix_pw'] == '') {
202 // Empty unix_pw, we'll take the MD5 as authoritative
203 // Update the (crypt) unix_pw and retry authentication
204 // It should work, except for status errors
205 $res = db_query_params ('UPDATE users SET unix_pw=$1 WHERE user_id=$2',
206 array (account_genunixpw($passwd),
208 return session_login_valid_dbonly($loginname, $passwd, $allowpending) ;
210 // Invalidate (MD5) user_pw, refuse authentication
211 $res = db_query_params ('UPDATE users SET user_pw=$1 WHERE user_id=$2',
212 array ('OUT OF DATE',
214 $feedback=_('Invalid Password Or User Name');
219 // Yay. The provided password matches both fields in the database.
220 // Let's check the status of this user
222 // if allowpending (for verify.php) then allow
223 $userstatus=$usr['status'];
224 if ($allowpending && ($usr['status'] == 'P')) {
227 if ($usr['status'] == 'S') {
229 $feedback = _('Account Suspended');
232 if ($usr['status'] == 'P') {
234 $feedback = _('Account Pending');
237 if ($usr['status'] == 'D') {
239 $feedback = _('Account Deleted');
242 if ($usr['status'] != 'A') {
243 //unacceptable account flag
244 $feedback = _('Account Not Active');
248 //create a new session
249 session_set_new(db_result($res,0,'user_id'));
256 * session_check_ip() - Check 2 IP addresses for match
258 * This function checks that IP addresses match
260 * IPv4 addresses are allowed to match with some
261 * fuzz factor (within 255.255.0.0 subnet).
263 * For IPv6 addresses, no fuzz is needed since there's
264 * usually no NAT in IPv6.
266 * @param string The old IP address
267 * @param string The new IP address
271 function session_check_ip($oldip,$newip) {
272 if (strstr ($oldip, ':')) {
274 if (strstr ($newip, ':')) {
275 // New IP is IPv6 too
276 return ($oldip == $newip) ;
282 if (strstr ($newip, ':')) {
286 $eoldip = explode(".",$oldip);
287 $enewip = explode(".",$newip);
289 // require same class b subnet
290 return ( ($eoldip[0] == $enewip[0])
291 && ($eoldip[1] == $enewip[1]) ) ;
297 * session_issecure() - Check if current session is secure
302 function session_issecure() {
303 return (strtoupper(getStringFromServer('HTTPS')) == "ON");
307 * session_cookie() - Set a session cookie
309 * Set a cookie with default temporal scope of the current browser session
310 * and URL space of the current webserver
312 * @param string Name of cookie
313 * @param string Value of cookie
314 * @param string Domain scope (default '')
315 * @param string Expiration time in UNIX seconds (default 0)
318 function session_cookie($name ,$value, $domain = '', $expiration = 0) {
319 if ( $expiration != 0){
320 setcookie($name, $value, time() + $expiration, '/', $domain, 0);
322 setcookie($name, $value, $expiration, '/', $domain, 0);
327 * session_redirect() - Redirect browser within the site
329 * @param string Absolute path within the site
330 * @return never returns
332 function session_redirect($loc) {
333 header('Location: '.util_make_url ($loc));
339 * session_require() - Convenience function to easily enforce permissions
341 * Calling page will terminate with error message if current user
344 * @param array Associative array specifying criteria
345 * @param string Override error string (optional)
346 * @return does not return if check is failed
349 function session_require($req, $reason='') {
350 if (!session_loggedin()) {
351 exit_not_logged_in();
354 if (array_key_exists('group', $req)) {
355 $group =& group_get_object($req['group']);
356 if (!$group || !is_object($group)) {
357 exit_error('Error',$reason == '' ? _('Could Not Get Group') : $reason);
358 } elseif ($group->isError()) {
359 exit_error('Error',$reason == '' ? $group->getErrorMessage() : $reason);
362 $perm =& $group->getPermission( session_get_user() );
363 if (!$perm || !is_object($perm) || $perm->isError()) {
364 exit_permission_denied($reason);
367 //don't really like this, but as admin_flags is not mandatory
368 //I add @ to remove the warning
369 if (@$req['admin_flags']) {
370 if (!$perm->isAdmin()) {
371 exit_permission_denied($reason);
374 if (!$perm->isMember()) {
375 exit_permission_denied($reason);
378 } else if ($req['isloggedin']) {
379 //no need to check as long as the check is present at top of function
381 exit_permission_denied($reason);
386 * session_set_new() - Setup session for the given user
388 * This function sets up SourceForge session for the given user,
389 * making one be "logged in".
391 * @param int The user ID
394 function session_set_new($user_id) {
395 global $G_SESSION,$session_ser;
397 // set session cookie
399 $cookie = session_build_session_cookie($user_id);
400 session_cookie("session_ser", $cookie, "", $GLOBALS['sys_session_expire']);
401 $session_ser=$cookie;
403 $res = db_query_params ('SELECT count(*) FROM user_session WHERE session_hash = "$1"',
404 array (session_get_session_cookie_hash($cookie))) ;
405 if (!$res || db_numrows($res) < 1) {
406 db_query_params ('INSERT INTO user_session (session_hash,ip_addr,time,user_id) VALUES ($1,$2,$3,$4)',
407 array (session_get_session_cookie_hash($cookie),
408 getStringFromServer('REMOTE_ADDR'),
413 // check uniqueness of the session_hash in the database
415 $res = session_getdata($user_id);
417 if (!$res || db_numrows($res) < 1) {
418 exit_error(_('ERROR'),_('ERROR').": ".db_error());
421 //set up the new user object
423 $G_SESSION = user_get_object($user_id,$res);
425 $G_SESSION->setLoggedIn(true);
433 * session_set_admin() - Setup session for the admin user
435 * This function sets up a session for the administrator
439 function session_set_admin() {
440 $res = db_query_params ('SELECT user_id FROM user_group WHERE admin_flags=$1 AND group_id=1',
446 if (db_numrows($res) == 0) {
447 echo "No admin users?\n" ;
450 $id = db_result ($res, 0, 0);
451 session_set_new ($id);
455 * Private optimization function for logins - fetches user data, language, and session
458 * @param int The user ID
461 function session_getdata($user_id) {
462 return db_query_params ('SELECT u.*,sl.language_id, sl.name, sl.filename, sl.classname, sl.language_code, t.dirname, t.fullname
463 FROM users u, supported_languages sl, themes t
464 WHERE u.language=sl.language_id
465 AND u.theme_id=t.theme_id
471 * session_set() - Re-initialize session for the logged in user
473 * This function checks that the user is logged in and if so, initialize
474 * internal session environment.
478 function session_set() {
479 plugin_hook('session_set_entry');
481 global $session_ser, $session_key;
483 // assume bad session_hash and session. If all checks work, then allow
484 // otherwise make new session
487 // If user says he's logged in (by presenting cookie), check that
490 $user_id = session_check_session_cookie($session_ser);
494 $result = session_getdata($user_id);
496 if (db_numrows($result) > 0) {
500 } // else (hash does not exist) or (session hash is bad)
503 $G_SESSION = user_get_object($user_id, $result);
505 $G_SESSION->setLoggedIn(true);
510 // if there was bad session cookie, kill it and the user cookie
516 plugin_hook('session_set_return');
519 //TODO - this should be generalized and used for pre.php, squal_pre.php,
520 //SOAP, forum_gateway.php, tracker_gateway.php, etc to
522 function session_continue($sessionKey) {
524 $session_ser = $sessionKey;
526 setup_gettext_from_context();
527 $LUSER =& session_get_user();
528 if (!is_object($LUSER) || $LUSER->isError()) {
531 putenv('TZ='. $LUSER->getTimeZone());
537 * session_get_user() - Wrapper function to return the User object for the logged in user.
542 function &session_get_user() {
549 * Get user_id of logged in user
552 function user_getid() {
555 return $G_SESSION->getID();
563 * See if user is logged in
565 function session_loggedin() {
569 return $G_SESSION->isLoggedIn();
577 // c-file-style: "bsd"