3 * SourceForge Session Module
5 * Copyright 1999-2001 (c) VA Linux Systems
9 * This file is part of GForge.
11 * GForge is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * GForge is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with GForge; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 require_once $gfcommon.'include/account.php';
27 require_once $gfcommon.'include/escapingUtils.php';
30 * A User object if user is logged in
32 * @var constant $G_SESSION
39 $session_ser = getStringFromCookie('session_ser');
42 * session_build_session_cookie() - Construct session cookie for the user
44 * @param int User_id of the logged in user
45 * @return cookie value
47 function session_build_session_cookie($user_id) {
48 $session_serial = $user_id.'-*-'.time().'-*-'.getStringFromServer('REMOTE_ADDR').'-*-'.getStringFromServer('HTTP_USER_AGENT');
49 $session_serial_hash = md5($session_serial.$GLOBALS['sys_session_key']);
50 $session_serial_cookie = base64_encode($session_serial).'-*-'.$session_serial_hash;
51 return $session_serial_cookie;
55 * session_get_session_cookie_hash() - Get hash of session cookie
57 * This hash can be used as a key to identify session, e.g. in DB.
59 * @param string Value of the session cookie
62 function session_get_session_cookie_hash($session_cookie) {
63 list ($junk, $hash) = explode('-*-', $session_cookie);
68 * session_check_session_cookie() - Check that session cookie passed from user is ok
70 * @param string Value of the session cookie
71 * @return user_id if cookie is ok, false otherwise
73 function session_check_session_cookie($session_cookie) {
75 list ($session_serial, $hash) = explode('-*-', $session_cookie);
76 $session_serial = base64_decode($session_serial);
77 $new_hash = md5($session_serial.$GLOBALS['sys_session_key']);
79 if ($hash != $new_hash) {
83 list($user_id, $time, $ip, $user_agent) = explode('-*-', $session_serial, 4);
85 if (!session_check_ip($ip, getStringFromServer('REMOTE_ADDR'))) {
88 if (trim($user_agent) != getStringFromServer('HTTP_USER_AGENT')) {
91 if (($GLOBALS['sys_session_expire'] > 0) &&
92 ($time - time() >= $GLOBALS['sys_session_expire'])) {
100 * session_logout() - Log the user off the system.
102 * This function destroys object associated with the current session,
103 * making user "logged out". Deletes both user and session cookies.
108 function session_logout() {
110 // delete both session and username cookies
111 // NB: cookies must be deleted with the same scope parameters they were set with
113 session_cookie('session_ser', '');
118 * session_login_valid() - Log the user to the system.
120 * High-level function for user login. Check credentials, and if they
121 * are valid, open new session.
123 * @param string User name
124 * @param string User password (in clear text)
125 * @param bool Allow login to non-confirmed user account (only for confirmation of the very account)
126 * @return true/false, if false reason is in global $feedback
130 function session_login_valid($loginname, $passwd, $allowpending=0) {
133 if (!$loginname || !$passwd) {
134 $feedback = _('Missing Password Or Users Name');
138 $hook_params = array () ;
139 $hook_params['loginname'] = $loginname ;
140 $hook_params['passwd'] = $passwd ;
141 plugin_hook ("session_before_login", $hook_params) ;
143 return session_login_valid_dbonly ($loginname, $passwd, $allowpending) ;
146 function session_login_valid_dbonly ($loginname, $passwd, $allowpending) {
147 global $feedback,$userstatus;
149 // Try to get the users from the database using user_id and (MD5) user_pw
151 SELECT user_id,status,unix_pw
153 WHERE user_name='$loginname'
154 AND user_pw='".md5($passwd)."'
156 if (!$res || db_numrows($res) < 1) {
157 // No user whose MD5 passwd matches the MD5 of the provided passwd
158 // Selecting by user_name only
159 $res = db_query("SELECT user_id,status,unix_pw
161 WHERE user_name='$loginname'");
162 if (!$res || db_numrows($res) < 1) {
163 // No user by that name
164 $feedback=_('Invalid Password Or User Name');
167 // There is a user with the provided user_name, but the MD5 passwds do not match
168 // We'll have to try checking the (crypt) unix_pw
169 $usr = db_fetch_array($res);
171 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
172 // Even the (crypt) unix_pw does not patch
173 // This one has clearly typed a bad passwd
174 $feedback=_('Invalid Password Or User Name');
177 // User exists, (crypt) unix_pw matches
178 // Update the (MD5) user_pw and retry authentication
179 // It should work, except for status errors
180 $res = db_query ("UPDATE users
181 SET user_pw='" . md5($passwd) . "'
182 WHERE user_id='".$usr['user_id']."'");
183 return session_login_valid_dbonly($loginname, $passwd, $allowpending) ;
186 // If we're here, then the user has typed a password matching the (MD5) user_pw
187 // Let's check whether it also matches the (crypt) unix_pw
188 $usr = db_fetch_array($res);
190 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
191 // The (crypt) unix_pw does not match
192 if ($usr['unix_pw'] == '') {
193 // Empty unix_pw, we'll take the MD5 as authoritative
194 // Update the (crypt) unix_pw and retry authentication
195 // It should work, except for status errors
196 $res = db_query ("UPDATE users
197 SET unix_pw='" . account_genunixpw($passwd) . "'
198 WHERE user_id='".$usr['user_id']."'");
199 return session_login_valid_dbonly($loginname, $passwd, $allowpending) ;
201 // Invalidate (MD5) user_pw, refuse authentication
202 $res = db_query ("UPDATE users
203 SET user_pw='OUT OF DATE'
204 WHERE user_id='".$usr['user_id']."'");
205 $feedback=_('Invalid Password Or User Name');
211 // Yay. The provided password matches both fields in the database.
212 // Let's check the status of this user
214 // if allowpending (for verify.php) then allow
215 $userstatus=$usr['status'];
216 if ($allowpending && ($usr['status'] == 'P')) {
219 if ($usr['status'] == 'S') {
221 $feedback = _('Account Suspended');
224 if ($usr['status'] == 'P') {
226 $feedback = _('Account Pending');
229 if ($usr['status'] == 'D') {
231 $feedback = _('Account Deleted');
234 if ($usr['status'] != 'A') {
235 //unacceptable account flag
236 $feedback = _('Account Not Active');
240 //create a new session
241 session_set_new(db_result($res,0,'user_id'));
248 * session_check_ip() - Check 2 IP addresses for match
250 * This function checks that IP addresses match
252 * IPv4 addresses are allowed to match with some
253 * fuzz factor (within 255.255.0.0 subnet).
255 * For IPv6 addresses, no fuzz is needed since there's
256 * usually no NAT in IPv6.
258 * @param string The old IP address
259 * @param string The new IP address
263 function session_check_ip($oldip,$newip) {
264 if (strstr ($oldip, ':')) {
266 if (strstr ($newip, ':')) {
267 // New IP is IPv6 too
268 return ($oldip == $newip) ;
274 if (strstr ($newip, ':')) {
278 $eoldip = explode(".",$oldip);
279 $enewip = explode(".",$newip);
281 // require same class b subnet
282 return ( ($eoldip[0] == $enewip[0])
283 && ($eoldip[1] == $enewip[1]) ) ;
289 * session_issecure() - Check if current session is secure
294 function session_issecure() {
295 return (strtoupper(getStringFromServer('HTTPS')) == "ON");
299 * session_cookie() - Set a session cookie
301 * Set a cookie with default temporal scope of the current browser session
302 * and URL space of the current webserver
304 * @param string Name of cookie
305 * @param string Value of cookie
306 * @param string Domain scope (default '')
307 * @param string Expiration time in UNIX seconds (default 0)
310 function session_cookie($name ,$value, $domain = '', $expiration = 0) {
311 if ( $expiration != 0){
312 setcookie($name, $value, time() + $expiration, '/', $domain, 0);
314 setcookie($name, $value, $expiration, '/', $domain, 0);
319 * session_redirect() - Redirect browser within the site
321 * @param string Absolute path within the site
322 * @return never returns
324 function session_redirect($loc) {
325 header('Location: '.util_make_url ($loc));
331 * session_require() - Convenience function to easily enforce permissions
333 * Calling page will terminate with error message if current user
336 * @param array Associative array specifying criteria
337 * @return does not return if check is failed
340 function session_require($req) {
341 if (!session_loggedin()) {
342 exit_not_logged_in();
346 $group =& group_get_object($req['group']);
347 if (!$group || !is_object($group)) {
348 exit_error('Error','Could Not Get Group');
349 } elseif ($group->isError()) {
350 exit_error('Error',$group->getErrorMessage());
353 $perm =& $group->getPermission( session_get_user() );
354 if (!$perm || !is_object($perm) || $perm->isError()) {
355 exit_permission_denied();
358 //don't really like this, but as admin_flags is not mandatory
359 //I add @ to remove the warning
360 if (@$req['admin_flags']) {
361 if (!$perm->isAdmin()) {
362 exit_permission_denied();
365 if (!$perm->isMember()) {
366 exit_permission_denied();
369 } else if ($req['isloggedin']) {
370 //no need to check as long as the check is present at top of function
372 exit_permission_denied();
377 * session_set_new() - Setup session for the given user
379 * This function sets up SourceForge session for the given user,
380 * making one be "logged in".
382 * @param int The user ID
385 function session_set_new($user_id) {
386 global $G_SESSION,$session_ser;
388 // set session cookie
390 $cookie = session_build_session_cookie($user_id);
391 session_cookie("session_ser", $cookie, "", $GLOBALS['sys_session_expire']);
392 $session_ser=$cookie;
395 INSERT INTO user_session (session_hash, ip_addr, time, user_id)
397 '".session_get_session_cookie_hash($cookie)."',
398 '".getStringFromServer('REMOTE_ADDR')."',
404 // check uniqueness of the session_hash in the database
406 $res = session_getdata($user_id);
408 if (!$res || db_numrows($res) < 1) {
409 exit_error(_('ERROR'),_('ERROR').": ".db_error());
412 //set up the new user object
414 $G_SESSION = user_get_object($user_id,$res);
416 $G_SESSION->setLoggedIn(true);
423 * Private optimization function for logins - fetches user data, language, and session
426 * @param int The user ID
429 function session_getdata($user_id) {
430 $res=db_query("SELECT
431 u.*,sl.language_id, sl.name, sl.filename, sl.classname, sl.language_code, t.dirname, t.fullname
433 supported_languages sl,
435 WHERE u.language=sl.language_id
436 AND u.theme_id=t.theme_id
437 AND u.user_id='$user_id'");
442 * session_set() - Re-initialize session for the logged in user
444 * This function checks that the user is logged in and if so, initialize
445 * internal session environment.
449 function session_set() {
450 plugin_hook('session_set_entry');
452 global $session_ser, $session_key;
454 // assume bad session_hash and session. If all checks work, then allow
455 // otherwise make new session
458 // If user says he's logged in (by presenting cookie), check that
461 $user_id = session_check_session_cookie($session_ser);
465 $result = session_getdata($user_id);
467 if (db_numrows($result) > 0) {
471 } // else (hash does not exist) or (session hash is bad)
474 $G_SESSION = user_get_object($user_id, $result);
476 $G_SESSION->setLoggedIn(true);
481 // if there was bad session cookie, kill it and the user cookie
487 plugin_hook('session_set_return');
490 //TODO - this should be generalized and used for pre.php, squal_pre.php,
491 //SOAP, forum_gateway.php, tracker_gateway.php, etc to
493 function session_continue($sessionKey) {
495 $session_ser = $sessionKey;
497 setup_gettext_from_browser() ;
498 $LUSER =& session_get_user();
499 if (!is_object($LUSER) || $LUSER->isError()) {
502 putenv('TZ='. $LUSER->getTimeZone());
508 * session_get_user() - Wrapper function to return the User object for the logged in user.
513 function &session_get_user() {
520 * Get user_id of logged in user
523 function user_getid() {
526 return $G_SESSION->getID();
534 * See if user is logged in
536 function session_loggedin() {
540 return $G_SESSION->isLoggedIn();
548 // c-file-style: "bsd"