merge? merge.
[phpbb.git] / phpBB / includes / session.php
blob14c21714d5e2ba23224e65edf3a23b1c966fd5ff
1 <?php
2 /**
4 * @package phpBB3
5 * @version $Id$
6 * @copyright (c) 2005 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 class session
25 var $cookie_data = array();
26 var $page = array();
27 var $data = array();
28 var $browser = '';
29 var $forwarded_for = '';
30 var $host = '';
31 var $session_id = '';
32 var $ip = '';
33 var $load = 0;
34 var $time_now = 0;
35 var $update_session_page = true;
37 /**
38 * Extract current session page
40 * @param string $root_path current root path (phpbb_root_path)
42 public static function extract_current_page($root_path)
44 $page_array = array();
46 // First of all, get the request uri...
47 $script_name = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
48 $args = (!empty($_SERVER['QUERY_STRING'])) ? explode('&', $_SERVER['QUERY_STRING']) : explode('&', getenv('QUERY_STRING'));
50 // If we are unable to get the script name we use REQUEST_URI as a failover and note it within the page array for easier support...
51 if (!$script_name)
53 $script_name = (!empty($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
54 $script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name;
55 $page_array['failover'] = 1;
58 // Replace backslashes and doubled slashes (could happen on some proxy setups)
59 $script_name = str_replace(array('\\', '//'), '/', $script_name);
61 // Now, remove the sid and let us get a clean query string...
62 $use_args = array();
64 // Since some browser do not encode correctly we need to do this with some "special" characters...
65 // " -> %22, ' => %27, < -> %3C, > -> %3E
66 $find = array('"', "'", '<', '>');
67 $replace = array('%22', '%27', '%3C', '%3E');
69 foreach ($args as $key => $argument)
71 if (strpos($argument, 'sid=') === 0)
73 continue;
76 $use_args[str_replace($find, $replace, $key)] = str_replace($find, $replace, $argument);
78 unset($args);
80 // The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2
82 // The current query string
83 $query_string = trim(implode('&', $use_args));
85 // basenamed page name (for example: index.php)
86 $page_name = basename($script_name);
87 $page_name = urlencode(htmlspecialchars($page_name));
89 // current directory within the phpBB root (for example: adm)
90 $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path)));
91 $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./')));
92 $intersection = array_intersect_assoc($root_dirs, $page_dirs);
94 $root_dirs = array_diff_assoc($root_dirs, $intersection);
95 $page_dirs = array_diff_assoc($page_dirs, $intersection);
97 $page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
99 if ($page_dir && substr($page_dir, -1, 1) == '/')
101 $page_dir = substr($page_dir, 0, -1);
104 // Current page from phpBB root (for example: adm/index.php?i=10&b=2)
105 $page = (($page_dir) ? $page_dir . '/' : '') . $page_name . (($query_string) ? "?$query_string" : '');
107 // The script path from the webroot to the current directory (for example: /phpBB3/adm/) : always prefixed with / and ends in /
108 $script_path = trim(str_replace('\\', '/', dirname($script_name)));
110 // The script path from the webroot to the phpBB root (for example: /phpBB3/)
111 $script_dirs = explode('/', $script_path);
112 array_splice($script_dirs, -sizeof($page_dirs));
113 $root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : '');
115 // We are on the base level (phpBB root == webroot), lets adjust the variables a bit...
116 if (!$root_script_path)
118 $root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path;
121 $script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/';
122 $root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/';
124 $page_array += array(
125 'page_name' => $page_name,
126 'page_dir' => $page_dir,
128 'query_string' => $query_string,
129 'script_path' => str_replace(' ', '%20', htmlspecialchars($script_path)),
130 'root_script_path' => str_replace(' ', '%20', htmlspecialchars($root_script_path)),
132 'page' => $page
135 return $page_array;
139 * Start session management
141 * This is where all session activity begins. We gather various pieces of
142 * information from the client and server. We test to see if a session already
143 * exists. If it does, fine and dandy. If it doesn't we'll go on to create a
144 * new one ... pretty logical heh? We also examine the system load (if we're
145 * running on a system which makes such information readily available) and
146 * halt if it's above an admin definable limit.
148 * @param bool $update_session_page if true the session page gets updated.
149 * This can be set to circumvent certain scripts to update the users last visited page.
151 function session_begin($update_session_page = true)
153 global $SID, $_SID, $_EXTRA_URL, $db, $config;
155 // Give us some basic information
156 $this->time_now = time();
157 $this->cookie_data = array('u' => 0, 'k' => '');
158 $this->update_session_page = $update_session_page;
159 $this->browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
160 $this->referer = (!empty($_SERVER['HTTP_REFERER'])) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : '';
161 $this->forwarded_for = (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) ? (string) $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
162 $this->host = (!empty($_SERVER['HTTP_HOST'])) ? (string) strtolower($_SERVER['HTTP_HOST']) : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
164 // Since HTTP_HOST may carry a port definition, we need to remove it here...
165 if (strpos($this->host, ':') !== false)
167 $this->host = substr($this->host, 0, strpos($this->host, ':'));
170 $this->page = self::extract_current_page(PHPBB_ROOT_PATH);
172 // if the forwarded for header shall be checked we have to validate its contents
173 if ($config['forwarded_for_check'])
175 $this->forwarded_for = preg_replace('#, +#', ', ', $this->forwarded_for);
177 // split the list of IPs
178 $ips = explode(', ', $this->forwarded_for);
179 foreach ($ips as $ip)
181 // check IPv4 first, the IPv6 is hopefully only going to be used very seldomly
182 if (!empty($ip) && !preg_match(get_preg_expression('ipv4'), $ip) && !preg_match(get_preg_expression('ipv6'), $ip))
184 // contains invalid data, don't use the forwarded for header
185 $this->forwarded_for = '';
186 break;
190 else
192 $this->forwarded_for = '';
195 // Add forum to the page for tracking online users - also adding a "x" to the end to properly identify the number
196 $this->page['page'] .= (isset($_REQUEST['f'])) ? ((strpos($this->page['page'], '?') !== false) ? '&' : '?') . '_f_=' . (int) $_REQUEST['f'] . 'x' : '';
198 if (isset($_COOKIE[$config['cookie_name'] . '_sid']) || isset($_COOKIE[$config['cookie_name'] . '_u']))
200 $this->cookie_data['u'] = request_var($config['cookie_name'] . '_u', 0, false, true);
201 $this->cookie_data['k'] = request_var($config['cookie_name'] . '_k', '', false, true);
202 $this->session_id = request_var($config['cookie_name'] . '_sid', '', false, true);
204 $SID = (defined('NEED_SID')) ? '?sid=' . $this->session_id : '?sid=';
205 $_SID = (defined('NEED_SID')) ? $this->session_id : '';
207 if (empty($this->session_id))
209 $this->session_id = $_SID = request_var('sid', '');
210 $SID = '?sid=' . $this->session_id;
211 $this->cookie_data = array('u' => 0, 'k' => '');
214 else
216 $this->session_id = $_SID = request_var('sid', '');
217 $SID = '?sid=' . $this->session_id;
220 $_EXTRA_URL = array();
222 // Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
223 // it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
224 $this->ip = (!empty($_SERVER['REMOTE_ADDR'])) ? htmlspecialchars($_SERVER['REMOTE_ADDR']) : '';
225 $this->load = false;
227 // Load limit check (if applicable)
228 if ($config['limit_load'] || $config['limit_search_load'])
230 if ((function_exists('sys_getloadavg') && $load = sys_getloadavg()) || ($load = explode(' ', @file_get_contents('/proc/loadavg'))))
232 $this->load = array_slice($load, 0, 1);
233 $this->load = floatval($this->load[0]);
235 else
237 set_config('limit_load', '0');
238 set_config('limit_search_load', '0');
242 // Is session_id is set or session_id is set and matches the url param if required
243 if (!empty($this->session_id) && (!defined('NEED_SID') || (isset($_GET['sid']) && $this->session_id === $_GET['sid'])))
245 $sql = 'SELECT u.*, s.*
246 FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . " u
247 WHERE s.session_id = '" . $db->sql_escape($this->session_id) . "'
248 AND u.user_id = s.session_user_id";
249 $result = $db->sql_query($sql);
250 $this->data = $db->sql_fetchrow($result);
251 $db->sql_freeresult($result);
253 // Did the session exist in the DB?
254 if (isset($this->data['user_id']))
256 // Validate IP length according to admin ... enforces an IP
257 // check on bots if admin requires this
258 // $quadcheck = ($config['ip_check_bot'] && $this->data['user_type'] & USER_BOT) ? 4 : $config['ip_check'];
260 if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false)
262 $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
263 $u_ip = short_ipv6($this->ip, $config['ip_check']);
265 else
267 $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
268 $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
271 $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
272 $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : '';
274 $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
275 $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : '';
277 // referer checks
278 $check_referer_path = $config['referer_validation'] == REFERER_VALIDATE_PATH;
279 $referer_valid = true;
280 // we assume HEAD and TRACE to be foul play and thus only whitelist GET
281 if ($config['referer_validation'] && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) !== 'get')
283 $referer_valid = $this->validate_referer($check_referer_path);
287 if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for && $referer_valid)
289 $session_expired = false;
291 // Check whether the session is still valid if we have one
292 $method = basename(trim($config['auth_method']));
293 include_once(PHPBB_ROOT_PATH . 'includes/auth/auth_' . $method . '.' . PHP_EXT);
295 $method = 'validate_session_' . $method;
296 if (function_exists($method))
298 if (!$method($this->data))
300 $session_expired = true;
304 if (!$session_expired)
306 // Check the session length timeframe if autologin is not enabled.
307 // Else check the autologin length... and also removing those having autologin enabled but no longer allowed board-wide.
308 if (!$this->data['session_autologin'])
310 if ($this->data['session_time'] < $this->time_now - ($config['session_length'] + 60))
312 $session_expired = true;
315 else if (!$config['allow_autologin'] || ($config['max_autologin_time'] && $this->data['session_time'] < $this->time_now - (86400 * (int) $config['max_autologin_time']) + 60))
317 $session_expired = true;
321 if (!$session_expired)
323 // Only update session DB a minute or so after last update or if page changes
324 if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page']))
326 $sql_ary = array('session_time' => $this->time_now);
328 if ($this->update_session_page)
330 $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
333 $db->sql_return_on_error(true);
335 $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
336 WHERE session_id = '" . $db->sql_escape($this->session_id) . "'";
337 $result = $db->sql_query($sql);
339 $db->sql_return_on_error(false);
341 // If the database is not yet updated, there will be an error due to the session_forum_id
342 // @todo REMOVE for 3.0.2
343 if ($result === false)
345 unset($sql_ary['session_forum_id']);
347 $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
348 WHERE session_id = '" . $db->sql_escape($this->session_id) . "'";
349 $db->sql_query($sql);
353 $this->data['is_registered'] = ($this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
354 $this->data['is_bot'] = (!$this->data['is_registered'] && $this->data['user_id'] != ANONYMOUS) ? true : false;
355 $this->data['user_lang'] = basename($this->data['user_lang']);
357 return true;
360 else
362 // Added logging temporarly to help debug bugs...
363 if (defined('DEBUG_EXTRA') && $this->data['user_id'] != ANONYMOUS)
365 if ($referer_valid)
367 add_log('critical', 'LOG_IP_BROWSER_FORWARDED_CHECK', $u_ip, $s_ip, $u_browser, $s_browser, htmlspecialchars($u_forwarded_for), htmlspecialchars($s_forwarded_for));
369 else
371 add_log('critical', 'LOG_REFERER_INVALID', $this->referer);
378 // If we reach here then no (valid) session exists. So we'll create a new one
379 return $this->session_create();
383 * Create a new session
385 * If upon trying to start a session we discover there is nothing existing we
386 * jump here. Additionally this method is called directly during login to regenerate
387 * the session for the specific user. In this method we carry out a number of tasks;
388 * garbage collection, (search)bot checking, banned user comparison. Basically
389 * though this method will result in a new session for a specific user.
391 function session_create($user_id = false, $set_admin = false, $persist_login = false, $viewonline = true)
393 global $SID, $_SID, $db, $config, $cache;
395 $this->data = array();
397 /* Garbage collection ... remove old sessions updating user information
398 // if necessary. It means (potentially) 11 queries but only infrequently
399 if ($this->time_now > $config['session_last_gc'] + $config['session_gc'])
401 $this->session_gc();
404 // Do we allow autologin on this board? No? Then override anything
405 // that may be requested here
406 if (!$config['allow_autologin'])
408 $this->cookie_data['k'] = $persist_login = false;
412 * Here we do a bot check, oh er saucy! No, not that kind of bot
413 * check. We loop through the list of bots defined by the admin and
414 * see if we have any useragent and/or IP matches. If we do, this is a
415 * bot, act accordingly
417 $bot = false;
418 $active_bots = cache::obtain_bots();
420 foreach ($active_bots as $row)
422 if ($row['bot_agent'] && preg_match('#' . str_replace('\*', '.*?', preg_quote($row['bot_agent'], '#')) . '#i', $this->browser))
424 $bot = $row['user_id'];
427 // If ip is supplied, we will make sure the ip is matching too...
428 if ($row['bot_ip'] && ($bot || !$row['bot_agent']))
430 // Set bot to false, then we only have to set it to true if it is matching
431 $bot = false;
433 foreach (explode(',', $row['bot_ip']) as $bot_ip)
435 if (strpos($this->ip, $bot_ip) === 0)
437 $bot = (int) $row['user_id'];
438 break;
443 if ($bot)
445 break;
449 $method = basename(trim($config['auth_method']));
450 include_once(PHPBB_ROOT_PATH . 'includes/auth/auth_' . $method . '.' . PHP_EXT);
452 $method = 'autologin_' . $method;
453 if (function_exists($method))
455 $this->data = $method();
457 if (sizeof($this->data))
459 $this->cookie_data['k'] = '';
460 $this->cookie_data['u'] = $this->data['user_id'];
464 // If we're presented with an autologin key we'll join against it.
465 // Else if we've been passed a user_id we'll grab data based on that
466 if (isset($this->cookie_data['k']) && $this->cookie_data['k'] && $this->cookie_data['u'] && !sizeof($this->data))
468 $sql = 'SELECT u.*
469 FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
470 WHERE u.user_id = ' . (int) $this->cookie_data['u'] . '
471 AND u.user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ")
472 AND k.user_id = u.user_id
473 AND k.key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'";
474 $result = $db->sql_query($sql);
475 $this->data = $db->sql_fetchrow($result);
476 $db->sql_freeresult($result);
477 $bot = false;
479 else if ($user_id !== false && !sizeof($this->data))
481 $this->cookie_data['k'] = '';
482 $this->cookie_data['u'] = $user_id;
484 $sql = 'SELECT *
485 FROM ' . USERS_TABLE . '
486 WHERE user_id = ' . (int) $this->cookie_data['u'] . '
487 AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')';
488 $result = $db->sql_query($sql);
489 $this->data = $db->sql_fetchrow($result);
490 $db->sql_freeresult($result);
491 $bot = false;
494 // If no data was returned one or more of the following occurred:
495 // Key didn't match one in the DB
496 // User does not exist
497 // User is inactive
498 // User is bot
499 if (!sizeof($this->data) || !is_array($this->data))
501 $this->cookie_data['k'] = '';
502 $this->cookie_data['u'] = ($bot) ? $bot : ANONYMOUS;
504 if (!$bot)
506 $sql = 'SELECT *
507 FROM ' . USERS_TABLE . '
508 WHERE user_id = ' . (int) $this->cookie_data['u'];
510 else
512 // We give bots always the same session if it is not yet expired.
513 $sql = 'SELECT u.*, s.*
514 FROM ' . USERS_TABLE . ' u
515 LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
516 WHERE u.user_id = ' . (int) $bot;
519 $result = $db->sql_query($sql);
520 $this->data = $db->sql_fetchrow($result);
521 $db->sql_freeresult($result);
524 if ($this->data['user_id'] != ANONYMOUS && !$bot)
526 $this->data['session_last_visit'] = (isset($this->data['session_time']) && $this->data['session_time']) ? $this->data['session_time'] : (($this->data['user_lastvisit']) ? $this->data['user_lastvisit'] : time());
528 else
530 $this->data['session_last_visit'] = $this->time_now;
533 // Force user id to be integer...
534 $this->data['user_id'] = (int) $this->data['user_id'];
536 // At this stage we should have a filled data array, defined cookie u and k data.
537 // data array should contain recent session info if we're a real user and a recent
538 // session exists in which case session_id will also be set
540 // Is user banned? Are they excluded? Won't return on ban, exists within method
541 if ($this->data['user_type'] != USER_FOUNDER)
543 if (!$config['forwarded_for_check'])
545 $this->check_ban($this->data['user_id'], $this->ip);
547 else
549 $ips = explode(', ', $this->forwarded_for);
550 $ips[] = $this->ip;
551 $this->check_ban($this->data['user_id'], $ips);
555 $this->data['is_registered'] = (!$bot && $this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
556 $this->data['is_bot'] = ($bot) ? true : false;
558 // If our friend is a bot, we re-assign a previously assigned session
559 if ($this->data['is_bot'] && $bot == $this->data['user_id'] && $this->data['session_id'])
561 // Only assign the current session if the ip, browser and forwarded_for match...
562 if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false)
564 $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
565 $u_ip = short_ipv6($this->ip, $config['ip_check']);
567 else
569 $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
570 $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
573 $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
574 $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : '';
576 $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
577 $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : '';
579 if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for)
581 $this->session_id = $this->data['session_id'];
583 // Only update session DB a minute or so after last update or if page changes
584 if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page']))
586 $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
588 $sql_ary = array('session_time' => $this->time_now, 'session_last_visit' => $this->time_now, 'session_admin' => 0);
590 if ($this->update_session_page)
592 $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
595 $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
596 WHERE session_id = '" . $db->sql_escape($this->session_id) . "'";
597 $db->sql_query($sql);
599 // Update the last visit time
600 $sql = 'UPDATE ' . USERS_TABLE . '
601 SET user_lastvisit = ' . (int) $this->data['session_time'] . '
602 WHERE user_id = ' . (int) $this->data['user_id'];
603 $db->sql_query($sql);
606 $SID = '?sid=';
607 $_SID = '';
608 return true;
610 else
612 // If the ip and browser does not match make sure we only have one bot assigned to one session
613 $db->sql_query('DELETE FROM ' . SESSIONS_TABLE . ' WHERE session_user_id = ' . $this->data['user_id']);
617 $session_autologin = (($this->cookie_data['k'] || $persist_login) && $this->data['is_registered']) ? true : false;
618 $set_admin = ($set_admin && $this->data['is_registered']) ? true : false;
620 // Create or update the session
621 $sql_ary = array(
622 'session_user_id' => (int) $this->data['user_id'],
623 'session_start' => (int) $this->time_now,
624 'session_last_visit' => (int) $this->data['session_last_visit'],
625 'session_time' => (int) $this->time_now,
626 'session_browser' => (string) trim(substr($this->browser, 0, 149)),
627 'session_forwarded_for' => (string) $this->forwarded_for,
628 'session_ip' => (string) $this->ip,
629 'session_autologin' => ($session_autologin) ? 1 : 0,
630 'session_admin' => ($set_admin) ? 1 : 0,
631 'session_viewonline' => ($viewonline) ? 1 : 0,
634 if ($this->update_session_page)
636 $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199);
639 $db->sql_return_on_error(true);
641 $sql = 'DELETE
642 FROM ' . SESSIONS_TABLE . '
643 WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\'
644 AND session_user_id = ' . ANONYMOUS;
646 if (!defined('IN_ERROR_HANDLER') && (!$this->session_id || !$db->sql_query($sql) || !$db->sql_affectedrows()))
648 // Limit new sessions in 1 minute period (if required)
649 if (empty($this->data['session_time']) && $config['active_sessions'])
651 $sql = 'SELECT COUNT(session_id) AS sessions
652 FROM ' . SESSIONS_TABLE . '
653 WHERE session_time >= ' . ($this->time_now - 60);
654 $result = $db->sql_query($sql);
655 $row = $db->sql_fetchrow($result);
656 $db->sql_freeresult($result);
658 if ((int) $row['sessions'] > (int) $config['active_sessions'])
660 header('HTTP/1.1 503 Service Unavailable');
661 trigger_error('BOARD_UNAVAILABLE');
666 $this->session_id = $this->data['session_id'] = md5(unique_id());
668 $sql_ary['session_id'] = (string) $this->session_id;
669 $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199);
671 $sql = 'INSERT INTO ' . SESSIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
672 $db->sql_query($sql);
674 $db->sql_return_on_error(false);
676 // Regenerate autologin/persistent login key
677 if ($session_autologin)
679 $this->set_login_key();
682 // refresh data
683 $SID = '?sid=' . $this->session_id;
684 $_SID = $this->session_id;
685 $this->data = array_merge($this->data, $sql_ary);
687 if (!$bot)
689 $cookie_expire = $this->time_now + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000);
691 $this->set_cookie('u', $this->cookie_data['u'], $cookie_expire);
692 $this->set_cookie('k', $this->cookie_data['k'], $cookie_expire);
693 $this->set_cookie('sid', $this->session_id, $cookie_expire);
695 unset($cookie_expire);
697 $sql = 'SELECT COUNT(session_id) AS sessions
698 FROM ' . SESSIONS_TABLE . '
699 WHERE session_user_id = ' . (int) $this->data['user_id'] . '
700 AND session_time >= ' . (int) ($this->time_now - (max($config['session_length'], $config['form_token_lifetime'])));
701 $result = $db->sql_query($sql);
702 $row = $db->sql_fetchrow($result);
703 $db->sql_freeresult($result);
705 if ((int) $row['sessions'] <= 1 || empty($this->data['user_form_salt']))
707 $this->data['user_form_salt'] = unique_id();
708 // Update the form key
709 $sql = 'UPDATE ' . USERS_TABLE . '
710 SET user_form_salt = \'' . $db->sql_escape($this->data['user_form_salt']) . '\'
711 WHERE user_id = ' . (int) $this->data['user_id'];
712 $db->sql_query($sql);
715 else
717 $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
719 // Update the last visit time
720 $sql = 'UPDATE ' . USERS_TABLE . '
721 SET user_lastvisit = ' . (int) $this->data['session_time'] . '
722 WHERE user_id = ' . (int) $this->data['user_id'];
723 $db->sql_query($sql);
725 $SID = '?sid=';
726 $_SID = '';
729 return true;
733 * Kills a session
735 * This method does what it says on the tin. It will delete a pre-existing session.
736 * It resets cookie information (destroying any autologin key within that cookie data)
737 * and update the users information from the relevant session data. It will then
738 * grab guest user information.
740 function session_kill($new_session = true)
742 global $SID, $_SID, $db, $config;
744 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
745 WHERE session_id = '" . $db->sql_escape($this->session_id) . "'
746 AND session_user_id = " . (int) $this->data['user_id'];
747 $db->sql_query($sql);
749 // Allow connecting logout with external auth method logout
750 $method = basename(trim($config['auth_method']));
751 include_once(PHPBB_ROOT_PATH . 'includes/auth/auth_' . $method . '.' . PHP_EXT);
753 $method = 'logout_' . $method;
754 if (function_exists($method))
756 $method($this->data, $new_session);
759 if ($this->data['user_id'] != ANONYMOUS)
761 // Delete existing session, update last visit info first!
762 if (!isset($this->data['session_time']))
764 $this->data['session_time'] = time();
767 $sql = 'UPDATE ' . USERS_TABLE . '
768 SET user_lastvisit = ' . (int) $this->data['session_time'] . '
769 WHERE user_id = ' . (int) $this->data['user_id'];
770 $db->sql_query($sql);
772 if ($this->cookie_data['k'])
774 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
775 WHERE user_id = ' . (int) $this->data['user_id'] . "
776 AND key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'";
777 $db->sql_query($sql);
780 // Reset the data array
781 $this->data = array();
783 $sql = 'SELECT *
784 FROM ' . USERS_TABLE . '
785 WHERE user_id = ' . ANONYMOUS;
786 $result = $db->sql_query($sql);
787 $this->data = $db->sql_fetchrow($result);
788 $db->sql_freeresult($result);
791 $cookie_expire = $this->time_now - 31536000;
792 $this->set_cookie('u', '', $cookie_expire);
793 $this->set_cookie('k', '', $cookie_expire);
794 $this->set_cookie('sid', '', $cookie_expire);
795 unset($cookie_expire);
797 $SID = '?sid=';
798 $this->session_id = $_SID = '';
800 // To make sure a valid session is created we create one for the anonymous user
801 if ($new_session)
803 $this->session_create(ANONYMOUS);
806 return true;
810 * Session garbage collection
812 * This looks a lot more complex than it really is. Effectively we are
813 * deleting any sessions older than an admin definable limit. Due to the
814 * way in which we maintain session data we have to ensure we update user
815 * data before those sessions are destroyed. In addition this method
816 * removes autologin key information that is older than an admin defined
817 * limit.
819 function session_gc()
821 global $db, $config;
823 $batch_size = 10;
825 if (!$this->time_now)
827 $this->time_now = time();
830 // Firstly, delete guest sessions
831 $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
832 WHERE session_user_id = ' . ANONYMOUS . '
833 AND session_time < ' . (int) ($this->time_now - $config['session_length']);
834 $db->sql_query($sql);
836 // Get expired sessions, only most recent for each user
837 $sql = 'SELECT session_user_id, session_page, MAX(session_time) AS recent_time
838 FROM ' . SESSIONS_TABLE . '
839 WHERE session_time < ' . ($this->time_now - $config['session_length']) . '
840 GROUP BY session_user_id, session_page';
841 $result = $db->sql_query_limit($sql, $batch_size);
843 $del_user_id = array();
844 $del_sessions = 0;
846 while ($row = $db->sql_fetchrow($result))
848 $sql = 'UPDATE ' . USERS_TABLE . '
849 SET user_lastvisit = ' . (int) $row['recent_time'] . ", user_lastpage = '" . $db->sql_escape($row['session_page']) . "'
850 WHERE user_id = " . (int) $row['session_user_id'];
851 $db->sql_query($sql);
853 $del_user_id[] = (int) $row['session_user_id'];
854 $del_sessions++;
856 $db->sql_freeresult($result);
858 if (sizeof($del_user_id))
860 // Delete expired sessions
861 $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
862 WHERE ' . $db->sql_in_set('session_user_id', $del_user_id) . '
863 AND session_time < ' . ($this->time_now - $config['session_length']);
864 $db->sql_query($sql);
867 if ($del_sessions < $batch_size)
869 // Less than 10 users, update gc timer ... else we want gc
870 // called again to delete other sessions
871 set_config('session_last_gc', $this->time_now, true);
873 if ($config['max_autologin_time'])
875 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
876 WHERE last_login < ' . (time() - (86400 * (int) $config['max_autologin_time']));
877 $db->sql_query($sql);
879 $this->confirm_gc();
882 return;
885 function confirm_gc($type = 0)
887 global $db, $config;
889 $sql = 'SELECT DISTINCT c.session_id
890 FROM ' . CONFIRM_TABLE . ' c
891 LEFT JOIN ' . SESSIONS_TABLE . ' s ON (c.session_id = s.session_id)
892 WHERE s.session_id IS NULL' .
893 ((empty($type)) ? '' : ' AND c.confirm_type = ' . (int) $type);
894 $result = $db->sql_query($sql);
896 if ($row = $db->sql_fetchrow($result))
898 $sql_in = array();
901 $sql_in[] = (string) $row['session_id'];
903 while ($row = $db->sql_fetchrow($result));
905 if (sizeof($sql_in))
907 $sql = 'DELETE FROM ' . CONFIRM_TABLE . '
908 WHERE ' . $db->sql_in_set('session_id', $sql_in);
909 $db->sql_query($sql);
912 $db->sql_freeresult($result);
917 * Sets a cookie
919 * 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.
921 * @param string $name Name of the cookie, will be automatically prefixed with the phpBB cookie name. track becomes [cookie_name]_track then.
922 * @param string $cookiedata The data to hold within the cookie
923 * @param int $cookietime The expiration time as UNIX timestamp. If 0 is provided, a session cookie is set.
925 function set_cookie($name, $cookiedata, $cookietime)
927 global $config;
929 $name_data = rawurlencode($config['cookie_name'] . '_' . $name) . '=' . rawurlencode($cookiedata);
930 $expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime);
931 $domain = (!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain'];
933 header('Set-Cookie: ' . $name_data . (($cookietime) ? '; expires=' . $expire : '') . '; path=' . $config['cookie_path'] . $domain . ((!$config['cookie_secure']) ? '' : '; secure') . '; HttpOnly', false);
937 * Check for banned user
939 * Checks whether the supplied user is banned by id, ip or email. If no parameters
940 * are passed to the method pre-existing session data is used. If $return is false
941 * this routine does not return on finding a banned user, it outputs a relevant
942 * message and stops execution.
944 * @param string|array $user_ips Can contain a string with one IP or an array of multiple IPs
946 function check_ban($user_id = false, $user_ips = false, $user_email = false, $return = false)
948 global $config, $db;
950 if (defined('IN_CHECK_BAN'))
952 return;
955 $banned = false;
956 $cache_ttl = 3600;
957 $where_sql = array();
959 $sql = 'SELECT ban_ip, ban_userid, ban_email, ban_exclude, ban_give_reason, ban_end
960 FROM ' . BANLIST_TABLE . '
961 WHERE ';
963 // Determine which entries to check, only return those
964 if ($user_email === false)
966 $where_sql[] = "ban_email = ''";
969 if ($user_ips === false)
971 $where_sql[] = "(ban_ip = '' OR ban_exclude = 1)";
974 if ($user_id === false)
976 $where_sql[] = '(ban_userid = 0 OR ban_exclude = 1)';
978 else
980 $cache_ttl = ($user_id == ANONYMOUS) ? 3600 : 0;
981 $_sql = '(ban_userid = ' . $user_id;
983 if ($user_email !== false)
985 $_sql .= " OR ban_email <> ''";
988 if ($user_ips !== false)
990 $_sql .= " OR ban_ip <> ''";
993 $_sql .= ')';
995 $where_sql[] = $_sql;
998 $sql .= (sizeof($where_sql)) ? implode(' AND ', $where_sql) : '';
999 $result = $db->sql_query($sql, $cache_ttl);
1001 $ban_triggered_by = 'user';
1002 while ($row = $db->sql_fetchrow($result))
1004 if ($row['ban_end'] && $row['ban_end'] < time())
1006 continue;
1009 $ip_banned = false;
1010 if (!empty($row['ban_ip']))
1012 if (!is_array($user_ips))
1014 $ip_banned = preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ips);
1016 else
1018 foreach ($user_ips as $user_ip)
1020 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ip))
1022 $ip_banned = true;
1023 break;
1029 if ((!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) ||
1030 $ip_banned ||
1031 (!empty($row['ban_email']) && preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')) . '$#i', $user_email)))
1033 if (!empty($row['ban_exclude']))
1035 $banned = false;
1036 break;
1038 else
1040 $banned = true;
1041 $ban_row = $row;
1043 if (!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id)
1045 $ban_triggered_by = 'user';
1047 else if ($ip_banned)
1049 $ban_triggered_by = 'ip';
1051 else
1053 $ban_triggered_by = 'email';
1056 // Don't break. Check if there is an exclude rule for this user
1060 $db->sql_freeresult($result);
1062 if ($banned && !$return)
1064 global $template;
1066 // If the session is empty we need to create a valid one...
1067 if (empty($this->session_id))
1069 // This seems to be no longer needed? - #14971
1070 // $this->session_create(ANONYMOUS);
1073 // Initiate environment ... since it won't be set at this stage
1074 $this->setup();
1076 // Logout the user, banned users are unable to use the normal 'logout' link
1077 if ($this->data['user_id'] != ANONYMOUS)
1079 $this->session_kill();
1082 // We show a login box here to allow founders accessing the board if banned by IP
1083 if (defined('IN_LOGIN') && $this->data['user_id'] == ANONYMOUS)
1085 $this->setup('ucp');
1086 $this->data['is_registered'] = $this->data['is_bot'] = false;
1088 // Set as a precaution to allow login_box() handling this case correctly as well as this function not being executed again.
1089 define('IN_CHECK_BAN', 1);
1091 login_box('index.' . PHP_EXT);
1093 // The false here is needed, else the user is able to circumvent the ban.
1094 $this->session_kill(false);
1097 // Ok, we catch the case of an empty session id for the anonymous user...
1098 // This can happen if the user is logging in, banned by username and the login_box() being called "again".
1099 if (empty($this->session_id) && defined('IN_CHECK_BAN'))
1101 $this->session_create(ANONYMOUS);
1105 // Determine which message to output
1106 $till_date = ($ban_row['ban_end']) ? $this->format_date($ban_row['ban_end']) : '';
1107 $message = ($ban_row['ban_end']) ? 'BOARD_BAN_TIME' : 'BOARD_BAN_PERM';
1109 $message = sprintf($this->lang[$message], $till_date, '<a href="mailto:' . $config['board_contact'] . '">', '</a>');
1110 $message .= ($ban_row['ban_give_reason']) ? '<br /><br />' . sprintf($this->lang['BOARD_BAN_REASON'], $ban_row['ban_give_reason']) : '';
1111 $message .= '<br /><br /><em>' . $this->lang['BAN_TRIGGERED_BY_' . strtoupper($ban_triggered_by)] . '</em>';
1113 // To circumvent session_begin returning a valid value and the check_ban() not called on second page view, we kill the session again
1114 $this->session_kill(false);
1116 // A very special case... we are within the cron script which is not supposed to print out the ban message... show blank page
1117 if (defined('IN_CRON'))
1119 garbage_collection();
1120 exit_handler();
1121 exit;
1124 trigger_error($message);
1127 return ($banned && $ban_row['ban_give_reason']) ? $ban_row['ban_give_reason'] : $banned;
1131 * Check if ip is blacklisted
1132 * This should be called only where absolutly necessary
1134 * Only IPv4 (rbldns does not support AAAA records/IPv6 lookups)
1136 * @author satmd (from the php manual)
1137 * @param string $mode register/post - spamcop for example is ommitted for posting
1138 * @return false if ip is not blacklisted, else an array([checked server], [lookup])
1140 function check_dnsbl($mode, $ip = false)
1142 if ($ip === false)
1144 $ip = $this->ip;
1147 $dnsbl_check = array(
1148 'list.dsbl.org' => 'http://dsbl.org/listing?',
1149 'sbl-xbl.spamhaus.org' => 'http://www.spamhaus.org/query/bl?ip=',
1152 if ($mode == 'register')
1154 $dnsbl_check['bl.spamcop.net'] = 'http://spamcop.net/bl.shtml?';
1157 if ($ip)
1159 $quads = explode('.', $ip);
1160 $reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
1162 // Need to be listed on all servers...
1163 $listed = true;
1164 $info = array();
1166 foreach ($dnsbl_check as $dnsbl => $lookup)
1168 if (phpbb_checkdnsrr($reverse_ip . '.' . $dnsbl . '.', 'A') === true)
1170 $info = array($dnsbl, $lookup . $ip);
1172 else
1174 $listed = false;
1178 if ($listed)
1180 return $info;
1184 return false;
1188 * Check if URI is blacklisted
1189 * This should be called only where absolutly necessary, for example on the submitted website field
1190 * This function is not in use at the moment and is only included for testing purposes, it may not work at all!
1191 * This means it is untested at the moment and therefore commented out
1193 * @param string $uri URI to check
1194 * @return true if uri is on blacklist, else false. Only blacklist is checked (~zero FP), no grey lists
1195 function check_uribl($uri)
1197 // Normally parse_url() is not intended to parse uris
1198 // We need to get the top-level domain name anyway... change.
1199 $uri = parse_url($uri);
1201 if ($uri === false || empty($uri['host']))
1203 return false;
1206 $uri = trim($uri['host']);
1208 if ($uri)
1210 // One problem here... the return parameter for the "windows" method is different from what
1211 // we expect... this may render this check useless...
1212 if (phpbb_checkdnsrr($uri . '.multi.uribl.com.', 'A') === true)
1214 return true;
1218 return false;
1223 * Set/Update a persistent login key
1225 * This method creates or updates a persistent session key. When a user makes
1226 * use of persistent (formerly auto-) logins a key is generated and stored in the
1227 * DB. When they revisit with the same key it's automatically updated in both the
1228 * DB and cookie. Multiple keys may exist for each user representing different
1229 * browsers or locations. As with _any_ non-secure-socket no passphrase login this
1230 * remains vulnerable to exploit.
1232 function set_login_key($user_id = false, $key = false, $user_ip = false)
1234 global $config, $db;
1236 $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id;
1237 $user_ip = ($user_ip === false) ? $this->ip : $user_ip;
1238 $key = ($key === false) ? (($this->cookie_data['k']) ? $this->cookie_data['k'] : false) : $key;
1240 $key_id = unique_id(hexdec(substr($this->session_id, 0, 8)));
1242 $sql_ary = array(
1243 'key_id' => (string) md5($key_id),
1244 'last_ip' => (string) $this->ip,
1245 'last_login' => (int) time()
1248 if (!$key)
1250 $sql_ary += array(
1251 'user_id' => (int) $user_id
1255 if ($key)
1257 $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . '
1258 SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
1259 WHERE user_id = ' . (int) $user_id . "
1260 AND key_id = '" . $db->sql_escape(md5($key)) . "'";
1262 else
1264 $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
1266 $db->sql_query($sql);
1268 $this->cookie_data['k'] = $key_id;
1270 return false;
1274 * Reset all login keys for the specified user
1276 * This method removes all current login keys for a specified (or the current)
1277 * user. It will be called on password change to render old keys unusable
1279 function reset_login_keys($user_id = false)
1281 global $config, $db;
1283 $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id;
1285 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
1286 WHERE user_id = ' . (int) $user_id;
1287 $db->sql_query($sql);
1289 // Let's also clear any current sessions for the specified user_id
1290 // If it's the current user then we'll leave this session intact
1291 $sql_where = 'session_user_id = ' . (int) $user_id;
1292 $sql_where .= ($user_id === $this->data['user_id']) ? " AND session_id <> '" . $db->sql_escape($this->session_id) . "'" : '';
1294 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
1295 WHERE $sql_where";
1296 $db->sql_query($sql);
1298 // We're changing the password of the current user and they have a key
1299 // Lets regenerate it to be safe
1300 if ($user_id === $this->data['user_id'] && $this->cookie_data['k'])
1302 $this->set_login_key($user_id);
1308 * Check if the request originated from the same page.
1309 * @param bool $check_script_path If true, the path will be checked as well
1311 function validate_referer($check_script_path = false)
1313 // no referer - nothing to validate, user's fault for turning it off (we only check on POST; so meta can't be the reason)
1314 if (empty($this->referer) || empty($this->host) )
1316 return true;
1319 $host = htmlspecialchars($this->host);
1320 $ref = substr($this->referer, strpos($this->referer, '://') + 3);
1322 if (!(stripos($ref , $host) === 0))
1324 return false;
1326 else if ($check_script_path && rtrim($this->page['root_script_path'], '/') !== '')
1328 $ref = substr($ref, strlen($host));
1329 $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
1331 if ($server_port !== 80 && $server_port !== 443 && stripos($ref, ":$server_port") === 0)
1333 $ref = substr($ref, strlen(":$server_port"));
1336 if (!(stripos(rtrim($ref, '/'), rtrim($this->page['root_script_path'], '/')) === 0))
1338 return false;
1342 return true;
1346 function unset_admin()
1348 global $db;
1349 $sql = 'UPDATE ' . SESSIONS_TABLE . '
1350 SET session_admin = 0
1351 WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\'';
1352 $db->sql_query($sql);
1358 * Base user class
1360 * This is the overarching class which contains (through session extend)
1361 * all methods utilised for user functionality during a session.
1363 * @package phpBB3
1365 class user extends session
1367 var $lang = array();
1368 var $help = array();
1369 var $theme = array();
1370 var $date_format;
1371 var $timezone;
1372 var $dst;
1374 var $lang_name;
1375 var $lang_id = false;
1376 var $lang_path;
1377 var $img_lang;
1378 var $img_array = array();
1380 // Able to add new option (id 7)
1381 var $keyoptions = array('viewimg' => 0, 'viewflash' => 1, 'viewsmilies' => 2, 'viewsigs' => 3, 'viewavatars' => 4, 'viewcensors' => 5, 'attachsig' => 6, 'bbcode' => 8, 'smilies' => 9, 'popuppm' => 10);
1382 var $keyvalues = array();
1385 * Setup basic user-specific items (style, language, ...)
1387 function setup($lang_set = false, $style = false)
1389 global $db, $template, $config, $auth, $cache;
1391 if ($this->data['user_id'] != ANONYMOUS)
1393 $this->lang_name = (file_exists(PHPBB_ROOT_PATH . 'language/' . $this->data['user_lang'] . '/common.' . PHP_EXT)) ? $this->data['user_lang'] : basename($config['default_lang']);
1394 $this->lang_path = PHPBB_ROOT_PATH . 'language/' . $this->lang_name . '/';
1396 $this->date_format = $this->data['user_dateformat'];
1397 $this->timezone = $this->data['user_timezone'] * 3600;
1398 $this->dst = $this->data['user_dst'] * 3600;
1400 else
1402 $this->lang_name = basename($config['default_lang']);
1403 $this->lang_path = PHPBB_ROOT_PATH . 'language/' . $this->lang_name . '/';
1404 $this->date_format = $config['default_dateformat'];
1405 $this->timezone = $config['board_timezone'] * 3600;
1406 $this->dst = $config['board_dst'] * 3600;
1409 * If a guest user is surfing, we try to guess his/her language first by obtaining the browser language
1410 * If re-enabled we need to make sure only those languages installed are checked
1411 * Commented out so we do not loose the code.
1413 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
1415 $accept_lang_ary = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
1417 foreach ($accept_lang_ary as $accept_lang)
1419 // Set correct format ... guess full xx_YY form
1420 $accept_lang = substr($accept_lang, 0, 2) . '_' . strtoupper(substr($accept_lang, 3, 2));
1421 $accept_lang = basename($accept_lang);
1423 if (file_exists(PHPBB_ROOT_PATH . 'language/' . $accept_lang . "/common." . PHP_EXT))
1425 $this->lang_name = $config['default_lang'] = $accept_lang;
1426 $this->lang_path = PHPBB_ROOT_PATH . 'language/' . $accept_lang . '/';
1427 break;
1429 else
1431 // No match on xx_YY so try xx
1432 $accept_lang = substr($accept_lang, 0, 2);
1433 $accept_lang = basename($accept_lang);
1435 if (file_exists(PHPBB_ROOT_PATH . 'language/' . $accept_lang . "/common." . PHP_EXT))
1437 $this->lang_name = $config['default_lang'] = $accept_lang;
1438 $this->lang_path = PHPBB_ROOT_PATH . 'language/' . $accept_lang . '/';
1439 break;
1447 // We include common language file here to not load it every time a custom language file is included
1448 $lang = &$this->lang;
1450 if ((@include $this->lang_path . 'common.' . PHP_EXT) === false)
1452 die('Language file ' . $this->lang_name . '/common.' . PHP_EXT . " couldn't be opened.");
1455 $this->add_lang($lang_set);
1456 unset($lang_set);
1458 if (!empty($_GET['style']) && $auth->acl_get('a_styles'))
1460 global $SID, $_EXTRA_URL;
1462 $style = request_var('style', 0);
1463 $SID .= '&amp;style=' . $style;
1464 $_EXTRA_URL = array('style=' . $style);
1466 else
1468 // Set up style
1469 $style = ($style) ? $style : ((!$config['override_user_style']) ? $this->data['user_style'] : $config['default_style']);
1472 $sql = 'SELECT s.style_id, t.template_storedb, t.template_path, t.template_id, t.bbcode_bitfield, c.theme_path, c.theme_name, c.theme_storedb, c.theme_id, i.imageset_path, i.imageset_id, i.imageset_name
1473 FROM ' . STYLES_TABLE . ' s, ' . STYLES_TEMPLATE_TABLE . ' t, ' . STYLES_THEME_TABLE . ' c, ' . STYLES_IMAGESET_TABLE . " i
1474 WHERE s.style_id = $style
1475 AND t.template_id = s.template_id
1476 AND c.theme_id = s.theme_id
1477 AND i.imageset_id = s.imageset_id";
1478 $result = $db->sql_query($sql, 3600);
1479 $this->theme = $db->sql_fetchrow($result);
1480 $db->sql_freeresult($result);
1482 // User has wrong style
1483 if (!$this->theme && $style == $this->data['user_style'])
1485 $style = $this->data['user_style'] = $config['default_style'];
1487 $sql = 'UPDATE ' . USERS_TABLE . "
1488 SET user_style = $style
1489 WHERE user_id = {$this->data['user_id']}";
1490 $db->sql_query($sql);
1492 $sql = 'SELECT s.style_id, t.template_storedb, t.template_path, t.template_id, t.bbcode_bitfield, c.theme_path, c.theme_name, c.theme_storedb, c.theme_id, i.imageset_path, i.imageset_id, i.imageset_name
1493 FROM ' . STYLES_TABLE . ' s, ' . STYLES_TEMPLATE_TABLE . ' t, ' . STYLES_THEME_TABLE . ' c, ' . STYLES_IMAGESET_TABLE . " i
1494 WHERE s.style_id = $style
1495 AND t.template_id = s.template_id
1496 AND c.theme_id = s.theme_id
1497 AND i.imageset_id = s.imageset_id";
1498 $result = $db->sql_query($sql, 3600);
1499 $this->theme = $db->sql_fetchrow($result);
1500 $db->sql_freeresult($result);
1503 if (!$this->theme)
1505 trigger_error('Could not get style data', E_USER_ERROR);
1508 // Now parse the cfg file and cache it,
1509 // we are only interested in the theme configuration for now
1510 $parsed_items = cache::obtain_cfg_item($this->theme, 'theme');
1512 $check_for = array(
1513 'parse_css_file' => (int) 0,
1514 'pagination_sep' => (string) ', '
1517 foreach ($check_for as $key => $default_value)
1519 $this->theme[$key] = (isset($parsed_items[$key])) ? $parsed_items[$key] : $default_value;
1520 settype($this->theme[$key], gettype($default_value));
1522 if (is_string($default_value))
1524 $this->theme[$key] = htmlspecialchars($this->theme[$key]);
1528 // If the style author specified the theme needs to be cached
1529 // (because of the used paths and variables) than make sure it is the case.
1530 // For example, if the theme uses language-specific images it needs to be stored in db.
1531 if (!$this->theme['theme_storedb'] && $this->theme['parse_css_file'])
1533 $this->theme['theme_storedb'] = 1;
1535 $stylesheet = file_get_contents(PHPBB_ROOT_PATH . "styles/{$this->theme['theme_path']}/theme/stylesheet.css");
1536 // Match CSS imports
1537 $matches = array();
1538 preg_match_all('/@import url\(["\'](.*)["\']\);/i', $stylesheet, $matches);
1540 if (sizeof($matches))
1542 $content = '';
1543 foreach ($matches[0] as $idx => $match)
1545 if ($content = @file_get_contents(PHPBB_ROOT_PATH . "styles/{$this->theme['theme_path']}/theme/" . $matches[1][$idx]))
1547 $content = trim($content);
1549 else
1551 $content = '';
1553 $stylesheet = str_replace($match, $content, $stylesheet);
1555 unset($content);
1558 $stylesheet = str_replace('./', 'styles/' . $this->theme['theme_path'] . '/theme/', $stylesheet);
1560 $sql_ary = array(
1561 'theme_data' => $stylesheet,
1562 'theme_mtime' => time(),
1563 'theme_storedb' => 1
1566 $sql = 'UPDATE ' . STYLES_THEME_TABLE . '
1567 SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
1568 WHERE theme_id = ' . $this->theme['theme_id'];
1569 $db->sql_query($sql);
1571 unset($sql_ary);
1574 $template->set_template();
1576 $this->img_lang = (file_exists(PHPBB_ROOT_PATH . 'styles/' . $this->theme['imageset_path'] . '/imageset/' . $this->lang_name)) ? $this->lang_name : $config['default_lang'];
1578 $sql = 'SELECT image_name, image_filename, image_lang, image_height, image_width
1579 FROM ' . STYLES_IMAGESET_DATA_TABLE . '
1580 WHERE imageset_id = ' . $this->theme['imageset_id'] . "
1581 AND image_filename <> ''
1582 AND image_lang IN ('" . $db->sql_escape($this->img_lang) . "', '')";
1583 $result = $db->sql_query($sql, 3600);
1585 $localised_images = false;
1586 while ($row = $db->sql_fetchrow($result))
1588 if ($row['image_lang'])
1590 $localised_images = true;
1593 $row['image_filename'] = rawurlencode($row['image_filename']);
1594 $this->img_array[$row['image_name']] = $row;
1596 $db->sql_freeresult($result);
1598 // there were no localised images, try to refresh the localised imageset for the user's language
1599 if (!$localised_images)
1601 // Attention: this code ignores the image definition list from acp_styles and just takes everything
1602 // that the config file contains
1603 $sql_ary = array();
1605 $db->sql_transaction('begin');
1607 $sql = 'DELETE FROM ' . STYLES_IMAGESET_DATA_TABLE . '
1608 WHERE imageset_id = ' . $this->theme['imageset_id'] . '
1609 AND image_lang = \'' . $db->sql_escape($this->img_lang) . '\'';
1610 $result = $db->sql_query($sql);
1612 if (@file_exists(PHPBB_ROOT_PATH . "styles/{$this->theme['imageset_path']}/imageset/{$this->img_lang}/imageset.cfg"))
1614 $cfg_data_imageset_data = parse_cfg_file(PHPBB_ROOT_PATH . "styles/{$this->theme['imageset_path']}/imageset/{$this->img_lang}/imageset.cfg");
1615 foreach ($cfg_data_imageset_data as $image_name => $value)
1617 if (strpos($value, '*') !== false)
1619 if (substr($value, -1, 1) === '*')
1621 list($image_filename, $image_height) = explode('*', $value);
1622 $image_width = 0;
1624 else
1626 list($image_filename, $image_height, $image_width) = explode('*', $value);
1629 else
1631 $image_filename = $value;
1632 $image_height = $image_width = 0;
1635 if (strpos($image_name, 'img_') === 0 && $image_filename)
1637 $image_name = substr($image_name, 4);
1638 $sql_ary[] = array(
1639 'image_name' => (string) $image_name,
1640 'image_filename' => (string) $image_filename,
1641 'image_height' => (int) $image_height,
1642 'image_width' => (int) $image_width,
1643 'imageset_id' => (int) $this->theme['imageset_id'],
1644 'image_lang' => (string) $this->img_lang,
1650 if (sizeof($sql_ary))
1652 $db->sql_multi_insert(STYLES_IMAGESET_DATA_TABLE, $sql_ary);
1653 $db->sql_transaction('commit');
1654 $cache->destroy('sql', STYLES_IMAGESET_DATA_TABLE);
1656 add_log('admin', 'LOG_IMAGESET_LANG_REFRESHED', $this->theme['imageset_name'], $this->img_lang);
1658 else
1660 $db->sql_transaction('commit');
1661 add_log('admin', 'LOG_IMAGESET_LANG_MISSING', $this->theme['imageset_name'], $this->img_lang);
1665 // Call phpbb_user_session_handler() in case external application want to "bend" some variables or replace classes...
1666 // After calling it we continue script execution...
1667 phpbb_user_session_handler();
1669 // If this function got called from the error handler we are finished here.
1670 if (defined('IN_ERROR_HANDLER'))
1672 return;
1675 // Disable board if the install/ directory is still present
1676 // For the brave development army we do not care about this, else we need to comment out this everytime we develop locally
1677 if (!defined('DEBUG_EXTRA') && !defined('ADMIN_START') && !defined('IN_INSTALL') && !defined('IN_LOGIN') && file_exists(PHPBB_ROOT_PATH . 'install'))
1679 // Adjust the message slightly according to the permissions
1680 if ($auth->acl_gets('a_', 'm_') || $auth->acl_getf_global('m_'))
1682 $message = 'REMOVE_INSTALL';
1684 else
1686 $message = (!empty($config['board_disable_msg'])) ? $config['board_disable_msg'] : 'BOARD_DISABLE';
1688 trigger_error($message);
1691 // Is board disabled and user not an admin or moderator?
1692 if ($config['board_disable'] && !defined('IN_LOGIN') && !$auth->acl_gets('a_', 'm_') && !$auth->acl_getf_global('m_'))
1694 header('HTTP/1.1 503 Service Unavailable');
1696 $message = (!empty($config['board_disable_msg'])) ? $config['board_disable_msg'] : 'BOARD_DISABLE';
1697 trigger_error($message);
1700 // Is load exceeded?
1701 if ($config['limit_load'] && $this->load !== false)
1703 if ($this->load > floatval($config['limit_load']) && !defined('IN_LOGIN'))
1705 // Set board disabled to true to let the admins/mods get the proper notification
1706 $config['board_disable'] = '1';
1708 if (!$auth->acl_gets('a_', 'm_') && !$auth->acl_getf_global('m_'))
1710 header('HTTP/1.1 503 Service Unavailable');
1711 trigger_error('BOARD_UNAVAILABLE');
1716 if (isset($this->data['session_viewonline']))
1718 // Make sure the user is able to hide his session
1719 if (!$this->data['session_viewonline'])
1721 // Reset online status if not allowed to hide the session...
1722 if (!$auth->acl_get('u_hideonline'))
1724 $sql = 'UPDATE ' . SESSIONS_TABLE . '
1725 SET session_viewonline = 1
1726 WHERE session_user_id = ' . $this->data['user_id'];
1727 $db->sql_query($sql);
1728 $this->data['session_viewonline'] = 1;
1731 else if (!$this->data['user_allow_viewonline'])
1733 // the user wants to hide and is allowed to -> cloaking device on.
1734 if ($auth->acl_get('u_hideonline'))
1736 $sql = 'UPDATE ' . SESSIONS_TABLE . '
1737 SET session_viewonline = 0
1738 WHERE session_user_id = ' . $this->data['user_id'];
1739 $db->sql_query($sql);
1740 $this->data['session_viewonline'] = 0;
1746 // Does the user need to change their password? If so, redirect to the
1747 // ucp profile reg_details page ... of course do not redirect if we're already in the ucp
1748 if (!defined('IN_ADMIN') && !defined('ADMIN_START') && $config['chg_passforce'] && $this->data['is_registered'] && $auth->acl_get('u_chgpasswd') && $this->data['user_passchg'] < time() - ($config['chg_passforce'] * 86400))
1750 if (strpos($this->page['query_string'], 'mode=reg_details') === false && $this->page['page_name'] != 'ucp.' . PHP_EXT)
1752 redirect(append_sid('ucp', 'i=profile&amp;mode=reg_details'));
1756 return;
1760 * Add Language Items - use_db and use_help are assigned where needed (only use them to force inclusion)
1762 * @param mixed $lang_set specifies the language entries to include
1763 * @param bool $use_db internal variable for recursion, do not use
1764 * @param bool $use_help internal variable for recursion, do not use
1766 * Examples:
1767 * <code>
1768 * $lang_set = array('posting', 'help' => 'faq');
1769 * $lang_set = array('posting', 'viewtopic', 'help' => array('bbcode', 'faq'))
1770 * $lang_set = array(array('posting', 'viewtopic'), 'help' => array('bbcode', 'faq'))
1771 * $lang_set = 'posting'
1772 * $lang_set = array('help' => 'faq', 'db' => array('help:faq', 'posting'))
1773 * </code>
1775 function add_lang($lang_set, $use_db = false, $use_help = false)
1777 if (is_array($lang_set))
1779 foreach ($lang_set as $key => $lang_file)
1781 // Please do not delete this line.
1782 // We have to force the type here, else [array] language inclusion will not work
1783 $key = (string) $key;
1785 if ($key == 'db')
1787 $this->add_lang($lang_file, true, $use_help);
1789 else if ($key == 'help')
1791 $this->add_lang($lang_file, $use_db, true);
1793 else if (!is_array($lang_file))
1795 $this->set_lang($this->lang, $this->help, $lang_file, $use_db, $use_help);
1797 else
1799 $this->add_lang($lang_file, $use_db, $use_help);
1802 unset($lang_set);
1804 else if ($lang_set)
1806 $this->set_lang($this->lang, $this->help, $lang_set, $use_db, $use_help);
1811 * Set language entry (called by add_lang)
1812 * @access private
1814 function set_lang(&$lang, &$help, $lang_file, $use_db = false, $use_help = false)
1816 // Make sure the language path is set (if the user setup did not happen it is not set)
1817 if (!$this->lang_path)
1819 global $config;
1821 $this->lang_path = PHPBB_ROOT_PATH . 'language/' . basename($config['default_lang']) . '/';
1824 // $lang == $this->lang
1825 // $help == $this->help
1826 // - add appropriate variables here, name them as they are used within the language file...
1827 if (!$use_db)
1829 if ($use_help && strpos($lang_file, '/') !== false)
1831 $language_filename = $this->lang_path . substr($lang_file, 0, stripos($lang_file, '/') + 1) . 'help_' . substr($lang_file, stripos($lang_file, '/') + 1) . '.' . PHP_EXT;
1833 else
1835 $language_filename = $this->lang_path . (($use_help) ? 'help_' : '') . $lang_file . '.' . PHP_EXT;
1838 if ((@include $language_filename) === false)
1840 trigger_error('Language file ' . basename($language_filename) . ' couldn\'t be opened.', E_USER_ERROR);
1843 else if ($use_db)
1845 // Get Database Language Strings
1846 // Put them into $lang if nothing is prefixed, put them into $help if help: is prefixed
1847 // For example: help:faq, posting
1852 * Format user date
1854 function format_date($gmepoch, $format = false, $forcedate = false)
1856 static $midnight;
1858 $lang_dates = $this->lang['datetime'];
1859 $format = (!$format) ? $this->date_format : $format;
1861 // Short representation of month in format
1862 if ((strpos($format, '\M') === false && strpos($format, 'M') !== false) || (strpos($format, '\r') === false && strpos($format, 'r') !== false))
1864 $lang_dates['May'] = $lang_dates['May_short'];
1867 unset($lang_dates['May_short']);
1869 if (!$midnight)
1871 list($d, $m, $y) = explode(' ', gmdate('j n Y', time() + $this->timezone + $this->dst));
1872 $midnight = gmmktime(0, 0, 0, $m, $d, $y) - $this->timezone - $this->dst;
1875 if (strpos($format, '|') === false || ($gmepoch < $midnight - 86400 && !$forcedate) || ($gmepoch > $midnight + 172800 && !$forcedate))
1877 return strtr(@gmdate(str_replace('|', '', $format), $gmepoch + $this->timezone + $this->dst), $lang_dates);
1880 if ($gmepoch > $midnight + 86400 && !$forcedate)
1882 $format = substr($format, 0, strpos($format, '|')) . '||' . substr(strrchr($format, '|'), 1);
1883 return str_replace('||', $this->lang['datetime']['TOMORROW'], strtr(@gmdate($format, $gmepoch + $this->timezone + $this->dst), $lang_dates));
1885 else if ($gmepoch > $midnight && !$forcedate)
1887 $format = substr($format, 0, strpos($format, '|')) . '||' . substr(strrchr($format, '|'), 1);
1888 return str_replace('||', $this->lang['datetime']['TODAY'], strtr(@gmdate($format, $gmepoch + $this->timezone + $this->dst), $lang_dates));
1890 else if ($gmepoch > $midnight - 86400 && !$forcedate)
1892 $format = substr($format, 0, strpos($format, '|')) . '||' . substr(strrchr($format, '|'), 1);
1893 return str_replace('||', $this->lang['datetime']['YESTERDAY'], strtr(@gmdate($format, $gmepoch + $this->timezone + $this->dst), $lang_dates));
1896 return strtr(@gmdate(str_replace('|', '', $format), $gmepoch + $this->timezone + $this->dst), $lang_dates);
1900 * Get language id currently used by the user
1902 function get_iso_lang_id()
1904 global $config, $db;
1906 if (!empty($this->lang_id))
1908 return $this->lang_id;
1911 if (!$this->lang_name)
1913 $this->lang_name = $config['default_lang'];
1916 $sql = 'SELECT lang_id
1917 FROM ' . LANG_TABLE . "
1918 WHERE lang_iso = '" . $db->sql_escape($this->lang_name) . "'";
1919 $result = $db->sql_query($sql);
1920 $this->lang_id = (int) $db->sql_fetchfield('lang_id');
1921 $db->sql_freeresult($result);
1923 return $this->lang_id;
1927 * Get users profile fields
1929 function get_profile_fields($user_id)
1931 global $db;
1933 if (isset($this->profile_fields))
1935 return;
1938 $sql = 'SELECT *
1939 FROM ' . PROFILE_FIELDS_DATA_TABLE . "
1940 WHERE user_id = $user_id";
1941 $result = $db->sql_query_limit($sql, 1);
1942 $this->profile_fields = (!($row = $db->sql_fetchrow($result))) ? array() : $row;
1943 $db->sql_freeresult($result);
1947 * Specify/Get image
1949 function img($img, $alt = '', $width = false, $suffix = '', $type = 'full_tag')
1951 static $imgs;
1953 $img_data = &$imgs[$img];
1955 if (empty($img_data))
1957 if (!isset($this->img_array[$img]))
1959 // Do not fill the image to let designers decide what to do if the image is empty
1960 $img_data = '';
1961 return $img_data;
1964 $img_data['src'] = PHPBB_ROOT_PATH . 'styles/' . $this->theme['imageset_path'] . '/imageset/' . ($this->img_array[$img]['image_lang'] ? $this->img_array[$img]['image_lang'] .'/' : '') . $this->img_array[$img]['image_filename'];
1965 $img_data['width'] = $this->img_array[$img]['image_width'];
1966 $img_data['height'] = $this->img_array[$img]['image_height'];
1969 $alt = (!empty($this->lang[$alt])) ? $this->lang[$alt] : $alt;
1971 switch ($type)
1973 case 'src':
1974 return $img_data['src'];
1975 break;
1977 case 'width':
1978 return ($width === false) ? $img_data['width'] : $width;
1979 break;
1981 case 'height':
1982 return $img_data['height'];
1983 break;
1985 default:
1986 $use_width = ($width === false) ? $img_data['width'] : $width;
1988 return '<img src="' . $img_data['src'] . '"' . (($use_width) ? ' width="' . $use_width . '"' : '') . (($img_data['height']) ? ' height="' . $img_data['height'] . '"' : '') . ' alt="' . $alt . '" title="' . $alt . '" />';
1989 break;
1994 * Get option bit field from user options
1996 function optionget($key, $data = false)
1998 if (!isset($this->keyvalues[$key]))
2000 $var = ($data) ? $data : $this->data['user_options'];
2001 $this->keyvalues[$key] = ($var & 1 << $this->keyoptions[$key]) ? true : false;
2004 return $this->keyvalues[$key];
2008 * Set option bit field for user options
2010 function optionset($key, $value, $data = false)
2012 $var = ($data) ? $data : $this->data['user_options'];
2014 if ($value && !($var & 1 << $this->keyoptions[$key]))
2016 $var += 1 << $this->keyoptions[$key];
2018 else if (!$value && ($var & 1 << $this->keyoptions[$key]))
2020 $var -= 1 << $this->keyoptions[$key];
2022 else
2024 return ($data) ? $var : false;
2027 if (!$data)
2029 $this->data['user_options'] = $var;
2030 return true;
2032 else
2034 return $var;