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 (php_sapi_name() != 'cli') {
320 if ( $expiration != 0){
321 setcookie($name, $value, time() + $expiration, '/', $domain, 0);
323 setcookie($name, $value, $expiration, '/', $domain, 0);
329 * session_redirect() - Redirect browser within the site
331 * @param string Absolute path within the site
332 * @return never returns
334 function session_redirect($loc) {
335 header('Location: '.util_make_url ($loc));
341 * session_require() - Convenience function to easily enforce permissions
343 * Calling page will terminate with error message if current user
346 * @param array Associative array specifying criteria
347 * @return does not return if check is failed
350 function session_require($req, $reason='') {
351 if (!session_loggedin()) {
352 exit_not_logged_in();
355 $user =& user_get_object(user_getid());
356 if (! $user->isActive()) {
358 exit_error('Error','Your account is no longer active ; you have been disconnected');
361 if (array_key_exists('group', $req)) {
362 $group =& group_get_object($req['group']);
363 if (!$group || !is_object($group)) {
364 exit_error('Error',$reason == '' ? _('Could Not Get Group') : $reason);
365 } elseif ($group->isError()) {
366 exit_error('Error',$reason == '' ? $group->getErrorMessage() : $reason);
369 $perm =& $group->getPermission( session_get_user() );
370 if (!$perm || !is_object($perm) || $perm->isError()) {
371 exit_permission_denied($reason);
374 if (isset($req['admin_flags']) && $req['admin_flags']) {
375 if (!$perm->isAdmin()) {
376 exit_permission_denied($reason);
379 if (!$perm->isMember()) {
380 exit_permission_denied($reason);
383 } else if ($req['isloggedin']) {
384 //no need to check as long as the check is present at top of function
386 exit_permission_denied($reason);
391 * session_set_new() - Setup session for the given user
393 * This function sets up SourceForge session for the given user,
394 * making one be "logged in".
396 * @param int The user ID
399 function session_set_new($user_id) {
400 global $G_SESSION,$session_ser;
402 // set session cookie
404 $cookie = session_build_session_cookie($user_id);
405 session_cookie("session_ser", $cookie, "", $GLOBALS['sys_session_expire']);
406 $session_ser=$cookie;
408 $res = db_query_params ('SELECT count(*) as c FROM user_session WHERE session_hash =$1',
409 array (session_get_session_cookie_hash($cookie))) ;
410 if (!$res || db_result($res,0,'c') < 1) {
411 db_query_params ('INSERT INTO user_session (session_hash,ip_addr,time,user_id) VALUES ($1,$2,$3,$4)',
412 array (session_get_session_cookie_hash($cookie),
413 getStringFromServer('REMOTE_ADDR'),
418 // check uniqueness of the session_hash in the database
420 $res = session_getdata($user_id);
422 if (!$res || db_numrows($res) < 1) {
423 exit_error(_('ERROR'),_('ERROR').": ".db_error());
426 //set up the new user object
428 $G_SESSION = user_get_object($user_id,$res);
430 $G_SESSION->setLoggedIn(true);
438 * session_set_admin() - Setup session for the admin user
440 * This function sets up a session for the administrator
444 function session_set_admin() {
445 $res = db_query_params ('SELECT user_id FROM user_group WHERE admin_flags=$1 AND group_id=1',
451 if (db_numrows($res) == 0) {
452 echo "No admin users?\n" ;
455 $id = db_result ($res, 0, 0);
456 session_set_new ($id);
460 * Private optimization function for logins - fetches user data, language, and session
463 * @param int The user ID
466 function session_getdata($user_id) {
467 return db_query_params ('SELECT u.*,sl.language_id, sl.name, sl.filename, sl.classname, sl.language_code, t.dirname, t.fullname
468 FROM users u, supported_languages sl, themes t
469 WHERE u.language=sl.language_id
470 AND u.theme_id=t.theme_id
476 * session_set() - Re-initialize session for the logged in user
478 * This function checks that the user is logged in and if so, initialize
479 * internal session environment.
483 function session_set() {
484 plugin_hook('session_set_entry');
486 global $session_ser, $session_key;
488 // assume bad session_hash and session. If all checks work, then allow
489 // otherwise make new session
492 // If user says he's logged in (by presenting cookie), check that
495 $user_id = session_check_session_cookie($session_ser);
499 $result = session_getdata($user_id);
501 if (db_numrows($result) > 0) {
505 } // else (hash does not exist) or (session hash is bad)
508 $G_SESSION = user_get_object($user_id, $result);
510 $G_SESSION->setLoggedIn(true);
515 // if there was bad session cookie, kill it and the user cookie
521 plugin_hook('session_set_return');
524 //TODO - this should be generalized and used for pre.php, squal_pre.php,
525 //SOAP, forum_gateway.php, tracker_gateway.php, etc to
527 function session_continue($sessionKey) {
529 $session_ser = $sessionKey;
531 setup_gettext_from_context();
532 $LUSER =& session_get_user();
533 if (!is_object($LUSER) || $LUSER->isError()) {
536 putenv('TZ='. $LUSER->getTimeZone());
542 * session_get_user() - Wrapper function to return the User object for the logged in user.
547 function &session_get_user() {
554 * Get user_id of logged in user
557 function user_getid() {
560 return $G_SESSION->getID();
568 * See if user is logged in
570 function session_loggedin() {
574 return $G_SESSION->isLoggedIn();
582 // c-file-style: "bsd"