<?php
ini_set("display_errors","1");
ini_set("display_startup_errors","1");
set_magic_quotes_runtime(0);
include("include/dbcommon.php");
header("Expires: Thu, 01 Jan 1970 00:00:01 GMT");
header("Pragma: no-cache");
header("Cache-Control: no-cache");

if(@$_POST["a"]=="logout" || @$_GET["a"]=="logout")
{
	session_unset();
	setcookie("username","",time()-365*1440*60);
	setcookie("password","",time()-365*1440*60);
	header("Location: login.php");
	exit();
}

include('include/xtempl.php');
$xt = new Xtempl();

##if @BUILDER.arrLanguages.len>1##

if(@$_REQUEST["language"])
	$_SESSION["language"]=@$_REQUEST["language"];

$var=GoodFieldName(mlang_getcurrentlang())."_langattrs";
$xt->assign($var,"selected");
$xt->assign("langselector_attrs","name=lang onchange=\"javascript: window.location='login.##@ext##?language='+this.options[this.selectedIndex].value\"");
$xt->assign("languages_block",true);
##endif##


//	Before Process event
if(function_exists("BeforeProcessLogin"))
	BeforeProcessLogin($conn);


$myurl=@$_SESSION["MyURL"];
unset($_SESSION["MyURL"]);

$defaulturl="";
##if CreateMenu##
		$defaulturl="menu.php";
##else##
	##foreach @BUILDER.Tables as @t filter @t.bMenuItem order @t.nMenuOrder##
		##if @first##
		##if @t.bList##
		$defaulturl="##@t.strShortTableName##_list.php";
		##elseif @t.nType==titREPORT##
		$defaulturl="##@t.strShortTableName##_report.php";
		##elseif @t.nType==titCHART##
		$defaulturl="##@t.strShortTableName##_chart.php";
		##else##
		$defaulturl="##@t.strShortTableName##_add.php";
		##endif##
		##endif##
	##endfor##
##endif##			
##if !@BUILDER.Tables[bMenuItem].len##
	##if @BUILDER.Tables.bList##
		$defaulturl="##@BUILDER.Tables.strShortTableName##_list.php";
	##elseif @t.nType==titREPORT##
		$defaulturl="##@BUILDER.Tables.strShortTableName##_report.php";
	##elseif @t.nType==titCHART##
		$defaulturl="##@BUILDER.Tables.strShortTableName##_chart.php";
	##else##
		$defaulturl="##@BUILDER.Tables.strShortTableName##_add.php";
	##endif##
##endif##


##if @BUILDER.nLoginMethod==LOGIN_HARDCODED##
$cUserName = "##@BUILDER.strUserName s##";
$cPassword = "##@BUILDER.strPassword s##";
##endif##

##if @BUILDER.bAdminUser##
$cAdminUserID = "##@BUILDER.strAdminUserID s##";
##endif##

$message="";

$pUsername=postvalue("username");
$pPassword=postvalue("password");

$rememberbox_checked="";
$rememberbox_attrs = "name=\"remember_password\" value=\"1\"";
if(@$_COOKIE["username"] || @$_COOKIE["password"])
	$rememberbox_checked=" checked";

