<?php
require_once(MODULE."/class/lib/adodb/adodb.inc.php");
require_once(MODULE. "/class/common/businessobject.php");
traceMessage("MODULE-".MODULE);
//require_once(MODULE. "/class/bllayer/session.php");
class session
{
		var $sessionid;
		var $userid;
		var $password;
		var $starttime;
		var $lastused;
		var $data;
		var $delim = "&&&";
		var $host ;
		var $pass ;
		var $Username;
		var $database;
		var $ipaddress;
		var $type;

	function session()
	{
		global $dbpassword;
		global $dbhostname;
		global $dbusername;
		global $dbdatabase;

		$this->host = '';
		$this->pass = '';
		$this->Username = '';
		$this->database = '';

	    $this->ipaddress = getenv("REMOTE_ADDR");
	    $this->sessionid = NULL;
	    $this->starttime = NULL;
	    $this->lastused = NULL;
	    $this->data = NULL;
	    $this->userid = NULL;
	    $this->password = NULL;
	}

	function unexpire($sid)
	{
		$t = gmdate("Y-m-d H:i:s");
		///traceMessage("Unexpiring ... $sid:$t");
		//$sql = "update web_sessions set lastusedtime='$t' where sessionid='$sid'";
		$sql = "update sessions set lastusedtime='$t' where session_id='$sid'";

		$conn = &ADONewConnection('mysqli');

		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;

		$res = $conn->Execute($sql);
		if (!$res)
			return false;
		else
			return true;
	}

	function startsession($userid, $password,$duration="",$sessionType=SESSION_TYPE_WEB_GENERAL)
	{
		
		logMsg('start');
		logMsg('in:$sessionid');
		//error_log("in session:comid:$companyId,custid:$customerId");
		srand((double)microtime()*10000000);
		$this->sessionid = md5(rand(0,9999999));
		//error_log("sessionid:".$this->sessionid);
		//$this->sessionid = 'c1a35c87ae712ddb09c13d6e97c67829';
		$this->userid=$userid;
	
		//$this->password=$password;
		$this->starttime=gmdate("Y-m-d H:i:s");

		$this->lastused=gmdate("Y-m-d H:i:s");
		$curDate=gmdate("Y-m-d H:i:s");

		$sql = "SELECT * FROM sessions limit 0,1";

		//echo "me inside startsession";
		$conn = &ADONewConnection('mysqli');

		//	$conn->debug = true;

		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;
		$rs = $conn->Execute($sql);

		$count=0;
		while(true)
		{
			$sql1 = "SELECT * FROM sessions where session_id='".$this->sessionid."'";
			$rs1 = $conn->Execute($sql1);
			$count++;
			if($rs1->_numOfRows>0)
			{
				srand((double)microtime()*10000000);
				$this->sessionid = md5(rand(0,9999999))."_spc_$count_".time();
			}
			else
				break;
			if($count ==100)
			{
				?>
				<script>
					location.href='/login.php'
				</script>
				
				<?
				die("something went wrong");
			}
		}
		$record = Array();

		$record["session_id"] = $this->sessionid;
		$record["username"] = $this->userid;
		//$record["password"] = base64_encode($this->password);
		//$record["creation_time"] =gmdate("Y-m-d H:i:s");
		
		$this->creation_time = gmdate("Y-m-d H:i:s");
		$record["creation_time"] = $this->creation_time;
		
		$this->last_updated = gmdate("Y-m-d H:i:s");
		$record["last_updated"] = $this->last_updated;
			
		//$record["last_updated"] = $curDate;
		$record["ipaddress"] = $this->ipaddress;
		$record["textvalue"] = $this->data;
		$record["session_type"] = $sessionType;
		//$record["company_id"] = $companyId;
		//$record["customer_id"] = $customerId;

		$insertSQL = $conn->GetInsertSQL($rs, $record);
		//error_log("in session:sql:$insertSQL");
		$result=$conn->Execute($insertSQL);
		$conn->Close();
		
		
		if ($result== true)
		{
			$result->Close();
			return TRUE;
		}
		return FALSE;
	}

