File: session.php

package info (click to toggle)
gforge 4.5.14-22etch13
  • links: PTS
  • area: main
  • in suites: etch
  • size: 13,004 kB
  • ctags: 11,918
  • sloc: php: 36,047; sql: 29,050; sh: 10,538; perl: 6,496; xml: 3,810; makefile: 341; python: 263; ansic: 256
file content (521 lines) | stat: -rw-r--r-- 14,070 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
<?php
/**
 * SourceForge Session Module
 *
 * Copyright 1999-2001 (c) VA Linux Systems
 *
 * @version   $Id: session.php 5588 2006-06-28 13:30:08Z federicot $
 *
 * This file is part of GForge.
 *
 * GForge is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GForge is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GForge; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

require_once('common/include/account.php');

/**
 * A User object if user is logged in
 *
 * @var	constant		$G_SESSION
 */
$G_SESSION = false;

/**
 *	session_build_session_cookie() - Construct session cookie for the user
 *
 *	@param		int		User_id of the logged in user
 *	@return cookie value
 */
function session_build_session_cookie($user_id) {
	$session_serial = $user_id.'-*-'.time().'-*-'.$GLOBALS['REMOTE_ADDR'].'-*-'.$GLOBALS['HTTP_USER_AGENT'];
	$session_serial_hash = md5($session_serial.$GLOBALS['sys_session_key']);
	$session_serial_cookie = base64_encode($session_serial).'-*-'.$session_serial_hash;
	return $session_serial_cookie;
}

/**
 *	session_get_session_cookie_hash() - Get hash of session cookie
 *
 *	This hash can be used as a key to identify session, e.g. in DB.
 *
 *	@param		string	Value of the session cookie
 *	@return hash
 */
function session_get_session_cookie_hash($session_cookie) {
	list ($junk, $hash) = explode('-*-', $session_cookie);
	return $hash;
}

/**
 *	session_check_session_cookie() - Check that session cookie passed from user is ok
 *
 *	@param		string	Value of the session cookie
 *	@return user_id if cookie is ok, false otherwise
 */
function session_check_session_cookie($session_cookie) {

	list ($session_serial, $hash) = explode('-*-', $session_cookie);
	$session_serial = base64_decode($session_serial);
	$new_hash = md5($session_serial.$GLOBALS['sys_session_key']);

	if ($hash != $new_hash) {
		return false;
	}

	list($user_id, $time, $ip, $user_agent) = explode('-*-', $session_serial, 4);

	if (!session_check_ip($ip, $GLOBALS['REMOTE_ADDR'])) {
		return false;
	}
	if (trim($user_agent) != $GLOBALS['HTTP_USER_AGENT']) {
		return false;
	}
	if ($time - time() >= $GLOBALS['sys_session_expire']) {
		return false;
	}

	return $user_id;
}

/**
 *	session_logout() - Log the user off the system.
 *
 *	This function destroys object associated with the current session,
 *	making user "logged out".  Deletes both user and session cookies.
 *
 *	@return true/false
 *
 */
function session_logout() {

	// delete both session and username cookies
	// NB: cookies must be deleted with the same scope parameters they were set with
	//
	session_cookie('session_ser', '');
	return true;
}

/**
 *	session_login_valid() - Log the user to the system.
 *
 *	High-level function for user login. Check credentials, and if they
 *	are valid, open new session.
 *
 *	@param		string	User name
 *	@param		string	User password (in clear text)
 *	@param		bool	Allow login to non-confirmed user account (only for confirmation of the very account)
 *	@return true/false, if false reason is in global $feedback
 *	@access public
 *
 */
function session_login_valid($loginname, $passwd, $allowpending=0)  {
	global $feedback,$Language;

	if (!$loginname || !$passwd) {
		$feedback = $Language->getText('session','missingpasswd');
		return false;
	}

	$hook_params = array () ;
	$hook_params['loginname'] = $loginname ;
	$hook_params['passwd'] = $passwd ;
	plugin_hook ("session_before_login", $hook_params) ;

	return session_login_valid_dbonly ($loginname, $passwd, $allowpending) ;
}