if (@$_POST["btnSubmit"] == "Login")
{
	if(@$_POST["remember_password"] == 1)
	{
		setcookie("username",$pUsername,time()+365*1440*60);
		setcookie("password",$pPassword,time()+365*1440*60);
		$rememberbox_checked=" checked";
	}
	else
	{
		setcookie("username","",time()-365*1440*60);
		setcookie("password","",time()-365*1440*60);
		$rememberbox_checked="";
	}
##if @BUILDER.nLoginMethod==LOGIN_HARDCODED##
//		 username and password are hardcoded
	$retval=true;
	$message="";
	if(function_exists("BeforeLogin"))
		$retval=BeforeLogin($pUsername,$pPassword,$message);

	if($retval && !strcmp($cPassword, $pPassword) && !strcmp($cUserName, $pUsername))
	{
		$_SESSION["UserID"] = $pUsername;
		$_SESSION["AccessLevel"] = ACCESS_LEVEL_USER;
		
		if(function_exists("AfterSuccessfulLogin"))
		{
			$dummy=array();
			AfterSuccessfulLogin($pUsername,$pPassword,$dummy);
		}
		
		
		if($myurl)
			header("Location: ".$myurl);
		else
			header("Location: ".$defaulturl);
		return;
	}
	else
	{
		if(function_exists("AfterUnsuccessfulLogin"))
			AfterUnsuccessfulLogin($pUsername,$pPassword,$message);
		if($message=="")
			$message = ##message INVALID_LOGIN##;
	}	
##else##
//   	 username and password are stored in the database
	$strUsername = (string)$pUsername;
	$strPassword = (string)$pPassword;
##if @BUILDER.bEncryptPasswords##
	$strPassword=md5($strPassword);
##endif##
	$sUsername=$strUsername;
	$sPassword=$strPassword;
	$rstemp=db_query("select * from ##@BUILDER.strLoginTable ts## where 1=0",$conn);
		
	if(FieldNeedQuotes($rstemp,$cUserNameField))
		$strUsername="'".db_addslashes($strUsername)."'";
	else
		$strUsername=(0+$strUsername);
	if(FieldNeedQuotes($rstemp,$cPasswordField))
		$strPassword="'".db_addslashes($strPassword)."'";
	else
		$strPassword=(0+$strPassword);
		$strSQL = "select * from ##@BUILDER.strLoginTable ts## where ".AddFieldWrappers($cUserNameField).
		"=".$strUsername." and ".AddFieldWrappers($cPasswordField).
		"=".$strPassword;
##if @BUILDER.bSendActivationLink##
		$strSQL.=" and ##@BUILDER.strActivationField ws##=1";
##endif##		
	$retval=true;
   	$logged=false;
	if(function_exists("BeforeLogin"))
		$retval=BeforeLogin($pUsername,$pPassword,$message);
	if($retval)
	{
		$rs=db_query($strSQL,$conn);
	 	$data=db_fetch_array($rs);
		if($data)
			if(@$data[$cUserNameField]==$sUsername && @$data[$cPasswordField]==$sPassword)
				$logged=true;
	}
	if($logged)
	{
		$_SESSION["UserID"] = $pUsername;
   		$_SESSION["AccessLevel"] = ACCESS_LEVEL_USER;

##if GroupSecurity && @BUILDER.strUserGroupField##
		$_SESSION["GroupID"] = $data["##@BUILDER.strUserGroupField s##"];
	##foreach @BUILDER.UserGroups as @u filter @u.bAdmin##
		if($_SESSION["GroupID"]=="##@u.strUserName s##")
	   		$_SESSION["AccessLevel"] = ACCESS_LEVEL_ADMINGROUP;
	##endfor##
##else##		
		$_SESSION["GroupID"] = "";
##endif##
		

##if @BUILDER.bAdminUser##
   		if($pUsername==$cAdminUserID)
			$_SESSION["AccessLevel"] = ACCESS_LEVEL_ADMIN;
##endif##


##foreach @BUILDER.tables as @t filter @t.strUsersTableOwnerID##
		##if @first##
			$_SESSION["OwnerID"] = $data["##@t.strUsersTableOwnerID s##"];
		##endif##
	$_SESSION["_##@t.strDataSourceTable s##_OwnerID"] = $data["##@t.strUsersTableOwnerID s##"];
##endfor##
	

		if(function_exists("AfterSuccessfulLogin"))
			AfterSuccessfulLogin($pUsername,$pPassword,$data);
		if($myurl)
			header("Location: ".$myurl);
		else
			header("Location: ".$defaulturl);
		return;
   	}
	else
	{
		if(function_exists("AfterUnsuccessfulLogin"))
			AfterUnsuccessfulLogin($pUsername,$pPassword,$message);
		if($message=="")
			$message = ##message INVALID_LOGIN##;
	}
##endif##	
}

$xt->assign("rememberbox_attrs",$rememberbox_attrs.$rememberbox_checked);


##if @BUILDER.bDynamicPermissions##
	// if guest have any permissions
	if (count(getGuestPermissions())>0)
	{
		$xt->assign("guestlink_block",true);		
	}else{
		$xt->assign("guestlink_block",false);
	}	
##elseif @BUILDER.bGuestLogin##	 
	$xt->assign("guestlink_block",true);
##else## 
	$xt->assign("guestlink_block",false);
##endif##

	
$_SESSION["MyURL"]=$myurl;
if($myurl)
	$xt->assign("guestlink_attrs","href=\"".$myurl."\"");
else
	$xt->assign("guestlink_attrs","href=\"".$defaulturl."\"");
	

if(@$_POST["username"] || @$_GET["username"])
	$xt->assign("username_attrs","value=\"".htmlspecialchars($pUsername)."\"");
else
	$xt->assign("username_attrs","value=\"".htmlspecialchars(refine(@$_COOKIE["username"]))."\"");


$password_attrs="onkeydown=\"e=event; if(!e) e = window.event; if (e.keyCode != 13) return; e.cancel = true; e.cancelBubble=true; document.forms[0].submit(); return false;\"";
if(@$_POST["password"])
	$password_attrs.=" value=\"".htmlspecialchars($pPassword)."\"";
else
	$password_attrs.=" value=\"".htmlspecialchars(refine(@$_COOKIE["password"]))."\"";
$xt->assign("password_attrs",$password_attrs);

if(@$_GET["message"]=="expired")
	$message = ##message SESSION_EXPIRED##;


if($message)
{
	$xt->assign("message_block",true);
	$xt->assign("message",$message);
}

$body=array();
$body["begin"]="<form method=post action=\"login.##@ext##\" id=form1 name=form1>
		<input type=hidden name=btnSubmit value=\"Login\">";
$body["end"]="</form>
<script>
function elementVisible(jselement)
{ 
	do
	{
		if (jselement.style.display.toUpperCase() == 'NONE')
			return false;
		jselement=jselement.parentNode; 
	}
	while (jselement.tagName.toUpperCase() != 'BODY'); 
	return true;
}
if(elementVisible(document.forms[0].elements['username']))
	document.forms[0].elements['username'].focus();
</script>";
$xt->assignbyref("body",$body);

$templatefile="login.htm";
if(function_exists("BeforeShowLogin"))
	BeforeShowLogin($xt,$templatefile);

$xt->display($templatefile);
?>