<?php

// +---------------------------------------------+
// |     Copyright  2008 - 2018 weenCompany      |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

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


$location = $categoryid;

$userip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : $REMOTE_ADDR );

define('USERIP', substr(addslashes($userip), 0, 15));
define('USERAGENT', substr(addslashes($_SERVER['HTTP_USER_AGENT']), 0, 252));

//define('TIMENOW', time()); - Already defined in core.php
if($sitedefaultlang == 'en') 
{
define('COOKIE_PREFIX', 'cwsen'.WEB_COOKIE_KEY);
}
else
{
define('COOKIE_PREFIX', 'cwscn'.WEB_COOKIE_KEY);
}

$mainsettings['cookietimeout'] = 1800;

// set defaults
unset($session);
unset($sessionid);

$sessioncreated = false;



$loginerrors = array();

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

function CreateSessionID()
{
  return  md5(uniqid(USERIP));
}



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

function CreateSession($userid = 0)
{
  global $DB, $sessioncreated, $location;

  $loggedin = $userid == 0 ? 0 : 1;

  $session = array('sessionid'    => CreateSessionID(),
                   'userid'       => intval($userid),
                   'ipaddress'    => USERIP,
                   'useragent'    => USERAGENT,
                   'lastactivity' => TIMENOW,
                   'location'     => $location,
                   'loggedin'     => $loggedin);

  // login creates its own session
  if(isset($_POST['login']))
  {
    return;
  }

  $DB->query("REPLACE INTO " . TABLE_PREFIX . "sessions (sessionid, userid, ipaddress, useragent, lastactivity, location, loggedin)
              VALUES ('" . $session['sessionid'] . "', '" . $session['userid'] . "', '" . $session['ipaddress'] . "',
                      '" . $session['useragent'] . "', '" . $session['lastactivity'] . "',
                      '" . $session['location']  . "',  '" . $session['loggedin'] . "') ");

  if(!isset($_POST['login']) && !isset($_GET['logout']))
  {
    // save the sessionid
    setcookie(COOKIE_PREFIX . "sessionid", $session['sessionid'], TIMENOW + 60*60*24*365, "/");
  }

  $sessioncreated = true;

  return $session;
}



// ############################## FIND SESSIONID ###############################

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



// ############################# CHECK IF SESSION ##############################

if(!empty($sessionid))
{
  $session = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "sessions
                               WHERE sessionid    = '$sessionid'
                               AND   lastactivity > " . (TIMENOW - $mainsettings['cookietimeout']) . "
                               AND   useragent    = '" . USERAGENT . "'
                               AND   admin        = 0");

}


if(empty($session) OR $session['userid'] == 0)
{
  if(!empty($_COOKIE[COOKIE_PREFIX . 'userid']) AND
     !empty($_COOKIE[COOKIE_PREFIX . 'password']) AND
     is_numeric($_COOKIE[COOKIE_PREFIX . 'userid']))
  {
    if($user = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "users WHERE userid = '" . $_COOKIE[COOKIE_PREFIX . 'userid'] . "' AND password = '" . $_COOKIE[COOKIE_PREFIX . 'password'] . "'"))
    {
      // cookie login is correct

      // delete old sessions
      if(!empty($session['sessionid']))
      {
        $DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE sessionid = '" . $sessionid . "'");
      }

      // create a new session for this user
      $session = CreateSession($_COOKIE[COOKIE_PREFIX . 'userid']);

    }
    else if(!isset($_POST['login']))
    {
      // user has bad cookies, set the cookies to empty if we are not logging in

      // cookie's bad and since we're not doing anything login related, kill the bad cookie
      setcookie(COOKIE_PREFIX . "userid",    "", TIMENOW + 60*60*24*365, "/");
      setcookie(COOKIE_PREFIX . "password",  "", TIMENOW + 60*60*24*365, "/");
    }
  }
}



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

if(empty($session))
{
  $session = CreateSession();
}



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

if($session['userid'] == 0)
{
  $user = array('userid'         => 0,
                'usergroupids'   => 4,  // weenCompany 2 - Guests
                'username'       => '',
                'loggedin'       => 0,
                'email'          => '',
                'timezoneoffset' => 0,
                'dstonoff'       => 0,
                'dstauto'        => 1);
}
else
{
  $user = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "users WHERE userid = '" . $session['userid'] . "'");

  // everything else is filled from the database query
  $user['usergroupids']   = $user['usergroupid'];
  $user['loggedin']       = 1;
  $user['timezoneoffset'] = 0;
  $user['dstonoff']       = 0;
  $user['dstauto']        = 1;

  // update user last activity date
  $DB->query("UPDATE " . TABLE_PREFIX . "users SET lastactivity = " . TIMENOW . " WHERE userid = $user[userid]");
}



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

