<?php
// +---------------------------------------------+
// |     Copyright  2003 - 2005 weenCompany      |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

if(!defined('IN_WEENCOMPANY'))
  die('File not found!');


$sessioncreated = false;


// ############################# PHPBB2 VARIABLES ###############################

$tableprefix  = $usersystem['tblprefix'];

$getcookiesecure  = $DB->query_first("SELECT config_value FROM " . $tableprefix . "config WHERE config_name = 'cookie_secure'");

$cookiesecure = $getcookiesecure['config_value'];
$cookietime   = $usersystem['cookietimeout'];
$cookieprefix = $usersystem['cookieprefix'];
$cookiedomain = "";
$cookiepath   = "/";


// ################################ ENCODE IP ##################################
// written by the authors of phpBB2

function encode_ip($dotquad_ip)
{
  $ip_sep = explode('.', $dotquad_ip);
  return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}


// ################################# USER IP ###################################

$clientip = ( !empty($_SERVER['REMOTE_ADDR']) ) ? $_SERVER['REMOTE_ADDR'] : ( ( !empty($_ENV['REMOTE_ADDR']) ) ? $_ENV['REMOTE_ADDR'] : $REMOTE_ADDR );
$userip   = encode_ip($clientip);



// ###############################  SET COOKIE ###############################

function sdsetcookie($name, $value = '', $permanent = 1)
{
  global $cookieprefix, $cookiesecure, $cookiepath, $cookiedomain;

  $expire = $permanent ? (TIMENOW + 60 * 60 * 24 * 365) : 0;
  $secure = $cookiesecure ? 1 : 0; // secure(1) = using SSL

  $name = $cookieprefix . $name;

  setcookie($name, $value, $expire, $cookiepath, $cookiedomain, $secure);
}



// ################################## DEFINES ##################################

define('TIMENOW', time());
define('SESSION_HOST', $userip);
define('ANONYMOUS', -1);



// ############################ CREATE SESSION HASH ############################

function CreateSessionHash()
{
  return md5(uniqid(SESSION_HOST));
}


function CreateAutoLoginID($userid, $session_id, $autologinid = '')
{
        global $DB, $tableprefix;

        list($sec, $usec) = explode(' ', microtime());
        mt_srand(hexdec(substr($session_id, 0, 8)) + (float) $sec + ((float) $usec * 1000000));
        $auto_login_key = uniqid(mt_rand(), true);

        if (isset($autologinid) && (string) $autologinid != '')
        {
                $sql = "UPDATE ". $tableprefix . "sessions_keys
                                SET last_ip = '" . SESSION_HOST . "', key_id = '" . md5($auto_login_key) . "', last_login = " . TIMENOW .
                                "WHERE key_id = '" . md5($autologinid) . "'";
        }
        else
        {
                $sql = "INSERT INTO ". $tableprefix . "sessions_keys (key_id, user_id, last_ip, last_login)
                                        VALUES ('" . md5($auto_login_key) . "', $userid, '" . SESSION_HOST . "', " . TIMENOW .")";
        }

        $DB->query($sql);

        return $auto_login_key;
}



// ############################## CREATE SESSION ###############################

