comment with intendation
[phpbb.git] / phpBB / includes / classes / session.php
blobb8f829efd58013e51a0dc1499342f1576d303015
1 <?php
2 /**
4 * @package phpBB3
5 * @version $Id$
6 * @copyright (c) 2005, 2008 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 */
11 /**
12 * @ignore
14 if (!defined('IN_PHPBB'))
16 exit;
19 /**
20 * Session class
21 * @package phpBB3
23 abstract class phpbb_session
25 /**
26 * @var array Cookie informations
28 private $cookie_data = array();
30 /**
31 * @var array User data
33 public $data = array();
35 /**
36 * @var string Session id
38 public $session_id = '';
40 /**
41 * @var int Current time
43 public $time_now = 0;
45 /**
46 * @var bool True if the current page is updated within the sessions table
48 public $update_session_page = true;
50 /**
51 * @var mixed Reference to authentication system.
53 public $auth = NULL;
55 /**
56 * @var mixed Reference to system array for obtaining server/system information
58 public $system = NULL;
60 /**
61 * @var bool Is true if the user is a logged in registered user
63 public $is_registered = false;
65 /**
66 * @var bool Is true if the user is logged in and a search engine/bot
68 public $is_bot = false;
70 /**
71 * @var array Extra url parameter to append to every URL in phpBB
73 public $extra_url = array();
75 /**
76 * @var bool If this is true then the session id (?sid=[session_id]) is required
78 public $need_sid = false;
80 /**
81 * Init session. Empties the user data and assigns the system object (phpbb::$instances['system'])
82 * @access public
84 public function __construct()
86 // Reset data array ;)
87 $this->data = array();
89 // Set auth to false (only valid for an user object)
90 $this->auth = false;
92 // Some system/server variables, directly generated by phpbb_system methods. Used like an array.
93 // We use the phpbb:: one, because it could've been modified and being a completely different class
94 $this->system = &phpbb::$instances['system'];
97 /**
98 * Specifiy the need for a session id within the URL
100 * @param bool $need_sid Specify if the session id is needed or not. Default is false.
101 * @access public
103 public function need_sid($need_sid = false)
105 $this->need_sid = $need_sid;
109 * Start session management
111 * This is where all session activity begins. We gather various pieces of
112 * information from the client and server. We test to see if a session already
113 * exists. If it does, fine and dandy. If it doesn't we'll go on to create a
114 * new one ... pretty logical heh? We also examine the system load (if we're
115 * running on a system which makes such information readily available) and
116 * halt if it's above an admin definable limit.
118 * @param bool $update_session_page If true the session page gets updated.
119 * This can be set to false to circumvent certain scripts to update the users last visited page.
121 * @return bool True if the session exist or has been created, else False.
122 * @access public
124 public function session_begin($update_session_page = true)
126 // Give us some basic information
127 $this->time_now = time();
128 $this->cookie_data = array('u' => 0, 'k' => '');
129 $this->update_session_page = $update_session_page;
131 if (request::is_set(phpbb::$config['cookie_name'] . '_sid', request::COOKIE) || request::is_set(phpbb::$config['cookie_name'] . '_u', request::COOKIE))
133 $this->cookie_data['u'] = request_var(phpbb::$config['cookie_name'] . '_u', 0, false, true);
134 $this->cookie_data['k'] = request_var(phpbb::$config['cookie_name'] . '_k', '', false, true);
135 $this->session_id = request_var(phpbb::$config['cookie_name'] . '_sid', '', false, true);
137 if (empty($this->session_id))
139 $this->session_id = request_var('sid', '');
140 $this->cookie_data = array('u' => 0, 'k' => '');
141 $this->need_sid = true;
144 else
146 $this->session_id = request_var('sid', '');
147 $this->need_sid = true;
150 $this->extra_url = array();
152 // Now check for an existing session
153 if ($this->session_exist())
155 return true;
158 // If we reach here then no (valid) session exists. So we'll create a new one
159 return $this->session_create();
163 * Create a new session
165 * If upon trying to start a session we discover there is nothing existing we
166 * jump here. Additionally this method is called directly during login to regenerate
167 * the session for the specific user. In this method we carry out a number of tasks;
168 * garbage collection, (search)bot checking, banned user comparison. Basically
169 * though this method will result in a new session for a specific user.
171 * @param int $user_id The user id to create the session for.
172 * @param bool $set_admin Set the users admin field to identify him/her as an admin?
173 * @param bool $persist_login Allow persistent login
174 * @param bool $viewonline If false then the user will be logged in as hidden
176 * @return bool True if session got created successfully.
177 * @access public
179 public function session_create($user_id = false, $set_admin = false, $persist_login = false, $viewonline = true)
181 // There is one case where we need to add a "failsafe" user... when we are not able to query the database
182 if (!phpbb::registered('db'))
184 $this->data = $this->default_data();
185 return true;
188 // If the data array is filled, chances are high that there was a different session active
189 if (sizeof($this->data))
191 // Kill the session and do not create a new one
192 $this->session_kill(false);
195 $this->data = array();
197 // Do we allow autologin on this board? No? Then override anything
198 // that may be requested here
199 if (!phpbb::$config['allow_autologin'])
201 $this->cookie_data['k'] = $persist_login = false;
204 // Check for autologin key. ;)
205 if ($this->auth !== false && method_exists($this->auth, 'autologin'))
207 $this->data = $this->auth->autologin();
209 if (sizeof($this->data))
211 $this->cookie_data['k'] = '';
212 $this->cookie_data['u'] = $this->data['user_id'];
216 // NULL indicates we need to check for a bot later. Sometimes it is apparant that it is not a bot. ;) No need to always check this.
217 $bot = NULL;
219 // If we're presented with an autologin key we'll join against it.
220 // Else if we've been passed a user_id we'll grab data based on that
221 if (isset($this->cookie_data['k']) && $this->cookie_data['k'] && $this->cookie_data['u'] && !sizeof($this->data))
223 $sql = 'SELECT u.*
224 FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
225 WHERE u.user_id = ' . (int) $this->cookie_data['u'] . '
226 AND u.user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ")
227 AND k.user_id = u.user_id
228 AND k.key_id = '" . phpbb::$db->sql_escape(md5($this->cookie_data['k'])) . "'";
229 $result = phpbb::$db->sql_query($sql);
230 $this->data = phpbb::$db->sql_fetchrow($result);
231 phpbb::$db->sql_freeresult($result);
233 $bot = false;
235 else if ($user_id !== false && !sizeof($this->data))
237 $this->cookie_data['k'] = '';
238 $this->cookie_data['u'] = $user_id;
240 $sql = 'SELECT *
241 FROM ' . USERS_TABLE . '
242 WHERE user_id = ' . (int) $this->cookie_data['u'] . '
243 AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')';
244 $result = phpbb::$db->sql_query($sql);
245 $this->data = phpbb::$db->sql_fetchrow($result);
246 phpbb::$db->sql_freeresult($result);
248 $bot = false;
251 if ($bot === NULL)
253 $bot = $this->check_bot();
256 // If no data was returned one or more of the following occurred:
257 // Key didn't match one in the DB
258 // User does not exist
259 // User is inactive
260 // User is bot
261 if (!sizeof($this->data) || !is_array($this->data))
263 $this->cookie_data['k'] = '';
264 $this->cookie_data['u'] = ($bot) ? $bot : ANONYMOUS;
266 if (!$bot)
268 $sql = 'SELECT *
269 FROM ' . USERS_TABLE . '
270 WHERE user_id = ' . (int) $this->cookie_data['u'];
272 else
274 // We give bots always the same session if it is not yet expired.
275 $sql = 'SELECT u.*, s.*
276 FROM ' . USERS_TABLE . ' u
277 LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
278 WHERE u.user_id = ' . (int) $bot;
281 $result = phpbb::$db->sql_query($sql);
282 $this->data = phpbb::$db->sql_fetchrow($result);
283 phpbb::$db->sql_freeresult($result);
285 $this->is_registered = false;
287 else
289 $this->is_registered = true;
292 // Force user id to be integer...
293 $this->data['user_id'] = (int) $this->data['user_id'];
295 // Code for ANONYMOUS user, INACTIVE user and BOTS
296 if (!$this->is_registered)
298 // Set last visit date to 'now'
299 $this->data['session_last_visit'] = $this->time_now;
300 $this->is_bot = ($bot) ? true : false;
302 // If our friend is a bot, we re-assign a previously assigned session
303 if ($this->is_bot && $bot == $this->data['user_id'] && $this->data['session_id'])
305 if ($this->session_valid(false))
307 $this->session_id = $this->data['session_id'];
309 // Only update session DB a minute or so after last update or if page changes
310 if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->system['page']['page']))
312 $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
313 $sql_ary = array('session_time' => $this->time_now, 'session_last_visit' => $this->time_now, 'session_admin' => 0);
315 if ($this->update_session_page)
317 $sql_ary['session_page'] = substr($this->system['page']['page'], 0, 199);
320 $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . phpbb::$db->sql_build_array('UPDATE', $sql_ary) . "
321 WHERE session_id = '" . phpbb::$db->sql_escape($this->session_id) . "'";
322 phpbb::$db->sql_query($sql);
324 // Update the last visit time
325 $sql = 'UPDATE ' . USERS_TABLE . '
326 SET user_lastvisit = ' . (int) $this->data['session_time'] . '
327 WHERE user_id = ' . (int) $this->data['user_id'];
328 phpbb::$db->sql_query($sql);
331 $this->session_id = '';
333 return true;
335 else
337 // If the ip and browser does not match make sure we only have one bot assigned to one session
338 phpbb::$db->sql_query('DELETE FROM ' . SESSIONS_TABLE . ' WHERE session_user_id = ' . $this->data['user_id']);
342 else
344 // Code for registered users
345 $this->data['session_last_visit'] = (!empty($this->data['session_time'])) ? $this->data['session_time'] : (($this->data['user_lastvisit']) ? $this->data['user_lastvisit'] : $this->time_now);
346 $this->is_bot = false;
349 // At this stage we should have a filled data array, defined cookie u and k data.
350 // data array should contain recent session info if we're a real user and a recent
351 // session exists in which case session_id will also be set
353 // Is user banned? Are they excluded? Won't return on ban, exists within method
354 if ($this->data['user_type'] != USER_FOUNDER)
356 if (!phpbb::$config['forwarded_for_check'])
358 $this->check_ban($this->data['user_id'], $this->system['ip']);
360 else
362 $ips = explode(', ', $this->forwarded_for);
363 $ips[] = $this->system['ip'];
364 $this->check_ban($this->data['user_id'], $ips);
368 $session_autologin = (($this->cookie_data['k'] || $persist_login) && $this->is_registered) ? true : false;
369 $set_admin = ($set_admin && $this->is_registered) ? true : false;
371 // Create or update the session
372 $sql_ary = array(
373 'session_user_id' => (int) $this->data['user_id'],
374 'session_start' => (int) $this->time_now,
375 'session_last_visit' => (int) $this->data['session_last_visit'],
376 'session_time' => (int) $this->time_now,
377 'session_browser' => (string) trim(substr($this->system['browser'], 0, 149)),
378 'session_forwarded_for' => (string) $this->system['forwarded_for'],
379 'session_ip' => (string) $this->system['ip'],
380 'session_autologin' => ($session_autologin) ? 1 : 0,
381 'session_admin' => ($set_admin) ? 1 : 0,
382 'session_viewonline' => ($viewonline) ? 1 : 0,
385 if ($this->update_session_page)
387 $sql_ary['session_page'] = (string) substr($this->system['page']['page'], 0, 199);
390 phpbb::$db->sql_return_on_error(true);
392 // Delete old session, if user id now different from anonymous
393 if (!defined('IN_ERROR_HANDLER'))
395 // We do not care about the user id, because we assign a new session later
396 $sql = 'DELETE
397 FROM ' . SESSIONS_TABLE . "
398 WHERE session_id = '" . phpbb::$db->sql_escape($this->session_id) . "'";
399 $result = phpbb::$db->sql_query($sql);
401 // If there were no sessions or the session id empty (then the affected rows will be empty too), then we have a brand new session and can check the active sessions limit
402 if ((!$result || !phpbb::$db->sql_affectedrows()) && (empty($this->data['session_time']) && phpbb::$config['active_sessions']))
404 $sql = 'SELECT COUNT(session_id) AS sessions
405 FROM ' . SESSIONS_TABLE . '
406 WHERE session_time >= ' . ($this->time_now - 60);
407 $result = phpbb::$db->sql_query($sql);
408 $row = phpbb::$db->sql_fetchrow($result);
409 phpbb::$db->sql_freeresult($result);
411 if ((int) $row['sessions'] > (int) phpbb::$config['active_sessions'])
413 header('HTTP/1.1 503 Service Unavailable');
414 trigger_error('BOARD_UNAVAILABLE');
419 $this->session_id = $this->data['session_id'] = md5(phpbb::$security->unique_id());
421 $sql_ary['session_id'] = (string) $this->session_id;
423 $sql = 'INSERT INTO ' . SESSIONS_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', $sql_ary);
424 phpbb::$db->sql_query($sql);
426 phpbb::$db->sql_return_on_error(false);
428 // Regenerate autologin/persistent login key
429 if ($session_autologin)
431 $this->set_login_key();
434 // refresh data
435 $this->data = array_merge($this->data, $sql_ary);
437 if (!$bot)
439 $cookie_expire = $this->time_now + ((phpbb::$config['max_autologin_time']) ? 86400 * (int) phpbb::$config['max_autologin_time'] : 31536000);
441 $this->set_cookie('u', $this->cookie_data['u'], $cookie_expire);
442 $this->set_cookie('k', $this->cookie_data['k'], $cookie_expire);
443 $this->set_cookie('sid', $this->session_id, $cookie_expire);
445 unset($cookie_expire);
447 // Only one session entry present...
448 $sql = 'SELECT COUNT(session_id) AS sessions
449 FROM ' . SESSIONS_TABLE . '
450 WHERE session_user_id = ' . (int) $this->data['user_id'] . '
451 AND session_time >= ' . (int) ($this->time_now - (max(phpbb::$config['session_length'], phpbb::$config['form_token_lifetime'])));
452 $result = phpbb::$db->sql_query($sql);
453 $row = phpbb::$db->sql_fetchrow($result);
454 phpbb::$db->sql_freeresult($result);
456 if ((int) $row['sessions'] <= 1 || empty($this->data['user_form_salt']))
458 $this->data['user_form_salt'] = phpbb::$security->unique_id();
460 // Update the form key
461 $sql = 'UPDATE ' . USERS_TABLE . '
462 SET user_form_salt = \'' . phpbb::$db->sql_escape($this->data['user_form_salt']) . '\'
463 WHERE user_id = ' . (int) $this->data['user_id'];
464 phpbb::$db->sql_query($sql);
467 else
469 $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
471 // Update the last visit time
472 $sql = 'UPDATE ' . USERS_TABLE . '
473 SET user_lastvisit = ' . (int) $this->data['session_time'] . '
474 WHERE user_id = ' . (int) $this->data['user_id'];
475 phpbb::$db->sql_query($sql);
477 $this->session_id = '';
480 return true;
484 * Kills a session
486 * This method does what it says on the tin. It will delete a pre-existing session.
487 * It resets cookie information (destroying any autologin key within that cookie data)
488 * and update the users information from the relevant session data. It will then
489 * grab guest user information.
491 * @param bool $new_session If true a new session will be generated after the original one got killed.
492 * @access public
494 public function session_kill($new_session = true)
496 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
497 WHERE session_id = '" . phpbb::$db->sql_escape($this->session_id) . "'
498 AND session_user_id = " . (int) $this->data['user_id'];
499 phpbb::$db->sql_query($sql);
501 // Allow connecting logout with external auth method logout
502 if ($this->auth !== false && method_exists($this->auth, 'logout'))
504 $this->auth->logout($this, $new_session);
507 if ($this->data['user_id'] != ANONYMOUS)
509 // Delete existing session, update last visit info first!
510 if (!isset($this->data['session_time']))
512 $this->data['session_time'] = time();
515 $sql = 'UPDATE ' . USERS_TABLE . '
516 SET user_lastvisit = ' . (int) $this->data['session_time'] . '
517 WHERE user_id = ' . (int) $this->data['user_id'];
518 phpbb::$db->sql_query($sql);
520 if ($this->cookie_data['k'])
522 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
523 WHERE user_id = ' . (int) $this->data['user_id'] . "
524 AND key_id = '" . phpbb::$db->sql_escape(md5($this->cookie_data['k'])) . "'";
525 phpbb::$db->sql_query($sql);
528 // Reset the data array
529 $this->data = array();
531 $sql = 'SELECT *
532 FROM ' . USERS_TABLE . '
533 WHERE user_id = ' . ANONYMOUS;
534 $result = phpbb::$db->sql_query($sql);
535 $this->data = phpbb::$db->sql_fetchrow($result);
536 phpbb::$db->sql_freeresult($result);
539 $cookie_expire = $this->time_now - 31536000;
540 $this->set_cookie('u', '', $cookie_expire);
541 $this->set_cookie('k', '', $cookie_expire);
542 $this->set_cookie('sid', '', $cookie_expire);
543 unset($cookie_expire);
545 $this->session_id = '';
547 // To make sure a valid session is created we create one for the anonymous user
548 if ($new_session)
550 $this->session_create(ANONYMOUS);
555 * Session garbage collection
557 * This looks a lot more complex than it really is. Effectively we are
558 * deleting any sessions older than an admin definable limit. Due to the
559 * way in which we maintain session data we have to ensure we update user
560 * data before those sessions are destroyed. In addition this method
561 * removes autologin key information that is older than an admin defined
562 * limit.
564 * @access public
566 public function session_gc()
568 $batch_size = 10;
570 if (!$this->time_now)
572 $this->time_now = time();
575 // Firstly, delete guest sessions
576 $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
577 WHERE session_user_id = ' . ANONYMOUS . '
578 AND session_time < ' . (int) ($this->time_now - phpbb::$config['session_length']);
579 phpbb::$db->sql_query($sql);
581 // Get expired sessions, only most recent for each user
582 $sql = 'SELECT session_user_id, session_page, MAX(session_time) AS recent_time
583 FROM ' . SESSIONS_TABLE . '
584 WHERE session_time < ' . ($this->time_now - phpbb::$config['session_length']) . '
585 GROUP BY session_user_id, session_page';
586 $result = phpbb::$db->sql_query_limit($sql, $batch_size);
588 $del_user_id = array();
589 $del_sessions = 0;
591 while ($row = phpbb::$db->sql_fetchrow($result))
593 $sql = 'UPDATE ' . USERS_TABLE . '
594 SET user_lastvisit = ' . (int) $row['recent_time'] . ", user_lastpage = '" . phpbb::$db->sql_escape($row['session_page']) . "'
595 WHERE user_id = " . (int) $row['session_user_id'];
596 phpbb::$db->sql_query($sql);
598 $del_user_id[] = (int) $row['session_user_id'];
599 $del_sessions++;
601 phpbb::$db->sql_freeresult($result);
603 if (sizeof($del_user_id))
605 // Delete expired sessions
606 $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
607 WHERE ' . phpbb::$db->sql_in_set('session_user_id', $del_user_id) . '
608 AND session_time < ' . ($this->time_now - phpbb::$config['session_length']);
609 phpbb::$db->sql_query($sql);
612 if ($del_sessions < $batch_size)
614 // Less than 10 users, update gc timer ... else we want gc
615 // called again to delete other sessions
616 set_config('session_last_gc', $this->time_now, true);
618 if (phpbb::$config['max_autologin_time'])
620 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
621 WHERE last_login < ' . (time() - (86400 * (int) phpbb::$config['max_autologin_time']));
622 phpbb::$db->sql_query($sql);
625 // only called from CRON; should be a safe workaround until the infrastructure gets going
626 if (!class_exists('captcha_factory'))
628 include(PHPBB_ROOT_PATH . "includes/captcha/captcha_factory." . PHP_EXT);
630 captcha_factory::garbage_collect(phpbb::$config['captcha_plugin']);
633 return;
638 * Sets a cookie of the given name with the specified data for the given length of time. If no time is specified, a session cookie will be set.
640 * @param string $name Name of the cookie, will be automatically prefixed with the phpBB cookie name. Track becomes [cookie_name]_track then.
641 * @param string $cookiedata The data to hold within the cookie
642 * @param int $cookietime The expiration time as UNIX timestamp. If 0 is provided, a session cookie is set.
644 * @access public
646 public function set_cookie($name, $cookiedata, $cookietime)
648 $name_data = rawurlencode(phpbb::$config['cookie_name'] . '_' . $name) . '=' . rawurlencode($cookiedata);
649 $expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime);
650 $domain = (!phpbb::$config['cookie_domain'] || phpbb::$config['cookie_domain'] == 'localhost' || phpbb::$config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . phpbb::$config['cookie_domain'];
652 header('Set-Cookie: ' . $name_data . (($cookietime) ? '; expires=' . $expire : '') . '; path=' . phpbb::$config['cookie_path'] . $domain . ((!phpbb::$config['cookie_secure']) ? '' : '; secure') . '; HttpOnly', false);
656 * Check for banned user
658 * Checks whether the supplied user is banned by id, ip or email. If no parameters
659 * are passed to the method pre-existing session data is used. If $return is false
660 * this routine does not return on finding a banned user, it outputs a relevant
661 * message and stops execution.
663 * @param int $user_id The user id to check. If false then do not check user ids
664 * @param string|array $user_ips Can contain a string with one IP or an array of multiple IPs. If false then no ips are checked.
665 * @param int $user_email The email address to check
666 * @param bool $return If false then the banned message is displayed and script halted
668 * @return bool|string True if banned and no reason given.
669 * False if not banned. A ban reason if banned and ban reason given. Check for !== false.
670 * @access public
672 public function check_ban($user_id = false, $user_ips = false, $user_email = false, $return = false)
674 if (defined('IN_CHECK_BAN'))
676 return;
679 $banned = false;
680 $cache_ttl = 3600;
681 $where_sql = array();
683 $sql = 'SELECT ban_ip, ban_userid, ban_email, ban_exclude, ban_give_reason, ban_end
684 FROM ' . BANLIST_TABLE . '
685 WHERE ';
687 // Determine which entries to check, only return those
688 if ($user_email === false)
690 $where_sql[] = "ban_email = ''";
693 if ($user_ips === false)
695 $where_sql[] = "(ban_ip = '' OR ban_exclude = 1)";
698 if ($user_id === false)
700 $where_sql[] = '(ban_userid = 0 OR ban_exclude = 1)';
702 else
704 $cache_ttl = ($user_id == ANONYMOUS) ? 3600 : 0;
705 $_sql = '(ban_userid = ' . $user_id;
707 if ($user_email !== false)
709 $_sql .= " OR ban_email <> ''";
712 if ($user_ips !== false)
714 $_sql .= " OR ban_ip <> ''";
717 $_sql .= ')';
719 $where_sql[] = $_sql;
722 $sql .= (sizeof($where_sql)) ? implode(' AND ', $where_sql) : '';
723 $result = phpbb::$db->sql_query($sql, $cache_ttl);
725 $ban_triggered_by = 'user';
726 while ($row = phpbb::$db->sql_fetchrow($result))
728 if ($row['ban_end'] && $row['ban_end'] < time())
730 continue;
733 $ip_banned = false;
734 if (!empty($row['ban_ip']))
736 if (!is_array($user_ips))
738 $ip_banned = preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ips);
740 else
742 foreach ($user_ips as $user_ip)
744 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ip))
746 $ip_banned = true;
747 break;
753 if ((!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) ||
754 $ip_banned ||
755 (!empty($row['ban_email']) && preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')) . '$#i', $user_email)))
757 if (!empty($row['ban_exclude']))
759 $banned = false;
760 break;
762 else
764 $banned = true;
765 $ban_row = $row;
767 if (!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id)
769 $ban_triggered_by = 'user';
771 else if ($ip_banned)
773 $ban_triggered_by = 'ip';
775 else
777 $ban_triggered_by = 'email';
780 // Don't break. Check if there is an exclude rule for this user
784 phpbb::$db->sql_freeresult($result);
786 if ($banned && !$return)
788 // If the session is empty we need to create a valid one...
789 if (empty($this->session_id))
791 // This seems to be no longer needed? - #14971
792 // $this->session_create(ANONYMOUS);
795 // Initiate environment ... since it won't be set at this stage
796 $this->setup();
798 // Logout the user, banned users are unable to use the normal 'logout' link
799 if ($this->data['user_id'] != ANONYMOUS)
801 $this->session_kill();
804 // We show a login box here to allow founders accessing the board if banned by IP
805 if (defined('IN_LOGIN') && $this->data['user_id'] == ANONYMOUS)
807 $this->setup('ucp');
808 $this->is_registered = $this->is_bot = false;
810 // Set as a precaution to allow login_box() handling this case correctly as well as this function not being executed again.
811 define('IN_CHECK_BAN', 1);
813 login_box('index.' . PHP_EXT);
815 // The false here is needed, else the user is able to circumvent the ban.
816 $this->session_kill(false);
819 // Ok, we catch the case of an empty session id for the anonymous user...
820 // This can happen if the user is logging in, banned by username and the login_box() being called "again".
821 if (empty($this->session_id) && defined('IN_CHECK_BAN'))
823 $this->session_create(ANONYMOUS);
827 // Determine which message to output
828 $till_date = ($ban_row['ban_end']) ? $this->format_date($ban_row['ban_end']) : '';
829 $message = ($ban_row['ban_end']) ? 'BOARD_BAN_TIME' : 'BOARD_BAN_PERM';
831 $message = sprintf($this->lang[$message], $till_date, '<a href="mailto:' . phpbb::$config['board_contact'] . '">', '</a>');
832 $message .= ($ban_row['ban_give_reason']) ? '<br /><br />' . sprintf($this->lang['BOARD_BAN_REASON'], $ban_row['ban_give_reason']) : '';
833 $message .= '<br /><br /><em>' . $this->lang['BAN_TRIGGERED_BY_' . strtoupper($ban_triggered_by)] . '</em>';
835 // To circumvent session_begin returning a valid value and the check_ban() not called on second page view, we kill the session again
836 $this->session_kill(false);
838 // A very special case... we are within the cron script which is not supposed to print out the ban message... show blank page
839 if (defined('IN_CRON'))
841 garbage_collection();
842 exit_handler();
843 exit;
846 trigger_error($message);
849 return ($banned && $ban_row['ban_give_reason']) ? $ban_row['ban_give_reason'] : $banned;
853 * Check if ip is blacklisted
854 * This should be called only where absolutly necessary
856 * Only IPv4 (rbldns does not support AAAA records/IPv6 lookups)
858 * @param string $mode Possible modes are: register and post
859 * spamhaus.org is used for both modes. Spamcop.net is additionally used for register.
860 * @param string $ip The ip to check. If false then the current IP is used
862 * @return bool|array False if ip is not blacklisted, else an array([checked server], [lookup])
863 * @author satmd (from the php manual)
864 * @access public
866 public function check_dnsbl($mode, $ip = false)
868 if ($ip === false)
870 $ip = $this->system['ip'];
873 $dnsbl_check = array(
874 'sbl-xbl.spamhaus.org' => 'http://www.spamhaus.org/query/bl?ip=',
877 if ($mode == 'register')
879 $dnsbl_check['bl.spamcop.net'] = 'http://spamcop.net/bl.shtml?';
882 if ($ip)
884 $quads = explode('.', $ip);
885 $reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
887 // Need to be listed on all servers...
888 $listed = true;
889 $info = array();
891 foreach ($dnsbl_check as $dnsbl => $lookup)
893 if (phpbb_checkdnsrr($reverse_ip . '.' . $dnsbl . '.', 'A') === true)
895 $info = array($dnsbl, $lookup . $ip);
897 else
899 $listed = false;
903 if ($listed)
905 return $info;
909 return false;
913 * Set/Update a persistent login key
915 * This method creates or updates a persistent session key. When a user makes
916 * use of persistent (formerly auto-) logins a key is generated and stored in the
917 * DB. When they revisit with the same key it's automatically updated in both the
918 * DB and cookie. Multiple keys may exist for each user representing different
919 * browsers or locations. As with _any_ non-secure-socket no passphrase login this
920 * remains vulnerable to exploit.
922 * @param int $user_id The user id. If false the current users user id will be used
923 * @param string $key A login key. If false then the current users login key stored within the cookie will be used
924 * @param string $user_ip The users ip. If false, then the current users IP will be used
925 * @access public
927 public function set_login_key($user_id = false, $key = false, $user_ip = false)
929 $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id;
930 $user_ip = ($user_ip === false) ? $this->system['ip'] : $user_ip;
931 $key = ($key === false) ? (($this->cookie_data['k']) ? $this->cookie_data['k'] : false) : $key;
933 $key_id = phpbb::$security->unique_id(hexdec(substr($this->session_id, 0, 8)));
935 $sql_ary = array(
936 'key_id' => (string) md5($key_id),
937 'last_ip' => (string) $this->system['ip'],
938 'last_login' => (int) $this->time_now,
941 if (!$key)
943 $sql_ary += array(
944 'user_id' => (int) $user_id
948 if ($key)
950 $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . '
951 SET ' . phpbb::$db->sql_build_array('UPDATE', $sql_ary) . '
952 WHERE user_id = ' . (int) $user_id . "
953 AND key_id = '" . phpbb::$db->sql_escape(md5($key)) . "'";
955 else
957 $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', $sql_ary);
959 phpbb::$db->sql_query($sql);
961 $this->cookie_data['k'] = $key_id;
965 * Reset all login keys for the specified user
967 * This method removes all current login keys for a specified (or the current)
968 * user. It will be called on password change to render old keys unusable
970 * @param int $user_id The user id. If false then the current users user id is used.
971 * @access public
973 public function reset_login_keys($user_id = false)
975 $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id;
977 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
978 WHERE user_id = ' . (int) $user_id;
979 phpbb::$db->sql_query($sql);
981 // Let's also clear any current sessions for the specified user_id
982 // If it's the current user then we'll leave this session intact
983 $sql_where = 'session_user_id = ' . (int) $user_id;
984 $sql_where .= ($user_id === $this->data['user_id']) ? " AND session_id <> '" . phpbb::$db->sql_escape($this->session_id) . "'" : '';
986 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
987 WHERE $sql_where";
988 phpbb::$db->sql_query($sql);
990 // We're changing the password of the current user and they have a key
991 // Lets regenerate it to be safe
992 if ($user_id === $this->data['user_id'] && $this->cookie_data['k'])
994 $this->set_login_key($user_id);
999 * Reset all admin sessions
1001 * @access public
1003 public function unset_admin()
1005 $sql = 'UPDATE ' . SESSIONS_TABLE . "
1006 SET session_admin = 0
1007 WHERE session_id = '" . phpbb::$db->sql_escape($this->session_id) . "'";
1008 phpbb::$db->sql_query($sql);
1012 * Check if a valid, non-expired session exist. Also make sure it errors out correctly if we do not have a db-setup yet. ;)
1014 * @return bool True if a valid, non-expired session exist
1015 * @access private
1017 private function session_exist()
1019 // If session is empty or does not match the session within the URL (if required - set by NEED_SID), then we need a new session
1020 if (empty($this->session_id) || ($this->need_sid && $this->session_id !== request::variable('sid', '', false, request::GET)))
1022 return false;
1025 // If the db is not initialized/registered, then we also need a new session (we are not able to go forward then...
1026 if (!phpbb::registered('db'))
1028 return false;
1031 // Now finally check the db for our provided session
1032 $sql = 'SELECT u.*, s.*
1033 FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . " u
1034 WHERE s.session_id = '" . phpbb::$db->sql_escape($this->session_id) . "'
1035 AND u.user_id = s.session_user_id";
1036 $result = phpbb::$db->sql_query($sql);
1037 $row = phpbb::$db->sql_fetchrow($result);
1038 phpbb::$db->sql_freeresult($result);
1040 // Also new session if it has not been found. ;)
1041 if (!$row)
1043 return false;
1046 $this->data = $row;
1048 // Now check the ip, the browser, forwarded for and referer
1049 if (!$this->session_valid())
1051 return false;
1054 // Ok, we are not finished yet. We need to know if the session is expired
1056 // Check whether the session is still valid if we have one
1057 if ($this->auth !== false && method_exists($this->auth, 'validate_session'))
1059 if (!$this->auth->validate_session($this))
1061 return false;
1065 // Check the session length timeframe if autologin is not enabled.
1066 // Else check the autologin length... and also removing those having autologin enabled but no longer allowed board-wide.
1067 if (!$this->data['session_autologin'])
1069 if ($this->data['session_time'] < $this->time_now - (phpbb::$config['session_length'] + 60))
1071 return false;
1074 else if (!phpbb::$config['allow_autologin'] || (phpbb::$config['max_autologin_time'] && $this->data['session_time'] < $this->time_now - (86400 * (int) phpbb::$config['max_autologin_time']) + 60))
1076 return false;
1079 // Only update session DB a minute or so after last update or if page changes
1080 if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->system['page']['page']))
1082 $sql_ary = array('session_time' => $this->time_now);
1084 if ($this->update_session_page)
1086 $sql_ary['session_page'] = substr($this->system['page']['page'], 0, 199);
1087 $sql_ary['session_forum_id'] = $this->system['page']['forum'];
1090 $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . phpbb::$db->sql_build_array('UPDATE', $sql_ary) . "
1091 WHERE session_id = '" . phpbb::$db->sql_escape($this->session_id) . "'";
1092 phpbb::$db->sql_query($sql);
1095 $this->is_registered = ($this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
1096 $this->is_bot = (!$this->is_registered && $this->data['user_id'] != ANONYMOUS) ? true : false;
1097 $this->data['user_lang'] = basename($this->data['user_lang']);
1099 return true;
1103 * Check if the request originated from the same page.
1105 * @param bool $check_script_path If true, the path will be checked as well
1107 * @return bool True if the referer is valid
1108 * @access private
1110 private function validate_referer($check_script_path = false)
1112 // no referer - nothing to validate, user's fault for turning it off (we only check on POST; so meta can't be the reason)
1113 if (empty($this->system['referer']) || empty($this->system['host']))
1115 return true;
1118 // Specialchar host, because it's the only one not specialchared
1119 $host = htmlspecialchars($this->system['host']);
1120 $ref = substr($this->system['referer'], strpos($this->system['referer'], '://') + 3);
1122 if (!(stripos($ref, $host) === 0))
1124 return false;
1126 else if ($check_script_path && rtrim($this->system['page']['root_script_path'], '/') !== '')
1128 $ref = substr($ref, strlen($host));
1129 $server_port = $this->system['port'];
1131 if ($server_port !== 80 && $server_port !== 443 && stripos($ref, ":$server_port") === 0)
1133 $ref = substr($ref, strlen(":$server_port"));
1136 if (!(stripos(rtrim($ref, '/'), rtrim($this->system['page']['root_script_path'], '/')) === 0))
1138 return false;
1142 return true;
1146 * Fill data array with a "faked" user account
1148 * @return array Default user data array
1149 * @access private
1151 private function default_data()
1153 return array(
1154 'user_id' => ANONYMOUS,
1159 * Check for a bot by comparing user agent and ip
1161 * Here we do a bot check, oh er saucy! No, not that kind of bot
1162 * check. We loop through the list of bots defined by the admin and
1163 * see if we have any useragent and/or IP matches. If we do, this is a
1164 * bot, act accordingly
1166 * @return bool True if it is a bot.
1167 * @access private
1169 private function check_bot()
1171 $bot = false;
1173 foreach (phpbb_cache::obtain_bots() as $row)
1175 if ($row['bot_agent'] && preg_match('#' . str_replace('\*', '.*?', preg_quote($row['bot_agent'], '#')) . '#i', $this->system['browser']))
1177 $bot = $row['user_id'];
1180 // If ip is supplied, we will make sure the ip is matching too...
1181 if ($row['bot_ip'] && ($bot || !$row['bot_agent']))
1183 // Set bot to false, then we only have to set it to true if it is matching
1184 $bot = false;
1186 foreach (explode(',', $row['bot_ip']) as $bot_ip)
1188 if (strpos($this->system['ip'], $bot_ip) === 0)
1190 $bot = (int) $row['user_id'];
1191 break;
1196 if ($bot)
1198 break;
1202 return $bot;
1206 * Check if session is valid by comparing ip, forwarded for, browser and referer
1208 * @param bool $log_failure If true then a non-match will be logged. Can cause huge logs.
1210 * @return bool True if the session is valid
1211 * @access private
1213 private function session_valid($log_failure = true)
1215 // Validate IP length according to admin ... enforces an IP
1216 // check on bots if admin requires this
1217 // $quadcheck = (phpbb::$config['ip_check_bot'] && $this->data['user_type'] & USER_BOT) ? 4 : phpbb::$config['ip_check'];
1219 if (strpos($this->system['ip'], ':') !== false && strpos($this->data['session_ip'], ':') !== false)
1221 $session_ip = short_ipv6($this->data['session_ip'], phpbb::$config['ip_check']);
1222 $user_ip = short_ipv6($this->system['ip'], phpbb::$config['ip_check']);
1224 else
1226 $session_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, phpbb::$config['ip_check']));
1227 $user_ip = implode('.', array_slice(explode('.', $this->system['ip']), 0, phpbb::$config['ip_check']));
1230 $session_browser = (phpbb::$config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
1231 $user_browser = (phpbb::$config['browser_check']) ? trim(strtolower(substr($this->system['browser'], 0, 149))) : '';
1233 $session_forwarded_for = (phpbb::$config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
1234 $user_forwarded_for = (phpbb::$config['forwarded_for_check']) ? substr($this->system['forwarded_for'], 0, 254) : '';
1236 // referer checks
1237 $check_referer_path = phpbb::$config['referer_validation'] == REFERER_VALIDATE_PATH;
1238 $referer_valid = true;
1240 // we assume HEAD and TRACE to be foul play and thus only whitelist GET
1241 if (phpbb::$config['referer_validation'] && $this->system['request_method'])
1243 $referer_valid = $this->validate_referer($check_referer_path);
1246 if ($user_ip !== $session_ip || $user_browser !== $session_browser || $user_forwarded_for !== $session_forwarded_for || !$referer_valid)
1248 // Added logging temporarly to help debug bugs...
1249 if (defined('DEBUG_EXTRA') && $this->data['user_id'] != ANONYMOUS && $log_failure)
1251 if ($referer_valid)
1253 add_log('critical', 'LOG_IP_BROWSER_FORWARDED_CHECK', $user_ip, $session_ip, $user_browser, $session_browser, htmlspecialchars($user_forwarded_for), htmlspecialchars($session_forwarded_for));
1255 else
1257 add_log('critical', 'LOG_REFERER_INVALID', $this->system['referer']);
1261 return false;
1264 return true;