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/utils.php';
29 require_once $gfcommon.'include/escapingUtils.php';
32 * A User object if user is logged in
34 * @var constant $G_SESSION
41 $session_ser = getStringFromCookie('session_ser');
44 * session_build_session_cookie() - Construct session cookie for the user
46 * @param int User_id of the logged in user
47 * @return cookie value
49 function session_build_session_cookie($user_id) {
50 $session_serial = $user_id.'-*-'.time().'-*-'.getStringFromServer('REMOTE_ADDR').'-*-'.getStringFromServer('HTTP_USER_AGENT');
51 $session_serial_hash = md5($session_serial.forge_get_config('session_key'));
52 $session_serial_cookie = base64_encode($session_serial).'-*-'.$session_serial_hash;
53 return $session_serial_cookie;
57 * session_get_session_cookie_hash() - Get hash of session cookie
59 * This hash can be used as a key to identify session, e.g. in DB.
61 * @param string Value of the session cookie
64 function session_get_session_cookie_hash($session_cookie) {
65 list ($junk, $hash) = explode('-*-', $session_cookie);
70 * session_check_session_cookie() - Check that session cookie passed from user is ok
72 * @param string Value of the session cookie
73 * @return user_id if cookie is ok, false otherwise
75 function session_check_session_cookie($session_cookie) {
77 list ($session_serial, $hash) = explode('-*-', $session_cookie);
78 $session_serial = base64_decode($session_serial);
79 $new_hash = md5($session_serial.forge_get_config('session_key'));
81 if ($hash != $new_hash) {
85 list($user_id, $time, $ip, $user_agent) = explode('-*-', $session_serial, 4);
87 if (!session_check_ip($ip, getStringFromServer('REMOTE_ADDR'))) {
90 if (trim($user_agent) != getStringFromServer('HTTP_USER_AGENT')) {
93 if ((forge_get_config('session_expire') > 0) &&
94 ($time - time() >= forge_get_config('session_expire'))) {
102 * session_logout() - Log the user off the system.
104 * This function destroys object associated with the current session,
105 * making user "logged out". Deletes both user and session cookies.
110 function session_logout() {
112 // delete both session and username cookies
113 // NB: cookies must be deleted with the same scope parameters they were set with
115 session_cookie('session_ser', '');
117 RBACEngine::getInstance()->invalidateRoleCaches() ;
122 * session_login_valid() - Log the user to the system.
124 * High-level function for user login. Check credentials, and if they
125 * are valid, open new session.
127 * @param string User name
128 * @param string User password (in clear text)
129 * @param bool Allow login to non-confirmed user account (only for confirmation of the very account)
130 * @return true/false, if false reason is in global $feedback
134 function session_login_valid($loginname, $passwd, $allowpending=0) {
135 global $feedback,$error_msg,$warning_msg;
137 if (!$loginname || !$passwd) {
138 $warning_msg = _('Missing Password Or Users Name');
142 $hook_params = array () ;
143 $hook_params['loginname'] = $loginname ;
144 $hook_params['passwd'] = $passwd ;
145 $result = plugin_hook ("session_before_login", $hook_params) ;
147 // Refuse login if not all the plugins are ok.
150 $warning_msg = _('Invalid Password Or User Name');
155 return session_login_valid_dbonly ($loginname, $passwd, $allowpending) ;
158 function session_login_valid_dbonly ($loginname, $passwd, $allowpending) {
159 global $feedback,$userstatus;
161 // Try to get the users from the database using user_id and (MD5) user_pw
162 if (forge_get_config('require_unique_email')) {
163 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE (user_name=$1 OR email=$1) AND user_pw=$2',
167 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1 AND user_pw=$2',
171 if (!$res || db_numrows($res) < 1) {
172 // No user whose MD5 passwd matches the MD5 of the provided passwd
173 // Selecting by user_name/email only
174 if (forge_get_config('require_unique_email')) {
175 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1 OR email=$1',
176 array ($loginname)) ;
178 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1',
179 array ($loginname)) ;
181 if (!$res || db_numrows($res) < 1) {
182 // No user by that name
183 $feedback=_('Invalid Password Or User Name');
186 // There is a user with the provided user_name/email, but the MD5 passwds do not match
187 // We'll have to try checking the (crypt) unix_pw
188 $usr = db_fetch_array($res);
189 $userstatus = $usr['status'] ;
191 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
192 // Even the (crypt) unix_pw does not patch
193 // This one has clearly typed a bad passwd
194 $feedback=_('Invalid Password Or User Name');
197 // User exists, (crypt) unix_pw matches
198 // Update the (MD5) user_pw and retry authentication
199 // It should work, except for status errors
200 $res = db_query_params ('UPDATE users SET user_pw=$1 WHERE user_id=$2',
203 return session_login_valid_dbonly($loginname, $passwd, $allowpending) ;
206 // If we're here, then the user has typed a password matching the (MD5) user_pw
207 // Let's check whether it also matches the (crypt) unix_pw
208 $usr = db_fetch_array($res);
210 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
211 // The (crypt) unix_pw does not match
212 if ($usr['unix_pw'] == '') {
213 // Empty unix_pw, we'll take the MD5 as authoritative
214 // Update the (crypt) unix_pw and retry authentication
215 // It should work, except for status errors
216 $res = db_query_params ('UPDATE users SET unix_pw=$1 WHERE user_id=$2',
217 array (account_genunixpw($passwd),
219 return session_login_valid_dbonly($loginname, $passwd, $allowpending) ;
221 // Invalidate (MD5) user_pw, refuse authentication
222 $res = db_query_params ('UPDATE users SET user_pw=$1 WHERE user_id=$2',
223 array ('OUT OF DATE',
225 $feedback=_('Invalid Password Or User Name');
230 // Yay. The provided password matches both fields in the database.
231 // Let's check the status of this user
233 // if allowpending (for verify.php) then allow
234 $userstatus=$usr['status'];
235 if ($allowpending && ($usr['status'] == 'P')) {
238 if ($usr['status'] == 'S') {
240 $feedback = _('Account Suspended');
243 if ($usr['status'] == 'P') {
245 $feedback = _('Account Pending');
248 if ($usr['status'] == 'D') {
250 $feedback = _('Account Deleted');
253 if ($usr['status'] != 'A') {
254 //unacceptable account flag
255 $feedback = _('Account Not Active');
259 //create a new session
260 session_set_new(db_result($res,0,'user_id'));
267 * session_check_ip() - Check 2 IP addresses for match
269 * This function checks that IP addresses match
271 * IPv4 addresses are allowed to match with some
272 * fuzz factor (within 255.255.0.0 subnet).
274 * For IPv6 addresses, no fuzz is needed since there's
275 * usually no NAT in IPv6.
277 * @param string The old IP address
278 * @param string The new IP address
282 function session_check_ip($oldip,$newip) {
283 if (strstr ($oldip, ':')) {
285 if (strstr ($newip, ':')) {
286 // New IP is IPv6 too
287 return ($oldip == $newip) ;
293 if (strstr ($newip, ':')) {
297 $eoldip = explode(".",$oldip);
298 $enewip = explode(".",$newip);
300 // require same class b subnet
301 return ( ($eoldip[0] == $enewip[0])
302 && ($eoldip[1] == $enewip[1]) ) ;
308 * session_issecure() - Check if current session is secure
313 function session_issecure() {
314 return (strtoupper(getStringFromServer('HTTPS')) == "ON");
318 * session_cookie() - Set a session cookie
320 * Set a cookie with default temporal scope of the current browser session
321 * and URL space of the current webserver
323 * @param string Name of cookie
324 * @param string Value of cookie
325 * @param string Domain scope (default '')
326 * @param string Expiration time in UNIX seconds (default 0)
329 function session_cookie($name ,$value, $domain = '', $expiration = 0) {
330 if (php_sapi_name() != 'cli') {
331 if ( $expiration != 0){
332 setcookie($name, $value, time() + $expiration, '/', $domain, 0);
334 setcookie($name, $value, $expiration, '/', $domain, 0);
340 * session_redirect() - Redirect browser within the site
342 * @param string Absolute path within the site
343 * @return never returns
345 function session_redirect($loc) {
346 header('Location: '.util_make_url ($loc));
352 * session_require() - DEPRECATED Convenience function to easily enforce permissions
354 * Calling page will terminate with error message if current user
357 * @param array Associative array specifying criteria
358 * @return does not return if check is failed
361 function session_require($req, $reason='') {
362 if (!session_loggedin()) {
363 exit_not_logged_in();
366 $user =& user_get_object(user_getid());
367 if (! $user->isActive()) {
369 exit_error(_('Your account is no longer active ; you have been disconnected'),'');
372 if (array_key_exists('group', $req)) {
373 $group = group_get_object($req['group']);
374 if (!$group || !is_object($group)) {
376 } elseif ($group->isError()) {
377 exit_error($reason == '' ? $group->getErrorMessage() : $reason, '');
380 $perm =& $group->getPermission ();
381 if (!$perm || !is_object($perm) || $perm->isError()) {
382 exit_permission_denied($reason,'');
385 if (isset($req['admin_flags']) && $req['admin_flags']) {
386 if (!$perm->isAdmin()) {
387 exit_permission_denied($reason,'');
390 if (!$perm->isMember()) {
391 exit_permission_denied($reason,'');
395 exit_permission_denied($reason,'');
400 * session_require_perm() - Convenience function to easily enforce permissions
402 * Calling page will terminate with error message if current user
406 function session_require_perm ($section, $reference, $action = NULL, $reason='') {
407 if (!forge_check_perm ($section, $reference, $action)) {
408 exit_permission_denied ($reason,'');
413 * session_require_global_perm() - Convenience function to easily enforce permissions
415 * Calling page will terminate with error message if current user
419 function session_require_global_perm ($section, $action = NULL, $reason='') {
420 if (!forge_check_global_perm ($section, $action)) {
422 $reason = sprintf (_('Permission denied. The %s administrators will have to grant you permission to view this page.'),
423 forge_get_config ('forge_name')) ;
425 exit_permission_denied ($reason,'');
430 * session_require_login() - Convenience function to easily enforce permissions
432 * Calling page will terminate with error message if current user
436 function session_require_login () {
437 if (!session_loggedin()) {
438 exit_not_logged_in () ;
443 * session_set_new() - Setup session for the given user
445 * This function sets up SourceForge session for the given user,
446 * making one be "logged in".
448 * @param int The user ID
451 function session_set_new($user_id) {
454 // set session cookie
456 $cookie = session_build_session_cookie($user_id);
457 session_cookie("session_ser", $cookie, "", forge_get_config('session_expire'));
458 $session_ser=$cookie;
460 $res = db_query_params ('SELECT count(*) as c FROM user_session WHERE session_hash =$1',
461 array (session_get_session_cookie_hash($cookie))) ;
462 if (!$res || db_result($res,0,'c') < 1) {
463 db_query_params ('INSERT INTO user_session (session_hash,ip_addr,time,user_id) VALUES ($1,$2,$3,$4)',
464 array (session_get_session_cookie_hash($cookie),
465 getStringFromServer('REMOTE_ADDR'),
470 // check uniqueness of the session_hash in the database
472 $res = session_getdata($user_id);
475 exit_error(db_error(),'');
477 else if (db_numrows($res) < 1) {
478 exit_error(_('Could not fetch user session data'),'');
480 session_set_internal ($user_id, $res) ;
484 function session_set_internal ($user_id, $res=false) {
487 $G_SESSION = user_get_object($user_id,$res);
489 $G_SESSION->setLoggedIn(true);
492 RBACEngine::getInstance()->invalidateRoleCaches() ;
497 * session_set_admin() - Setup session for the admin user
499 * This function sets up a session for the administrator
503 function session_set_admin() {
504 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('forge_admin', -1) ;
505 if (count ($admins) == 0) {
506 exit_error(_('No admin users ?'),'');
508 session_set_new ($admins[0]->getID());
512 * Private optimization function for logins - fetches user data, language, and session
515 * @param int The user ID
518 function session_getdata($user_id) {
519 return db_query_params ('SELECT u.*,sl.language_id, sl.name, sl.filename, sl.classname, sl.language_code, t.dirname, t.fullname
520 FROM users u, supported_languages sl, themes t
521 WHERE u.language=sl.language_id
522 AND u.theme_id=t.theme_id
528 * session_set() - Re-initialize session for the logged in user
530 * This function checks that the user is logged in and if so, initialize
531 * internal session environment.
535 function session_set() {
536 plugin_hook('session_set_entry');
540 // assume bad session_hash and session. If all checks work, then allow
541 // otherwise make new session
544 // If user says he's logged in (by presenting cookie), check that
547 $user_id = session_check_session_cookie($session_ser);
551 $result = session_getdata($user_id);
553 if (db_numrows($result) > 0) {
557 } // else (hash does not exist) or (session hash is bad)
560 $G_SESSION = user_get_object($user_id, $result);
562 $G_SESSION->setLoggedIn(true);
567 // if there was bad session cookie, kill it and the user cookie
573 plugin_hook('session_set_return');
575 RBACEngine::getInstance()->invalidateRoleCaches() ;
578 //TODO - this should be generalized and used for pre.php,
579 //SOAP, forum_gateway.php, tracker_gateway.php, etc to
581 function session_continue($sessionKey) {
583 $session_ser = $sessionKey;
585 setup_gettext_from_context();
586 $LUSER =& session_get_user();
587 if (!is_object($LUSER) || $LUSER->isError()) {
590 putenv('TZ='. $LUSER->getTimeZone());
596 * session_get_user() - Wrapper function to return the User object for the logged in user.
601 function &session_get_user() {
608 * Get user_id of logged in user
611 function user_getid() {
614 return $G_SESSION->getID();
622 * See if user is logged in
624 function session_loggedin() {
628 return $G_SESSION->isLoggedIn();
636 // c-file-style: "bsd"