	function updatedata($sessionid)
	{
		logMsg('start');
		logMsg('in:$sessionid');

		global $ActionResults;
		$sql = "SELECT * FROM sessions where session_id='$sessionid'";//AND ipaddress='".$this->ipaddress."'";

		$conn = &ADONEWConnection('mysqli');

		//$conn->debug = true;
		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;
		$rs = $conn->Execute($sql);

		if (!$rs)
		{
		  	ReportError(new ErrorData($conn->ErrorMsg(),__FILE__,__LINE__,"warning"));
			$conn->Close();
			return FALSE;
		}

		$this->Username = $rs->fields["username"];
		$this->userid = $rs->fields["username"];
		//$this->password = base64_decode($rs->fields["password"]);
		$this->starttime = $rs->fields["creation_time"];
		$this->lastused = $rs->fields["last_updated"];
		$this->data = $rs->fields["textvalue"];

		$t = strtotime(gmdate("Y-m-d H:i:s"));
		$lastUpdatedTime = strtotime($this->lastused);
		//error_log("updatesession:last time from db:$lastUpdatedTime, new time:$t");
		$diff=($t-$lastUpdatedTime);


		if ($diff <= SESSION_TIMEOUT ) // difference in milliseconds
		{
			if( $diff == 0)
				sleep(1);

			$this->lastused = gmdate("Y-m-d H:i:s");

			$updateSQL ="UPDATE sessions SET me_id ='".$rs->fields["me_id"]."' ,user_id='".$rs->fields["user_id"]."',username='".$rs->fields["username"]."',user_type='".$rs->fields["user_type"]."',session_vars='".$rs->fields["session_vars"]."', creation_time='".$rs->fields["creation_time"]."',last_updated = '".$this->lastused."', textvalue = '".$this->data."' where session_id = '".$this->sessionid."'";
			//echo "<br>$updateSQL";
			$result=$conn->Execute($updateSQL);
			$conn->Close();

		    if ($result == true)
	    	{
				$result->Close();
	    		return TRUE;
	    	}
			else
	            return FALSE;
		}
		else
	    {
			global $SCREEN;
			$SCREEN="logout";

			$this->closesession($sessionid);
			array_push($ActionResults,"Your session has been expired please re-login");
			JsErrorMessage ( Array ( 'Sorry, your session has expired, please login again ') );
			return TRUE;
		}
	}

