PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/station/forum/includes/session.php

https://github.com/bryanveloso/sayonarane
PHP | 2192 lines | 1503 code | 290 blank | 399 comment | 307 complexity | 829f56a95139ebd960414f6e6e85befb MD5 | raw file
Possible License(s): AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. *
  4. * @package phpBB3
  5. * @version $Id: session.php 9037 2008-10-26 10:52:43Z acydburn $
  6. * @copyright (c) 2005 phpBB Group
  7. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  8. *
  9. */
  10. /**
  11. * @ignore
  12. */
  13. if (!defined('IN_PHPBB'))
  14. {
  15. exit;
  16. }
  17. /**
  18. * Session class
  19. * @package phpBB3
  20. */
  21. class session
  22. {
  23. var $cookie_data = array();
  24. var $page = array();
  25. var $data = array();
  26. var $browser = '';
  27. var $forwarded_for = '';
  28. var $host = '';
  29. var $session_id = '';
  30. var $ip = '';
  31. var $load = 0;
  32. var $time_now = 0;
  33. var $update_session_page = true;
  34. /**
  35. * Extract current session page
  36. *
  37. * @param string $root_path current root path (phpbb_root_path)
  38. */
  39. function extract_current_page($root_path)
  40. {
  41. $page_array = array();
  42. // First of all, get the request uri...
  43. $script_name = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
  44. $args = (!empty($_SERVER['QUERY_STRING'])) ? explode('&', $_SERVER['QUERY_STRING']) : explode('&', getenv('QUERY_STRING'));
  45. // 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...
  46. if (!$script_name)
  47. {
  48. $script_name = (!empty($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
  49. $script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name;
  50. $page_array['failover'] = 1;
  51. }
  52. // Replace backslashes and doubled slashes (could happen on some proxy setups)
  53. $script_name = str_replace(array('\\', '//'), '/', $script_name);
  54. // Now, remove the sid and let us get a clean query string...
  55. $use_args = array();
  56. // Since some browser do not encode correctly we need to do this with some "special" characters...
  57. // " -> %22, ' => %27, < -> %3C, > -> %3E
  58. $find = array('"', "'", '<', '>');
  59. $replace = array('%22', '%27', '%3C', '%3E');
  60. foreach ($args as $key => $argument)
  61. {
  62. if (strpos($argument, 'sid=') === 0)
  63. {
  64. continue;
  65. }
  66. $use_args[] = str_replace($find, $replace, $argument);
  67. }
  68. unset($args);
  69. // The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2
  70. // The current query string
  71. $query_string = trim(implode('&', $use_args));
  72. // basenamed page name (for example: index.php)
  73. $page_name = basename($script_name);
  74. $page_name = urlencode(htmlspecialchars($page_name));
  75. // current directory within the phpBB root (for example: adm)
  76. $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path)));
  77. $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./')));
  78. $intersection = array_intersect_assoc($root_dirs, $page_dirs);
  79. $root_dirs = array_diff_assoc($root_dirs, $intersection);
  80. $page_dirs = array_diff_assoc($page_dirs, $intersection);
  81. $page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
  82. if ($page_dir && substr($page_dir, -1, 1) == '/')
  83. {
  84. $page_dir = substr($page_dir, 0, -1);
  85. }
  86. // Current page from phpBB root (for example: adm/index.php?i=10&b=2)
  87. $page = (($page_dir) ? $page_dir . '/' : '') . $page_name . (($query_string) ? "?$query_string" : '');
  88. // The script path from the webroot to the current directory (for example: /phpBB3/adm/) : always prefixed with / and ends in /
  89. $script_path = trim(str_replace('\\', '/', dirname($script_name)));
  90. // The script path from the webroot to the phpBB root (for example: /phpBB3/)
  91. $script_dirs = explode('/', $script_path);
  92. array_splice($script_dirs, -sizeof($page_dirs));
  93. $root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : '');
  94. // We are on the base level (phpBB root == webroot), lets adjust the variables a bit...
  95. if (!$root_script_path)
  96. {
  97. $root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path;
  98. }
  99. $script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/';
  100. $root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/';
  101. $page_array += array(
  102. 'page_name' => $page_name,
  103. 'page_dir' => $page_dir,
  104. 'query_string' => $query_string,
  105. 'script_path' => str_replace(' ', '%20', htmlspecialchars($script_path)),
  106. 'root_script_path' => str_replace(' ', '%20', htmlspecialchars($root_script_path)),
  107. 'page' => $page,
  108. 'forum' => (isset($_REQUEST['f']) && $_REQUEST['f'] > 0) ? (int) $_REQUEST['f'] : 0,
  109. );
  110. return $page_array;
  111. }
  112. /**
  113. * Get valid hostname/port. HTTP_HOST is used, SERVER_NAME if HTTP_HOST not present.
  114. */
  115. function extract_current_hostname()
  116. {
  117. global $config;
  118. // Get hostname
  119. $host = (!empty($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
  120. // Should be a string and lowered
  121. $host = (string) strtolower($host);
  122. // If host is equal the cookie domain or the server name (if config is set), then we assume it is valid
  123. if ((isset($config['cookie_domain']) && $host === $config['cookie_domain']) || (isset($config['server_name']) && $host === $config['server_name']))
  124. {
  125. return $host;
  126. }
  127. // Is the host actually a IP? If so, we use the IP... (IPv4)
  128. if (long2ip(ip2long($host)) === $host)
  129. {
  130. return $host;
  131. }
  132. // Now return the hostname (this also removes any port definition). The http:// is prepended to construct a valid URL, hosts never have a scheme assigned
  133. $host = @parse_url('http://' . $host);
  134. $host = (!empty($host['host'])) ? $host['host'] : '';
  135. // Remove any portions not removed by parse_url (#)
  136. $host = str_replace('#', '', $host);
  137. // If, by any means, the host is now empty, we will use a "best approach" way to guess one
  138. if (empty($host))
  139. {
  140. if (!empty($config['server_name']))
  141. {
  142. $host = $config['server_name'];
  143. }
  144. else if (!empty($config['cookie_domain']))
  145. {
  146. $host = (strpos($config['cookie_domain'], '.') === 0) ? substr($config['cookie_domain'], 1) : $config['cookie_domain'];
  147. }
  148. else
  149. {
  150. // Set to OS hostname or localhost
  151. $host = (function_exists('php_uname')) ? php_uname('n') : 'localhost';
  152. }
  153. }
  154. // It may be still no valid host, but for sure only a hostname (we may further expand on the cookie domain... if set)
  155. return $host;
  156. }
  157. /**
  158. * Start session management
  159. *
  160. * This is where all session activity begins. We gather various pieces of
  161. * information from the client and server. We test to see if a session already
  162. * exists. If it does, fine and dandy. If it doesn't we'll go on to create a
  163. * new one ... pretty logical heh? We also examine the system load (if we're
  164. * running on a system which makes such information readily available) and
  165. * halt if it's above an admin definable limit.
  166. *
  167. * @param bool $update_session_page if true the session page gets updated.
  168. * This can be set to circumvent certain scripts to update the users last visited page.
  169. */
  170. function session_begin($update_session_page = true)
  171. {
  172. global $phpEx, $SID, $_SID, $_EXTRA_URL, $db, $config, $phpbb_root_path;
  173. // Give us some basic information
  174. $this->time_now = time();
  175. $this->cookie_data = array('u' => 0, 'k' => '');
  176. $this->update_session_page = $update_session_page;
  177. $this->browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
  178. $this->referer = (!empty($_SERVER['HTTP_REFERER'])) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : '';
  179. $this->forwarded_for = (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) ? (string) $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
  180. $this->host = $this->extract_current_hostname();
  181. $this->page = $this->extract_current_page($phpbb_root_path);
  182. // if the forwarded for header shall be checked we have to validate its contents
  183. if ($config['forwarded_for_check'])
  184. {
  185. $this->forwarded_for = preg_replace('#, +#', ', ', $this->forwarded_for);
  186. // split the list of IPs
  187. $ips = explode(', ', $this->forwarded_for);
  188. foreach ($ips as $ip)
  189. {
  190. // check IPv4 first, the IPv6 is hopefully only going to be used very seldomly
  191. if (!empty($ip) && !preg_match(get_preg_expression('ipv4'), $ip) && !preg_match(get_preg_expression('ipv6'), $ip))
  192. {
  193. // contains invalid data, don't use the forwarded for header
  194. $this->forwarded_for = '';
  195. break;
  196. }
  197. }
  198. }
  199. else
  200. {
  201. $this->forwarded_for = '';
  202. }
  203. if (isset($_COOKIE[$config['cookie_name'] . '_sid']) || isset($_COOKIE[$config['cookie_name'] . '_u']))
  204. {
  205. $this->cookie_data['u'] = request_var($config['cookie_name'] . '_u', 0, false, true);
  206. $this->cookie_data['k'] = request_var($config['cookie_name'] . '_k', '', false, true);
  207. $this->session_id = request_var($config['cookie_name'] . '_sid', '', false, true);
  208. $SID = (defined('NEED_SID')) ? '?sid=' . $this->session_id : '?sid=';
  209. $_SID = (defined('NEED_SID')) ? $this->session_id : '';
  210. if (empty($this->session_id))
  211. {
  212. $this->session_id = $_SID = request_var('sid', '');
  213. $SID = '?sid=' . $this->session_id;
  214. $this->cookie_data = array('u' => 0, 'k' => '');
  215. }
  216. }
  217. else
  218. {
  219. $this->session_id = $_SID = request_var('sid', '');
  220. $SID = '?sid=' . $this->session_id;
  221. }
  222. $_EXTRA_URL = array();
  223. // Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
  224. // it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
  225. $this->ip = (!empty($_SERVER['REMOTE_ADDR'])) ? htmlspecialchars($_SERVER['REMOTE_ADDR']) : '';
  226. $this->load = false;
  227. // Load limit check (if applicable)
  228. if ($config['limit_load'] || $config['limit_search_load'])
  229. {
  230. if ((function_exists('sys_getloadavg') && $load = sys_getloadavg()) || ($load = explode(' ', @file_get_contents('/proc/loadavg'))))
  231. {
  232. $this->load = array_slice($load, 0, 1);
  233. $this->load = floatval($this->load[0]);
  234. }
  235. else
  236. {
  237. set_config('limit_load', '0');
  238. set_config('limit_search_load', '0');
  239. }
  240. }
  241. // Is session_id is set or session_id is set and matches the url param if required
  242. if (!empty($this->session_id) && (!defined('NEED_SID') || (isset($_GET['sid']) && $this->session_id === $_GET['sid'])))
  243. {
  244. $sql = 'SELECT u.*, s.*
  245. FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . " u
  246. WHERE s.session_id = '" . $db->sql_escape($this->session_id) . "'
  247. AND u.user_id = s.session_user_id";
  248. $result = $db->sql_query($sql);
  249. $this->data = $db->sql_fetchrow($result);
  250. $db->sql_freeresult($result);
  251. // Did the session exist in the DB?
  252. if (isset($this->data['user_id']))
  253. {
  254. // Validate IP length according to admin ... enforces an IP
  255. // check on bots if admin requires this
  256. // $quadcheck = ($config['ip_check_bot'] && $this->data['user_type'] & USER_BOT) ? 4 : $config['ip_check'];
  257. if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false)
  258. {
  259. $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
  260. $u_ip = short_ipv6($this->ip, $config['ip_check']);
  261. }
  262. else
  263. {
  264. $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
  265. $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
  266. }
  267. $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
  268. $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : '';
  269. $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
  270. $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : '';
  271. // referer checks
  272. // The @ before $config['referer_validation'] suppresses notices present while running the updater
  273. $check_referer_path = (@$config['referer_validation'] == REFERER_VALIDATE_PATH);
  274. $referer_valid = true;
  275. // we assume HEAD and TRACE to be foul play and thus only whitelist GET
  276. if (@$config['referer_validation'] && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) !== 'get')
  277. {
  278. $referer_valid = $this->validate_referer($check_referer_path);
  279. }
  280. if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for && $referer_valid)
  281. {
  282. $session_expired = false;
  283. // Check whether the session is still valid if we have one
  284. $method = basename(trim($config['auth_method']));
  285. include_once($phpbb_root_path . 'includes/auth/auth_' . $method . '.' . $phpEx);
  286. $method = 'validate_session_' . $method;
  287. if (function_exists($method))
  288. {
  289. if (!$method($this->data))
  290. {
  291. $session_expired = true;
  292. }
  293. }
  294. if (!$session_expired)
  295. {
  296. // Check the session length timeframe if autologin is not enabled.
  297. // Else check the autologin length... and also removing those having autologin enabled but no longer allowed board-wide.
  298. if (!$this->data['session_autologin'])
  299. {
  300. if ($this->data['session_time'] < $this->time_now - ($config['session_length'] + 60))
  301. {
  302. $session_expired = true;
  303. }
  304. }
  305. else if (!$config['allow_autologin'] || ($config['max_autologin_time'] && $this->data['session_time'] < $this->time_now - (86400 * (int) $config['max_autologin_time']) + 60))
  306. {
  307. $session_expired = true;
  308. }
  309. }
  310. if (!$session_expired)
  311. {
  312. // Only update session DB a minute or so after last update or if page changes
  313. if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page']))
  314. {
  315. $sql_ary = array('session_time' => $this->time_now);
  316. if ($this->update_session_page)
  317. {
  318. $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
  319. $sql_ary['session_forum_id'] = $this->page['forum'];
  320. }
  321. $db->sql_return_on_error(true);
  322. $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
  323. WHERE session_id = '" . $db->sql_escape($this->session_id) . "'";
  324. $result = $db->sql_query($sql);
  325. $db->sql_return_on_error(false);
  326. // If the database is not yet updated, there will be an error due to the session_forum_id
  327. // @todo REMOVE for 3.0.2
  328. if ($result === false)
  329. {
  330. unset($sql_ary['session_forum_id']);
  331. $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
  332. WHERE session_id = '" . $db->sql_escape($this->session_id) . "'";
  333. $db->sql_query($sql);
  334. }
  335. }
  336. $this->data['is_registered'] = ($this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
  337. $this->data['is_bot'] = (!$this->data['is_registered'] && $this->data['user_id'] != ANONYMOUS) ? true : false;
  338. $this->data['user_lang'] = basename($this->data['user_lang']);
  339. return true;
  340. }
  341. }
  342. else
  343. {
  344. // Added logging temporarly to help debug bugs...
  345. if (defined('DEBUG_EXTRA') && $this->data['user_id'] != ANONYMOUS)
  346. {
  347. if ($referer_valid)
  348. {
  349. add_log('critical', 'LOG_IP_BROWSER_FORWARDED_CHECK', $u_ip, $s_ip, $u_browser, $s_browser, htmlspecialchars($u_forwarded_for), htmlspecialchars($s_forwarded_for));
  350. }
  351. else
  352. {
  353. add_log('critical', 'LOG_REFERER_INVALID', $this->referer);
  354. }
  355. }
  356. }
  357. }
  358. }
  359. // If we reach here then no (valid) session exists. So we'll create a new one
  360. return $this->session_create();
  361. }
  362. /**
  363. * Create a new session
  364. *
  365. * If upon trying to start a session we discover there is nothing existing we
  366. * jump here. Additionally this method is called directly during login to regenerate
  367. * the session for the specific user. In this method we carry out a number of tasks;
  368. * garbage collection, (search)bot checking, banned user comparison. Basically
  369. * though this method will result in a new session for a specific user.
  370. */
  371. function session_create($user_id = false, $set_admin = false, $persist_login = false, $viewonline = true)
  372. {
  373. global $SID, $_SID, $db, $config, $cache, $phpbb_root_path, $phpEx;
  374. $this->data = array();
  375. /* Garbage collection ... remove old sessions updating user information
  376. // if necessary. It means (potentially) 11 queries but only infrequently
  377. if ($this->time_now > $config['session_last_gc'] + $config['session_gc'])
  378. {
  379. $this->session_gc();
  380. }*/
  381. // Do we allow autologin on this board? No? Then override anything
  382. // that may be requested here
  383. if (!$config['allow_autologin'])
  384. {
  385. $this->cookie_data['k'] = $persist_login = false;
  386. }
  387. /**
  388. * Here we do a bot check, oh er saucy! No, not that kind of bot
  389. * check. We loop through the list of bots defined by the admin and
  390. * see if we have any useragent and/or IP matches. If we do, this is a
  391. * bot, act accordingly
  392. */
  393. $bot = false;
  394. $active_bots = $cache->obtain_bots();
  395. foreach ($active_bots as $row)
  396. {
  397. if ($row['bot_agent'] && preg_match('#' . str_replace('\*', '.*?', preg_quote($row['bot_agent'], '#')) . '#i', $this->browser))
  398. {
  399. $bot = $row['user_id'];
  400. }
  401. // If ip is supplied, we will make sure the ip is matching too...
  402. if ($row['bot_ip'] && ($bot || !$row['bot_agent']))
  403. {
  404. // Set bot to false, then we only have to set it to true if it is matching
  405. $bot = false;
  406. foreach (explode(',', $row['bot_ip']) as $bot_ip)
  407. {
  408. if (strpos($this->ip, $bot_ip) === 0)
  409. {
  410. $bot = (int) $row['user_id'];
  411. break;
  412. }
  413. }
  414. }
  415. if ($bot)
  416. {
  417. break;
  418. }
  419. }
  420. $method = basename(trim($config['auth_method']));
  421. include_once($phpbb_root_path . 'includes/auth/auth_' . $method . '.' . $phpEx);
  422. $method = 'autologin_' . $method;
  423. if (function_exists($method))
  424. {
  425. $this->data = $method();
  426. if (sizeof($this->data))
  427. {
  428. $this->cookie_data['k'] = '';
  429. $this->cookie_data['u'] = $this->data['user_id'];
  430. }
  431. }
  432. // If we're presented with an autologin key we'll join against it.
  433. // Else if we've been passed a user_id we'll grab data based on that
  434. if (isset($this->cookie_data['k']) && $this->cookie_data['k'] && $this->cookie_data['u'] && !sizeof($this->data))
  435. {
  436. $sql = 'SELECT u.*
  437. FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
  438. WHERE u.user_id = ' . (int) $this->cookie_data['u'] . '
  439. AND u.user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ")
  440. AND k.user_id = u.user_id
  441. AND k.key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'";
  442. $result = $db->sql_query($sql);
  443. $this->data = $db->sql_fetchrow($result);
  444. $db->sql_freeresult($result);
  445. $bot = false;
  446. }
  447. else if ($user_id !== false && !sizeof($this->data))
  448. {
  449. $this->cookie_data['k'] = '';
  450. $this->cookie_data['u'] = $user_id;
  451. $sql = 'SELECT *
  452. FROM ' . USERS_TABLE . '
  453. WHERE user_id = ' . (int) $this->cookie_data['u'] . '
  454. AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')';
  455. $result = $db->sql_query($sql);
  456. $this->data = $db->sql_fetchrow($result);
  457. $db->sql_freeresult($result);
  458. $bot = false;
  459. }
  460. // If no data was returned one or more of the following occurred:
  461. // Key didn't match one in the DB
  462. // User does not exist
  463. // User is inactive
  464. // User is bot
  465. if (!sizeof($this->data) || !is_array($this->data))
  466. {
  467. $this->cookie_data['k'] = '';
  468. $this->cookie_data['u'] = ($bot) ? $bot : ANONYMOUS;
  469. if (!$bot)
  470. {
  471. $sql = 'SELECT *
  472. FROM ' . USERS_TABLE . '
  473. WHERE user_id = ' . (int) $this->cookie_data['u'];
  474. }
  475. else
  476. {
  477. // We give bots always the same session if it is not yet expired.
  478. $sql = 'SELECT u.*, s.*
  479. FROM ' . USERS_TABLE . ' u
  480. LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
  481. WHERE u.user_id = ' . (int) $bot;
  482. }
  483. $result = $db->sql_query($sql);
  484. $this->data = $db->sql_fetchrow($result);
  485. $db->sql_freeresult($result);
  486. }
  487. if ($this->data['user_id'] != ANONYMOUS && !$bot)
  488. {
  489. $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());
  490. }
  491. else
  492. {
  493. $this->data['session_last_visit'] = $this->time_now;
  494. }
  495. // Force user id to be integer...
  496. $this->data['user_id'] = (int) $this->data['user_id'];
  497. // At this stage we should have a filled data array, defined cookie u and k data.
  498. // data array should contain recent session info if we're a real user and a recent
  499. // session exists in which case session_id will also be set
  500. // Is user banned? Are they excluded? Won't return on ban, exists within method
  501. if ($this->data['user_type'] != USER_FOUNDER)
  502. {
  503. if (!$config['forwarded_for_check'])
  504. {
  505. $this->check_ban($this->data['user_id'], $this->ip);
  506. }
  507. else
  508. {
  509. $ips = explode(', ', $this->forwarded_for);
  510. $ips[] = $this->ip;
  511. $this->check_ban($this->data['user_id'], $ips);
  512. }
  513. }
  514. $this->data['is_registered'] = (!$bot && $this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
  515. $this->data['is_bot'] = ($bot) ? true : false;
  516. // If our friend is a bot, we re-assign a previously assigned session
  517. if ($this->data['is_bot'] && $bot == $this->data['user_id'] && $this->data['session_id'])
  518. {
  519. // Only assign the current session if the ip, browser and forwarded_for match...
  520. if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false)
  521. {
  522. $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
  523. $u_ip = short_ipv6($this->ip, $config['ip_check']);
  524. }
  525. else
  526. {
  527. $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
  528. $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
  529. }
  530. $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
  531. $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : '';
  532. $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
  533. $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : '';
  534. if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for)
  535. {
  536. $this->session_id = $this->data['session_id'];
  537. // Only update session DB a minute or so after last update or if page changes
  538. if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page']))
  539. {
  540. $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
  541. $sql_ary = array('session_time' => $this->time_now, 'session_last_visit' => $this->time_now, 'session_admin' => 0);
  542. if ($this->update_session_page)
  543. {
  544. $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
  545. $sql_ary['session_forum_id'] = $this->page['forum'];
  546. }
  547. $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
  548. WHERE session_id = '" . $db->sql_escape($this->session_id) . "'";
  549. $db->sql_query($sql);
  550. // Update the last visit time
  551. $sql = 'UPDATE ' . USERS_TABLE . '
  552. SET user_lastvisit = ' . (int) $this->data['session_time'] . '
  553. WHERE user_id = ' . (int) $this->data['user_id'];
  554. $db->sql_query($sql);
  555. }
  556. $SID = '?sid=';
  557. $_SID = '';
  558. return true;
  559. }
  560. else
  561. {
  562. // If the ip and browser does not match make sure we only have one bot assigned to one session
  563. $db->sql_query('DELETE FROM ' . SESSIONS_TABLE . ' WHERE session_user_id = ' . $this->data['user_id']);
  564. }
  565. }
  566. $session_autologin = (($this->cookie_data['k'] || $persist_login) && $this->data['is_registered']) ? true : false;
  567. $set_admin = ($set_admin && $this->data['is_registered']) ? true : false;
  568. // Create or update the session
  569. $sql_ary = array(
  570. 'session_user_id' => (int) $this->data['user_id'],
  571. 'session_start' => (int) $this->time_now,
  572. 'session_last_visit' => (int) $this->data['session_last_visit'],
  573. 'session_time' => (int) $this->time_now,
  574. 'session_browser' => (string) trim(substr($this->browser, 0, 149)),
  575. 'session_forwarded_for' => (string) $this->forwarded_for,
  576. 'session_ip' => (string) $this->ip,
  577. 'session_autologin' => ($session_autologin) ? 1 : 0,
  578. 'session_admin' => ($set_admin) ? 1 : 0,
  579. 'session_viewonline' => ($viewonline) ? 1 : 0,
  580. );
  581. if ($this->update_session_page)
  582. {
  583. $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199);
  584. $sql_ary['session_forum_id'] = $this->page['forum'];
  585. }
  586. $db->sql_return_on_error(true);
  587. $sql = 'DELETE
  588. FROM ' . SESSIONS_TABLE . '
  589. WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\'
  590. AND session_user_id = ' . ANONYMOUS;
  591. if (!defined('IN_ERROR_HANDLER') && (!$this->session_id || !$db->sql_query($sql) || !$db->sql_affectedrows()))
  592. {
  593. // Limit new sessions in 1 minute period (if required)
  594. if (empty($this->data['session_time']) && $config['active_sessions'])
  595. {
  596. // $db->sql_return_on_error(false);
  597. $sql = 'SELECT COUNT(session_id) AS sessions
  598. FROM ' . SESSIONS_TABLE . '
  599. WHERE session_time >= ' . ($this->time_now - 60);
  600. $result = $db->sql_query($sql);
  601. $row = $db->sql_fetchrow($result);
  602. $db->sql_freeresult($result);
  603. if ((int) $row['sessions'] > (int) $config['active_sessions'])
  604. {
  605. header('HTTP/1.1 503 Service Unavailable');
  606. trigger_error('BOARD_UNAVAILABLE');
  607. }
  608. }
  609. }
  610. // Since we re-create the session id here, the inserted row must be unique. Therefore, we display potential errors.
  611. // Commented out because it will not allow forums to update correctly
  612. // $db->sql_return_on_error(false);
  613. $this->session_id = $this->data['session_id'] = md5(unique_id());
  614. $sql_ary['session_id'] = (string) $this->session_id;
  615. $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199);
  616. $sql_ary['session_forum_id'] = $this->page['forum'];
  617. $sql = 'INSERT INTO ' . SESSIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
  618. $db->sql_query($sql);
  619. $db->sql_return_on_error(false);
  620. // Regenerate autologin/persistent login key
  621. if ($session_autologin)
  622. {
  623. $this->set_login_key();
  624. }
  625. // refresh data
  626. $SID = '?sid=' . $this->session_id;
  627. $_SID = $this->session_id;
  628. $this->data = array_merge($this->data, $sql_ary);
  629. if (!$bot)
  630. {
  631. $cookie_expire = $this->time_now + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000);
  632. $this->set_cookie('u', $this->cookie_data['u'], $cookie_expire);
  633. $this->set_cookie('k', $this->cookie_data['k'], $cookie_expire);
  634. $this->set_cookie('sid', $this->session_id, $cookie_expire);
  635. unset($cookie_expire);
  636. $sql = 'SELECT COUNT(session_id) AS sessions
  637. FROM ' . SESSIONS_TABLE . '
  638. WHERE session_user_id = ' . (int) $this->data['user_id'] . '
  639. AND session_time >= ' . (int) ($this->time_now - (max($config['session_length'], $config['form_token_lifetime'])));
  640. $result = $db->sql_query($sql);
  641. $row = $db->sql_fetchrow($result);
  642. $db->sql_freeresult($result);
  643. if ((int) $row['sessions'] <= 1 || empty($this->data['user_form_salt']))
  644. {
  645. $this->data['user_form_salt'] = unique_id();
  646. // Update the form key
  647. $sql = 'UPDATE ' . USERS_TABLE . '
  648. SET user_form_salt = \'' . $db->sql_escape($this->data['user_form_salt']) . '\'
  649. WHERE user_id = ' . (int) $this->data['user_id'];
  650. $db->sql_query($sql);
  651. }
  652. }
  653. else
  654. {
  655. $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
  656. // Update the last visit time
  657. $sql = 'UPDATE ' . USERS_TABLE . '
  658. SET user_lastvisit = ' . (int) $this->data['session_time'] . '
  659. WHERE user_id = ' . (int) $this->data['user_id'];
  660. $db->sql_query($sql);
  661. $SID = '?sid=';
  662. $_SID = '';
  663. }
  664. return true;
  665. }
  666. /**
  667. * Kills a session
  668. *
  669. * This method does what it says on the tin. It will delete a pre-existing session.
  670. * It resets cookie information (destroying any autologin key within that cookie data)
  671. * and update the users information from the relevant session data. It will then
  672. * grab guest user information.
  673. */
  674. function session_kill($new_session = true)
  675. {
  676. global $SID, $_SID, $db, $config, $phpbb_root_path, $phpEx;
  677. $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
  678. WHERE session_id = '" . $db->sql_escape($this->session_id) . "'
  679. AND session_user_id = " . (int) $this->data['user_id'];
  680. $db->sql_query($sql);
  681. // Allow connecting logout with external auth method logout
  682. $method = basename(trim($config['auth_method']));
  683. include_once($phpbb_root_path . 'includes/auth/auth_' . $method . '.' . $phpEx);
  684. $method = 'logout_' . $method;
  685. if (function_exists($method))
  686. {
  687. $method($this->data, $new_session);
  688. }
  689. if ($this->data['user_id'] != ANONYMOUS)
  690. {
  691. // Delete existing session, update last visit info first!
  692. if (!isset($this->data['session_time']))
  693. {
  694. $this->data['session_time'] = time();
  695. }
  696. $sql = 'UPDATE ' . USERS_TABLE . '
  697. SET user_lastvisit = ' . (int) $this->data['session_time'] . '
  698. WHERE user_id = ' . (int) $this->data['user_id'];
  699. $db->sql_query($sql);
  700. if ($this->cookie_data['k'])
  701. {
  702. $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
  703. WHERE user_id = ' . (int) $this->data['user_id'] . "
  704. AND key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'";
  705. $db->sql_query($sql);
  706. }
  707. // Reset the data array
  708. $this->data = array();
  709. $sql = 'SELECT *
  710. FROM ' . USERS_TABLE . '
  711. WHERE user_id = ' . ANONYMOUS;
  712. $result = $db->sql_query($sql);
  713. $this->data = $db->sql_fetchrow($result);
  714. $db->sql_freeresult($result);
  715. }
  716. $cookie_expire = $this->time_now - 31536000;
  717. $this->set_cookie('u', '', $cookie_expire);
  718. $this->set_cookie('k', '', $cookie_expire);
  719. $this->set_cookie('sid', '', $cookie_expire);
  720. unset($cookie_expire);
  721. $SID = '?sid=';
  722. $this->session_id = $_SID = '';
  723. // To make sure a valid session is created we create one for the anonymous user
  724. if ($new_session)
  725. {
  726. $this->session_create(ANONYMOUS);
  727. }
  728. return true;
  729. }
  730. /**
  731. * Session garbage collection
  732. *
  733. * This looks a lot more complex than it really is. Effectively we are
  734. * deleting any sessions older than an admin definable limit. Due to the
  735. * way in which we maintain session data we have to ensure we update user
  736. * data before those sessions are destroyed. In addition this method
  737. * removes autologin key information that is older than an admin defined
  738. * limit.
  739. */
  740. function session_gc()
  741. {
  742. global $db, $config;
  743. $batch_size = 10;
  744. if (!$this->time_now)
  745. {
  746. $this->time_now = time();
  747. }
  748. // Firstly, delete guest sessions
  749. $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
  750. WHERE session_user_id = ' . ANONYMOUS . '
  751. AND session_time < ' . (int) ($this->time_now - $config['session_length']);
  752. $db->sql_query($sql);
  753. // Get expired sessions, only most recent for each user
  754. $sql = 'SELECT session_user_id, session_page, MAX(session_time) AS recent_time
  755. FROM ' . SESSIONS_TABLE . '
  756. WHERE session_time < ' . ($this->time_now - $config['session_length']) . '
  757. GROUP BY session_user_id, session_page';
  758. $result = $db->sql_query_limit($sql, $batch_size);
  759. $del_user_id = array();
  760. $del_sessions = 0;
  761. while ($row = $db->sql_fetchrow($result))
  762. {
  763. $sql = 'UPDATE ' . USERS_TABLE . '
  764. SET user_lastvisit = ' . (int) $row['recent_time'] . ", user_lastpage = '" . $db->sql_escape($row['session_page']) . "'
  765. WHERE user_id = " . (int) $row['session_user_id'];
  766. $db->sql_query($sql);
  767. $del_user_id[] = (int) $row['session_user_id'];
  768. $del_sessions++;
  769. }
  770. $db->sql_freeresult($result);
  771. if (sizeof($del_user_id))
  772. {
  773. // Delete expired sessions
  774. $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
  775. WHERE ' . $db->sql_in_set('session_user_id', $del_user_id) . '
  776. AND session_time < ' . ($this->time_now - $config['session_length']);
  777. $db->sql_query($sql);
  778. }
  779. if ($del_sessions < $batch_size)
  780. {
  781. // Less than 10 users, update gc timer ... else we want gc
  782. // called again to delete other sessions
  783. set_config('session_last_gc', $this->time_now, true);
  784. if ($config['max_autologin_time'])
  785. {
  786. $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
  787. WHERE last_login < ' . (time() - (86400 * (int) $config['max_autologin_time']));
  788. $db->sql_query($sql);
  789. }
  790. $this->confirm_gc();
  791. }
  792. return;
  793. }
  794. function confirm_gc($type = 0)
  795. {
  796. global $db, $config;
  797. $sql = 'SELECT DISTINCT c.session_id
  798. FROM ' . CONFIRM_TABLE . ' c
  799. LEFT JOIN ' . SESSIONS_TABLE . ' s ON (c.session_id = s.session_id)
  800. WHERE s.session_id IS NULL' .
  801. ((empty($type)) ? '' : ' AND c.confirm_type = ' . (int) $type);
  802. $result = $db->sql_query($sql);
  803. if ($row = $db->sql_fetchrow($result))
  804. {
  805. $sql_in = array();
  806. do
  807. {
  808. $sql_in[] = (string) $row['session_id'];
  809. }
  810. while ($row = $db->sql_fetchrow($result));
  811. if (sizeof($sql_in))
  812. {
  813. $sql = 'DELETE FROM ' . CONFIRM_TABLE . '
  814. WHERE ' . $db->sql_in_set('session_id', $sql_in);
  815. $db->sql_query($sql);
  816. }
  817. }
  818. $db->sql_freeresult($result);
  819. }
  820. /**
  821. * Sets a cookie
  822. *
  823. * 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.
  824. *
  825. * @param string $name Name of the cookie, will be automatically prefixed with the phpBB cookie name. track becomes [cookie_name]_track then.
  826. * @param string $cookiedata The data to hold within the cookie
  827. * @param int $cookietime The expiration time as UNIX timestamp. If 0 is provided, a session cookie is set.
  828. */
  829. function set_cookie($name, $cookiedata, $cookietime)
  830. {
  831. global $config;
  832. $name_data = rawurlencode($config['cookie_name'] . '_' . $name) . '=' . rawurlencode($cookiedata);
  833. $expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime);
  834. $domain = (!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain'];
  835. header('Set-Cookie: ' . $name_data . (($cookietime) ? '; expires=' . $expire : '') . '; path=' . $config['cookie_path'] . $domain . ((!$config['cookie_secure']) ? '' : '; secure') . '; HttpOnly', false);
  836. }
  837. /**
  838. * Check for banned user
  839. *
  840. * Checks whether the supplied user is banned by id, ip or email. If no parameters
  841. * are passed to the method pre-existing session data is used. If $return is false
  842. * this routine does not return on finding a banned user, it outputs a relevant
  843. * message and stops execution.
  844. *
  845. * @param string|array $user_ips Can contain a string with one IP or an array of multiple IPs
  846. */
  847. function check_ban($user_id = false, $user_ips = false, $user_email = false, $return = false)
  848. {
  849. global $config, $db;
  850. if (defined('IN_CHECK_BAN'))
  851. {
  852. return;
  853. }
  854. $banned = false;
  855. $cache_ttl = 3600;
  856. $where_sql = array();
  857. $sql = 'SELECT ban_ip, ban_userid, ban_email, ban_exclude, ban_give_reason, ban_end
  858. FROM ' . BANLIST_TABLE . '
  859. WHERE ';
  860. // Determine which entries to check, only return those
  861. if ($user_email === false)
  862. {
  863. $where_sql[] = "ban_email = ''";
  864. }
  865. if ($user_ips === false)
  866. {
  867. $where_sql[] = "(ban_ip = '' OR ban_exclude = 1)";
  868. }
  869. if ($user_id === false)
  870. {
  871. $where_sql[] = '(ban_userid = 0 OR ban_exclude = 1)';
  872. }
  873. else
  874. {
  875. $cache_ttl = ($user_id == ANONYMOUS) ? 3600 : 0;
  876. $_sql = '(ban_userid = ' . $user_id;
  877. if ($user_email !== false)
  878. {
  879. $_sql .= " OR ban_email <> ''";
  880. }
  881. if ($user_ips !== false)
  882. {
  883. $_sql .= " OR ban_ip <> ''";
  884. }
  885. $_sql .= ')';
  886. $where_sql[] = $_sql;
  887. }
  888. $sql .= (sizeof($where_sql)) ? implode(' AND ', $where_sql) : '';
  889. $result = $db->sql_query($sql, $cache_ttl);
  890. $ban_triggered_by = 'user';
  891. while ($row = $db->sql_fetchrow($result))
  892. {
  893. if ($row['ban_end'] && $row['ban_end'] < time())
  894. {
  895. continue;
  896. }
  897. $ip_banned = false;
  898. if (!empty($row['ban_ip']))
  899. {
  900. if (!is_array($user_ips))
  901. {
  902. $ip_banned = preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ips);
  903. }
  904. else
  905. {
  906. foreach ($user_ips as $user_ip)
  907. {
  908. if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ip))
  909. {
  910. $ip_banned = true;
  911. break;
  912. }
  913. }
  914. }
  915. }
  916. if ((!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) ||
  917. $ip_banned ||
  918. (!empty($row['ban_email']) && preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')) . '$#i', $user_email)))
  919. {
  920. if (!empty($row['ban_exclude']))
  921. {
  922. $banned = false;
  923. break;
  924. }
  925. else
  926. {
  927. $banned = true;
  928. $ban_row = $row;
  929. if (!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id)
  930. {
  931. $ban_triggered_by = 'user';
  932. }
  933. else if ($ip_banned)
  934. {
  935. $ban_triggered_by = 'ip';
  936. }
  937. else
  938. {
  939. $ban_triggered_by = 'email';
  940. }
  941. // Don't break. Check if there is an exclude rule for this user
  942. }
  943. }
  944. }
  945. $db->sql_freeresult($result);
  946. if ($banned && !$return)
  947. {
  948. global $template;
  949. // If the session is empty we need to create a valid one...
  950. if (empty($this->session_id))
  951. {
  952. // This seems to be no longer needed? - #14971
  953. // $this->session_create(ANONYMOUS);
  954. }
  955. // Initiate environment ... since it won't be set at this stage
  956. $this->setup();
  957. // Logout the user, banned users are unable to use the normal 'logout' link
  958. if ($this->data['user_id'] != ANONYMOUS)
  959. {
  960. $this->session_kill();
  961. }
  962. // We show a login box here to allow founders accessing the board if banned by IP
  963. if (defined('IN_LOGIN') && $this->data['user_id'] == ANONYMOUS)
  964. {
  965. global $phpEx;
  966. $this->setup('ucp');
  967. $this->data['is_registered'] = $this->data['is_bot'] = false;
  968. // Set as a precaution to allow login_box() handling this case correctly as well as this function not being executed again.
  969. define('IN_CHECK_BAN', 1);
  970. login_box("index.$phpEx");
  971. // The false here is needed, else the user is able to circumvent the ban.
  972. $this->session_kill(false);
  973. }
  974. // Ok, we catch the case of an empty session id for the anonymous user...
  975. // This can happen if the user is logging in, banned by username and the login_box() being called "again".
  976. if (empty($this->session_id) && defined('IN_CHECK_BAN'))
  977. {
  978. $this->session_create(ANONYMOUS);
  979. }
  980. // Determine which message to output
  981. $till_date = ($ban_row['ban_end']) ? $this->format_date($ban_row['ban_end']) : '';
  982. $message = ($ban_row['ban_end']) ? 'BOARD_BAN_TIME' : 'BOARD_BAN_PERM';
  983. $message = sprintf($this->lang[$message], $till_date, '<a href="mailto:' . $config['board_contact'] . '">', '</a>');
  984. $message .= ($ban_row['ban_give_reason']) ? '<br /><br />' . sprintf($this->lang['BOARD_BAN_REASON'], $ban_row['ban_give_reason']) : '';
  985. $message .= '<br /><br /><em>' . $this->lang['BAN_TRIGGERED_BY_' . strtoupper($ban_triggered_by)] . '</em>';
  986. // To circumvent session_begin returning a valid value and the check_ban() not called on second page view, we kill the session again
  987. $this->session_kill(false);
  988. // A very special case... we are within the cron script which is not supposed to print out the ban message... show blank page
  989. if (defined('IN_CRON'))
  990. {
  991. garbage_collection();
  992. exit_handler();
  993. exit;
  994. }
  995. trigger_error($message);
  996. }
  997. return ($banned && $ban_row['ban_give_reason']) ? $ban_row['ban_give_reason'] : $banned;
  998. }
  999. /**
  1000. * Check if ip is blacklisted
  1001. * This should be called only where absolutly necessary
  1002. *
  1003. * Only IPv4 (rbldns does not support AAAA records/IPv6 lookups)
  1004. *
  1005. * @author satmd (from the php manual)
  1006. * @param string $mode register/post - spamcop for example is ommitted for posting
  1007. * @return false if ip is not blacklisted, else an array([checked server], [lookup])
  1008. */
  1009. function check_dnsbl($mode, $ip = false)
  1010. {
  1011. if ($ip === false)
  1012. {
  1013. $ip = $this->ip;
  1014. }
  1015. $dnsbl_check = array(
  1016. 'sbl-xbl.spamhaus.org' => 'http://www.spamhaus.org/query/bl?ip=',
  1017. );
  1018. if ($mode == 'register')
  1019. {
  1020. $dnsbl_check['bl.spamcop.net'] = 'http://spamcop.net/bl.shtml?';
  1021. }
  1022. if ($ip)
  1023. {
  1024. $quads = explode('.', $ip);
  1025. $reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
  1026. // Need to be listed on all servers...
  1027. $listed = true;
  1028. $info = array();
  1029. foreach ($dnsbl_check as $dnsbl => $lookup)
  1030. {
  1031. if (phpbb_checkdnsrr($reverse_ip . '.' . $dnsbl . '.', 'A') === true)
  1032. {
  1033. $info = array($dnsbl, $lookup . $ip);
  1034. }
  1035. else
  1036. {
  1037. $listed = false;
  1038. }
  1039. }
  1040. if ($listed)
  1041. {
  1042. return $info;
  1043. }
  1044. }
  1045. return false;
  1046. }
  1047. /**
  1048. * Check if URI is blacklisted
  1049. * This should be called only where absolutly necessary, for example on the submitted website field
  1050. * This function is not in use at the moment and is only included for testing purposes, it may not work at all!
  1051. * This means it is untested at the moment and therefore commented out
  1052. *
  1053. * @param string $uri URI to check
  1054. * @return true if uri is on blacklist, else false. Only blacklist is checked (~zero FP), no grey lists
  1055. function check_uribl($uri)
  1056. {
  1057. // Normally parse_url() is not intended to parse uris
  1058. // We need to get the top-level domain name anyway... change.
  1059. $uri = parse_url($uri);
  1060. if ($uri === false || empty($uri['host']))
  1061. {
  1062. return false;
  1063. }
  1064. $uri = trim($uri['host']);
  1065. if ($uri)
  1066. {
  1067. // One problem here... the return parameter for the "windows" method is different from what
  1068. // we expect... this may render this check useless...
  1069. if (phpbb_checkdnsrr($uri . '.multi.uribl.com.', 'A') === true)
  1070. {
  1071. return true;
  1072. }
  1073. }
  1074. return false;
  1075. }
  1076. */
  1077. /**
  1078. * Set/Update a persistent login key
  1079. *
  1080. * This method creates or updates a persistent session key. When a user makes
  1081. * use of persistent (formerly auto-) logins a key is generated and stored in the
  1082. * DB. When they revisit with the same key it's automatically updated in both the
  1083. * DB and cookie. Multiple keys may exist for each user representing different
  1084. * browsers or locations. As with _any_ non-secure-socket no passphrase login this
  1085. * remains vulnerable to exploit.
  1086. */
  1087. function set_login_key($user_id = false, $key = false, $user_ip = false)
  1088. {
  1089. global $config, $db;
  1090. $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id;
  1091. $user_ip = ($user_ip === false) ? $this->ip : $user_ip;
  1092. $key = ($key === false) ? (($this->cookie_data['k']) ? $this->cookie_data['k'] : false) : $key;
  1093. $key_id = unique_id(hexdec(substr($this->session_id, 0, 8)));
  1094. $sql_ary = array(
  1095. 'key_id' => (string) md5($key_id),
  1096. 'last_ip' => (string) $this->ip,
  1097. 'last_login' => (int) time()
  1098. );
  1099. if (!$key)
  1100. {
  1101. $sql_ary += array(
  1102. 'user_id' => (int) $user_id
  1103. );
  1104. }
  1105. if ($key)
  1106. {
  1107. $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . '
  1108. SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
  1109. WHERE user_id = ' . (int) $user_id . "
  1110. AND key_id = '" . $db->sql_escape(md5($key)) . "'";
  1111. }
  1112. else
  1113. {
  1114. $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
  1115. }
  1116. $db->sql_query($sql);
  1117. $this->cookie_data['k'] = $key_id;
  1118. return false;
  1119. }
  1120. /**
  1121. * Reset all login keys for the specified user
  1122. *
  1123. * This method removes all current login keys for a specified (or the current)
  1124. * user. It will be called on password change to render old keys unusable
  1125. */
  1126. function reset_login_keys($user_id = false)
  1127. {
  1128. global $config, $db;
  1129. $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id;
  1130. $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
  1131. WHERE user_id = ' . (int) $user_id;
  1132. $db->sql_query($sql);
  1133. // Let's also clear any current sessions for the specified user_id
  1134. // If it's the current user then we'll leave this session intact
  1135. $sql_where = 'session_user_id = ' . (int) $user_id;
  1136. $sql_where .= ($user_id === $this->data['user_id']) ? " AND session_id <> '" . $db->sql_escape($this->session_id) . "'" : '';
  1137. $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
  1138. WHERE $sql_where";
  1139. $db->sql_query($sql);
  1140. // We're changing the password of the current user and they have a key
  1141. // Lets regenerate it to be safe
  1142. if ($user_id === $this->data['user_id'] && $this->cookie_data['k'])
  1143. {
  1144. $this->set_login_key($user_id);
  1145. }
  1146. }
  1147. /**
  1148. * Check if the request originated from the same page.
  1149. * @param bool $check_script_path If true, the path will be checked as well
  1150. */
  1151. function validate_referer($check_script_path = false)
  1152. {
  1153. // no referer - nothing to validate, user's fault for turning it off (we only check on POST; so meta can't be the reason)
  1154. if (empty($this->referer) || empty($this->host))
  1155. {
  1156. return true;
  1157. }
  1158. $host = htmlspecialchars($this->host);
  1159. $ref = substr($this->referer, strpos($this->referer, '://') + 3);
  1160. if (!(stripos($ref, $host) === 0))
  1161. {
  1162. return false;
  1163. }
  1164. else if ($check_script_path && rtrim($this->page['root_script_path'], '/') !== '')
  1165. {
  1166. $ref = substr($ref, strlen($host));
  1167. $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
  1168. if ($server_port !== 80 && $server_port !== 443 && stripos($ref, ":$server_port") === 0)
  1169. {
  1170. $ref = substr($ref, strlen(":$server_port"));
  1171. }
  1172. if (!(stripos(rtrim($ref, '/'), rtrim($this->page['root_script_path'], '/')) === 0))
  1173. {
  1174. return false;
  1175. }
  1176. }
  1177. return true;
  1178. }
  1179. function unset_admin()
  1180. {
  1181. global $db;
  1182. $sql = 'UPDATE ' . SESSIONS_TABLE . '
  1183. SET session_admin = 0
  1184. WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\'';
  1185. $db->sql_query($sql);
  1186. }
  1187. }
  1188. /**
  1189. * Base user class
  1190. *
  1191. * This is the overarching class which contains (through session extend)
  1192. * all methods utilised for user functionality during a session.
  1193. *
  1194. * @package phpBB3
  1195. */
  1196. class user extends session
  1197. {
  1198. var $lang = array();
  1199. var $help = array();
  1200. var $theme = array();
  1201. var $date_format;
  1202. var $timezone;
  1203. var $dst;
  1204. var $lang_name = false;
  1205. var $lang_id = false;
  1206. var $lang_path;
  1207. var $img_lang;
  1208. var $img_array = array();
  1209. // Able to add new option (id 7)
  1210. var $keyoptions = array('viewimg' => 0, 'viewflash' => 1, 'viewsmilies' => 2, 'viewsigs' => 3, 'viewavatars' => 4, 'viewcensors' => 5, 'attachsig' => 6, 'bbcode' => 8, 'smilies' => 9, 'popuppm' => 10);
  1211. var $keyvalues = array();
  1212. /**
  1213. * Constructor to set the lang path
  1214. */
  1215. function user()
  1216. {
  1217. global $phpbb_root_path;
  1218. $this->lang_path = $phpbb_root_path . 'language/';
  1219. }
  1220. /**
  1221. * Function to set custom language path (able to use directory outside of phpBB)
  1222. *
  1223. * @param string $lang_path New language path used.
  1224. * @access public
  1225. */
  1226. function set_custom_lang_path($lang_path)
  1227. {
  1228. $this->lang_path = $lang_path;
  1229. if (substr($this->lang_path, -1) != '/')
  1230. {
  1231. $this->lang_path .= '/';
  1232. }
  1233. }
  1234. /**
  1235. * Setup basic user-specific items (style, language, ...)
  1236. */
  1237. function setup($lang_set = false, $style = false)
  1238. {
  1239. global $db, $template, $config, $auth, $phpEx, $phpbb_root_path, $cache;
  1240. if ($this->data['user_id'] != ANONYMOUS)
  1241. {
  1242. $this->lang_name = (file_exists($this->lang_path . $this->data['user_lang'] . "/common.$phpEx")) ? $this->data['user_lang'] : basename($config['default_lang']);
  1243. $this->date_format = $this->data['user_dateformat'];
  1244. $this->timezone = $this->data['user_timezone'] * 3600;
  1245. $this->dst = $this->data['user_dst'] * 3600;
  1246. }
  1247. else
  1248. {
  1249. $this->lang_name = basename($config['default_lang']);
  1250. $this->date_format = $config['default_dateformat'];
  1251. $this->timezone = $config['board_timezone'] * 3600;
  1252. $this->dst = $config['board_dst'] * 3600;
  1253. /**
  1254. * If a guest user is surfing, we try to guess his/her language first by obtaining the browser language
  1255. * If re-enabled we need to make sure only those languages installed are checked
  1256. * Commented out so we do not loose the code.
  1257. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
  1258. {
  1259. $accept_lang_ary = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
  1260. foreach ($accept_lang_ary as $accept_lang)
  1261. {
  1262. // Set correct format ... guess full xx_YY form
  1263. $accept_lang = substr($accept_lang, 0, 2) . '_' . strtoupper(substr($accept_lang, 3, 2));
  1264. $accept_lang = basename($accept_lang);
  1265. if (file_exists($this->lang_path . $accept_lang . "/common.$phpEx"))
  1266. {
  1267. $this->lang_name = $config['default_lang'] = $accept_lang;
  1268. break;
  1269. }
  1270. else
  1271. {
  1272. // No match on xx_YY so try xx
  1273. $accept_lang = substr($accept_lang, 0, 2);
  1274. $accept_lang = basename($accept_lang);
  1275. if (file_exists($this->lang_path . $accept_lang . "/common.$phpEx"))
  1276. {
  1277. $this->lang_name = $config['default_lang'] = $accept_lang;
  1278. break;
  1279. }
  1280. }
  1281. }
  1282. }
  1283. */
  1284. }
  1285. // We include common language file here to not load it every time a custom language file is included
  1286. $lang = &$this->lang;
  1287. if ((@include $this->lang_path . $this->lang_name . "/common.$phpEx") === false)
  1288. {
  1289. die('Language file ' . $this->lang_path . $this->lang_name . "/common.$phpEx" . " couldn't be opened.");
  1290. }
  1291. $this->add_lang($lang_set);
  1292. unset($lang_set);
  1293. if (!empty($_GET['style']) && $auth->acl_get('a_styles'))
  1294. {
  1295. global $SID, $_EXTRA_URL;
  1296. $style = request_var('style', 0);
  1297. $SID .= '&amp;style=' . $style;
  1298. $_EXTRA_URL = array('style=' . $style);
  1299. }
  1300. else
  1301. {
  1302. // Set up style
  1303. $style = ($style) ? $style : ((!$config['override_user_style']) ? $this->

Large files files are truncated, but you can click here to view the full file