]> scripts.mit.edu Git - autoinstalls/phpBB.git/blob - includes/sessions.php
phpBB 2.0.19
[autoinstalls/phpBB.git] / includes / sessions.php
1 <?php
2 /***************************************************************************
3  *                                sessions.php
4  *                            -------------------
5  *   begin                : Saturday, Feb 13, 2001
6  *   copyright            : (C) 2001 The phpBB Group
7  *   email                : support@phpbb.com
8  *
9  *   $Id: sessions.php,v 1.58.2.16 2005/10/30 15:17:14 acydburn Exp $
10  *
11  *
12  ***************************************************************************/
13
14 /***************************************************************************
15  *
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.
20  *
21  ***************************************************************************/
22
23 //
24 // Adds/updates a new session to the database for the given userid.
25 // Returns the new session ID on success.
26 //
27 function session_begin($user_id, $user_ip, $page_id, $auto_create = 0, $enable_autologin = 0, $admin = 0)
28 {
29         global $db, $board_config;
30         global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
31
32         $cookiename = $board_config['cookie_name'];
33         $cookiepath = $board_config['cookie_path'];
34         $cookiedomain = $board_config['cookie_domain'];
35         $cookiesecure = $board_config['cookie_secure'];
36
37         if ( isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) || isset($HTTP_COOKIE_VARS[$cookiename . '_data']) )
38         {
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;
42         }
43         else
44         {
45                 $sessiondata = array();
46                 $session_id = ( isset($HTTP_GET_VARS['sid']) ) ? $HTTP_GET_VARS['sid'] : '';
47                 $sessionmethod = SESSION_METHOD_GET;
48         }
49
50         //
51         if (!preg_match('/^[A-Za-z0-9]*$/', $session_id)) 
52         {
53                 $session_id = '';
54         }
55
56         $page_id = (int) $page_id;
57
58         $last_visit = 0;
59         $current_time = time();
60
61         //
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)
65         //
66         if (isset($board_config['allow_autologin']) && !$board_config['allow_autologin'])
67         {
68                 $enable_autologin = $sessiondata['autologinid'] = false;
69         }
70
71         // 
72         // First off attempt to join with the autologin value if we have one
73         // If not, just use the user_id value
74         //
75         $userdata = array();
76
77         if ($user_id != ANONYMOUS)
78         {
79                 if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '' && $user_id)
80                 {
81                         $sql = 'SELECT u.* 
82                                 FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
83                                 WHERE u.user_id = ' . (int) $user_id . "
84                                         AND u.user_active = 1
85                                         AND k.user_id = u.user_id
86                                         AND k.key_id = '" . md5($sessiondata['autologinid']) . "'";
87                         if (!($result = $db->sql_query($sql)))
88                         {
89                                 message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
90                         }
91
92                         $userdata = $db->sql_fetchrow($result);
93                         $db->sql_freeresult($result);
94                 
95                         $enable_autologin = $login = 1;
96                 }
97                 else if (!$auto_create)
98                 {
99                         $sessiondata['autologinid'] = '';
100                         $sessiondata['userid'] = $user_id;
101
102                         $sql = 'SELECT *
103                                 FROM ' . USERS_TABLE . '
104                                 WHERE user_id = ' . (int) $user_id . '
105                                         AND user_active = 1';
106                         if (!($result = $db->sql_query($sql)))
107                         {
108                                 message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
109                         }
110
111                         $userdata = $db->sql_fetchrow($result);
112                         $db->sql_freeresult($result);
113
114                         $login = 1;
115                 }
116         }
117
118         //
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
124         //
125         if (!sizeof($userdata) || !is_array($userdata) || !$userdata)
126         {
127                 $sessiondata['autologinid'] = '';
128                 $sessiondata['userid'] = $user_id = ANONYMOUS;
129                 $enable_autologin = $login = 0;
130
131                 $sql = 'SELECT *
132                         FROM ' . USERS_TABLE . '
133                         WHERE user_id = ' . (int) $user_id;
134                 if (!($result = $db->sql_query($sql)))
135                 {
136                         message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
137                 }
138
139                 $userdata = $db->sql_fetchrow($result);
140                 $db->sql_freeresult($result);
141         }
142
143
144         //
145         // Initial ban check against user id, IP and email address
146         //
147         preg_match('/(..)(..)(..)(..)/', $user_ip, $user_ip_parts);
148
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 )
154         {
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']), "@")) . "'";
157         }
158         if ( !($result = $db->sql_query($sql)) )
159         {
160                 message_die(CRITICAL_ERROR, 'Could not obtain ban information', '', __LINE__, __FILE__, $sql);
161         }
162
163         if ( $ban_info = $db->sql_fetchrow($result) )
164         {
165                 if ( $ban_info['ban_ip'] || $ban_info['ban_userid'] || $ban_info['ban_email'] )
166                 {
167                         message_die(CRITICAL_MESSAGE, 'You_been_banned');
168                 }
169         }
170
171         //
172         // Create or update the session
173         //
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() )
179         {
180                 list($sec, $usec) = explode(' ', microtime());
181                 mt_srand((float) $sec + ((float) $usec * 100000));
182                 $session_id = md5(uniqid(mt_rand(), true));
183
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) )
188                 {
189                         message_die(CRITICAL_ERROR, 'Error creating new session', '', __LINE__, __FILE__, $sql);
190                 }
191         }
192
193         if ( $user_id != ANONYMOUS )
194         {
195                 $last_visit = ( $userdata['user_session_time'] > 0 ) ? $userdata['user_session_time'] : $current_time; 
196
197                 if (!$admin)
198                 {
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) )
203                         {
204                                 message_die(CRITICAL_ERROR, 'Error updating last visit time', '', __LINE__, __FILE__, $sql);
205                         }
206                 }
207
208                 $userdata['user_lastvisit'] = $last_visit;
209
210                 //
211                 // Regenerate the auto-login key
212                 //
213                 if ($enable_autologin)
214                 {
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);
218                         
219                         if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '')
220                         {
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']) . "'";
224                         }
225                         else
226                         {
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)";
229                         }
230
231                         if ( !$db->sql_query($sql) )
232                         {
233                                 message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
234                         }
235                         
236                         $sessiondata['autologinid'] = $auto_login_key;
237                         unset($auto_login_key);
238                 }
239                 else
240                 {
241                         $sessiondata['autologinid'] = '';
242                 }
243
244 //              $sessiondata['autologinid'] = (!$admin) ? (( $enable_autologin && $sessionmethod == SESSION_METHOD_COOKIE ) ? $auto_login_key : '') : $sessiondata['autologinid'];
245                 $sessiondata['userid'] = $user_id;
246         }
247
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'];
257
258         setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
259         setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
260
261         $SID = 'sid=' . $session_id;
262
263         return $userdata;
264 }
265
266 //
267 // Checks for a given user session, tidies session table and updates user
268 // sessions at each page refresh
269 //
270 function session_pagestart($user_ip, $thispage_id)
271 {
272         global $db, $lang, $board_config;
273         global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
274
275         $cookiename = $board_config['cookie_name'];
276         $cookiepath = $board_config['cookie_path'];
277         $cookiedomain = $board_config['cookie_domain'];
278         $cookiesecure = $board_config['cookie_secure'];
279
280         $current_time = time();
281         unset($userdata);
282
283         if ( isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) || isset($HTTP_COOKIE_VARS[$cookiename . '_data']) )
284         {
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;
288         }
289         else
290         {
291                 $sessiondata = array();
292                 $session_id = ( isset($HTTP_GET_VARS['sid']) ) ? $HTTP_GET_VARS['sid'] : '';
293                 $sessionmethod = SESSION_METHOD_GET;
294         }
295
296         // 
297         if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
298         {
299                 $session_id = '';
300         }
301
302         $thispage_id = (int) $thispage_id;
303
304         //
305         // Does a session exist?
306         //
307         if ( !empty($session_id) )
308         {
309                 //
310                 // session_id exists so go ahead and attempt to grab all
311                 // data in preparation
312                 //
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)) )
318                 {
319                         message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
320                 }
321
322                 $userdata = $db->sql_fetchrow($result);
323
324                 //
325                 // Did the session exist in the DB?
326                 //
327                 if ( isset($userdata['user_id']) )
328                 {
329                         //
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.
333                         //
334                         $ip_check_s = substr($userdata['session_ip'], 0, 6);
335                         $ip_check_u = substr($user_ip, 0, 6);
336
337                         if ($ip_check_s == $ip_check_u)
338                         {
339                                 $SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '';
340
341                                 //
342                                 // Only update session DB a minute or so after last update
343                                 //
344                                 if ( $current_time - $userdata['session_time'] > 60 )
345                                 {
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' : '';
348
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) )
353                                         {
354                                                 message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
355                                         }
356
357                                         if ( $userdata['user_id'] != ANONYMOUS )
358                                         {
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) )
363                                                 {
364                                                         message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
365                                                 }
366                                         }
367
368                                         session_clean($userdata['session_id']);
369
370                                         setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
371                                         setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
372                                 }
373
374                                 return $userdata;
375                         }
376                 }
377         }
378
379         //
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.
382         //
383         $user_id = ( isset($sessiondata['userid']) ) ? intval($sessiondata['userid']) : ANONYMOUS;
384
385         if ( !($userdata = session_begin($user_id, $user_ip, $thispage_id, TRUE)) )
386         {
387                 message_die(CRITICAL_ERROR, 'Error creating user session', '', __LINE__, __FILE__, $sql);
388         }
389
390         return $userdata;
391
392 }
393
394 /**
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
398 */
399 function session_end($session_id, $user_id)
400 {
401         global $db, $lang, $board_config, $userdata;
402         global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
403
404         $cookiename = $board_config['cookie_name'];
405         $cookiepath = $board_config['cookie_path'];
406         $cookiedomain = $board_config['cookie_domain'];
407         $cookiesecure = $board_config['cookie_secure'];
408
409         $current_time = time();
410
411         if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
412         {
413                 return;
414         }
415         
416         //
417         // Delete existing session
418         //
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) )
423         {
424                 message_die(CRITICAL_ERROR, 'Error removing user session', '', __LINE__, __FILE__, $sql);
425         }
426
427         //
428         // Remove this auto-login entry (if applicable)
429         //
430         if ( isset($userdata['session_key']) && $userdata['session_key'] != '' )
431         {
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) )
437                 {
438                         message_die(CRITICAL_ERROR, 'Error removing auto-login key', '', __LINE__, __FILE__, $sql);
439                 }
440         }
441
442         //
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
445         //
446         $sql = 'SELECT *
447                 FROM ' . USERS_TABLE . '
448                 WHERE user_id = ' . ANONYMOUS;
449         if ( !($result = $db->sql_query($sql)) )
450         {
451                 message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
452         }
453         if ( !($userdata = $db->sql_fetchrow($result)) )
454         {
455                 message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
456         }
457         $db->sql_freeresult($result);
458
459
460         setcookie($cookiename . '_data', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
461         setcookie($cookiename . '_sid', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
462
463         return true;
464 }
465
466 /**
467 * Removes expired sessions and auto-login keys from the database
468 */
469 function session_clean($session_id)
470 {
471         global $board_config, $db;
472
473         //
474         // Delete expired sessions
475         //
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) )
480         {
481                 message_die(CRITICAL_ERROR, 'Error clearing sessions table', '', __LINE__, __FILE__, $sql);
482         }
483
484         //
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)
488         //
489         if (!empty($board_config['max_autologin_time']) && $board_config['max_autologin_time'] > 0)
490         {
491                 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
492                         WHERE last_login < ' . (time() - (86400 * (int) $board_config['max_autologin_time']));
493                 $db->sql_query($sql);
494         }
495
496         return true;
497 }
498
499 //
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.
504 //
505 function append_sid($url, $non_html_amp = false)
506 {
507         global $SID;
508
509         if ( !empty($SID) && !preg_match('#sid=#', $url) )
510         {
511                 $url .= ( ( strpos($url, '?') !== false ) ?  ( ( $non_html_amp ) ? '&' : '&amp;' ) : '?' ) . $SID;
512         }
513
514         return $url;
515 }
516
517 ?>