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.16 2005/10/30 15:17:14 acydburn 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 list($sec, $usec) = explode(' ', microtime());
181 mt_srand((float) $sec + ((float) $usec * 100000));
182 $session_id = md5(uniqid(mt_rand(), true));
184 $sql = "INSERT INTO " . SESSIONS_TABLE . "
185 (session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in, session_admin)
186 VALUES ('$session_id', $user_id, $current_time, $current_time, '$user_ip', $page_id, $login, $admin)";
187 if ( !$db->sql_query($sql) )
189 message_die(CRITICAL_ERROR, 'Error creating new session', '', __LINE__, __FILE__, $sql);
193 if ( $user_id != ANONYMOUS )
195 $last_visit = ( $userdata['user_session_time'] > 0 ) ? $userdata['user_session_time'] : $current_time;
199 $sql = "UPDATE " . USERS_TABLE . "
200 SET user_session_time = $current_time, user_session_page = $page_id, user_lastvisit = $last_visit
201 WHERE user_id = $user_id";
202 if ( !$db->sql_query($sql) )
204 message_die(CRITICAL_ERROR, 'Error updating last visit time', '', __LINE__, __FILE__, $sql);
208 $userdata['user_lastvisit'] = $last_visit;
211 // Regenerate the auto-login key
213 if ($enable_autologin)
215 list($sec, $usec) = explode(' ', microtime());
216 mt_srand(hexdec(substr($session_id, 0, 8)) + (float) $sec + ((float) $usec * 1000000));
217 $auto_login_key = uniqid(mt_rand(), true);
219 if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '')
221 $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
222 SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
223 WHERE key_id = '" . md5($sessiondata['autologinid']) . "'";
227 $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . "(key_id, user_id, last_ip, last_login)
228 VALUES ('" . md5($auto_login_key) . "', $user_id, '$user_ip', $current_time)";
231 if ( !$db->sql_query($sql) )
233 message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
236 $sessiondata['autologinid'] = $auto_login_key;
237 unset($auto_login_key);
241 $sessiondata['autologinid'] = '';
244 // $sessiondata['autologinid'] = (!$admin) ? (( $enable_autologin && $sessionmethod == SESSION_METHOD_COOKIE ) ? $auto_login_key : '') : $sessiondata['autologinid'];
245 $sessiondata['userid'] = $user_id;
248 $userdata['session_id'] = $session_id;
249 $userdata['session_ip'] = $user_ip;
250 $userdata['session_user_id'] = $user_id;
251 $userdata['session_logged_in'] = $login;
252 $userdata['session_page'] = $page_id;
253 $userdata['session_start'] = $current_time;
254 $userdata['session_time'] = $current_time;
255 $userdata['session_admin'] = $admin;
256 $userdata['session_key'] = $sessiondata['autologinid'];
258 setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
259 setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
261 $SID = 'sid=' . $session_id;
267 // Checks for a given user session, tidies session table and updates user
268 // sessions at each page refresh
270 function session_pagestart($user_ip, $thispage_id)
272 global $db, $lang, $board_config;
273 global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
275 $cookiename = $board_config['cookie_name'];
276 $cookiepath = $board_config['cookie_path'];
277 $cookiedomain = $board_config['cookie_domain'];
278 $cookiesecure = $board_config['cookie_secure'];
280 $current_time = time();
283 if ( isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) || isset($HTTP_COOKIE_VARS[$cookiename . '_data']) )
285 $sessiondata = isset( $HTTP_COOKIE_VARS[$cookiename . '_data'] ) ? unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename . '_data'])) : array();
286 $session_id = isset( $HTTP_COOKIE_VARS[$cookiename . '_sid'] ) ? $HTTP_COOKIE_VARS[$cookiename . '_sid'] : '';
287 $sessionmethod = SESSION_METHOD_COOKIE;
291 $sessiondata = array();
292 $session_id = ( isset($HTTP_GET_VARS['sid']) ) ? $HTTP_GET_VARS['sid'] : '';
293 $sessionmethod = SESSION_METHOD_GET;
297 if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
302 $thispage_id = (int) $thispage_id;
305 // Does a session exist?
307 if ( !empty($session_id) )
310 // session_id exists so go ahead and attempt to grab all
311 // data in preparation
313 $sql = "SELECT u.*, s.*
314 FROM " . SESSIONS_TABLE . " s, " . USERS_TABLE . " u
315 WHERE s.session_id = '$session_id'
316 AND u.user_id = s.session_user_id";
317 if ( !($result = $db->sql_query($sql)) )
319 message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
322 $userdata = $db->sql_fetchrow($result);
325 // Did the session exist in the DB?
327 if ( isset($userdata['user_id']) )
330 // Do not check IP assuming equivalence, if IPv4 we'll check only first 24
331 // bits ... I've been told (by vHiker) this should alleviate problems with
332 // load balanced et al proxies while retaining some reliance on IP security.
334 $ip_check_s = substr($userdata['session_ip'], 0, 6);
335 $ip_check_u = substr($user_ip, 0, 6);
337 if ($ip_check_s == $ip_check_u)
339 $SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '';
342 // Only update session DB a minute or so after last update
344 if ( $current_time - $userdata['session_time'] > 60 )
346 // A little trick to reset session_admin on session re-usage
347 $update_admin = (!defined('IN_ADMIN') && $current_time - $userdata['session_time'] > ($board_config['session_length']+60)) ? ', session_admin = 0' : '';
349 $sql = "UPDATE " . SESSIONS_TABLE . "
350 SET session_time = $current_time, session_page = $thispage_id$update_admin
351 WHERE session_id = '" . $userdata['session_id'] . "'";
352 if ( !$db->sql_query($sql) )
354 message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
357 if ( $userdata['user_id'] != ANONYMOUS )
359 $sql = "UPDATE " . USERS_TABLE . "
360 SET user_session_time = $current_time, user_session_page = $thispage_id
361 WHERE user_id = " . $userdata['user_id'];
362 if ( !$db->sql_query($sql) )
364 message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
368 session_clean($userdata['session_id']);
370 setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
371 setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
380 // If we reach here then no (valid) session exists. So we'll create a new one,
381 // using the cookie user_id if available to pull basic user prefs.
383 $user_id = ( isset($sessiondata['userid']) ) ? intval($sessiondata['userid']) : ANONYMOUS;
385 if ( !($userdata = session_begin($user_id, $user_ip, $thispage_id, TRUE)) )
387 message_die(CRITICAL_ERROR, 'Error creating user session', '', __LINE__, __FILE__, $sql);
395 * Terminates the specified session
396 * It will delete the entry in the sessions table for this session,
397 * remove the corresponding auto-login key and reset the cookies
399 function session_end($session_id, $user_id)
401 global $db, $lang, $board_config, $userdata;
402 global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
404 $cookiename = $board_config['cookie_name'];
405 $cookiepath = $board_config['cookie_path'];
406 $cookiedomain = $board_config['cookie_domain'];
407 $cookiesecure = $board_config['cookie_secure'];
409 $current_time = time();
411 if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
417 // Delete existing session
419 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
420 WHERE session_id = '$session_id'
421 AND session_user_id = $user_id";
422 if ( !$db->sql_query($sql) )
424 message_die(CRITICAL_ERROR, 'Error removing user session', '', __LINE__, __FILE__, $sql);
428 // Remove this auto-login entry (if applicable)
430 if ( isset($userdata['session_key']) && $userdata['session_key'] != '' )
432 $autologin_key = md5($userdata['session_key']);
433 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
434 WHERE user_id = ' . (int) $user_id . "
435 AND key_id = '$autologin_key'";
436 if ( !$db->sql_query($sql) )
438 message_die(CRITICAL_ERROR, 'Error removing auto-login key', '', __LINE__, __FILE__, $sql);
443 // We expect that message_die will be called after this function,
444 // but just in case it isn't, reset $userdata to the details for a guest
447 FROM ' . USERS_TABLE . '
448 WHERE user_id = ' . ANONYMOUS;
449 if ( !($result = $db->sql_query($sql)) )
451 message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
453 if ( !($userdata = $db->sql_fetchrow($result)) )
455 message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
457 $db->sql_freeresult($result);
460 setcookie($cookiename . '_data', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
461 setcookie($cookiename . '_sid', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
467 * Removes expired sessions and auto-login keys from the database
469 function session_clean($session_id)
471 global $board_config, $db;
474 // Delete expired sessions
476 $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
477 WHERE session_time < ' . (time() - (int) $board_config['session_length']) . "
478 AND session_id <> '$session_id'";
479 if ( !$db->sql_query($sql) )
481 message_die(CRITICAL_ERROR, 'Error clearing sessions table', '', __LINE__, __FILE__, $sql);
485 // Delete expired auto-login keys
486 // If max_autologin_time is not set then keys will never be deleted
487 // (same behaviour as old 2.0.x session code)
489 if (!empty($board_config['max_autologin_time']) && $board_config['max_autologin_time'] > 0)
491 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
492 WHERE last_login < ' . (time() - (86400 * (int) $board_config['max_autologin_time']));
493 $db->sql_query($sql);
500 // Append $SID to a url. Borrowed from phplib and modified. This is an
501 // extra routine utilised by the session code above and acts as a wrapper
502 // around every single URL and form action. If you replace the session
503 // code you must include this routine, even if it's empty.
505 function append_sid($url, $non_html_amp = false)
509 if ( !empty($SID) && !preg_match('#sid=#', $url) )
511 $url .= ( ( strpos($url, '?') !== false ) ? ( ( $non_html_amp ) ? '&' : '&' ) : '?' ) . $SID;