function CreateSession($userid = -1, $user_session_time = -1, $autologin = 0, $autologinid = '')
{
  global $DB, $sessioncreated, $tableprefix, $v2018;

  $userid = intval($userid);

  $loggedin = $userid > 1 ? 1 : 0;  // phpbb2 users start from id 1

  // setup the session
  $session = array('session_id'        => CreateSessionHash(),
                   'session_user_id'   => $userid,
                   'session_start'     => TIMENOW,
                   'session_time'      => TIMENOW,
                   'session_ip'        => SESSION_HOST,
                   'session_page'      => 0,
        'session_logged_in'                 => $loggedin,
        'session_autologinid'        => '');

  // insert the session into the database
  $DB->query("REPLACE INTO " . $tableprefix . "sessions (session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in)
              VALUES ('" . addslashes($session['session_id']) . "', $session[session_user_id], $session[session_start], $session[session_time],
                      '" . addslashes($session['session_ip']) . "', $session[session_page], $session[session_logged_in])");

  // update last activity
  if($userid > 0)
  {
        $last_visit = ( $user_session_time > 0 ) ? $user_session_time : TIMENOW;

        $DB->query("UPDATE " . $tableprefix . "users SET user_session_time = " . TIMENOW . ", user_lastvisit = " . $last_visit . " WHERE user_id = $userid");

                if($autologin && $v2018)
                {
                        $session['session_autologinid'] = CreateAutoLoginID($userid, $session['session_id'], $autologinid);
                }
        }

  // return if we are logging in our logging out (since logging in and out already creates sessions)
  if(!isset($_POST['login']) AND !isset($_GET['logout']))
  {
    // save the session id
    sdsetcookie('_sid', $session['session_id'], 0);
  }

  // set sessioncreated to true so that we don't update this session later on in the script
  // (because it was just created)
  $sessioncreated = true;

  return $session;
}



// ############################# FIND SESSION HASH #############################

if(!empty($_POST['s']))
{
  $sessionhash = $_POST['s'];
}
else if (!empty($_GET['s']))
{
  $sessionhash = $_GET['s'];
}
else
{
  $sessionhash = isset($_COOKIE[$cookieprefix . '_sid']) ? $_COOKIE[$cookieprefix . '_sid'] : '';
}

// ########################## IS THIS VERSION 2.1.8 or later? #####################

function CheckVersion($major, $minor)
{
        global $DB, $tableprefix;

        $version = $DB->query_first("SELECT config_value FROM " . $tableprefix . "config WHERE config_name = 'version'");

        if(isset($version[0]))
        {
                $ver = explode('.', $version[0]);

                if(count($ver) == 3 && ((intval($ver[1]) > $major) || (intval($ver[2]) > $minor)))
                {
                        return true;
                }
        }

        return false;
}

$v2018 = CheckVersion(0, 18);


// ############################# CONTINUE SESSION ##############################

if(!empty($sessionhash))
{
  $session = $DB->query_first("SELECT * FROM " . $tableprefix . "sessions
                               WHERE session_id = '" . addslashes(trim($sessionhash)) . "'
                               AND session_time > " . (TIMENOW - $cookietime) . "
                               AND session_ip = '" . addslashes(SESSION_HOST) . "'");
}



// ############################### COOKIE LOGIN ################################

if(empty($session) OR $session['session_user_id'] == 0)
{
  // session is not set or the user is a guest, lets check the cookies:

  if(isset($_COOKIE[$cookieprefix . '_data']))
  {
    $sessiondata = unserialize(stripslashes($HTTP_COOKIE_VARS[$cookieprefix . '_data']));

    if(!empty($sessiondata['userid']) AND
       !empty($sessiondata['autologinid']) AND
       is_numeric($sessiondata['userid']))
    {
      if($v2018)
      {
        $user = $DB->query_first("SELECT u.* FROM " . $tableprefix . "users u, ". $tableprefix . "sessions_keys k
                                                                           WHERE u.user_id = " . (int) $sessiondata['userid'] . "
                                                                        AND u.user_active = 1
                                                                        AND k.user_id = u.user_id
                                                                        AND k.key_id = '" . md5($sessiondata['autologinid']) . "'");
      }
      else
      {
        $user = $user = $DB->query_first("SELECT * FROM " . $tableprefix . "users
                                                                  WHERE user_id = '" . $sessiondata['userid'] . "'
                                                                  AND user_password = '" . addslashes($sessiondata['autologinid']) . "'");
      }

      if($user)
      {
        // combination is valid
        if(!empty($session['session_id']))
        {
          // old session still exists; kill it
          $DB->query("DELETE FROM " . $tableprefix . "sessions WHERE session_id = '" . addslashes($session['session_id']). "'");
        }

        $session = CreateSession($user['user_id'], $user['user_session_time']);
      }
      else if(isset($_POST['login'])) // cookie is bad!
      {
        // cookie's bad and since we're not doing anything login related, kill the bad cookie
        sdsetcookie('_data', '', 1);
        sdsetcookie('_sid', '', 0);
      }
    }
  }
}



// ########################### CREATE GUEST SESSION ############################

if(empty($session))
{
  // still no session, create a guest session
  $session = CreateSession(-1);
}



// ############################ SETUP USER VARIABLE ############################

if($session['session_user_id'] < 1)
{
  $user = array('userid'         => -1,   // phpbb guests are -1 userid
                'usergroupids'   => 1,    // phpBB2 - Unregistered / Not Logged In
                'username'       => '',
                'loggedin'       => 0,
                'email'          => '',
                'timezoneoffset' => 0,
                'dstonoff'       => 0,
                'dstauto'        => 1);
}
else // greater or equal to 2
{
  $getuser = $DB->query_first("SELECT * FROM " . $tableprefix . "users WHERE user_id = $session[session_user_id]");

  $user = array('userid'         => $getuser['user_id'],   // phpbb guests are -1 userid
                'username'       => $getuser['username'],
                'loggedin'       => 1,
                'email'          => $getuser['user_email'],
                'timezoneoffset' => $getuser['user_timezone'],
                'dstonoff'       => 0,    // phpBB2 doesn't have a dst option
                'dstauto'        => 0);   // phpBB2 doesn't have a dst option

  unset($getuser);

  // find the usergroupids
  // phpbb2 creates a new usergroup for each user, but I don't want to show hundreds of usergroups in the admin panel
  // so lets only select the usergroups that don't have a strlen of 0

  //$usergroupids[] = 5; // default of 5

  $usergroupids = array();

  $getusergroups = $DB->query("SELECT g.group_id FROM " . $tableprefix . "groups g, " . $tableprefix . "user_group u
                               WHERE u.user_id = $user[userid] AND u.group_id = g.group_id AND g.group_name != ''");

  while($usergroup = $DB->fetch_array($getusergroups))
  {
    // now find the usergroup name
    if(count($usergroupids) <= 0 || !in_array($usergroup['group_id'], $usergroupids))
    {
      $usergroupids[] = $usergroup['group_id'];
    }
  }

  // add the 'fake' registered group?
  if(count($usergroupids) <= 0 && $isregistered = $DB->query_first("SELECT g.group_id FROM " . $tableprefix . "groups g, " . $tableprefix . "user_group u
                                       WHERE u.user_id = $user[userid] AND u.group_id = g.group_id AND g.group_name = ''"))
  {
    $usergroupids[] = -3; // usergroup id -3 is an emulated registered usergroup for phpBB2 created by weenCompany
  }

  $user['usergroupids'] = $usergroupids;

  unset($usergroupids);
}



// ############################## UPDATE SESSION ###############################

if(!$sessioncreated)  // unless the session was just created....
{
  $DB->query("UPDATE " . $tableprefix . "sessions SET session_time = " . TIMENOW . "
                                                WHERE session_id    = '" . addslashes($session['session_id']) . "'");
}


// ################################### LOGIN ###################################

if(isset($_POST['login']))
{
  $loginusername = $_POST['loginusername'];
  $loginpassword = $_POST['loginpassword'];

  if(strlen($loginusername) != 0)
  {
    // get userid for given username
    if($getuser = $DB->query_first("SELECT * FROM " . $tableprefix . "users WHERE username = '" . addslashes($loginusername) . "'"))
    {
      if(md5($loginpassword) === $getuser['user_password'] AND $getuser['user_active'] AND $getuser['user_id'] != ANONYMOUS)
      {
        // logged in
        $user = array('userid'         => $getuser['user_id'],   // phpbb guests are -1 userid
                      'usergroupids'   => 5,    // phpBB2 Registered, this is just the default group, more or gathered next:
                      'username'       => $getuser['username'],
                      'loggedin'       => 1,
                      'email'          => $getuser['user_email'],
                      'timezoneoffset' => $getuser['user_timezone'],
                      'dstonoff'       => 0,    // phpBB2 doesn't have a dst option
                      'dstauto'        => 0);   // phpBB2 doesn't have a dst option

        $user_password = $getuser['user_password'];
        unset($getuser);

                // find the usergroupids
        // phpbb2 creates a new usergroup for each user, but I don't want to show hundreds of usergroups in the admin panel
        // so lets only select the usergroups that don't have a strlen of 0
                //$usergroupids[] = 5; // default of 5

                $getusergroups = $DB->query("SELECT g.group_id FROM " . $tableprefix . "groups g, " . $tableprefix . "user_group u
                               WHERE u.user_id = $user[userid] AND u.group_id = g.group_id AND g.group_name != ''");

                while($usergroup = $DB->fetch_array($getusergroups))
                {
                        // now find the usergroup name
                        if(count($usergroupids) <= 0 || !in_array($usergroup['group_id'], $usergroupids))
                        {
                                $usergroupids[] = $usergroup['group_id'];
                        }
                }

                // add the 'fake' registered group?
                if(count($usergroupids) <= 0 && $isregistered = $DB->query_first("SELECT g.group_id FROM " . $tableprefix . "groups g, " . $tableprefix . "user_group u
                                       WHERE u.user_id = $user[userid] AND u.group_id = g.group_id AND g.group_name = ''"))
                {
                        $usergroupids[] = -3; // usergroup id -3 is an emulated registered usergroup for phpBB2 created by weenCompany
                }

        $user['usergroupids'] = $usergroupids;

        unset($usergroupids);

        // erase old session
        $DB->query("DELETE FROM " . $tableprefix . "sessions WHERE session_id = '" . addslashes($session['session_id']) . "'");

        // insert new session
        $session['session_id'] = CreateSessionHash();

        // insert the session into the database
        $DB->query("REPLACE INTO " . $tableprefix . "sessions (session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in)
                    VALUES ('" . addslashes($session['session_id']) . "', " . intval($user['userid']) . ", " . TIMENOW . ", " . TIMENOW . ",
                            '" . addslashes(SESSION_HOST) . "', 0, 1)");

        // save the sessionhash in the cookie
        sdsetcookie('_sid', $session['session_id'], 0);

        // save the password if the user has selected the 'remember me' option
        if($v2018)
        {
          $sessiondata['autologinid'] = $_POST['rememberme'] ? CreateAutoLoginID($user['userid'], $session['session_id']) : '';
        }
        else
        {
          $sessiondata['autologinid'] = $_POST['rememberme'] ? $user_password : '';
        }

        $sessiondata['userid']      = $user['userid'];

        sdsetcookie('_data', serialize($sessiondata), 1);
      }
      else
      {
        $loginerrors[] = $sdlanguage['wrong_password'];
      }
    }
    else
    {
      // wront username OR: username = ANONYMOUS, probably a hacker
      // lets just give them wrong username to throw them off
      $loginerrors[] = $sdlanguage['wrong_username'];
    }
  }
  else
  {
    $loginerrors[] = $sdlanguage['please_enter_username'];
  }
}



// ################################## LOGOUT ###################################

if(isset($_GET['logout']))
{
  // clear cookies
  sdsetcookie('_data', '', 1);
  sdsetcookie('_sid', '', 0);

  if($user['userid'] > 1)
  {
    $DB->query("UPDATE " . $tableprefix . "users SET user_lastvisit = " . TIMENOW . " WHERE user_id = $user[userid]");

    // make sure any other of this user's sessions are deleted (in case they ended up with more than one)
    $DB->query("DELETE FROM " . $tableprefix . "sessions WHERE session_user_id = $user[userid]");
  }

  $DB->query("DELETE FROM " . $tableprefix . "sessions WHERE session_id = '" . addslashes($session['session_id']) . "'");

  $session['session_id'] = CreateSessionHash();

  // insert the session into the database
  $DB->query("REPLACE INTO " . $tableprefix . "sessions (session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in)
              VALUES ('" . addslashes($session['session_id']) . "', '-1', " . TIMENOW . ", " . TIMENOW . ", '" . addslashes(SESSION_HOST) . "', 0, 0)");

  sdsetcookie('_sid', $session['session_id'], 0);

  $user = array('userid'         => -1,   // phpbb guests are -1 userid
                'usergroupids'   => 1,    // phpBB2 - Unregistered / Not Logged In
                'username'       => '',
                'loggedin'       => 0,
                'email'          => '',
                'timezoneoffset' => 0,
                'dstonoff'       => 0,
                'dstauto'        => 1);
}



// ############################ ADD SESSION TO URL? ############################

if(sizeof($_COOKIE) > 0 OR preg_match("#(google|msnbot|yahoo! slurp)#si", $_SERVER['HTTP_USER_AGENT']))
{
  $user['sessionurl'] = '';
}
else if (strlen($session['session_id']) > 0)
{
  $user['sessionurl'] = 's=' . $session['session_id'];
}



// ############################ DELETE OLD SESSIONS ############################

$DB->query("DELETE FROM " . $tableprefix . "sessions WHERE session_time < " . intval(TIMENOW - $cookietime));



// ###################### WEENCOMPANY USER SETTINGS SETUP #######################

$usersettings = array('userid'         => $user['userid'],
                      'usergroupids'   => $user['usergroupids'],
                      'username'       => $user['username'],
                      'loggedin'       => $user['loggedin'],
                      'email'          => $user['email'],
                      'timezoneoffset' => $user['timezoneoffset'],
                      'dstonoff'       => $user['dstonoff'],
                      'dstauto'        => $user['dstauto'],
                      'sessionurl'     => $user['sessionurl']);



// ############################## UNSET VARIABLES ##############################

unset($user, $session, $sessionhash);

// ############################## USER FUNCTIONS ##############################

function IsIPBanned($clientip)
{
  global $DB, $usersystem, $dbname;

  $user_ip_parts = null;

  preg_match('/(..)(..)(..)(..)/', encode_ip($clientip), $user_ip_parts);

  $query = "SELECT ban_ip FROM " . $usersystem['tblprefix'] . "banlist
                    WHERE ban_ip IN ('" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . $user_ip_parts[4] . "', '" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . "ff', '" . $user_ip_parts[1] . $user_ip_parts[2] . "ffff', '" . $user_ip_parts[1] . "ffffff')";

  if($usersystem['dbname'] != $dbname)
  {
    // weenCompany is being integrated with a Forum in a different database
    $DB->select_db($usersystem['dbname']);
    $getbanip = $DB->query($query);
    $DB->select_db($dbname);
  }
  else
  {
    $getbanip = $DB->query($query);
  }

  if($banip = $DB->fetch_array($getbanip))
  {
          if($banip['ban_ip'])
            return true;
  }

  return false;
}

// Returns the relevent forum link url
// linkType
// 1 - Register
// 2 - UserCP
// 3 - Recover Password
// 4 - UserCP (requires $userid)
// 5 - SendPM (requires $userid)
function ForumLink($linkType, $userid = -1)
{
  global $weenurl, $usersystem;

  switch($linkType)
  {
  case 1:
    $url = 'profile.php?mode=register';
        break;
  case 2:
    $url = 'profile.php?mode=editprofile';
        break;
  case 3:
    $url = 'profile.php?mode=sendpassword';
        break;
  case 4:
    $url = 'profile.php?mode=viewprofile&u=' . $userid;
        break;
  case 5:
    $url = 'privmsg.php?mode=post&u=' . $userid;
        break;
  }

  return $weenurl . $usersystem['folderpath'] . $url;
}

?>