<?php

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

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

// ########################## LOAD ADMIN SESSION #############################

$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('COOKIE_PREFIX', 'cwsa');
define('ONE_YEAR',                 60*60*24*365);


$usersettings = array();

if(!isset($mainsettings['admincookietimeout']) || !is_numeric($mainsettings['admincookietimeout']) || $mainsettings['admincookietimeout'] <= 0)
{
  $mainsettings['admincookietimeout'] = 1800;
}

function AdminLoginOut(){
	  if(defined('ADMIN_LOGIN'))
	  {
			LogIn();
			exit;
	  }
	  else
	  {
			header("Location: index.php");
			exit;
	  }
}


function CreateSession($userid, $username, $password)
{
  global $DB;

  $session = array('sessionid'    => md5(uniqid($username . $password)),
                   'userid'       => intval($userid),
                   'ipaddress'    => USERIP,
                   'useragent'    => USERAGENT,
                   'lastactivity' => TIMENOW,
                   'location'     => '0');

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

  setcookie(COOKIE_PREFIX . "sessionid", $session['sessionid'], TIMENOW + ONE_YEAR, "/");

  return $session;
}


// check and secure login info
if(isset($_POST['loginusername']) AND isset($_POST['loginpassword']))
{
	// first secure the data
 
	if(empty($_POST['loginusername']) OR empty($_POST['loginpassword']))
	{
		LogIn();

	}elseif(!isName($_POST['loginusername']) OR !isPass($_POST['loginpassword'])){
		$logininfo = '用戶名或密碼存在非法字符!';
		LogIn();
	}

  if($usersystem['name'] == 'Invision Power Board 2')
  {
    $_POST['loginusername'] = str_replace('&#039;', '&#39;', htmlspecialchars($_POST['loginusername'], ENT_QUOTES));
    $_POST['loginpassword'] = str_replace('&#039;', '&#39;', htmlspecialchars($_POST['loginpassword'], ENT_QUOTES));
  }

  // switch database?
  if($usersystem['dbname'] != $dbname)
  {
        // weenCompany is being integrated with a Forum in a different database
        $DB->select_db($usersystem['dbname']);
        require($rootpath . ADMIN_DIR.'/login/adminlogin_' . $usersystem['queryfile']);
        $usersettings = LoginUser($_POST['loginusername'], $_POST['loginpassword']);
        $DB->select_db($dbname);

		if(!is_array($usersettings))
		{
				$logininfo = '用戶不存在或密碼錯誤!';
				LogIn();
		}
		else
		{
				$session = CreateSession($usersettings['userid'], $usersettings['username'], $usersettings['password']);
		}
  }
  else
  {
        // weenCompany may be integrated with a forum in the same database,
        // or is using the weenCompany User System
        require($rootpath . ADMIN_DIR.'/login/adminlogin_' . $usersystem['queryfile']);
        $usersettings = LoginUser($_POST['loginusername'], $_POST['loginpassword']);

		if(!is_array($usersettings))
		{
				$logininfo = '用戶不存在或密碼錯誤!';
				LogIn();
		}
		else
		{
				$session = CreateSession($usersettings['userid'], $usersettings['username'], $usersettings['password']);
		}
  }
}
else if (isset($_GET['logout']))
{
		$sessionid = isset($_COOKIE[COOKIE_PREFIX . 'sessionid']) ? $_COOKIE[COOKIE_PREFIX . 'sessionid'] : '';

		if(!empty($sessionid))
        {
               $DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE sessionid = '$sessionid'");
        }

        setcookie(COOKIE_PREFIX . "sessionid", "", TIMENOW + ONE_YEAR, "/");
		LogIn();
		exit;
}
elseif(!defined('IN_GETPASS'))
{
		$sessionid = isset($_COOKIE[COOKIE_PREFIX . 'sessionid']) ? $_COOKIE[COOKIE_PREFIX . 'sessionid'] : '';

        if(!empty($sessionid))
        {
				$sql = "SELECT * FROM " . TABLE_PREFIX . "sessions
                               WHERE sessionid    = '$sessionid'
                               AND   lastactivity > " . (TIMENOW - $mainsettings['admincookietimeout']) . "
                               AND   useragent    = '" . USERAGENT . "'
                               AND   admin = 1";

                $session = $DB->query_first($sql);

				if(isset($session))
				{

					$DB->query("UPDATE " . TABLE_PREFIX . "sessions SET lastactivity = " . TIMENOW . "  WHERE sessionid    = '$sessionid' ");

					if($usersystem['dbname'] != $dbname)
					{
							$DB->select_db($usersystem['dbname']);
							require($rootpath . ADMIN_DIR.'/login/adminlogin_' . $usersystem['queryfile']);
							$usersettings = GetUser($session['userid']);
							$DB->select_db($dbname);
					}
					else
					{
							require($rootpath . ADMIN_DIR.'/login/adminlogin_' . $usersystem['queryfile']);
							$usersettings = GetUser($session['userid']);
					}

					$DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE lastactivity < " . intval(TIMENOW - $mainsettings['admincookietimeout']));
				}else{
					AdminLoginOut();
				}

        }else{
			AdminLoginOut();
		}

}


if(count($usersettings) <= 0)
{
        $usersettings = array('userid'         => -1,
                      'usergroupids'   => '',
                      'username'       => '',
                      'loggedin'       => 0,
                      'email'          => '',
                      'timezoneoffset' => 0,
                      'dstonoff'       => 0,
                      'dstauto'        => 0,
                      'sessionurl'     => '');
}else{

	unset($userinfo);
	$userinfo = GetUserInfo($usersettings);
	unset($usersettings);

	if($userinfo['userid'] > 0)
	{
	  if(!$userinfo['adminaccess'] AND count($userinfo['moduleadminids']) == 0 AND count($userinfo['custommoduleadminids']) == 0)
	  {
		$kickuser = true;
	  }
	}
	else
	{
	  $kickuser = true;
	}

	// is the user a moderator?
	if(count($userinfo['moduleadminids']) != 0 OR count($userinfo['custommoduleadminids']) != 0)
	{
	  // and does this moderator have access to this page?
	  if(!$userinfo['adminaccess'] AND !defined('MOD_ACCESS'))
	  {
		$kickuser = true;
	  }
	}

	// if mod, then make sure he has access to the module
	if(!$userinfo['adminaccess'])
	{
	  // check if the user is in a module
	  if(isset($_GET['moduleid']) AND !@in_array($_GET['moduleid'], $userinfo['moduleadminids']))
	  {
		$kickuser = true;
	  }

	  // check if the user is in a custom module
	  if(isset($_GET['custommoduleid']) AND !@in_array($_GET['custommoduleid'], $userinfo['custommoduleadminids']))
	  {
		$kickuser = true;
	  }

	  if(defined('CUSTOM_MODULE') AND !is_numeric($_GET['custommoduleid']) AND !is_numeric($_POST['custommoduleid']))
	  {
		$kickuser = true;
	  }
	}


	if(isset($kickuser) OR isset($_GET['login']))
	{
			AdminLoginOut();
	}

	$stylepath   = 'styles/advanced/';

}


?>
