<?php
session_start();
/*************************************************************\
+-------------------------------------------------------------+
| 通灵佛教网在线烧香程序 System                                 |
| Copyright (c) 2003-2010 Alfred China                        |
| All rights reserved.                                        |
+-------------------------------------------------------------+
\*************************************************************/
require_once('chk.php');

if ($REQUEST_METHOD == "POST") {
	if ($mode == "login") {
	
		if($_POST['code'] != $_SESSION['code']){
			echo "<script language=\"JavaScript\">\r\n"; 
			echo " alert(\"验证码验证失败，请重试！\");\r\n"; 
			echo " history.go(-1);\r\n";echo "</script>"; 
			exit; 
		}
	
		$username = addslashes($_POST["username"]);
		$password = md5($_POST["password"]);
		
		if ($username == "" or $password == "") {
		
			echo "<script language=\"JavaScript\">\r\n"; 
			echo " alert(\"请输入用户名和密码！\");\r\n"; 
			echo " history.go(-1);\r\n";echo "</script>"; 
			exit; 
		}
		
		$user_data = ng_query_first("SELECT aid, ngadmin, password, adminsion, admintype  FROM $sql_tbl[admins] WHERE ngadmin='$username' AND status='Y'");
		
		if ($user_data == "") {
			
			echo "<script language=\"JavaScript\">\r\n"; 
			echo " alert(\"用户名错误，请重试！\");\r\n"; 
			echo " history.go(-1);\r\n";echo "</script>"; 
			exit; 
			
		}elseif(!empty($password) && $password == $user_data["password"]){
		# Success
			setCOOKIE('ngadmin', $username);
			setCOOKIE('password', $password);
			setCOOKIE('aid', $user_data['aid']);
			
			$tm = time();
			db_query("UPDATE $sql_tbl[admins] SET last_login='$tm', loginip = '$REMOTE_ADDR' WHERE ngadmin='$username'");
			db_query("REPLACE INTO $sql_tbl[logins] (login, date_time, usertype, action, status, ip) VALUES ('$username','$tm','P','login','success','$REMOTE_ADDR')");
	
		}else{
		# failure
			
			db_query("REPLACE INTO $sql_tbl[logins] (login, date_time, usertype, action, status, ip) VALUES ('$username','".time()."','P','login','failure', '$REMOTE_ADDR')");

			echo "<script language=\"JavaScript\">\r\n"; 
			echo " alert(\"登录失败，请重试！\");\r\n"; 
			echo " history.go(-1);\r\n";echo "</script>"; 
			exit; 
		}
	}
	
}elseif($mode == "logout") { 

	db_query("REPLACE INTO $sql_tbl[logins] (login, date_time, usertype, action, status, ip) VALUES ('".$_COOKIE['ngadmin']."','".time()."','P','logout','success','$REMOTE_ADDR')");

	setCOOKIE('ngadmin', '');
	setCOOKIE('password', '');
	setCOOKIE('aid', '');

}

ng_header_location("./");
?>