Rev Author Line No. Line
130 kaklik 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.25 2006/05/18 19:23:07 grahamje 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 $session_id = md5(dss_rand());
181  
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) )
186 {
187 message_die(CRITICAL_ERROR, 'Error creating new session', '', __LINE__, __FILE__, $sql);
188 }
189 }
190  
191 if ( $user_id != ANONYMOUS )
192 {
193 $last_visit = ( $userdata['user_session_time'] > 0 ) ? $userdata['user_session_time'] : $current_time;
194  
195 if (!$admin)
196 {
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) )
201 {
202 message_die(CRITICAL_ERROR, 'Error updating last visit time', '', __LINE__, __FILE__, $sql);
203 }
204 }
205  
206 $userdata['user_lastvisit'] = $last_visit;
207  
208 //
209 // Regenerate the auto-login key
210 //
211 if ($enable_autologin)
212 {
213 $auto_login_key = dss_rand() . dss_rand();
214  
215 if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '')
216 {
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']) . "'";
220 }
221 else
222 {
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)";
225 }
226  
227 if ( !$db->sql_query($sql) )
228 {
229 message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
230 }
231  
232 $sessiondata['autologinid'] = $auto_login_key;
233 unset($auto_login_key);
234 }
235 else
236 {
237 $sessiondata['autologinid'] = '';
238 }
239  
240 // $sessiondata['autologinid'] = (!$admin) ? (( $enable_autologin && $sessionmethod == SESSION_METHOD_COOKIE ) ? $auto_login_key : '') : $sessiondata['autologinid'];
241 $sessiondata['userid'] = $user_id;
242 }
243  
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'];
253  
254 setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
255 setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
256  
257 $SID = 'sid=' . $session_id;
258  
259 return $userdata;
260 }
261  
262 //
263 // Checks for a given user session, tidies session table and updates user
264 // sessions at each page refresh
265 //
266 function session_pagestart($user_ip, $thispage_id)
267 {
268 global $db, $lang, $board_config;
269 global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
270  
271 $cookiename = $board_config['cookie_name'];
272 $cookiepath = $board_config['cookie_path'];
273 $cookiedomain = $board_config['cookie_domain'];
274 $cookiesecure = $board_config['cookie_secure'];
275  
276 $current_time = time();
277 unset($userdata);
278  
279 if ( isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) || isset($HTTP_COOKIE_VARS[$cookiename . '_data']) )
280 {
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;
284 }
285 else
286 {
287 $sessiondata = array();
288 $session_id = ( isset($HTTP_GET_VARS['sid']) ) ? $HTTP_GET_VARS['sid'] : '';
289 $sessionmethod = SESSION_METHOD_GET;
290 }
291  
292 //
293 if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
294 {
295 $session_id = '';
296 }
297  
298 $thispage_id = (int) $thispage_id;
299  
300 //
301 // Does a session exist?
302 //
303 if ( !empty($session_id) )
304 {
305 //
306 // session_id exists so go ahead and attempt to grab all
307 // data in preparation
308 //
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)) )
314 {
315 message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
316 }
317  
318 $userdata = $db->sql_fetchrow($result);
319  
320 //
321 // Did the session exist in the DB?
322 //
323 if ( isset($userdata['user_id']) )
324 {
325 //
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.
329 //
330 $ip_check_s = substr($userdata['session_ip'], 0, 6);
331 $ip_check_u = substr($user_ip, 0, 6);
332  
333 if ($ip_check_s == $ip_check_u)
334 {
335 $SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '';
336  
337 //
338 // Only update session DB a minute or so after last update
339 //
340 if ( $current_time - $userdata['session_time'] > 60 )
341 {
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' : '';
344  
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) )
349 {
350 message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
351 }
352  
353 if ( $userdata['user_id'] != ANONYMOUS )
354 {
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) )
359 {
360 message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
361 }
362 }
363  
364 session_clean($userdata['session_id']);
365  
366 setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
367 setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
368 }
369  
370 // Add the session_key to the userdata array if it is set
371 if ( isset($sessiondata['autologinid']) && $sessiondata['autologinid'] != '' )
372 {
373 $userdata['session_key'] = $sessiondata['autologinid'];
374 }
375  
376 return $userdata;
377 }
378 }
379 }
380  
381 //
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.
384 //
385 $user_id = ( isset($sessiondata['userid']) ) ? intval($sessiondata['userid']) : ANONYMOUS;
386  
387 if ( !($userdata = session_begin($user_id, $user_ip, $thispage_id, TRUE)) )
388 {
389 message_die(CRITICAL_ERROR, 'Error creating user session', '', __LINE__, __FILE__, $sql);
390 }
391  
392 return $userdata;
393  
394 }
395  
396 /**
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
400 */
401 function session_end($session_id, $user_id)
402 {
403 global $db, $lang, $board_config, $userdata;
404 global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
405  
406 $cookiename = $board_config['cookie_name'];
407 $cookiepath = $board_config['cookie_path'];
408 $cookiedomain = $board_config['cookie_domain'];
409 $cookiesecure = $board_config['cookie_secure'];
410  
411 $current_time = time();
412  
413 if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
414 {
415 return;
416 }
417  
418 //
419 // Delete existing session
420 //
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) )
425 {
426 message_die(CRITICAL_ERROR, 'Error removing user session', '', __LINE__, __FILE__, $sql);
427 }
428  
429 //
430 // Remove this auto-login entry (if applicable)
431 //
432 if ( isset($userdata['session_key']) && $userdata['session_key'] != '' )
433 {
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) )
439 {
440 message_die(CRITICAL_ERROR, 'Error removing auto-login key', '', __LINE__, __FILE__, $sql);
441 }
442 }
443  
444 //
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
447 //
448 $sql = 'SELECT *
449 FROM ' . USERS_TABLE . '
450 WHERE user_id = ' . ANONYMOUS;
451 if ( !($result = $db->sql_query($sql)) )
452 {
453 message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
454 }
455 if ( !($userdata = $db->sql_fetchrow($result)) )
456 {
457 message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
458 }
459 $db->sql_freeresult($result);
460  
461  
462 setcookie($cookiename . '_data', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
463 setcookie($cookiename . '_sid', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
464  
465 return true;
466 }
467  
468 /**
469 * Removes expired sessions and auto-login keys from the database
470 */
471 function session_clean($session_id)
472 {
473 global $board_config, $db;
474  
475 //
476 // Delete expired sessions
477 //
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) )
482 {
483 message_die(CRITICAL_ERROR, 'Error clearing sessions table', '', __LINE__, __FILE__, $sql);
484 }
485  
486 //
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)
490 //
491 if (!empty($board_config['max_autologin_time']) && $board_config['max_autologin_time'] > 0)
492 {
493 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
494 WHERE last_login < ' . (time() - (86400 * (int) $board_config['max_autologin_time']));
495 $db->sql_query($sql);
496 }
497  
498 return true;
499 }
500  
501 /**
502 * Reset all login keys for the specified user
503 * Called on password changes
504 */
505 function session_reset_keys($user_id, $user_ip)
506 {
507 global $db, $userdata, $board_config;
508  
509 $key_sql = ($user_id == $userdata['user_id'] && !empty($userdata['session_key'])) ? "AND key_id != '" . md5($userdata['session_key']) . "'" : '';
510  
511 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
512 WHERE user_id = ' . (int) $user_id . "
513 $key_sql";
514  
515 if ( !$db->sql_query($sql) )
516 {
517 message_die(CRITICAL_ERROR, 'Error removing auto-login keys', '', __LINE__, __FILE__, $sql);
518 }
519  
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 . "
523 WHERE $where_sql";
524 if ( !$db->sql_query($sql) )
525 {
526 message_die(CRITICAL_ERROR, 'Error removing user session(s)', '', __LINE__, __FILE__, $sql);
527 }
528  
529 if ( !empty($key_sql) )
530 {
531 $auto_login_key = dss_rand() . dss_rand();
532  
533 $current_time = time();
534  
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']) . "'";
538  
539 if ( !$db->sql_query($sql) )
540 {
541 message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
542 }
543  
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'];
551  
552 setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
553  
554 $userdata['session_key'] = $auto_login_key;
555 unset($sessiondata);
556 unset($auto_login_key);
557 }
558 }
559  
560 //
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.
565 //
566 function append_sid($url, $non_html_amp = false)
567 {
568 global $SID;
569  
570 if ( !empty($SID) && !preg_match('#sid=#', $url) )
571 {
572 $url .= ( ( strpos($url, '?') !== false ) ? ( ( $non_html_amp ) ? '&' : '&amp;' ) : '?' ) . $SID;
573 }
574  
575 return $url;
576 }
577  
578 ?>