if(!$sessioncreated)
{

  $DB->query("UPDATE " . TABLE_PREFIX . "sessions SET useragent    = '" . USERAGENT . "',
                                                      lastactivity = " . TIMENOW . ",
                                                      location     = '$location'
                                                WHERE sessionid    = '" . $session['sessionid'] . "' ");
}



// ################################ FORM LOGIN ################################

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

  if(strlen($loginusername))
  {
     $sql = "SELECT userid, usergroupid, email, username, password, banned, activated FROM " . TABLE_PREFIX . "users WHERE username = '$loginusername'";

    if($user = $DB->query_first($sql))
    {
      if($user['banned'] == 1)
      {
              $loginerrors[] = $sdlanguage['you_are_banned'];
      }
      else if($user['activated'] == 0)
      {
              $loginerrors[] = $sdlanguage['not_yet_activated'];
      }
      else if($user['password'] != md5($loginpassword))
      {
        $loginerrors[] = $sdlanguage['wrong_password'];
      }
      else
      {
        // user successfully logged in

        // everything else is filled from the database query
        $user['usergroupids']   = $user['usergroupid'];
        $user['loggedin']       = 1;
        $user['timezoneoffset'] = 0;
        $user['dstonoff']       = 0;
        $user['dstauto']        = 1;

        $DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE sessionid = '" . $sessionid . "'");

        // create new session
        $DB->query("REPLACE INTO " . TABLE_PREFIX . "sessions (sessionid, userid, ipaddress, useragent, lastactivity, location, loggedin)
                    VALUES ('$sessionid', '" . $user['userid'] . "', '" . USERIP . "', '" . USERAGENT . "', '" . TIMENOW . "', '$location', 1)");

        // save sessionid into cookie
        setcookie(COOKIE_PREFIX . "sessionid", $sessionid, TIMENOW + 60*60*24*365, "/");

        // if remember me then save username and password
        if($rememberme)
        {
          setcookie(COOKIE_PREFIX . "userid",   $user['userid'],   TIMENOW + 60*60*24*365, "/");
          setcookie(COOKIE_PREFIX . "password", $user['password'], TIMENOW + 60*60*24*365, "/");
        }

      }
    }
    else
    {
      $loginerrors[] = $sdlanguage['wrong_username'];
    }

  }
  else
  {
    $loginerrors[] = $sdlanguage['please_enter_username'];
  }

}



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

if(isset($_GET['logout']))
{
  // erase all cookies
  setcookie(COOKIE_PREFIX . "sessionid", "", TIMENOW + 60*60*24*365, "/");
  setcookie(COOKIE_PREFIX . "userid",    "", TIMENOW + 60*60*24*365, "/");
  setcookie(COOKIE_PREFIX . "password",  "", TIMENOW + 60*60*24*365, "/");

  if($user['userid'] != 0 AND $user['userid'] != -1)
  {
    // update user lastactivity and user lastvisit
    $DB->query("UPDATE " . TABLE_PREFIX . "users SET lastactivity = " . (TIMENOW - $mainsettings['cookietimeout']) . " WHERE userid = $user[userid]");

    // delete sessions with same userid
    $DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE userid = $user[userid] AND admin = 0");
  }

  // delete sessions with same sessionid
  $DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE sessionid = '" . $sessionid . "'");

  // create a new sessionid for this guest
  $sessionid = CreateSessionID();

  // save this new sessionid in the sessions table
  $DB->query("REPLACE INTO " . TABLE_PREFIX . "sessions (sessionid, userid, ipaddress, useragent, lastactivity, location, loggedin)
              VALUES ('" . $sessionid . "', '0', '" . USERIP . "', '" . USERAGENT . "', '" . TIMENOW . "', '$location', 0)");

  // save sessionid into cookie
  setcookie(COOKIE_PREFIX . "sessionid", $sessionid, TIMENOW + 60*60*24*365, "/");

  $user = array('userid'         => 0,
                'usergroupids'   => 4,  // weenCompany 2 - Guests
                '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['sessionhash']) > 0)
{
  $user['sessionurl'] = 's=' . $session['sessionhash'];
}


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

$DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE lastactivity < " . intval(TIMENOW - $mainsettings['cookietimeout']));



// ###################### 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, $sessionid);

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

function IsIPBanned($clientip)
{
  global $DB;

  $getbanip = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid='12' AND title = '禁止IP地址'");

  $addresses = explode(' ', preg_replace("/[[:space:]]+/", " ", trim($getbanip[0])) );

  if(count($addresses) > 0)
  {
    foreach ( $addresses as $ip )
    {
      if(strpos($ip, '*') === false)
      {
              // Not wildcard so go for exact match
              if($ip == $clientip)
                return true;
      }
      elseif(preg_match('/'.$ip.'/i', $clientip))
      {
            return true;
          }
    }
  }

  return false;
}

function ForumLink($linkType, $userid = -1)
{
  global $DB, $weenurl, $usersystem;

  $url = '';

  switch($linkType)
  {
  case 1:
    $getregpath = $DB->query_first("SELECT categoryid FROM " . TABLE_PREFIX . "pagesort WHERE moduleid = 12");
    if(isset($getregpath[0]) && $getregpath[0] > 0)
    {
      $url = RewriteLink('index.php?categoryid=' . $getregpath['categoryid']);
    }
        break;
  case 2:
    $getcppath = $DB->query_first("SELECT categoryid FROM " . TABLE_PREFIX . "pagesort WHERE moduleid = 11");
    if(isset($getcppath[0]) && $getcppath[0] > 0)
    {
      $url = RewriteLink('index.php?categoryid=' . $getcppath['categoryid']);
    }
        break;
  case 3:
    $getregpath = $DB->query_first("SELECT categoryid FROM " . TABLE_PREFIX . "pagesort WHERE moduleid = 12");
    if(isset($getregpath[0]) && $getregpath[0] > 0)
    {
      $url = RewriteLink('index.php?categoryid=' . $getregpath['categoryid'] . '&m12_forgotpwd=1');
    }
        break;
  case 4:
        break;
  case 5:
        break;
  }

  return $url;
}

?>
