[ Index ]

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


Generated: Thu Jan 11 23:14:31 2018 Cross-referenced by PHPXref 0.7.1