function session_login_valid_dbonly ($loginname, $passwd, $allowpending) {
	global $feedback,$userstatus,$Language;

	//  Try to get the users from the database using user_id and (MD5) user_pw
	$res = db_query("
		SELECT user_id,status,unix_pw
		FROM users
		WHERE user_name='$loginname' 
		AND user_pw='".md5($passwd)."'
	");
	if (!$res || db_numrows($res) < 1) {
		// No user whose MD5 passwd matches the MD5 of the provided passwd
		// Selecting by user_name only
		$res = db_query("SELECT user_id,status,unix_pw
					FROM users
					WHERE user_name='$loginname'");
		if (!$res || db_numrows($res) < 1) {
			// No user by that name
			$feedback=$Language->getText('session','invalidpasswd');
			return false;
		} else {
			// There is a user with the provided user_name, but the MD5 passwds do not match
			// We'll have to try checking the (crypt) unix_pw
			$usr = db_fetch_array($res);

			if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
				// Even the (crypt) unix_pw does not patch
				// This one has clearly typed a bad passwd
				$feedback=$Language->getText('session','invalidpasswd');
				return false;
			}
			// User exists, (crypt) unix_pw matches
			// Update the (MD5) user_pw and retry authentication
			// It should work, except for status errors
			$res = db_query ("UPDATE users
				SET user_pw='" . md5($passwd) . "'
				WHERE user_id='".$usr['user_id']."'");
			return session_login_valid_dbonly($loginname, $passwd, $allowpending) ;
		}
	} else {
		// If we're here, then the user has typed a password matching the (MD5) user_pw
		// Let's check whether it also matches the (crypt) unix_pw
		$usr = db_fetch_array($res);

		if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
			// The (crypt) unix_pw does not match
			if ($usr['unix_pw'] == '') {
				// Empty unix_pw, we'll take the MD5 as authoritative
				// Update the (crypt) unix_pw and retry authentication
				// It should work, except for status errors
				$res = db_query ("UPDATE users
					SET unix_pw='" . account_genunixpw($passwd) . "'
					WHERE user_id='".$usr['user_id']."'");
				return session_login_valid_dbonly($loginname, $passwd, $allowpending) ;
			} else {
				// Invalidate (MD5) user_pw, refuse authentication
				$res = db_query ("UPDATE users
					SET user_pw='OUT OF DATE'
					WHERE user_id='".$usr['user_id']."'");
				$feedback=$Language->getText('session','invalidpasswd');
				return false;
			}
		}

		// Yay.  The provided password matches both fields in the database.
		// Let's check the status of this user

		// if allowpending (for verify.php) then allow
		$userstatus=$usr['status'];
		if ($allowpending && ($usr['status'] == 'P')) {
			//1;
		} else {
			if ($usr['status'] == 'S') { 
				//acount suspended
				$feedback = $Language->getText('session','suspended');
				return false;
			}
			if ($usr['status'] == 'P') { 
				//account pending
				$feedback = $Language->getText('session','pending');
				return false;
			} 
			if ($usr['status'] == 'D') { 
				//account deleted
				$feedback = $Language->getText('session','deleted');
				return false;
			}
			if ($usr['status'] != 'A') {
				//unacceptable account flag
				$feedback = $Language->getText('session','notactive');
				return false;
			}
		}
		//create a new session
		session_set_new(db_result($res,0,'user_id'));

		return true;
	}
}

/**
 *	session_check_ip() - Check 2 IP addresses for match
 *
 *	This function checks that IP addresses match with the
 *	given fuzz factor (within 255.255.0.0 subnet).
 *
 *	@param		string	The old IP address
 *	@param		string	The new IP address
 *	@return true/false
 *	@access private
 */
function session_check_ip($oldip,$newip) {
	$eoldip = explode(".",$oldip);
	$enewip = explode(".",$newip);

	// ## require same class b subnet
	if (($eoldip[0]!=$enewip[0])||($eoldip[1]!=$enewip[1])) {
		return 0;
	} else {
		return 1;
	}
}

/**
 *	session_issecure() - Check if current session is secure
 *
 *	@return true/false
 *	@access public
 */
function session_issecure() {
	global $HTTP_SERVER_VARS;
	return (strtoupper($HTTP_SERVER_VARS['HTTPS']) == "ON");
}

/**
 *	session_cookie() - Set a session cookie
 *
 *	Set a cookie with default temporal scope of the current browser session
 *	and URL space of the current webserver
 *
 *	@param		string	Name of cookie
 *	@param		string	Value of cookie
 *	@param		string	Domain scope (default '')
 *	@param		string	Expiration time in UNIX seconds (default 0)
 *	@return true/false
 */
function session_cookie($name ,$value, $domain = '', $expiration = 0) {
	if ( $expiration != 0){
		setcookie($name, $value, time() + $expiration, '/', $domain, 0);
	} else {
		setcookie($name, $value, $expiration, '/', $domain, 0);
	}
}

/**
 *	session_redirect() - Redirect browser within the site
 *
 *	@param		string	Absolute path within the site
 *	@return never returns
 */
function session_redirect($loc) {
	header('Location: http' . (session_issecure()?'s':'') . '://' . getStringFromServer('HTTP_HOST') . $loc);
	print("\n\n");
	exit;
}

/**
 *	session_require() - Convenience function to easily enforce permissions
 *
 *	Calling page will terminate with error message if current user
 *	fails checks.
 *
 *	@param		array	Associative array specifying criteria
 *	@return does not return if check is failed
 *
 */
function session_require($req) {
	if (!session_loggedin()) {
		exit_not_logged_in();	
	}

	if ($req['group']) {
		$group =& group_get_object($req['group']);
		if (!$group || !is_object($group)) {
			exit_error('Error','Could Not Get Group');
		} elseif ($group->isError()) {
			exit_error('Error',$group->getErrorMessage());
		}

		$perm =& $group->getPermission( session_get_user() );
		if (!$perm || !is_object($perm) || $perm->isError()) {
			exit_permission_denied();
		}

		if ($req['admin_flags']) {
			if (!$perm->isAdmin()) {
				exit_permission_denied();
			}
		} else {
			if (!$perm->isMember()) {
				exit_permission_denied();
			}
		}
	} else if ($req['isloggedin']) {
		//no need to check as long as the check is present at top of function
	} else {
		exit_permission_denied();
	}
}

/**
 *	session_set_new() - Setup session for the given user
 *
 *	This function sets up SourceForge session for the given user,
 *	making one be "logged in".
 *
 *	@param		int		The user ID
 *	@return none
 */
function session_set_new($user_id) {
	global $G_SESSION,$session_ser,$Language;

	// set session cookie
  //
	$cookie = session_build_session_cookie($user_id);
	session_cookie("session_ser", $cookie, "", $GLOBALS['sys_session_expire']);
	$session_ser=$cookie;

	db_query("
		INSERT INTO user_session (session_hash, ip_addr, time, user_id) 
		VALUES (
			'".session_get_session_cookie_hash($cookie)."', 
			'".$GLOBALS['REMOTE_ADDR']."',
			'".time()."',
			$user_id
		)
	");

	// check uniqueness of the session_hash in the database
	// 
	$res = session_getdata($user_id);

	if (!$res || db_numrows($res) < 1) {
		exit_error($Language->getText('global','error'),$Language->getText('session','cannotinit').": ".db_error());
	} else {

		//set up the new user object
		//
		$G_SESSION = user_get_object($user_id,$res);
		if ($G_SESSION) {
			$G_SESSION->setLoggedIn(true);
		}
	}

}

/**
 *	Private optimization function for logins - fetches user data, language, and session
 *	with one query
 *
 *  @param		int		The user ID
 *	@access private
 */
function session_getdata($user_id) {
	$res=db_query("SELECT
		u.*,sl.language_id, sl.name, sl.filename, sl.classname, sl.language_code, t.dirname, t.fullname
		FROM users u,
		supported_languages sl,
		themes t
		WHERE u.language=sl.language_id 
		AND u.theme_id=t.theme_id
		AND u.user_id='$user_id'");
	return $res;
}

/**
 *	session_set() - Re-initialize session for the logged in user
 *
 *	This function checks that the user is logged in and if so, initialize
 *	internal session environment.
 *
 *	@return none
 */
function session_set() {
	global $G_SESSION;
	global $session_ser, $session_key;

	// assume bad session_hash and session. If all checks work, then allow
	// otherwise make new session
	$id_is_good = false;

	// If user says he's logged in (by presenting cookie), check that
	if ($session_ser) {

		$user_id = session_check_session_cookie($session_ser);

		if ($user_id) {

			$result = session_getdata($user_id);

			if (db_numrows($result) > 0) {
				$id_is_good = true;
			}
		}
	} // else (hash does not exist) or (session hash is bad)

	if ($id_is_good) {
		$G_SESSION = user_get_object($user_id, $result);
		if ($G_SESSION) {
			$G_SESSION->setLoggedIn(true);
		}
	} else {
		$G_SESSION=false;

		// if there was bad session cookie, kill it and the user cookie
		//
		if ($session_ser) {
			session_logout();
		}
	}
}

//TODO - this should be generalized and used for pre.php, squal_pre.php, 
//SOAP, forum_gateway.php, tracker_gateway.php, etc to 
//setup languages
function session_continue($sessionKey) {
	global $session_ser, $Language, $sys_strftimefmt, $sys_datefmt;
	$session_ser = $sessionKey;
	session_set();
 	$Language=new BaseLanguage();
	$Language->loadLanguage("English"); // TODO use the user's default language
	setlocale (LC_TIME, $Language->getText('system','locale'));
	$sys_strftimefmt = $Language->getText('system','strftimefmt');
	$sys_datefmt = $Language->getText('system','datefmt');
	$LUSER =& session_get_user();
	if (!is_object($LUSER) || $LUSER->isError()) {
		return false;
	} else {
		putenv('TZ='. $LUSER->getTimeZone());
		return true;
	}
}

/**
 *	session_get_user() - Wrapper function to return the User object for the logged in user.
 *	
 *	@return User
 *	@access public
 */
function &session_get_user() {
	global $G_SESSION;
	return $G_SESSION;
}

/**
 *  user_getid()
 *  Get user_id of logged in user
 */

function user_getid() {
	global $G_SESSION;
	if ($G_SESSION) {
		return $G_SESSION->getID();
	} else {
		return false;
	}
}

/**
 *  session_loggedin()
 *  See if user is logged in
 */
function session_loggedin() {
	global $G_SESSION;

	if ($G_SESSION) {
		return $G_SESSION->isLoggedIn();
	} else {
		return false;
	}
}

?>