[ Index ]

PHP Cross Reference of phpBB-3.1.12-deutsch

title

Body

[close]

/phpbb/ -> session.php (source)

   1  <?php
   2  /**
   3  *
   4  * This file is part of the phpBB Forum Software package.
   5  *
   6  * @copyright (c) phpBB Limited <https://www.phpbb.com>
   7  * @license GNU General Public License, version 2 (GPL-2.0)
   8  *
   9  * For full copyright and license information, please see
  10  * the docs/CREDITS.txt file.
  11  *
  12  */
  13  
  14  namespace phpbb;
  15  
  16  /**
  17  * Session class
  18  */
  19  class session
  20  {
  21      var $cookie_data = array();
  22      var $page = array();
  23      var $data = array();
  24      var $browser = '';
  25      var $forwarded_for = '';
  26      var $host = '';
  27      var $session_id = '';
  28      var $ip = '';
  29      var $load = 0;
  30      var $time_now = 0;
  31      var $update_session_page = true;
  32  
  33      /**
  34       * Extract current session page
  35       *
  36       * @param string $root_path current root path (phpbb_root_path)
  37       * @return array
  38       */
  39  	static function extract_current_page($root_path)
  40      {
  41          global $request, $symfony_request, $phpbb_filesystem;
  42  
  43          $page_array = array();
  44  
  45          // First of all, get the request uri...
  46          $script_name = $request->escape($symfony_request->getScriptName(), true);
  47          $args = $request->escape(explode('&', $symfony_request->getQueryString()), true);
  48  
  49          // 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...
  50          if (!$script_name)
  51          {
  52              $script_name = htmlspecialchars_decode($request->server('REQUEST_URI'));
  53              $script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name;
  54              $page_array['failover'] = 1;
  55          }
  56  
  57          // Replace backslashes and doubled slashes (could happen on some proxy setups)
  58          $script_name = str_replace(array('\\', '//'), '/', $script_name);
  59  
  60          // Now, remove the sid and let us get a clean query string...
  61          $use_args = array();
  62  
  63          // Since some browser do not encode correctly we need to do this with some "special" characters...
  64          // " -> %22, ' => %27, < -> %3C, > -> %3E
  65          $find = array('"', "'", '<', '>', '&quot;', '&lt;', '&gt;');
  66          $replace = array('%22', '%27', '%3C', '%3E', '%22', '%3C', '%3E');
  67  
  68          foreach ($args as $key => $argument)
  69          {
  70              if (strpos($argument, 'sid=') === 0)
  71              {
  72                  continue;
  73              }
  74  
  75              $use_args[] = str_replace($find, $replace, $argument);
  76          }
  77          unset($args);
  78  
  79          // The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2
  80  
  81          // The current query string
  82          $query_string = trim(implode('&', $use_args));
  83  
  84          // basenamed page name (for example: index.php)
  85          $page_name = (substr($script_name, -1, 1) == '/') ? '' : basename($script_name);
  86          $page_name = urlencode(htmlspecialchars($page_name));
  87  
  88          $symfony_request_path = $phpbb_filesystem->clean_path($symfony_request->getPathInfo());
  89          if ($symfony_request_path !== '/')
  90          {
  91              $page_name .= str_replace('%2F', '/', urlencode($symfony_request_path));
  92          }
  93  
  94          // current directory within the phpBB root (for example: adm)
  95          $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path)));
  96          $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./')));
  97          $intersection = array_intersect_assoc($root_dirs, $page_dirs);
  98  
  99          $root_dirs = array_diff_assoc($root_dirs, $intersection);
 100          $page_dirs = array_diff_assoc($page_dirs, $intersection);
 101  
 102          $page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
 103  
 104          if ($page_dir && substr($page_dir, -1, 1) == '/')
 105          {
 106              $page_dir = substr($page_dir, 0, -1);
 107          }
 108  
 109          // Current page from phpBB root (for example: adm/index.php?i=10&b=2)
 110          $page = (($page_dir) ? $page_dir . '/' : '') . $page_name;
 111          if ($query_string)
 112          {
 113              $page .= '?' . $query_string;
 114          }
 115  
 116          // The script path from the webroot to the current directory (for example: /phpBB3/adm/) : always prefixed with / and ends in /
 117          $script_path = $symfony_request->getBasePath();
 118  
 119          // The script path from the webroot to the phpBB root (for example: /phpBB3/)
 120          $script_dirs = explode('/', $script_path);
 121          array_splice($script_dirs, -sizeof($page_dirs));
 122          $root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : '');
 123  
 124          // We are on the base level (phpBB root == webroot), lets adjust the variables a bit...
 125          if (!$root_script_path)
 126          {
 127              $root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path;
 128          }
 129  
 130          $script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/';
 131          $root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/';
 132  
 133          $forum_id = $request->variable('f', 0);
 134          // maximum forum id value is maximum value of mediumint unsigned column
 135          $forum_id = ($forum_id > 0 && $forum_id < 16777215) ? $forum_id : 0;
 136  
 137          $page_array += array(
 138              'page_name'            => $page_name,
 139              'page_dir'            => $page_dir,
 140  
 141              'query_string'        => $query_string,
 142              'script_path'        => str_replace(' ', '%20', htmlspecialchars($script_path)),
 143              'root_script_path'    => str_replace(' ', '%20', htmlspecialchars($root_script_path)),
 144  
 145              'page'                => $page,
 146              'forum'                => $forum_id,
 147          );
 148  
 149          return $page_array;
 150      }
 151  
 152      /**
 153      * Get valid hostname/port. HTTP_HOST is used, SERVER_NAME if HTTP_HOST not present.
 154      */
 155  	function extract_current_hostname()
 156      {
 157          global $config, $request;
 158  
 159          // Get hostname
 160          $host = htmlspecialchars_decode($request->header('Host', $request->server('SERVER_NAME')));
 161  
 162          // Should be a string and lowered
 163          $host = (string) strtolower($host);
 164  
 165          // If host is equal the cookie domain or the server name (if config is set), then we assume it is valid
 166          if ((isset($config['cookie_domain']) && $host === $config['cookie_domain']) || (isset($config['server_name']) && $host === $config['server_name']))
 167          {
 168              return $host;
 169          }
 170  
 171          // Is the host actually a IP? If so, we use the IP... (IPv4)
 172          if (long2ip(ip2long($host)) === $host)
 173          {
 174              return $host;
 175          }
 176  
 177          // 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
 178          $host = @parse_url('http://' . $host);
 179          $host = (!empty($host['host'])) ? $host['host'] : '';
 180  
 181          // Remove any portions not removed by parse_url (#)
 182          $host = str_replace('#', '', $host);
 183  
 184          // If, by any means, the host is now empty, we will use a "best approach" way to guess one
 185          if (empty($host))
 186          {
 187              if (!empty($config['server_name']))
 188              {
 189                  $host = $config['server_name'];
 190              }
 191              else if (!empty($config['cookie_domain']))
 192              {
 193                  $host = (strpos($config['cookie_domain'], '.') === 0) ? substr($config['cookie_domain'], 1) : $config['cookie_domain'];
 194              }
 195              else
 196              {
 197                  // Set to OS hostname or localhost
 198                  $host = (function_exists('php_uname')) ? php_uname('n') : 'localhost';
 199              }
 200          }
 201  
 202          // It may be still no valid host, but for sure only a hostname (we may further expand on the cookie domain... if set)
 203          return $host;
 204      }
 205  
 206      /**
 207      * Start session management
 208      *
 209      * This is where all session activity begins. We gather various pieces of
 210      * information from the client and server. We test to see if a session already
 211      * exists. If it does, fine and dandy. If it doesn't we'll go on to create a
 212      * new one ... pretty logical heh? We also examine the system load (if we're
 213      * running on a system which makes such information readily available) and
 214      * halt if it's above an admin definable limit.
 215      *
 216      * @param bool $update_session_page if true the session page gets updated.
 217      *            This can be set to circumvent certain scripts to update the users last visited page.
 218      */
 219  	function session_begin($update_session_page = true)
 220      {
 221          global $phpEx, $SID, $_SID, $_EXTRA_URL, $db, $config, $phpbb_root_path;
 222          global $request, $phpbb_container, $phpbb_dispatcher;
 223  
 224          // Give us some basic information
 225          $this->time_now                = time();
 226          $this->cookie_data            = array('u' => 0, 'k' => '');
 227          $this->update_session_page    = $update_session_page;
 228          $this->browser                = $request->header('User-Agent');
 229          $this->referer                = $request->header('Referer');
 230          $this->forwarded_for        = $request->header('X-Forwarded-For');
 231  
 232          $this->host                    = $this->extract_current_hostname();
 233          $this->page                    = $this->extract_current_page($phpbb_root_path);
 234  
 235          // if the forwarded for header shall be checked we have to validate its contents
 236          if ($config['forwarded_for_check'])
 237          {
 238              $this->forwarded_for = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $this->forwarded_for));
 239  
 240              // split the list of IPs
 241              $ips = explode(' ', $this->forwarded_for);
 242              foreach ($ips as $ip)
 243              {
 244                  // check IPv4 first, the IPv6 is hopefully only going to be used very seldomly
 245                  if (!empty($ip) && !preg_match(get_preg_expression('ipv4'), $ip) && !preg_match(get_preg_expression('ipv6'), $ip))
 246                  {
 247                      // contains invalid data, don't use the forwarded for header
 248                      $this->forwarded_for = '';
 249                      break;
 250                  }
 251              }
 252          }
 253          else
 254          {
 255              $this->forwarded_for = '';
 256          }
 257  
 258          if ($request->is_set($config['cookie_name'] . '_sid', \phpbb\request\request_interface::COOKIE) || $request->is_set($config['cookie_name'] . '_u', \phpbb\request\request_interface::COOKIE))
 259          {
 260              $this->cookie_data['u'] = request_var($config['cookie_name'] . '_u', 0, false, true);
 261              $this->cookie_data['k'] = request_var($config['cookie_name'] . '_k', '', false, true);
 262              $this->session_id         = request_var($config['cookie_name'] . '_sid', '', false, true);
 263  
 264              $SID = (defined('NEED_SID')) ? '?sid=' . $this->session_id : '?sid=';
 265              $_SID = (defined('NEED_SID')) ? $this->session_id : '';
 266  
 267              if (empty($this->session_id))
 268              {
 269                  $this->session_id = $_SID = request_var('sid', '');
 270                  $SID = '?sid=' . $this->session_id;
 271                  $this->cookie_data = array('u' => 0, 'k' => '');
 272              }
 273          }
 274          else
 275          {
 276              $this->session_id = $_SID = request_var('sid', '');
 277              $SID = '?sid=' . $this->session_id;
 278          }
 279  
 280          $_EXTRA_URL = array();
 281  
 282          // Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
 283          // it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
 284          $ip = htmlspecialchars_decode($request->server('REMOTE_ADDR'));
 285          $ip = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $ip));
 286  
 287          /**
 288          * Event to alter user IP address
 289          *
 290          * @event core.session_ip_after
 291          * @var    string    ip    REMOTE_ADDR
 292          * @since 3.1.10-RC1
 293          */
 294          $vars = array('ip');
 295          extract($phpbb_dispatcher->trigger_event('core.session_ip_after', compact($vars)));
 296  
 297          // split the list of IPs
 298          $ips = explode(' ', trim($ip));
 299  
 300          // Default IP if REMOTE_ADDR is invalid
 301          $this->ip = '127.0.0.1';
 302  
 303          foreach ($ips as $ip)
 304          {
 305              if (function_exists('phpbb_ip_normalise'))
 306              {
 307                  // Normalise IP address
 308                  $ip = phpbb_ip_normalise($ip);
 309  
 310                  if (empty($ip))
 311                  {
 312                      // IP address is invalid.
 313                      break;
 314                  }
 315  
 316                  // IP address is valid.
 317                  $this->ip = $ip;
 318  
 319                  // Skip legacy code.
 320                  continue;
 321              }
 322  
 323              if (preg_match(get_preg_expression('ipv4'), $ip))
 324              {
 325                  $this->ip = $ip;
 326              }
 327              else if (preg_match(get_preg_expression('ipv6'), $ip))
 328              {
 329                  // Quick check for IPv4-mapped address in IPv6
 330                  if (stripos($ip, '::ffff:') === 0)
 331                  {
 332                      $ipv4 = substr($ip, 7);
 333  
 334                      if (preg_match(get_preg_expression('ipv4'), $ipv4))
 335                      {
 336                          $ip = $ipv4;
 337                      }
 338                  }
 339  
 340                  $this->ip = $ip;
 341              }
 342              else
 343              {
 344                  // We want to use the last valid address in the chain
 345                  // Leave foreach loop when address is invalid
 346                  break;
 347              }
 348          }
 349  
 350          $this->load = false;
 351  
 352          // Load limit check (if applicable)
 353          if ($config['limit_load'] || $config['limit_search_load'])
 354          {
 355              if ((function_exists('sys_getloadavg') && $load = sys_getloadavg()) || ($load = explode(' ', @file_get_contents('/proc/loadavg'))))
 356              {
 357                  $this->load = array_slice($load, 0, 1);
 358                  $this->load = floatval($this->load[0]);
 359              }
 360              else
 361              {
 362                  set_config('limit_load', '0');
 363                  set_config('limit_search_load', '0');
 364              }
 365          }
 366  
 367          // if no session id is set, redirect to index.php
 368          $session_id = $request->variable('sid', '');
 369          if (defined('NEED_SID') && (empty($session_id) || $this->session_id !== $session_id))
 370          {
 371              send_status_line(401, 'Unauthorized');
 372              redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
 373          }
 374  
 375          // if session id is set
 376          if (!empty($this->session_id))
 377          {
 378              $sql = 'SELECT u.*, s.*
 379                  FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . " u
 380                  WHERE s.session_id = '" . $db->sql_escape($this->session_id) . "'
 381                      AND u.user_id = s.session_user_id";
 382              $result = $db->sql_query($sql);
 383              $this->data = $db->sql_fetchrow($result);
 384              $db->sql_freeresult($result);
 385  
 386              // Did the session exist in the DB?
 387              if (isset($this->data['user_id']))
 388              {
 389                  // Validate IP length according to admin ... enforces an IP
 390                  // check on bots if admin requires this
 391  //                $quadcheck = ($config['ip_check_bot'] && $this->data['user_type'] & USER_BOT) ? 4 : $config['ip_check'];
 392  
 393                  if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false)
 394                  {
 395                      $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
 396                      $u_ip = short_ipv6($this->ip, $config['ip_check']);
 397                  }
 398                  else
 399                  {
 400                      $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
 401                      $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
 402                  }
 403  
 404                  $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
 405                  $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : '';
 406  
 407                  $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
 408                  $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : '';
 409  
 410                  // referer checks
 411                  // The @ before $config['referer_validation'] suppresses notices present while running the updater
 412                  $check_referer_path = (@$config['referer_validation'] == REFERER_VALIDATE_PATH);
 413                  $referer_valid = true;
 414  
 415                  // we assume HEAD and TRACE to be foul play and thus only whitelist GET
 416                  if (@$config['referer_validation'] && strtolower($request->server('REQUEST_METHOD')) !== 'get')
 417                  {
 418                      $referer_valid = $this->validate_referer($check_referer_path);
 419                  }
 420  
 421                  if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for && $referer_valid)
 422                  {
 423                      $session_expired = false;
 424  
 425                      // Check whether the session is still valid if we have one
 426                      $provider_collection = $phpbb_container->get('auth.provider_collection');
 427                      $provider = $provider_collection->get_provider();
 428  
 429                      if (!($provider instanceof \phpbb\auth\provider\provider_interface))
 430                      {
 431                          throw new \RuntimeException($provider . ' must implement \phpbb\auth\provider\provider_interface');
 432                      }
 433  
 434                      $ret = $provider->validate_session($this->data);
 435                      if ($ret !== null && !$ret)
 436                      {
 437                          $session_expired = true;
 438                      }
 439  
 440                      if (!$session_expired)
 441                      {
 442                          // Check the session length timeframe if autologin is not enabled.
 443                          // Else check the autologin length... and also removing those having autologin enabled but no longer allowed board-wide.
 444                          if (!$this->data['session_autologin'])
 445                          {
 446                              if ($this->data['session_time'] < $this->time_now - ($config['session_length'] + 60))
 447                              {
 448                                  $session_expired = true;
 449                              }
 450                          }
 451                          else if (!$config['allow_autologin'] || ($config['max_autologin_time'] && $this->data['session_time'] < $this->time_now - (86400 * (int) $config['max_autologin_time']) + 60))
 452                          {
 453                              $session_expired = true;
 454                          }
 455                      }
 456  
 457                      if (!$session_expired)
 458                      {
 459                          $this->data['is_registered'] = ($this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
 460                          $this->data['is_bot'] = (!$this->data['is_registered'] && $this->data['user_id'] != ANONYMOUS) ? true : false;
 461                          $this->data['user_lang'] = basename($this->data['user_lang']);
 462  
 463                          // Is user banned? Are they excluded? Won't return on ban, exists within method
 464                          $this->check_ban_for_current_session($config);
 465  
 466                          return true;
 467                      }
 468                  }
 469                  else
 470                  {
 471                      // Added logging temporarly to help debug bugs...
 472                      if (defined('DEBUG') && $this->data['user_id'] != ANONYMOUS)
 473                      {
 474                          if ($referer_valid)
 475                          {
 476                              add_log('critical', 'LOG_IP_BROWSER_FORWARDED_CHECK', $u_ip, $s_ip, $u_browser, $s_browser, htmlspecialchars($u_forwarded_for), htmlspecialchars($s_forwarded_for));
 477                          }
 478                          else
 479                          {
 480                              add_log('critical', 'LOG_REFERER_INVALID', $this->referer);
 481                          }
 482                      }
 483                  }
 484              }
 485          }
 486  
 487          // If we reach here then no (valid) session exists. So we'll create a new one
 488          return $this->session_create();
 489      }
 490  
 491      /**
 492      * Create a new session
 493      *
 494      * If upon trying to start a session we discover there is nothing existing we
 495      * jump here. Additionally this method is called directly during login to regenerate
 496      * the session for the specific user. In this method we carry out a number of tasks;
 497      * garbage collection, (search)bot checking, banned user comparison. Basically
 498      * though this method will result in a new session for a specific user.
 499      */
 500  	function session_create($user_id = false, $set_admin = false, $persist_login = false, $viewonline = true)
 501      {
 502          global $SID, $_SID, $db, $config, $cache, $phpbb_root_path, $phpEx, $phpbb_container, $phpbb_dispatcher;
 503  
 504          $this->data = array();
 505  
 506          /* Garbage collection ... remove old sessions updating user information
 507          // if necessary. It means (potentially) 11 queries but only infrequently
 508          if ($this->time_now > $config['session_last_gc'] + $config['session_gc'])
 509          {
 510              $this->session_gc();
 511          }*/
 512  
 513          // Do we allow autologin on this board? No? Then override anything
 514          // that may be requested here
 515          if (!$config['allow_autologin'])
 516          {
 517              $this->cookie_data['k'] = $persist_login = false;
 518          }
 519  
 520          /**
 521          * Here we do a bot check, oh er saucy! No, not that kind of bot
 522          * check. We loop through the list of bots defined by the admin and
 523          * see if we have any useragent and/or IP matches. If we do, this is a
 524          * bot, act accordingly
 525          */
 526          $bot = false;
 527          $active_bots = $cache->obtain_bots();
 528  
 529          foreach ($active_bots as $row)
 530          {
 531              if ($row['bot_agent'] && preg_match('#' . str_replace('\*', '.*?', preg_quote($row['bot_agent'], '#')) . '#i', $this->browser))
 532              {
 533                  $bot = $row['user_id'];
 534              }
 535  
 536              // If ip is supplied, we will make sure the ip is matching too...
 537              if ($row['bot_ip'] && ($bot || !$row['bot_agent']))
 538              {
 539                  // Set bot to false, then we only have to set it to true if it is matching
 540                  $bot = false;
 541  
 542                  foreach (explode(',', $row['bot_ip']) as $bot_ip)
 543                  {
 544                      $bot_ip = trim($bot_ip);
 545  
 546                      if (!$bot_ip)
 547                      {
 548                          continue;
 549                      }
 550  
 551                      if (strpos($this->ip, $bot_ip) === 0)
 552                      {
 553                          $bot = (int) $row['user_id'];
 554                          break;
 555                      }
 556                  }
 557              }
 558  
 559              if ($bot)
 560              {
 561                  break;
 562              }
 563          }
 564  
 565          $provider_collection = $phpbb_container->get('auth.provider_collection');
 566          $provider = $provider_collection->get_provider();
 567          $this->data = $provider->autologin();
 568  
 569          if ($user_id !== false && sizeof($this->data) && $this->data['user_id'] != $user_id)
 570          {
 571              $this->data = array();
 572          }
 573  
 574          if (sizeof($this->data))
 575          {
 576              $this->cookie_data['k'] = '';
 577              $this->cookie_data['u'] = $this->data['user_id'];
 578          }
 579  
 580          // If we're presented with an autologin key we'll join against it.
 581          // Else if we've been passed a user_id we'll grab data based on that
 582          if (isset($this->cookie_data['k']) && $this->cookie_data['k'] && $this->cookie_data['u'] && !sizeof($this->data))
 583          {
 584              $sql = 'SELECT u.*
 585                  FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
 586                  WHERE u.user_id = ' . (int) $this->cookie_data['u'] . '
 587                      AND u.user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ")
 588                      AND k.user_id = u.user_id
 589                      AND k.key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'";
 590              $result = $db->sql_query($sql);
 591              $user_data = $db->sql_fetchrow($result);
 592  
 593              if ($user_id === false || (isset($user_data['user_id']) && $user_id == $user_data['user_id']))
 594              {
 595                  $this->data = $user_data;
 596                  $bot = false;
 597              }
 598  
 599              $db->sql_freeresult($result);
 600          }
 601  
 602          if ($user_id !== false && !sizeof($this->data))
 603          {
 604              $this->cookie_data['k'] = '';
 605              $this->cookie_data['u'] = $user_id;
 606  
 607              $sql = 'SELECT *
 608                  FROM ' . USERS_TABLE . '
 609                  WHERE user_id = ' . (int) $this->cookie_data['u'] . '
 610                      AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')';
 611              $result = $db->sql_query($sql);
 612              $this->data = $db->sql_fetchrow($result);
 613              $db->sql_freeresult($result);
 614              $bot = false;
 615          }
 616  
 617          // Bot user, if they have a SID in the Request URI we need to get rid of it
 618          // otherwise they'll index this page with the SID, duplicate content oh my!
 619          if ($bot && isset($_GET['sid']))
 620          {
 621              send_status_line(301, 'Moved Permanently');
 622              redirect(build_url(array('sid')));
 623          }
 624  
 625          // If no data was returned one or more of the following occurred:
 626          // Key didn't match one in the DB
 627          // User does not exist
 628          // User is inactive
 629          // User is bot
 630          if (!sizeof($this->data) || !is_array($this->data))
 631          {
 632              $this->cookie_data['k'] = '';
 633              $this->cookie_data['u'] = ($bot) ? $bot : ANONYMOUS;
 634  
 635              if (!$bot)
 636              {
 637                  $sql = 'SELECT *
 638                      FROM ' . USERS_TABLE . '
 639                      WHERE user_id = ' . (int) $this->cookie_data['u'];
 640              }
 641              else
 642              {
 643                  // We give bots always the same session if it is not yet expired.
 644                  $sql = 'SELECT u.*, s.*
 645                      FROM ' . USERS_TABLE . ' u
 646                      LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
 647                      WHERE u.user_id = ' . (int) $bot;
 648              }
 649  
 650              $result = $db->sql_query($sql);
 651              $this->data = $db->sql_fetchrow($result);
 652              $db->sql_freeresult($result);
 653          }
 654  
 655          if ($this->data['user_id'] != ANONYMOUS && !$bot)
 656          {
 657              $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());
 658          }
 659          else
 660          {
 661              $this->data['session_last_visit'] = $this->time_now;
 662          }
 663  
 664          // Force user id to be integer...
 665          $this->data['user_id'] = (int) $this->data['user_id'];
 666  
 667          // At this stage we should have a filled data array, defined cookie u and k data.
 668          // data array should contain recent session info if we're a real user and a recent
 669          // session exists in which case session_id will also be set
 670  
 671          // Is user banned? Are they excluded? Won't return on ban, exists within method
 672          $this->check_ban_for_current_session($config);
 673  
 674          $this->data['is_registered'] = (!$bot && $this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
 675          $this->data['is_bot'] = ($bot) ? true : false;
 676  
 677          // If our friend is a bot, we re-assign a previously assigned session
 678          if ($this->data['is_bot'] && $bot == $this->data['user_id'] && $this->data['session_id'])
 679          {
 680              // Only assign the current session if the ip, browser and forwarded_for match...
 681              if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false)
 682              {
 683                  $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
 684                  $u_ip = short_ipv6($this->ip, $config['ip_check']);
 685              }
 686              else
 687              {
 688                  $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
 689                  $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
 690              }
 691  
 692              $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
 693              $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : '';
 694  
 695              $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
 696              $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : '';
 697  
 698              if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for)
 699              {
 700                  $this->session_id = $this->data['session_id'];
 701  
 702                  // Only update session DB a minute or so after last update or if page changes
 703                  if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page']))
 704                  {
 705                      // Update the last visit time
 706                      $sql = 'UPDATE ' . USERS_TABLE . '
 707                          SET user_lastvisit = ' . (int) $this->data['session_time'] . '
 708                          WHERE user_id = ' . (int) $this->data['user_id'];
 709                      $db->sql_query($sql);
 710                  }
 711  
 712                  $SID = '?sid=';
 713                  $_SID = '';
 714                  return true;
 715              }
 716              else
 717              {
 718                  // If the ip and browser does not match make sure we only have one bot assigned to one session
 719                  $db->sql_query('DELETE FROM ' . SESSIONS_TABLE . ' WHERE session_user_id = ' . $this->data['user_id']);
 720              }
 721          }
 722  
 723          $session_autologin = (($this->cookie_data['k'] || $persist_login) && $this->data['is_registered']) ? true : false;
 724          $set_admin = ($set_admin && $this->data['is_registered']) ? true : false;
 725  
 726          // Create or update the session
 727          $sql_ary = array(
 728              'session_user_id'        => (int) $this->data['user_id'],
 729              'session_start'            => (int) $this->time_now,
 730              'session_last_visit'    => (int) $this->data['session_last_visit'],
 731              'session_time'            => (int) $this->time_now,
 732              'session_browser'        => (string) trim(substr($this->browser, 0, 149)),
 733              'session_forwarded_for'    => (string) $this->forwarded_for,
 734              'session_ip'            => (string) $this->ip,
 735              'session_autologin'        => ($session_autologin) ? 1 : 0,
 736              'session_admin'            => ($set_admin) ? 1 : 0,
 737              'session_viewonline'    => ($viewonline) ? 1 : 0,
 738          );
 739  
 740          if ($this->update_session_page)
 741          {
 742              $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199);
 743              $sql_ary['session_forum_id'] = $this->page['forum'];
 744          }
 745  
 746          $db->sql_return_on_error(true);
 747  
 748          $sql = 'DELETE
 749              FROM ' . SESSIONS_TABLE . '
 750              WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\'
 751                  AND session_user_id = ' . ANONYMOUS;
 752  
 753          if (!defined('IN_ERROR_HANDLER') && (!$this->session_id || !$db->sql_query($sql) || !$db->sql_affectedrows()))
 754          {
 755              // Limit new sessions in 1 minute period (if required)
 756              if (empty($this->data['session_time']) && $config['active_sessions'])
 757              {
 758  //                $db->sql_return_on_error(false);
 759  
 760                  $sql = 'SELECT COUNT(session_id) AS sessions
 761                      FROM ' . SESSIONS_TABLE . '
 762                      WHERE session_time >= ' . ($this->time_now - 60);
 763                  $result = $db->sql_query($sql);
 764                  $row = $db->sql_fetchrow($result);
 765                  $db->sql_freeresult($result);
 766  
 767                  if ((int) $row['sessions'] > (int) $config['active_sessions'])
 768                  {
 769                      send_status_line(503, 'Service Unavailable');
 770                      trigger_error('BOARD_UNAVAILABLE');
 771                  }
 772              }
 773          }
 774  
 775          // Since we re-create the session id here, the inserted row must be unique. Therefore, we display potential errors.
 776          // Commented out because it will not allow forums to update correctly
 777  //        $db->sql_return_on_error(false);
 778  
 779          // Something quite important: session_page always holds the *last* page visited, except for the *first* visit.
 780          // We are not able to simply have an empty session_page btw, therefore we need to tell phpBB how to detect this special case.
 781          // If the session id is empty, we have a completely new one and will set an "identifier" here. This identifier is able to be checked later.
 782          if (empty($this->data['session_id']))
 783          {
 784              // This is a temporary variable, only set for the very first visit
 785              $this->data['session_created'] = true;
 786          }
 787  
 788          $this->session_id = $this->data['session_id'] = md5(unique_id());
 789  
 790          $sql_ary['session_id'] = (string) $this->session_id;
 791          $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199);
 792          $sql_ary['session_forum_id'] = $this->page['forum'];
 793  
 794          $sql = 'INSERT INTO ' . SESSIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
 795          $db->sql_query($sql);
 796  
 797          $db->sql_return_on_error(false);
 798  
 799          // Regenerate autologin/persistent login key
 800          if ($session_autologin)
 801          {
 802              $this->set_login_key();
 803          }
 804  
 805          // refresh data
 806          $SID = '?sid=' . $this->session_id;
 807          $_SID = $this->session_id;
 808          $this->data = array_merge($this->data, $sql_ary);
 809  
 810          if (!$bot)
 811          {
 812              $cookie_expire = $this->time_now + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000);
 813  
 814              $this->set_cookie('u', $this->cookie_data['u'], $cookie_expire);
 815              $this->set_cookie('k', $this->cookie_data['k'], $cookie_expire);
 816              $this->set_cookie('sid', $this->session_id, $cookie_expire);
 817  
 818              unset($cookie_expire);
 819  
 820              $sql = 'SELECT COUNT(session_id) AS sessions
 821                      FROM ' . SESSIONS_TABLE . '
 822                      WHERE session_user_id = ' . (int) $this->data['user_id'] . '
 823                      AND session_time >= ' . (int) ($this->time_now - (max($config['session_length'], $config['form_token_lifetime'])));
 824              $result = $db->sql_query($sql);
 825              $row = $db->sql_fetchrow($result);
 826              $db->sql_freeresult($result);
 827  
 828              if ((int) $row['sessions'] <= 1 || empty($this->data['user_form_salt']))
 829              {
 830                  $this->data['user_form_salt'] = unique_id();
 831                  // Update the form key
 832                  $sql = 'UPDATE ' . USERS_TABLE . '
 833                      SET user_form_salt = \'' . $db->sql_escape($this->data['user_form_salt']) . '\'
 834                      WHERE user_id = ' . (int) $this->data['user_id'];
 835                  $db->sql_query($sql);
 836              }
 837          }
 838          else
 839          {
 840              $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
 841  
 842              // Update the last visit time
 843              $sql = 'UPDATE ' . USERS_TABLE . '
 844                  SET user_lastvisit = ' . (int) $this->data['session_time'] . '
 845                  WHERE user_id = ' . (int) $this->data['user_id'];
 846              $db->sql_query($sql);
 847  
 848              $SID = '?sid=';
 849              $_SID = '';
 850          }
 851  
 852          $session_data = $sql_ary;
 853          /**
 854          * Event to send new session data to extension
 855          * Read-only event
 856          *
 857          * @event core.session_create_after
 858          * @var    array        session_data                Associative array of session keys to be updated
 859          * @since 3.1.6-RC1
 860          */
 861          $vars = array('session_data');
 862          extract($phpbb_dispatcher->trigger_event('core.session_create_after', compact($vars)));
 863          unset($session_data);
 864  
 865          return true;
 866      }
 867  
 868      /**
 869      * Kills a session
 870      *
 871      * This method does what it says on the tin. It will delete a pre-existing session.
 872      * It resets cookie information (destroying any autologin key within that cookie data)
 873      * and update the users information from the relevant session data. It will then
 874      * grab guest user information.
 875      */
 876  	function session_kill($new_session = true)
 877      {
 878          global $SID, $_SID, $db, $config, $phpbb_root_path, $phpEx, $phpbb_container, $phpbb_dispatcher;
 879  
 880          $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
 881              WHERE session_id = '" . $db->sql_escape($this->session_id) . "'
 882                  AND session_user_id = " . (int) $this->data['user_id'];
 883          $db->sql_query($sql);
 884  
 885          $user_id = (int) $this->data['user_id'];
 886          $session_id = $this->session_id;
 887          /**
 888          * Event to send session kill information to extension
 889          * Read-only event
 890          *
 891          * @event core.session_kill_after
 892          * @var    int        user_id                user_id of the session user.
 893          * @var    string        session_id                current user's session_id
 894          * @var    bool    new_session     should we create new session for user
 895          * @since 3.1.6-RC1
 896          */
 897          $vars = array('user_id', 'session_id', 'new_session');
 898          extract($phpbb_dispatcher->trigger_event('core.session_kill_after', compact($vars)));
 899          unset($user_id);
 900          unset($session_id);
 901  
 902          // Allow connecting logout with external auth method logout
 903          $provider_collection = $phpbb_container->get('auth.provider_collection');
 904          $provider = $provider_collection->get_provider();
 905          $provider->logout($this->data, $new_session);
 906  
 907          if ($this->data['user_id'] != ANONYMOUS)
 908          {
 909              // Delete existing session, update last visit info first!
 910              if (!isset($this->data['session_time']))
 911              {
 912                  $this->data['session_time'] = time();
 913              }
 914  
 915              $sql = 'UPDATE ' . USERS_TABLE . '
 916                  SET user_lastvisit = ' . (int) $this->data['session_time'] . '
 917                  WHERE user_id = ' . (int) $this->data['user_id'];
 918              $db->sql_query($sql);
 919  
 920              if ($this->cookie_data['k'])
 921              {
 922                  $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
 923                      WHERE user_id = ' . (int) $this->data['user_id'] . "
 924                          AND key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'";
 925                  $db->sql_query($sql);
 926              }
 927  
 928              // Reset the data array
 929              $this->data = array();
 930  
 931              $sql = 'SELECT *
 932                  FROM ' . USERS_TABLE . '
 933                  WHERE user_id = ' . ANONYMOUS;
 934              $result = $db->sql_query($sql);
 935              $this->data = $db->sql_fetchrow($result);
 936              $db->sql_freeresult($result);
 937          }
 938  
 939          $cookie_expire = $this->time_now - 31536000;
 940          $this->set_cookie('u', '', $cookie_expire);
 941          $this->set_cookie('k', '', $cookie_expire);
 942          $this->set_cookie('sid', '', $cookie_expire);
 943          unset($cookie_expire);
 944  
 945          $SID = '?sid=';
 946          $this->session_id = $_SID = '';
 947  
 948          // To make sure a valid session is created we create one for the anonymous user
 949          if ($new_session)
 950          {
 951              $this->session_create(ANONYMOUS);
 952          }
 953  
 954          return true;
 955      }
 956  
 957      /**
 958      * Session garbage collection
 959      *
 960      * This looks a lot more complex than it really is. Effectively we are
 961      * deleting any sessions older than an admin definable limit. Due to the
 962      * way in which we maintain session data we have to ensure we update user
 963      * data before those sessions are destroyed. In addition this method
 964      * removes autologin key information that is older than an admin defined
 965      * limit.
 966      */
 967  	function session_gc()
 968      {
 969          global $db, $config, $phpbb_root_path, $phpEx, $phpbb_container, $phpbb_dispatcher;
 970  
 971          $batch_size = 10;
 972  
 973          if (!$this->time_now)
 974          {
 975              $this->time_now = time();
 976          }
 977  
 978          // Firstly, delete guest sessions
 979          $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
 980              WHERE session_user_id = ' . ANONYMOUS . '
 981                  AND session_time < ' . (int) ($this->time_now - $config['session_length']);
 982          $db->sql_query($sql);
 983  
 984          // Get expired sessions, only most recent for each user
 985          $sql = 'SELECT session_user_id, session_page, MAX(session_time) AS recent_time
 986              FROM ' . SESSIONS_TABLE . '
 987              WHERE session_time < ' . ($this->time_now - $config['session_length']) . '
 988              GROUP BY session_user_id, session_page';
 989          $result = $db->sql_query_limit($sql, $batch_size);
 990  
 991          $del_user_id = array();
 992          $del_sessions = 0;
 993  
 994          while ($row = $db->sql_fetchrow($result))
 995          {
 996              $sql = 'UPDATE ' . USERS_TABLE . '
 997                  SET user_lastvisit = ' . (int) $row['recent_time'] . ", user_lastpage = '" . $db->sql_escape($row['session_page']) . "'
 998                  WHERE user_id = " . (int) $row['session_user_id'];
 999              $db->sql_query($sql);
1000  
1001              $del_user_id[] = (int) $row['session_user_id'];
1002              $del_sessions++;
1003          }
1004          $db->sql_freeresult($result);
1005  
1006          if (sizeof($del_user_id))
1007          {
1008              // Delete expired sessions
1009              $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
1010                  WHERE ' . $db->sql_in_set('session_user_id', $del_user_id) . '
1011                      AND session_time < ' . ($this->time_now - $config['session_length']);
1012              $db->sql_query($sql);
1013          }
1014  
1015          if ($del_sessions < $batch_size)
1016          {
1017              // Less than 10 users, update gc timer ... else we want gc
1018              // called again to delete other sessions
1019              set_config('session_last_gc', $this->time_now, true);
1020  
1021              if ($config['max_autologin_time'])
1022              {
1023                  $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
1024                      WHERE last_login < ' . (time() - (86400 * (int) $config['max_autologin_time']));
1025                  $db->sql_query($sql);
1026              }
1027  
1028              // only called from CRON; should be a safe workaround until the infrastructure gets going
1029              $captcha_factory = $phpbb_container->get('captcha.factory');
1030              $captcha_factory->garbage_collect($config['captcha_plugin']);
1031  
1032              $sql = 'DELETE FROM ' . LOGIN_ATTEMPT_TABLE . '
1033                  WHERE attempt_time < ' . (time() - (int) $config['ip_login_limit_time']);
1034              $db->sql_query($sql);
1035          }
1036  
1037          /**
1038          * Event to trigger extension on session_gc
1039          *
1040          * @event core.session_gc_after
1041          * @since 3.1.6-RC1
1042          */
1043          $phpbb_dispatcher->dispatch('core.session_gc_after');
1044  
1045          return;
1046      }
1047  
1048      /**
1049      * Sets a cookie
1050      *
1051      * 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.
1052      *
1053      * @param string $name        Name of the cookie, will be automatically prefixed with the phpBB cookie name. track becomes [cookie_name]_track then.
1054      * @param string $cookiedata    The data to hold within the cookie
1055      * @param int $cookietime    The expiration time as UNIX timestamp. If 0 is provided, a session cookie is set.
1056      * @param bool $httponly        Use HttpOnly. Defaults to true. Use false to make cookie accessible by client-side scripts.
1057      */
1058  	function set_cookie($name, $cookiedata, $cookietime, $httponly = true)
1059      {
1060          global $config;
1061  
1062          $name_data = rawurlencode($config['cookie_name'] . '_' . $name) . '=' . rawurlencode($cookiedata);
1063          $expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime);
1064          $domain = (!$config['cookie_domain'] || $config['cookie_domain'] == '127.0.0.1' || strpos($config['cookie_domain'], '.') === false) ? '' : '; domain=' . $config['cookie_domain'];
1065  
1066          header('Set-Cookie: ' . $name_data . (($cookietime) ? '; expires=' . $expire : '') . '; path=' . $config['cookie_path'] . $domain . ((!$config['cookie_secure']) ? '' : '; secure') . ';' . (($httponly) ? ' HttpOnly' : ''), false);
1067      }
1068  
1069      /**
1070      * Check for banned user
1071      *
1072      * Checks whether the supplied user is banned by id, ip or email. If no parameters
1073      * are passed to the method pre-existing session data is used.
1074      *
1075      * @param int|false        $user_id        The user id
1076      * @param mixed            $user_ips        Can contain a string with one IP or an array of multiple IPs
1077      * @param string|false    $user_email        The user email
1078      * @param bool            $return            If $return is false this routine does not return on finding a banned user,
1079      *    it outputs a relevant message and stops execution.
1080      */
1081  	function check_ban($user_id = false, $user_ips = false, $user_email = false, $return = false)
1082      {
1083          global $config, $db, $phpbb_dispatcher;
1084  
1085          if (defined('IN_CHECK_BAN') || defined('SKIP_CHECK_BAN'))
1086          {
1087              return;
1088          }
1089  
1090          $banned = false;
1091          $cache_ttl = 3600;
1092          $where_sql = array();
1093  
1094          $sql = 'SELECT ban_ip, ban_userid, ban_email, ban_exclude, ban_give_reason, ban_end
1095              FROM ' . BANLIST_TABLE . '
1096              WHERE ';
1097  
1098          // Determine which entries to check, only return those
1099          if ($user_email === false)
1100          {
1101              $where_sql[] = "ban_email = ''";
1102          }
1103  
1104          if ($user_ips === false)
1105          {
1106              $where_sql[] = "(ban_ip = '' OR ban_exclude = 1)";
1107          }
1108  
1109          if ($user_id === false)
1110          {
1111              $where_sql[] = '(ban_userid = 0 OR ban_exclude = 1)';
1112          }
1113          else
1114          {
1115              $cache_ttl = ($user_id == ANONYMOUS) ? 3600 : 0;
1116              $_sql = '(ban_userid = ' . $user_id;
1117  
1118              if ($user_email !== false)
1119              {
1120                  $_sql .= " OR ban_email <> ''";
1121              }
1122  
1123              if ($user_ips !== false)
1124              {
1125                  $_sql .= " OR ban_ip <> ''";
1126              }
1127  
1128              $_sql .= ')';
1129  
1130              $where_sql[] = $_sql;
1131          }
1132  
1133          $sql .= (sizeof($where_sql)) ? implode(' AND ', $where_sql) : '';
1134          $result = $db->sql_query($sql, $cache_ttl);
1135  
1136          $ban_triggered_by = 'user';
1137          while ($row = $db->sql_fetchrow($result))
1138          {
1139              if ($row['ban_end'] && $row['ban_end'] < time())
1140              {
1141                  continue;
1142              }
1143  
1144              $ip_banned = false;
1145              if (!empty($row['ban_ip']))
1146              {
1147                  if (!is_array($user_ips))
1148                  {
1149                      $ip_banned = preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ips);
1150                  }
1151                  else
1152                  {
1153                      foreach ($user_ips as $user_ip)
1154                      {
1155                          if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ip))
1156                          {
1157                              $ip_banned = true;
1158                              break;
1159                          }
1160                      }
1161                  }
1162              }
1163  
1164              if ((!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) ||
1165                  $ip_banned ||
1166                  (!empty($row['ban_email']) && preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')) . '$#i', $user_email)))
1167              {
1168                  if (!empty($row['ban_exclude']))
1169                  {
1170                      $banned = false;
1171                      break;
1172                  }
1173                  else
1174                  {
1175                      $banned = true;
1176                      $ban_row = $row;
1177  
1178                      if (!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id)
1179                      {
1180                          $ban_triggered_by = 'user';
1181                      }
1182                      else if ($ip_banned)
1183                      {
1184                          $ban_triggered_by = 'ip';
1185                      }
1186                      else
1187                      {
1188                          $ban_triggered_by = 'email';
1189                      }
1190  
1191                      // Don't break. Check if there is an exclude rule for this user
1192                  }
1193              }
1194          }
1195          $db->sql_freeresult($result);
1196  
1197          /**
1198          * Event to set custom ban type
1199          *
1200          * @event core.session_set_custom_ban
1201          * @var    bool        return                If $return is false this routine does not return on finding a banned user, it outputs a relevant message and stops execution
1202          * @var    bool        banned                Check if user already banned
1203          * @var    array|false    ban_row                Ban data
1204          * @var    string        ban_triggered_by    Method that caused ban, can be your custom method
1205          * @since 3.1.3-RC1
1206          */
1207          $ban_row = isset($ban_row) ? $ban_row : false;
1208          $vars = array('return', 'banned', 'ban_row', 'ban_triggered_by');
1209          extract($phpbb_dispatcher->trigger_event('core.session_set_custom_ban', compact($vars)));
1210  
1211          if ($banned && !$return)
1212          {
1213              global $template, $phpbb_root_path, $phpEx;
1214  
1215              // If the session is empty we need to create a valid one...
1216              if (empty($this->session_id))
1217              {
1218                  // This seems to be no longer needed? - #14971
1219  //                $this->session_create(ANONYMOUS);
1220              }
1221  
1222              // Initiate environment ... since it won't be set at this stage
1223              $this->setup();
1224  
1225              // Logout the user, banned users are unable to use the normal 'logout' link
1226              if ($this->data['user_id'] != ANONYMOUS)
1227              {
1228                  $this->session_kill();
1229              }
1230  
1231              // We show a login box here to allow founders accessing the board if banned by IP
1232              if (defined('IN_LOGIN') && $this->data['user_id'] == ANONYMOUS)
1233              {
1234                  $this->setup('ucp');
1235                  $this->data['is_registered'] = $this->data['is_bot'] = false;
1236  
1237                  // Set as a precaution to allow login_box() handling this case correctly as well as this function not being executed again.
1238                  define('IN_CHECK_BAN', 1);
1239  
1240                  login_box("index.$phpEx");
1241  
1242                  // The false here is needed, else the user is able to circumvent the ban.
1243                  $this->session_kill(false);
1244              }
1245  
1246              // Ok, we catch the case of an empty session id for the anonymous user...
1247              // This can happen if the user is logging in, banned by username and the login_box() being called "again".
1248              if (empty($this->session_id) && defined('IN_CHECK_BAN'))
1249              {
1250                  $this->session_create(ANONYMOUS);
1251              }
1252  
1253              // Determine which message to output
1254              $till_date = ($ban_row['ban_end']) ? $this->format_date($ban_row['ban_end']) : '';
1255              $message = ($ban_row['ban_end']) ? 'BOARD_BAN_TIME' : 'BOARD_BAN_PERM';
1256  
1257              $contact_link = phpbb_get_board_contact_link($config, $phpbb_root_path, $phpEx);
1258              $message = sprintf($this->lang[$message], $till_date, '<a href="' . $contact_link . '">', '</a>');
1259              $message .= ($ban_row['ban_give_reason']) ? '<br /><br />' . sprintf($this->lang['BOARD_BAN_REASON'], $ban_row['ban_give_reason']) : '';
1260              $message .= '<br /><br /><em>' . $this->lang['BAN_TRIGGERED_BY_' . strtoupper($ban_triggered_by)] . '</em>';
1261  
1262              // A very special case... we are within the cron script which is not supposed to print out the ban message... show blank page
1263              if (defined('IN_CRON'))
1264              {
1265                  garbage_collection();
1266                  exit_handler();
1267                  exit;
1268              }
1269  
1270              // To circumvent session_begin returning a valid value and the check_ban() not called on second page view, we kill the session again
1271              $this->session_kill(false);
1272  
1273              trigger_error($message);
1274          }
1275  
1276          return ($banned && $ban_row['ban_give_reason']) ? $ban_row['ban_give_reason'] : $banned;
1277      }
1278  
1279      /**
1280       * Check the current session for bans
1281       *
1282       * @return true if session user is banned.
1283       */
1284  	protected function check_ban_for_current_session($config)
1285      {
1286          if (!defined('SKIP_CHECK_BAN') && $this->data['user_type'] != USER_FOUNDER)
1287          {
1288              if (!$config['forwarded_for_check'])
1289              {
1290                  $this->check_ban($this->data['user_id'], $this->ip);
1291              }
1292              else
1293              {
1294                  $ips = explode(' ', $this->forwarded_for);
1295                  $ips[] = $this->ip;
1296                  $this->check_ban($this->data['user_id'], $ips);
1297              }
1298          }
1299      }
1300  
1301      /**
1302      * Check if ip is blacklisted
1303      * This should be called only where absolutely necessary
1304      *
1305      * Only IPv4 (rbldns does not support AAAA records/IPv6 lookups)
1306      *
1307      * @author satmd (from the php manual)
1308      * @param string         $mode    register/post - spamcop for example is ommitted for posting
1309      * @param string|false    $ip        the IPv4 address to check
1310      *
1311      * @return false if ip is not blacklisted, else an array([checked server], [lookup])
1312      */
1313  	function check_dnsbl($mode, $ip = false)
1314      {
1315          if ($ip === false)
1316          {
1317              $ip = $this->ip;
1318          }
1319  
1320          // Neither Spamhaus nor Spamcop supports IPv6 addresses.
1321          if (strpos($ip, ':') !== false)
1322          {
1323              return false;
1324          }
1325  
1326          $dnsbl_check = array(
1327              'sbl.spamhaus.org'    => 'http://www.spamhaus.org/query/bl?ip=',
1328          );
1329  
1330          if ($mode == 'register')
1331          {
1332              $dnsbl_check['bl.spamcop.net'] = 'http://spamcop.net/bl.shtml?';
1333          }
1334  
1335          if ($ip)
1336          {
1337              $quads = explode('.', $ip);
1338              $reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
1339  
1340              // Need to be listed on all servers...
1341              $listed = true;
1342              $info = array();
1343  
1344              foreach ($dnsbl_check as $dnsbl => $lookup)
1345              {
1346                  if (phpbb_checkdnsrr($reverse_ip . '.' . $dnsbl . '.', 'A') === true)
1347                  {
1348                      $info = array($dnsbl, $lookup . $ip);
1349                  }
1350                  else
1351                  {
1352                      $listed = false;
1353                  }
1354              }
1355  
1356              if ($listed)
1357              {
1358                  return $info;
1359              }
1360          }
1361  
1362          return false;
1363      }
1364  
1365      /**
1366      * Check if URI is blacklisted
1367      * This should be called only where absolutly necessary, for example on the submitted website field
1368      * This function is not in use at the moment and is only included for testing purposes, it may not work at all!
1369      * This means it is untested at the moment and therefore commented out
1370      *
1371      * @param string $uri URI to check
1372      * @return true if uri is on blacklist, else false. Only blacklist is checked (~zero FP), no grey lists
1373      function check_uribl($uri)
1374      {
1375          // Normally parse_url() is not intended to parse uris
1376          // We need to get the top-level domain name anyway... change.
1377          $uri = parse_url($uri);
1378  
1379          if ($uri === false || empty($uri['host']))
1380          {
1381              return false;
1382          }
1383  
1384          $uri = trim($uri['host']);
1385  
1386          if ($uri)
1387          {
1388              // One problem here... the return parameter for the "windows" method is different from what
1389              // we expect... this may render this check useless...
1390              if (phpbb_checkdnsrr($uri . '.multi.uribl.com.', 'A') === true)
1391              {
1392                  return true;
1393              }
1394          }
1395  
1396          return false;
1397      }
1398      */
1399  
1400      /**
1401      * Set/Update a persistent login key
1402      *
1403      * This method creates or updates a persistent session key. When a user makes
1404      * use of persistent (formerly auto-) logins a key is generated and stored in the
1405      * DB. When they revisit with the same key it's automatically updated in both the
1406      * DB and cookie. Multiple keys may exist for each user representing different
1407      * browsers or locations. As with _any_ non-secure-socket no passphrase login this
1408      * remains vulnerable to exploit.
1409      */
1410  	function set_login_key($user_id = false, $key = false, $user_ip = false)
1411      {
1412          global $config, $db;
1413  
1414          $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id;
1415          $user_ip = ($user_ip === false) ? $this->ip : $user_ip;
1416          $key = ($key === false) ? (($this->cookie_data['k']) ? $this->cookie_data['k'] : false) : $key;
1417  
1418          $key_id = unique_id(hexdec(substr($this->session_id, 0, 8)));
1419  
1420          $sql_ary = array(
1421              'key_id'        => (string) md5($key_id),
1422              'last_ip'        => (string) $this->ip,
1423              'last_login'    => (int) time()
1424          );
1425  
1426          if (!$key)
1427          {
1428              $sql_ary += array(
1429                  'user_id'    => (int) $user_id
1430              );
1431          }
1432  
1433          if ($key)
1434          {
1435              $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . '
1436                  SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
1437                  WHERE user_id = ' . (int) $user_id . "
1438                      AND key_id = '" . $db->sql_escape(md5($key)) . "'";
1439          }
1440          else
1441          {
1442              $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
1443          }
1444          $db->sql_query($sql);
1445  
1446          $this->cookie_data['k'] = $key_id;
1447  
1448          return false;
1449      }
1450  
1451      /**
1452      * Reset all login keys for the specified user
1453      *
1454      * This method removes all current login keys for a specified (or the current)
1455      * user. It will be called on password change to render old keys unusable
1456      */
1457  	function reset_login_keys($user_id = false)
1458      {
1459          global $config, $db;
1460  
1461          $user_id = ($user_id === false) ? (int) $this->data['user_id'] : (int) $user_id;
1462  
1463          $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
1464              WHERE user_id = ' . (int) $user_id;
1465          $db->sql_query($sql);
1466  
1467          // If the user is logged in, update last visit info first before deleting sessions
1468          $sql = 'SELECT session_time, session_page
1469              FROM ' . SESSIONS_TABLE . '
1470              WHERE session_user_id = ' . (int) $user_id . '
1471              ORDER BY session_time DESC';
1472          $result = $db->sql_query_limit($sql, 1);
1473          $row = $db->sql_fetchrow($result);
1474          $db->sql_freeresult($result);
1475  
1476          if ($row)
1477          {
1478              $sql = 'UPDATE ' . USERS_TABLE . '
1479                  SET user_lastvisit = ' . (int) $row['session_time'] . ", user_lastpage = '" . $db->sql_escape($row['session_page']) . "'
1480                  WHERE user_id = " . (int) $user_id;
1481              $db->sql_query($sql);
1482          }
1483  
1484          // Let's also clear any current sessions for the specified user_id
1485          // If it's the current user then we'll leave this session intact
1486          $sql_where = 'session_user_id = ' . (int) $user_id;
1487          $sql_where .= ($user_id === (int) $this->data['user_id']) ? " AND session_id <> '" . $db->sql_escape($this->session_id) . "'" : '';
1488  
1489          $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
1490              WHERE $sql_where";
1491          $db->sql_query($sql);
1492  
1493          // We're changing the password of the current user and they have a key
1494          // Lets regenerate it to be safe
1495          if ($user_id === (int) $this->data['user_id'] && $this->cookie_data['k'])
1496          {
1497              $this->set_login_key($user_id);
1498          }
1499      }
1500  
1501  
1502      /**
1503      * Check if the request originated from the same page.
1504      * @param bool $check_script_path If true, the path will be checked as well
1505      */
1506  	function validate_referer($check_script_path = false)
1507      {
1508          global $config, $request;
1509  
1510          // no referer - nothing to validate, user's fault for turning it off (we only check on POST; so meta can't be the reason)
1511          if (empty($this->referer) || empty($this->host))
1512          {
1513              return true;
1514          }
1515  
1516          $host = htmlspecialchars($this->host);
1517          $ref = substr($this->referer, strpos($this->referer, '://') + 3);
1518  
1519          if (!(stripos($ref, $host) === 0) && (!$config['force_server_vars'] || !(stripos($ref, $config['server_name']) === 0)))
1520          {
1521              return false;
1522          }
1523          else if ($check_script_path && rtrim($this->page['root_script_path'], '/') !== '')
1524          {
1525              $ref = substr($ref, strlen($host));
1526              $server_port = $request->server('SERVER_PORT', 0);
1527  
1528              if ($server_port !== 80 && $server_port !== 443 && stripos($ref, ":$server_port") === 0)
1529              {
1530                  $ref = substr($ref, strlen(":$server_port"));
1531              }
1532  
1533              if (!(stripos(rtrim($ref, '/'), rtrim($this->page['root_script_path'], '/')) === 0))
1534              {
1535                  return false;
1536              }
1537          }
1538  
1539          return true;
1540      }
1541  
1542  
1543  	function unset_admin()
1544      {
1545          global $db;
1546          $sql = 'UPDATE ' . SESSIONS_TABLE . '
1547              SET session_admin = 0
1548              WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\'';
1549          $db->sql_query($sql);
1550      }
1551  
1552      /**
1553      * Update the session data
1554      *
1555      * @param array $session_data associative array of session keys to be updated
1556      * @param string $session_id optional session_id, defaults to current user's session_id
1557      */
1558  	public function update_session($session_data, $session_id = null)
1559      {
1560          global $db, $phpbb_dispatcher;
1561  
1562          $session_id = ($session_id) ? $session_id : $this->session_id;
1563  
1564          $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $session_data) . "
1565              WHERE session_id = '" . $db->sql_escape($session_id) . "'";
1566          $db->sql_query($sql);
1567  
1568          /**
1569          * Event to send update session information to extension
1570          * Read-only event
1571          *
1572          * @event core.update_session_after
1573          * @var    array        session_data                Associative array of session keys to be updated
1574          * @var    string        session_id                current user's session_id
1575          * @since 3.1.6-RC1
1576          */
1577          $vars = array('session_data', 'session_id');
1578          extract($phpbb_dispatcher->trigger_event('core.update_session_after', compact($vars)));
1579      }
1580  
1581  	public function update_session_infos()
1582      {
1583          global $config, $db, $request;
1584  
1585          // No need to update if it's a new session. Informations are already inserted by session_create()
1586          if (isset($this->data['session_created']) && $this->data['session_created'])
1587          {
1588              return;
1589          }
1590  
1591          // Only update session DB a minute or so after last update or if page changes
1592          if ($this->time_now - ((isset($this->data['session_time'])) ? $this->data['session_time'] : 0) > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page']))
1593          {
1594              $sql_ary = array('session_time' => $this->time_now);
1595  
1596              // Do not update the session page for ajax requests, so the view online still works as intended
1597              if ($this->update_session_page && !$request->is_ajax())
1598              {
1599                  $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
1600                  $sql_ary['session_forum_id'] = $this->page['forum'];
1601              }
1602  
1603              $db->sql_return_on_error(true);
1604  
1605              $this->update_session($sql_ary);
1606  
1607              $db->sql_return_on_error(false);
1608  
1609              $this->data = array_merge($this->data, $sql_ary);
1610  
1611              if ($this->data['user_id'] != ANONYMOUS && isset($config['new_member_post_limit']) && $this->data['user_new'] && $config['new_member_post_limit'] <= $this->data['user_posts'])
1612              {
1613                  $this->leave_newly_registered();
1614              }
1615          }
1616      }
1617  }


Generated: Thu Jan 11 00:25:41 2018 Cross-referenced by PHPXref 0.7.1