	function EmptySession($sessionid)
	{
		logMsg('start');
		logMsg('in:$sessionid');

		global $ActionResults;
		global $errorMessages;
		$sql = "SELECT * FROM sessions where session_id='$sessionid'";//AND ipaddress='".$this->ipaddress."'";
		error_log("updatesession:$sql");
		$conn = &ADONEWConnection('mysqli');

		//$conn->debug = true;
		traceMessage("1");
		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;
		$rs = $conn->Execute($sql);
		//echo "DATABASE ".$this->database . "<BR>";
		//error_log("rs".print_r_log($rs));
		if (!$rs || $rs->_numOfRows==0)
		{
			array_push($ActionResults,$conn->ErrorMsg());
			$conn->Close();
			traceMessage("updatesession:ret false1");
			error_log("updatesession:ret false1");
			traceMessage("ret false 1");
			return FALSE;
		}
	 	$this->sessionid = $rs->fields["session_id"];
		$this->userid = $rs->fields["username"];
		//$this->password = base64_decode($rs->fields["password"]);
		$this->starttime = $rs->fields["creation_time"];
		$this->lastused = $rs->fields["last_updated"];
		$this->data = "";
		$ip = $rs->fields["ipaddress"];
		global $SAFE_LIST ;
		//error_log("from db:".$ip."--- from pc".$_SERVER["REMOTE_ADDR"]);
		traceMessage("2");
		// Create Business Object for Notice Reporting
		$objNotice = new SessionData();
		if((!in_array("*",$SAFE_LIST)) && ($ip != $_SERVER["REMOTE_ADDR"] and (!in_array($ip,$SAFE_LIST))))
		{
			global $SCREEN;
			//$this->closesession($sessionid);
			ReportError(new ErrorData($objNotice->INVALID_IP,__FILE__,__LINE__,'notice'));

			$SCREEN="logout";
			//ShowMessages();
			//return TRUE;
		}

		$t = strtotime(gmdate("Y-m-d H:i:s"));
		$lastUpdatedTime = strtotime($this->lastused);
		//error_log("updatesession:last time from db:$lastUpdatedTime, new time:$t");
		$diff=($t-$lastUpdatedTime);
traceMessage("3");
		if ( $diff <= SESSION_TIMEOUT ) // difference in milliseconds
		{

			//if( $diff == 0)
				//sleep(1);

			$this->lastused = gmdate("Y-m-d H:i:s");
			$record["textvalue"] = '';
			$updateSQL = $conn->GetUpdateSQL($rs, $record);
			traceMessage("4::$updateSQL");
			traceMessage("conn::".print_r_log($conn));
			$result=$conn->Execute($updateSQL);
			$conn->Close();
			return TRUE;

		}
		else
		{
			error_log("last use time:".$this->lastused.", cur time=$t,systemtime=".time().",diff=$diff,sessiontimeout=".SESSION_TIMEOUT." ,sessionid:".$mysession->sessionid);
			global $SCREEN;
			//$this->closesession($sessionid);

			$objNotice = new SessionData();
			ReportError(new ErrorData($objNotice->SESSION_EXPIRE,__FILE__,__LINE__,'notice'));
			$SCREEN="logout";
			$ACTION="";
			ShowMessages();
			traceMessage("ERRORSTACK11111:".print_r_log(GetErrorMessages()));
			return false;
		}
		logMsg('end');
	}
	function updatesession($sessionid)
	{
		logMsg('start');
		logMsg('in:$sessionid');
		//traceMessage("In update session $sessionid");
		global $ActionResults;
		global $errorMessages;
		$sql = "SELECT * FROM sessions where session_id='$sessionid'";//AND ipaddress='".$this->ipaddress."'";
		//error_log("updatesession:$sql");
		$conn = &ADONEWConnection('mysqli');

		//$conn->debug = true;

		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;
		$rs = $conn->Execute($sql);
		//echo "DATABASE ".$this->database . "<BR>";
		//error_log("rs".print_r_log($rs));
		if (!$rs || $rs->_numOfRows==0)
		{
			$conn->Close();
			traceMessage("updatesession:ret false1");
			error_log("updatesession:ret false1");
			return FALSE;
		}

		$this->sessionid = $rs->fields["session_id"];
		$this->userid = $rs->fields["username"];
		//$this->password = base64_decode($rs->fields["password"]);
		$this->starttime = $rs->fields["creation_time"];
		$this->lastused = $rs->fields["last_updated"];
		$this->data = $rs->fields["textvalue"];
		$ip = $rs->fields["ipaddress"];
		$this->type = $rs->fields["session_type"];
		global $SAFE_LIST ;
		//error_log("from db:".$ip."--- from pc".$_SERVER["REMOTE_ADDR"]);
		// Create Business Object for Notice Reporting
		$objNotice = new SessionData();


		$t = strtotime(gmdate("Y-m-d H:i:s"));
		$lastUpdatedTime = strtotime($this->lastused);
		//traceMessage("updatesession:last time from db:$lastUpdatedTime, new time:$t");
		$diff=($t-$lastUpdatedTime);
		//echo $diff."--".$this->lastused."--".date("Y-m-d H:i:s");
		//die();
		$timeOut = ($rs->fields["session_type"]!=SESSION_TYPE_WEB_EMAIL_LINK)?SESSION_TIMEOUT:LINK_EXPIRE_TIME;
		/*
		if ($diff <= $timeOut ) // difference in milliseconds
		{
			traceMessage("ERR1: CurrTime:".gmdate("Y-m-d H:i:s")."last use time:".$this->lastused.", cur time=$t,systemtime=".time().",diff=$diff,sessiontimeout=".SESSION_TIMEOUT." ,sessionid:".$sessionid);
			
		}
		else
			traceMessage("ERR2: CurrTime:".gmdate("Y-m-d H:i:s")."last use time:".$this->lastused.", cur time=$t,systemtime=".time().",diff=$diff,sessiontimeout=".SESSION_TIMEOUT." ,sessionid:".$sessionid);
		*/		
		
		if ($diff <= $timeOut ) // difference in milliseconds
		{
			//traceMessage("less time");
			$this->lastused = gmdate("Y-m-d H:i:s");
			$record["last_updated"] = $this->lastused;
			$updateSQL = $conn->GetUpdateSQL($rs, $record);
			$result=$conn->Execute($updateSQL);
			$conn->Close();
			return TRUE;

		}
		else
		{
			traceMessage("ERR2: CurrTime:".gmdate("Y-m-d H:i:s")."last use time:".$this->lastused.", cur time=$t,systemtime=".time().",diff=$diff,sessiontimeout=".SESSION_TIMEOUT." ,sessionid:".$sessionid);
			global $SCREEN;
			//$this->closesession($sessionid);

			$objNotice = new SessionData();
			ReportError(new ErrorData($objNotice->SESSION_EXPIRE,__FILE__,__LINE__,'notice'));

			$SCREEN="logout";
			$ACTION="";
			ShowMessages();
			return false;
		}
		logMsg('end');
	}

