<?php
namespace Bitrix\Main\Security;

class CurrentUser
{
	protected $provider;
	protected $isAuthenticated = false;
	protected $userId;
	protected $userName;
	protected $arUserGroups = array(2);

	public function __construct($userId = null, $isAuthenticated = false, $userName = "",  array $arUserGroups = array(2), $provider = "")
	{
		$this->userId = intval($userId);
		$this->isAuthenticated = (($this->userId > 0) && is_bool($isAuthenticated)) ? $isAuthenticated : false;
		$this->userName = $userName;
		$this->provider = $provider;

		if ($this->isAuthenticated)
		{
			$this->arUserGroups = $arUserGroups;

			if (!in_array(2, $this->arUserGroups))
				$this->arUserGroups[] = 2;
		}
		else
		{
			$this->arUserGroups = array(2);
		}
	}

	public static function createByUser(array $arUser, array $arUserGroups)
	{
		return new CurrentUser($arUser["ID"], true, $arUser["LOGIN"], $arUserGroups, $arUser["PROVIDER"]);
	}

	public function getAuthenticationProvider()
	{
		return $this->provider;
	}

	public function isAuthenticated()
	{
		return $this->isAuthenticated;
	}

	public function getUserId()
	{
		return $this->userId;
	}

	public function getUserName()
	{
		return $this->userName;
	}

	public function getUserGroups()
	{
		return $this->arUserGroups;
	}

	public function isInGroup($groupId)
	{
		$groupId = intval($groupId);
		return ($groupId == 2) || in_array($groupId, $this->arUserGroups);
	}

	public function isAdmin()
	{
		return in_array(1, $this->arUserGroups);
	}

	public static function current()
	{
		$context = \Bitrix\Main\Application::getCurrent()->getContext();
		return $context->getUser();
	}

	public function checkSecurity()
	{
		//session control from group policy
		$arPolicy = $GLOBALS["USER"]->GetSecurityPolicy();
		$currTime = time();
		if(
			(
				//IP address changed
				$_SESSION['SESS_IP']
				&& strlen($arPolicy["SESSION_IP_MASK"])>0
				&& (
					(ip2long($arPolicy["SESSION_IP_MASK"]) & ip2long($_SESSION['SESS_IP']))
					!=
					(ip2long($arPolicy["SESSION_IP_MASK"]) & ip2long($_SERVER['REMOTE_ADDR']))
				)
			)
			||
			(
				//session timeout
				$arPolicy["SESSION_TIMEOUT"]>0
				&& $_SESSION['SESS_TIME']>0
				&& $currTime-$arPolicy["SESSION_TIMEOUT"]*60 > $_SESSION['SESS_TIME']
			)
			||
			(
				//session expander control
				$_SESSION["BX_SESSION_TERMINATE_TIME"] > 0
				&& $currTime > $_SESSION["BX_SESSION_TERMINATE_TIME"]
			)
		)
		{
			$_SESSION = array();
			@session_destroy();

			//session_destroy cleans user sesssion handles in some PHP versions
			//see http://bugs.php.net/bug.php?id=32330 discussion
			if(\COption::GetOptionString("security", "session", "N") === "Y"	&& \CModule::IncludeModule("security"))
				\CSecuritySession::Init();

			session_id(md5(uniqid(rand(), true)));
			session_start();
			$GLOBALS["USER"] = new \CUser;
		}
		$_SESSION['SESS_IP'] = $_SERVER['REMOTE_ADDR'];
		$_SESSION['SESS_TIME'] = time();

		//session control from security module
		if(
			(\COption::GetOptionString("main", "use_session_id_ttl", "N") == "Y")
			&& (\COption::GetOptionInt("main", "session_id_ttl", 0) > 0)
			&& !defined("BX_SESSION_ID_CHANGE")
		)
		{
			if(!array_key_exists('SESS_ID_TIME', $_SESSION))
			{
				$_SESSION['SESS_ID_TIME'] = $_SESSION['SESS_TIME'];
			}
			elseif(($_SESSION['SESS_ID_TIME'] + \COption::GetOptionInt("main", "session_id_ttl")) < $_SESSION['SESS_TIME'])
			{
				if(\COption::GetOptionString("security", "session", "N") === "Y" && \CModule::IncludeModule("security"))
				{
					\CSecuritySession::UpdateSessID();
				}
				else
				{
					session_regenerate_id();
					if(!version_compare(phpversion(),"4.3.3",">="))
						setcookie(session_name(), session_id(), ini_get("session.cookie_lifetime"), "/");
				}
				$_SESSION['SESS_ID_TIME'] = $_SESSION['SESS_TIME'];
			}
		}
	}
}
