2 /***************************************************************************
5 * begin : Saturday, Feb 13, 2001
6 * copyright : (C) 2001 The phpBB Group
7 * email : support@phpbb.com
9 * $Id: sessions.php,v 1.58.2.25 2006/05/18 19:23:07 grahamje Exp $
12 ***************************************************************************/
14 /***************************************************************************
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
21 ***************************************************************************/
24 // Adds/updates a new session to the database for the given userid.
25 // Returns the new session ID on success.
27 function session_begin($user_id, $user_ip, $page_id, $auto_create = 0, $enable_autologin = 0, $admin = 0)
29 global $db, $board_config;
30 global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
32 $cookiename = $board_config['cookie_name'];
33 $cookiepath = $board_config['cookie_path'];
34 $cookiedomain = $board_config['cookie_domain'];
35 $cookiesecure = $board_config['cookie_secure'];
37 if ( isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) || isset($HTTP_COOKIE_VARS[$cookiename . '_data']) )
39 $session_id = isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) ? $HTTP_COOKIE_VARS[$cookiename . '_sid'] : '';
40 $sessiondata = isset($HTTP_COOKIE_VARS[$cookiename . '_data']) ? unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename . '_data'])) : array();
41 $sessionmethod = SESSION_METHOD_COOKIE;
45 $sessiondata = array();
46 $session_id = ( isset($HTTP_GET_VARS['sid']) ) ? $HTTP_GET_VARS['sid'] : '';
47 $sessionmethod = SESSION_METHOD_GET;
51 if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
56 $page_id = (int) $page_id;
59 $current_time = time();
62 // Are auto-logins allowed?
63 // If allow_autologin is not set or is true then they are
64 // (same behaviour as old 2.0.x session code)
66 if (isset($board_config['allow_autologin']) && !$board_config['allow_autologin'])
68 $enable_autologin = $sessiondata['autologinid'] = false;
72 // First off attempt to join with the autologin value if we have one
73 // If not, just use the user_id value
77 if ($user_id != ANONYMOUS)
79 if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '' && $user_id)
82 FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
83 WHERE u.user_id = ' . (int) $user_id . "
85 AND k.user_id = u.user_id
86 AND k.key_id = '" . md5($sessiondata['autologinid']) . "'";
87 if (!($result = $db->sql_query($sql)))
89 message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
92 $userdata = $db->sql_fetchrow($result);
93 $db->sql_freeresult($result);
95 $enable_autologin = $login = 1;
97 else if (!$auto_create)
99 $sessiondata['autologinid'] = '';
100 $sessiondata['userid'] = $user_id;
103 FROM ' . USERS_TABLE . '
104 WHERE user_id = ' . (int) $user_id . '
105 AND user_active = 1';
106 if (!($result = $db->sql_query($sql)))
108 message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
111 $userdata = $db->sql_fetchrow($result);
112 $db->sql_freeresult($result);
119 // At this point either $userdata should be populated or
120 // one of the below is true
121 // * Key didn't match one in the DB
122 // * User does not exist
123 // * User is inactive
125 if (!sizeof($userdata) || !is_array($userdata) || !$userdata)
127 $sessiondata['autologinid'] = '';
128 $sessiondata['userid'] = $user_id = ANONYMOUS;
129 $enable_autologin = $login = 0;
132 FROM ' . USERS_TABLE . '
133 WHERE user_id = ' . (int) $user_id;
134 if (!($result = $db->sql_query($sql)))
136 message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
139 $userdata = $db->sql_fetchrow($result);
140 $db->sql_freeresult($result);
145 // Initial ban check against user id, IP and email address
147 preg_match('/(..)(..)(..)(..)/', $user_ip, $user_ip_parts);
149 $sql = "SELECT ban_ip, ban_userid, ban_email
150 FROM " . BANLIST_TABLE . "
151 WHERE ban_ip IN ('" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . $user_ip_parts[4] . "', '" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . "ff', '" . $user_ip_parts[1] . $user_ip_parts[2] . "ffff', '" . $user_ip_parts[1] . "ffffff')
152 OR ban_userid = $user_id";
153 if ( $user_id != ANONYMOUS )
155 $sql .= " OR ban_email LIKE '" . str_replace("\'", "''", $userdata['user_email']) . "'
156 OR ban_email LIKE '" . substr(str_replace("\'", "''", $userdata['user_email']), strpos(str_replace("\'", "''", $userdata['user_email']), "@")) . "'";
158 if ( !($result = $db->sql_query($sql)) )
160 message_die(CRITICAL_ERROR, 'Could not obtain ban information', '', __LINE__, __FILE__, $sql);
163 if ( $ban_info = $db->sql_fetchrow($result) )
165 if ( $ban_info['ban_ip'] || $ban_info['ban_userid'] || $ban_info['ban_email'] )
167 message_die(CRITICAL_MESSAGE, 'You_been_banned');
172 // Create or update the session
174 $sql = "UPDATE " . SESSIONS_TABLE . "
175 SET session_user_id = $user_id, session_start = $current_time, session_time = $current_time, session_page = $page_id, session_logged_in = $login, session_admin = $admin
176 WHERE session_id = '" . $session_id . "'
177 AND session_ip = '$user_ip'";
178 if ( !$db->sql_query($sql) || !$db->sql_affectedrows() )
180 $session_id = md5(dss_rand());
182 $sql = "INSERT INTO " . SESSIONS_TABLE . "
183 (session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in, session_admin)
184 VALUES ('$session_id', $user_id, $current_time, $current_time, '$user_ip', $page_id, $login, $admin)";
185 if ( !$db->sql_query($sql) )
187 message_die(CRITICAL_ERROR, 'Error creating new session', '', __LINE__, __FILE__, $sql);
191 if ( $user_id != ANONYMOUS )
193 $last_visit = ( $userdata['user_session_time'] > 0 ) ? $userdata['user_session_time'] : $current_time;
197 $sql = "UPDATE " . USERS_TABLE . "
198 SET user_session_time = $current_time, user_session_page = $page_id, user_lastvisit = $last_visit
199 WHERE user_id = $user_id";
200 if ( !$db->sql_query($sql) )
202 message_die(CRITICAL_ERROR, 'Error updating last visit time', '', __LINE__, __FILE__, $sql);
206 $userdata['user_lastvisit'] = $last_visit;
209 // Regenerate the auto-login key
211 if ($enable_autologin)
213 $auto_login_key = dss_rand() . dss_rand();
215 if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '')
217 $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
218 SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
219 WHERE key_id = '" . md5($sessiondata['autologinid']) . "'";
223 $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . "(key_id, user_id, last_ip, last_login)
224 VALUES ('" . md5($auto_login_key) . "', $user_id, '$user_ip', $current_time)";
227 if ( !$db->sql_query($sql) )
229 message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
232 $sessiondata['autologinid'] = $auto_login_key;
233 unset($auto_login_key);
237 $sessiondata['autologinid'] = '';
240 // $sessiondata['autologinid'] = (!$admin) ? (( $enable_autologin && $sessionmethod == SESSION_METHOD_COOKIE ) ? $auto_login_key : '') : $sessiondata['autologinid'];
241 $sessiondata['userid'] = $user_id;
244 $userdata['session_id'] = $session_id;
245 $userdata['session_ip'] = $user_ip;
246 $userdata['session_user_id'] = $user_id;
247 $userdata['session_logged_in'] = $login;
248 $userdata['session_page'] = $page_id;
249 $userdata['session_start'] = $current_time;
250 $userdata['session_time'] = $current_time;
251 $userdata['session_admin'] = $admin;
252 $userdata['session_key'] = $sessiondata['autologinid'];
254 setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
255 setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
257 $SID = 'sid=' . $session_id;
263 // Checks for a given user session, tidies session table and updates user
264 // sessions at each page refresh
266 function session_pagestart($user_ip, $thispage_id)
268 global $db, $lang, $board_config;
269 global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
271 $cookiename = $board_config['cookie_name'];
272 $cookiepath = $board_config['cookie_path'];
273 $cookiedomain = $board_config['cookie_domain'];
274 $cookiesecure = $board_config['cookie_secure'];
276 $current_time = time();
279 if ( isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) || isset($HTTP_COOKIE_VARS[$cookiename . '_data']) )
281 $sessiondata = isset( $HTTP_COOKIE_VARS[$cookiename . '_data'] ) ? unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename . '_data'])) : array();
282 $session_id = isset( $HTTP_COOKIE_VARS[$cookiename . '_sid'] ) ? $HTTP_COOKIE_VARS[$cookiename . '_sid'] : '';
283 $sessionmethod = SESSION_METHOD_COOKIE;
287 $sessiondata = array();
288 $session_id = ( isset($HTTP_GET_VARS['sid']) ) ? $HTTP_GET_VARS['sid'] : '';
289 $sessionmethod = SESSION_METHOD_GET;
293 if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
298 $thispage_id = (int) $thispage_id;
301 // Does a session exist?
303 if ( !empty($session_id) )
306 // session_id exists so go ahead and attempt to grab all
307 // data in preparation
309 $sql = "SELECT u.*, s.*
310 FROM " . SESSIONS_TABLE . " s, " . USERS_TABLE . " u
311 WHERE s.session_id = '$session_id'
312 AND u.user_id = s.session_user_id";
313 if ( !($result = $db->sql_query($sql)) )
315 message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
318 $userdata = $db->sql_fetchrow($result);
321 // Did the session exist in the DB?
323 if ( isset($userdata['user_id']) )
326 // Do not check IP assuming equivalence, if IPv4 we'll check only first 24
327 // bits ... I've been told (by vHiker) this should alleviate problems with
328 // load balanced et al proxies while retaining some reliance on IP security.
330 $ip_check_s = substr($userdata['session_ip'], 0, 6);
331 $ip_check_u = substr($user_ip, 0, 6);
333 if ($ip_check_s == $ip_check_u)
335 $SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '';
338 // Only update session DB a minute or so after last update
340 if ( $current_time - $userdata['session_time'] > 60 )
342 // A little trick to reset session_admin on session re-usage
343 $update_admin = (!defined('IN_ADMIN') && $current_time - $userdata['session_time'] > ($board_config['session_length']+60)) ? ', session_admin = 0' : '';
345 $sql = "UPDATE " . SESSIONS_TABLE . "
346 SET session_time = $current_time, session_page = $thispage_id$update_admin
347 WHERE session_id = '" . $userdata['session_id'] . "'";
348 if ( !$db->sql_query($sql) )
350 message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
353 if ( $userdata['user_id'] != ANONYMOUS )
355 $sql = "UPDATE " . USERS_TABLE . "
356 SET user_session_time = $current_time, user_session_page = $thispage_id
357 WHERE user_id = " . $userdata['user_id'];
358 if ( !$db->sql_query($sql) )
360 message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
364 session_clean($userdata['session_id']);
366 setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
367 setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
370 // Add the session_key to the userdata array if it is set
371 if ( isset($sessiondata['autologinid']) && $sessiondata['autologinid'] != '' )
373 $userdata['session_key'] = $sessiondata['autologinid'];
382 // If we reach here then no (valid) session exists. So we'll create a new one,
383 // using the cookie user_id if available to pull basic user prefs.
385 $user_id = ( isset($sessiondata['userid']) ) ? intval($sessiondata['userid']) : ANONYMOUS;
387 if ( !($userdata = session_begin($user_id, $user_ip, $thispage_id, TRUE)) )
389 message_die(CRITICAL_ERROR, 'Error creating user session', '', __LINE__, __FILE__, $sql);
397 * Terminates the specified session
398 * It will delete the entry in the sessions table for this session,
399 * remove the corresponding auto-login key and reset the cookies
401 function session_end($session_id, $user_id)
403 global $db, $lang, $board_config, $userdata;
404 global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
406 $cookiename = $board_config['cookie_name'];
407 $cookiepath = $board_config['cookie_path'];
408 $cookiedomain = $board_config['cookie_domain'];
409 $cookiesecure = $board_config['cookie_secure'];
411 $current_time = time();
413 if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
419 // Delete existing session
421 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
422 WHERE session_id = '$session_id'
423 AND session_user_id = $user_id";
424 if ( !$db->sql_query($sql) )
426 message_die(CRITICAL_ERROR, 'Error removing user session', '', __LINE__, __FILE__, $sql);
430 // Remove this auto-login entry (if applicable)
432 if ( isset($userdata['session_key']) && $userdata['session_key'] != '' )
434 $autologin_key = md5($userdata['session_key']);
435 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
436 WHERE user_id = ' . (int) $user_id . "
437 AND key_id = '$autologin_key'";
438 if ( !$db->sql_query($sql) )
440 message_die(CRITICAL_ERROR, 'Error removing auto-login key', '', __LINE__, __FILE__, $sql);
445 // We expect that message_die will be called after this function,
446 // but just in case it isn't, reset $userdata to the details for a guest
449 FROM ' . USERS_TABLE . '
450 WHERE user_id = ' . ANONYMOUS;
451 if ( !($result = $db->sql_query($sql)) )
453 message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
455 if ( !($userdata = $db->sql_fetchrow($result)) )
457 message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
459 $db->sql_freeresult($result);
462 setcookie($cookiename . '_data', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
463 setcookie($cookiename . '_sid', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
469 * Removes expired sessions and auto-login keys from the database
471 function session_clean($session_id)
473 global $board_config, $db;
476 // Delete expired sessions
478 $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
479 WHERE session_time < ' . (time() - (int) $board_config['session_length']) . "
480 AND session_id <> '$session_id'";
481 if ( !$db->sql_query($sql) )
483 message_die(CRITICAL_ERROR, 'Error clearing sessions table', '', __LINE__, __FILE__, $sql);
487 // Delete expired auto-login keys
488 // If max_autologin_time is not set then keys will never be deleted
489 // (same behaviour as old 2.0.x session code)
491 if (!empty($board_config['max_autologin_time']) && $board_config['max_autologin_time'] > 0)
493 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
494 WHERE last_login < ' . (time() - (86400 * (int) $board_config['max_autologin_time']));
495 $db->sql_query($sql);
502 * Reset all login keys for the specified user
503 * Called on password changes
505 function session_reset_keys($user_id, $user_ip)
507 global $db, $userdata, $board_config;
509 $key_sql = ($user_id == $userdata['user_id'] && !empty($userdata['session_key'])) ? "AND key_id != '" . md5($userdata['session_key']) . "'" : '';
511 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
512 WHERE user_id = ' . (int) $user_id . "
515 if ( !$db->sql_query($sql) )
517 message_die(CRITICAL_ERROR, 'Error removing auto-login keys', '', __LINE__, __FILE__, $sql);
520 $where_sql = 'session_user_id = ' . (int) $user_id;
521 $where_sql .= ($user_id == $userdata['user_id']) ? " AND session_id <> '" . $userdata['session_id'] . "'" : '';
522 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
524 if ( !$db->sql_query($sql) )
526 message_die(CRITICAL_ERROR, 'Error removing user session(s)', '', __LINE__, __FILE__, $sql);
529 if ( !empty($key_sql) )
531 $auto_login_key = dss_rand() . dss_rand();
533 $current_time = time();
535 $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
536 SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
537 WHERE key_id = '" . md5($userdata['session_key']) . "'";
539 if ( !$db->sql_query($sql) )
541 message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
544 // And now rebuild the cookie
545 $sessiondata['userid'] = $user_id;
546 $sessiondata['autologinid'] = $auto_login_key;
547 $cookiename = $board_config['cookie_name'];
548 $cookiepath = $board_config['cookie_path'];
549 $cookiedomain = $board_config['cookie_domain'];
550 $cookiesecure = $board_config['cookie_secure'];
552 setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
554 $userdata['session_key'] = $auto_login_key;
556 unset($auto_login_key);
561 // Append $SID to a url. Borrowed from phplib and modified. This is an
562 // extra routine utilised by the session code above and acts as a wrapper
563 // around every single URL and form action. If you replace the session
564 // code you must include this routine, even if it's empty.
566 function append_sid($url, $non_html_amp = false)
570 if ( !empty($SID) && !preg_match('#sid=#', $url) )
572 $url .= ( ( strpos($url, '?') !== false ) ? ( ( $non_html_amp ) ? '&' : '&' ) : '?' ) . $SID;