	function updatesessionip($sessionid,$ip)
	{

		traceMessage("updatesession");
		global $ActionResults;
		global $errorMessages;
		$sql = "SELECT * FROM sessions where session_id='$sessionid'";//AND ipaddress='".$this->ipaddress."'";
		traceMessage("updatesession:$sql");
		$conn = &ADONEWConnection('mysqli');

		//$conn->debug = true;
		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;
		$rs = $conn->Execute($sql);
		//echo "DATABASE ".$this->database . "<BR>";

		if (!$rs || $rs->_numOfRows==0)
		{
			array_push($ActionResults,$conn->ErrorMsg());
			$conn->Close();
			traceMessage("updatesession:ret false1");
			return FALSE;
		}
	 	//$ip="1";
		$record["ipaddress"] =$ip;
		$updateSQL = $conn->GetUpdateSQL($rs, $record);

		//print_r_pre($updateSQL,"A");
		$result=$conn->Execute($updateSQL);
		$conn->Close();
		return TRUE;


	}
	function closesession($sessionid)
	{
		$sql = "delete from sessions where session_id='$sessionid'";

		$conn = &ADONewConnection('mysqli');

		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;

		$rs = $conn->Execute($sql);
		$conn->Close();
		if($rs==true)
			return true ;
	}

	function setvalue($name, $value)
	{

	 	if ( ($value=="") || ($name == "") )
			return false;
		$name = urlencode($name);
		$value = urlencode($value);
		$new = $name . "=" . $value;
		$name.="=";

	//	print "NEw <BR> ".$new;

		$pos = strpos($this->data, "&&&".$name);
		if ($pos===false)
		{
			$this->data .= $new . $this->delim;
		}
		else
		{
			$temp=explode($this->delim,$this->data);
		 	foreach ($temp as $anothertemp)
			{
				$leftside = explode("=",$anothertemp);

				if ($leftside[0]."="!=$name)
					$kkkkk=1;
				else
				{
				  	$this->data=str_replace($anothertemp,$new,$this->data);
				}
				//traceMessage("name:$name anothertemp : ".$anothertemp."   New : ".$new);
			}
		//	print $this->data;
		}

		//error_log("sessionid:".$this->sessionid);
		$sql = "SELECT * FROM sessions where session_id='".$this->sessionid."'";
		$conn = &ADONewConnection('mysqli');
		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;
		$rs = $conn->Execute($sql);
		if ($rs->RecordCount() != 1 )
		{
			$conn->Close();
			return FALSE;
		}

		$record = Array();

		$record["textvalue"] = $this->data;

		$updateSQL = $conn->GetUpdateSQL($rs, $record);
		$result=$conn->Execute($updateSQL);
		$conn->Close();
		if ($result== true)
		{
			$result->Close();
			return TRUE;
		}

		return FALSE;
	}

	function deletevalue($name)
	{

		$tempval = $this->getvalue($name);
		if ($tempval == false)
			return false;

		$tempval = urlencode($tempval);
		$name = urlencode($name);

		$temp = $name . "=" . $tempval.$this->delim;
		$this->data=str_replace ($temp, "", $this->data);

		$sql = "SELECT * from sessions where session_id='".$this->sessionid."'";
		$conn = &ADONewConnection('mysqli');

		if (!$conn->Connect(DESKTOPDBHOSTNAME,DESKTOPDBUSERNAME,DESKTOPDBPASSWORD,DESKTOPDBDATABASE))
			return FALSE;

		$rs = $conn->Execute($sql);
		if ($rs->RecordCount() != 1 )
		{
			$conn->Close();
			return FALSE;
		}

		$record = Array();
		$record["textvalue"] = $this->data;

		$updateSQL = $conn->GetUpdateSQL($rs, $record);

		$result=$conn->Execute($updateSQL);
		$conn->Close();

		if ($result== true)
		{
			$result->Close();
			return TRUE;
		}

	}

	function getvalue($name)
{
	//error_log("in:$name");
	if ($name=="")
	{
		error_log("0");
		return false;
	}
	//error_log("*************");
	$name = urlencode($name);

	$name.="=";
	$start = strpos($this->data,$name);
	if ($start === false)
	{
		//error_log("1:".$this->data);
		return false;
	}
	$start = $start + strlen($name);
	$temp = substr($this->data,$start,strlen($this->data));
	$end = strpos($temp,$this->delim);
	if ($end === false)
	{
		//error_log("2");

		return false;
	}
	$value = substr($this->data,$start,$end);
	$value = urldecode($value);
	//error_log("out:$value");
	return $value;
}

}
?>