<?php
$loginname=trim($_REQUEST["loginname"]);
$password=trim($_REQUEST["password"]);
$saveuid=trim($_REQUEST["saveuid"]);
$ClientUID=$_COOKIE["SIPUID"];
$ClientPWD=$_COOKIE["SIPPWD"];

$isLogined=FALSE;  //页级变量，判断是否登录，默认为False，在CheckLogin()设置为True，在LogOut()设置为False
$isLogOut=FALSE;   //页级变量，判断是否退出操作
$bCookieAuth=FALSE;
$Work = $_REQUEST["Work"];
if ($Work=="") {				//第一次浏览
	if ($ClientUID!="") {		//有COOKIE身份数据
		$Work="CheckLogin";
		$bCookieAuth=TRUE;
	}
}
if ($Work=="CheckLogin") { //检验用户登录
	$ret = CheckLogin();
	if ($ret==0) {
		ob_clean();
		header("Location: confirm.php");
		exit;
	}
	else {
		if ($ret>0) $isLogined=TRUE;
	}
}
elseif ($Work=="Confirm") {  	//用户上网确认
	$bCookieAuth=TRUE;
	$ret = CheckLogin();
	if ($ret>0) $isLogined=TRUE;
}
elseif ($Work=="Other") {  	//以其它帐号上网
	$loginname="";
	$password="";
	$ClientUID="";
	$ClientPWD="";
	$Work="";
}
elseif ($Work=="LogOut") {  	//退出
	$isLogined = LogOut();
	$isLogOut=TRUE;
}
else {
}

$strUID="";
if ($isLogined) {
	$strUID=$loginname;
	if ($strUID=="") {
		$strUID=$ClientUID;
	}
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta http-equiv="Content-Language" content="zh-cn">
<title>SIP酒店上网计费管理系统</title>
<link href="images/style.css" rel="stylesheet" type="text/css">
<script language="javascript">

document.oncontextmenu=mymenu;
<?php
if ($isLogined) {			//成功登录才执行
?>
window.onbeforeunload = myconfirm;
window.onunload = myclose;
timerid=window.setTimeout("mytimer()",3000);
starttime=0;
contacttime=0;
bQuit=0;
<?php
}
?>
//关闭或离开窗口前的警告
function myconfirm()
{
	if (bQuit>0) return;
	else return "\r\n\r\n\r\n\r\n\r\n警告：关闭或离开本页面，您将不能继续上网！！！\r\n      如您需要继续上网，请按“取消”回到当前页面！！！\r\n      请另外运行一个新的浏览器进行上网浏览！！！\r\n\r\n\r\n\r\n\r\n";
}

//关闭计时器
function myclose()
{
	window.clearTimeout(timerid);
	if (bQuit<1) {
		bQuit=1;
		document.frmLogOut.submit();
		alert("感谢您的使用！");
	}
}

//屏蔽右键菜单
function mymenu()
{
	window.event.returnValue=false;
}

//计时器
function mytimer()
{
	var d=new Date();
	tmptime=Math.round(d.getTime()/1000);
	showtime(tmptime-starttime);
	if (tmptime-contacttime>=20) {	//间隔上次联系超过20秒，再次联系
		contacttime=tmptime;
		mycontact(tmptime);
	}
	timerid=window.setTimeout("mytimer()",3000);
}

//刷新页面计时器
function showtime(times)
{
	var d=1,h=1,m=1,s=1;
	d=Math.floor(times/(24*3600));
	s=times-d*24*3600;
	h=Math.floor(s/3600);
	s=s-h*3600;
	m=Math.floor(s/60);
	s=s-m*60;
	var str="";
	if (d>0) str=str+d+"天，";
	if (h>0) str=str+h+"小时，";
	if (m>0) str=str+m+"分钟，";
	str=str+s+"秒";
	document.frmLogOut.TimeText.value=str;
}

//手工退出系统，先关闭计时器和警告
function myQuit()
{
	window.clearTimeout(timerid);
	bQuit=1;
	document.frmLogOut.submit();
}

//保持与服务器通讯
function mycontact(currenttime)
{
	var strurl="contact.php?serial="+currenttime.toString();
	parent.sip_myright.location=strurl;
}

//网页载入时，初始化操作
function myload()
{	
<?php
if ($isLogined) {
?>
	var d=new Date();
	contacttime=Math.round(d.getTime()/1000);
	starttime=contacttime;
	showtime(0);
	mycontact(starttime);
	bQuit=0;
<?php
}
?>
}

function mysaveid()
{
	var str="";
	if (document.frmLogin.saveuid.checked) {
		str=showModalDialog("saveuid.html");
		if (str!="saveuid") 
		{
			document.frmLogin.saveuid.checked=false;
		}
	}
}
</script>

</head>

<body onload="javascript:myload();">
<table width="778" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr valign="top"> 
    <td width="78"><a href="http://www.feware.com/" target="_blank"><img src="images/logo.jpg" width="182" height="78" border="0"></a></td>
    <td><img src="images/banner.jpg" width="596" height="78"></td>
  </tr>
</table>
<table width="778" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr valign="top"> 
    <td width="182" background="images/lf_bg.gif"> 
<?php
if ($isLogined) {	
	//登录用户信息
	ShowInfo();
}
else {
	//登录窗口
	Login();
}
?>

           
<?php
//还没有登录或登录失败，显示登录窗口
function Login()
{
?>
	<table width="100%" border="0" cellpadding="5" cellspacing="0" height="233" background="images/login_bg.jpg">
<form name="frmLogin" method="POST" action="login.php" onSubmit="return CheckInput(this);">
		<tr> 
		  <td width="35%" align="right" height="36">　</td>
		  <td width="65%" height="36">　</td>
		</tr>
		<tr> 
		  <td width="35%" align="right" height="27"><font color="#FFFF00">帐号:</font></td>
		  <td width="65%" height="27"><input name="loginname" type="text" size="10" tabindex="1" onKeyDown="if(event.keyCode==13)event.keyCode=9" maxlength="20" onFocus="this.select();"></td>
		</tr>
		<tr> 
		  <td align="right" width="35%" height="15"><font color="#FFFF00">密码:</font></td>
		  <td width="65%" height="15">
		  <input name="password" type="password" size="10"  tabindex="2" onKeyDown="if(event.keyCode==13){frmLogin.frmSubmit.click();}" maxlength="20" onFocus="this.select();">
<input name="Work" type="hidden" value="CheckLogin"> 
<script language="javascript">
<!--
function CheckInput(obj){
if(obj.loginname.value==""){
alert("请输入[帐号]");
obj.loginname.focus();
return false;
}
if(obj.password.value==""){
alert("请输入[密码]");
obj.password.focus();
return false;
}
return true;    
}
//-->
</script>
<input name="frmSubmit" type="submit" id="frmSubmit" value="Submit" style="display:none">
		  </td>
		</tr>
		<tr> 
		  <td align="center" width="100%" height="27" colspan="2" valign="middle"><input type=checkbox name=saveuid value="yes" onclick="javascript:mysaveid();"><font color="#FFCC99">保存密码</font></td>
		</tr>
		<tr> 
		  <td width="100%" colspan="2" height="62" align="center">
            <table border="0" cellpadding="0" cellspacing="0" width="90%" height="43">
              <tr>
                <td width="50%" height="43" align="center"><img border="0" src="images/btn_Login.gif" style="cursor:hand" onClick="frmLogin.frmSubmit.click();"></td>
                <td width="50%" height="43" align="center"><img border="0" src="images/btn_Reset.gif" style="cursor:hand" onClick="frmLogin.reset();"></td>
              </tr>
            </table>
          </td>
		</tr>
</form>
	</table> 
<?php
return;
}
?>


<?php
//登录成功，显示用户信息
function ShowInfo()
{
	global $strUID;
?>
                  <table border="0" cellpadding="0" cellspacing="0" width="100%" height="233" background="images/HelpSelf_bg.jpg">
                    <tr>
                      <td width="100%" height="31">　</td>
                    </tr>
                    <tr>
                      <td width="100%" height="29" align="center" style="padding:0px 0px 0px 10px"><font color="#FFFF00">房号：</font><font color="#FFFFFF"><?php echo $strUID?></font></td>
                    </tr>
                    <tr>
                      <td width="100%" height="35" align="center">
                        <table border="0" cellpadding="0" cellspacing="0" width="80%" height="100%" background="images/item.jpg">
                          <tr>
                            <td width="100%" align="center" valign="top"><a href="pass.php" target="_blank">修改密码</a></td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                    <tr>
                      <td width="100%" height="34" align="center">
                        <table border="0" cellpadding="0" cellspacing="0" width="80%" height="100%" background="images/item.jpg">
                          <tr>
                            <td width="100%" align="center" valign="top"><a href="query2.php" target="_blank">清单查询</a></td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                    <tr>
                      <td width="100%" height="34" align="center">
                        <table border="0" cellpadding="0" cellspacing="0" width="80%" height="100%" background="images/item.jpg">
                          <tr>
                            <td width="100%" align="center" valign="top"><img border="0" src="images/btn_exit.jpg" style="cursor:hand" onClick="frmLogOut.btnQuit.click();"></td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                    <tr>
                      <td width="100%" height="57" align="center" valign="top">
              <form name="frmLogOut" method="POST" action="logout_result.php">
					本次上网用时:<br><input type="text" name="TimeText" size="15" readonly="true" class="TimeCount">
                 	<input name="btnQuit" type="submit" id="btnQuit" value="退出上网" style="display:none" onclick="javascript:myQuit();">             
					<input name="Work" type="hidden" value="LogOut">             
			  </form>
                      </td>
                    </tr>
                  </table>
<?php
return;
}
?>

      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr> 
          <td width="100%" align="center"><img src="images/QA_tp.gif" width="147" height="75"></td>
        </tr>
      </table>
      <table width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr> 
          <td width="100%">
            1. 登录后无法上网，请退出上网，再将电脑的TCP/IP属性设置为自动获取IP地址和DNS服务器，重新登录，或联系前台。<br>                                                                      
            <font color="#FF0000">    
            2. 登录后，请另外重新运行浏览器程序，在新的浏览器中上网浏览网站。登录窗口不能关闭，否则将自动被禁止上网！</font><br>   
            3. 如果还是不能登录上网，或有其它问题，请直接和前台联系。<br>                                  
          </td>
        </tr>
      </table> 
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr> 
          <td width="35%" align="center"><img src="images/QA_bt1.gif" width="40" height="43"></td>
          <td width="26%" align="center"><img src="images/QA_bt2.gif" width="40" height="43"></td>
          <td width="39%" align="center"><img src="images/QA_bt3.gif" width="40" height="43"></td>
        </tr>
      </table> 
      <br>
      <br>
      <br>
      <br>
      <br>
      <br>
      <br>
      <br>
      <br>
      
    </td>
    <td width="596" background="images/rt_bg.gif">
      <iframe src="myshow.html" width="100%" height="100%" border="0" frameborder="0" scrolling="no" resize="no"></iframe>
    </td>
  </tr>
</table>
</body>
</html>


<?php
function CheckLogin()
{
	global $loginname,$password,$saveuid,$ClientUID,$ClientPWD,$isLogined,$isLogOut,$bCookieAuth,$Work,$strUID;
	$db=mysql_pconnect(get_cfg_var("SIPSERVER"),get_cfg_var("SIPUSER"),get_cfg_var("SIPPWD"));
	mysql_select_db(get_cfg_var("SIPDB"),$db);
	$timestr=strftime("%Y-%m-%d %H:%M:%S");

	$password1="";
	$bHaveUserInfo=FALSE;
	if ($loginname!="" && $password!="") {
		$bHaveUserInfo=TRUE;
	}
	else {
		if ($ClientUID!="") {
			$bHaveUserInfo=TRUE;
			$loginname=$ClientUID;
			$password="";
		}
	}

	$n=0;
	$userIP = $_SERVER["REMOTE_ADDR"];			//读取该用户当前使用电脑IP地址
	$rs = mysql_query("select userid from login where ipaddr='".$userIP."'",$db);		//查找该IP是否已经登录
	if (($row = mysql_fetch_array($rs))==FALSE) {			//还没有登录
		mysql_free_result($rs);
		//合法性和有效性校验	
		if (!$bHaveUserInfo) {
    		$n=0;
		} else {
			$rs = mysql_query("select userid,password,type,onlines,cookiemask,suspendtime from users where loginname='".$loginname."' and checked='n'",$db);		//查找该用户ID记录
			if (($row = mysql_fetch_array($rs))==FALSE) {			//没有找到
				mysql_free_result($rs);
				$n=1;				//不存在该用户ID
			} else {
				$userid = $row["userid"];
				$usertype = $row["type"];
				$password1=$row["password"];
				$maxonlines=$row["onlines"];
				$cookiemask=$row["cookiemask"];
				$suspendtime=$row["suspendtime"];
				if (is_null($suspendtime)) {
					$suspendtime="";
				}
				mysql_free_result($rs);
				if (is_null($maxonlines)) {
					$maxonlines=1;
				}
				if (is_null($cookiemask)) {
					$cookiemask="1234567890";
				}
				$bPass=FALSE;
				if ($loginname!="" && $password!="") {
					if ($password==$password1) {					//比较密码
						$bPass=TRUE;
					}
				} else {
					$md5str=md5($loginname.",".$cookiemask.",".$password1);
					if ($md5str==$ClientPWD) {
						$bPass=TRUE;
					}
				}
				if (!$bPass) {
					$n=2;			//密码不对
				} else {
					if ($password=="" && $ClientUID!="" && $ClientPWD!="" && $Work!="Confirm") {	//客户端已经存在合法COOKIE，而且不是上网确认
						//转到是否上网提示页面
						mysql_close($db);
						return 0;	//需要转到确认网页
					}
					$onlines=0;
					$rs = mysql_query("select count(ipaddr) as allcount from login where userid='".$userid."'",$db);		//查找该用户ID是否已经登录过
					if ($row = mysql_fetch_array($rs)) {
						$onlines=$row["allcount"];
						if (is_null($onlines)) {
							$onlines=0;
						}
					}
					mysql_free_result($rs);
					if ($onlines<$maxonlines) {	//还没有超过并发人数限制
						if ($suspendtime=="") {
							$remaintime=0;		//不限制上网时间
							$remaindata=0;		//不限制上网流量
							//向登录表中插入当前用户上网新记录
							mysql_query( "insert into login(ipaddr,userid,type,remaintime,remaindata,logintime,maskword) values('".$userIP."','".$userid."','".$usertype."',".strval($remaintime).",".strval($remaindata).",'".$timestr."','n')",$db );
							$tmprs = mysql_query("select ipaddr from contact where ipaddr='".$userIP."'",$db);
							if ( ($tmprow = mysql_fetch_array($tmprs))==FALSE ) {
								mysql_free_result($tmprs);
								mysql_query( "insert into contact(ipaddr,contacttime) values('".$userIP."',".strval(time()).")",$db );
							}
							else {
								mysql_free_result($tmprs);
								mysql_query( "update contact set contacttime=".strval(time())." where ipaddr='".$userIP."'",$db );
							}
							$_SESSION["userid"]=$userid;
							$_SESSION["StartTime"]=$timestr;
							$n=3;				//登录成功
						}
						else {
							$n=6;		//已经被暂停
						}
					} else {
						$n=5;					//用户ID已经登录过
					}
				}
			}
		}
	} else {
		$_SESSION["userid"]=$row["userid"];
		mysql_free_result($rs);
		$_SESSION["StartTime"]=$timestr;
		$n=4;					//客户机IP已经登录
	}

	//登录未成功，显示原因
	$bPass=FALSE;
	if ($n==1) {
		if (!$bCookieAuth) {		//不是COOKIE验证
			echo("<script>alert(\"<操作失败>\\n您输入的登录帐号（房号）不存在，或者暂时没有开通上网功能。\\n如果您需要开通上网功能，请咨询前台。\\n请检查。\");</script>");
		}
	} elseif ($n==2) {
		if (!$bCookieAuth) {		//不是COOKIE验证
			echo("<script>alert(\"<操作失败>\\n您输入的登录密码错误！\\n如果您忘记密码，请咨询前台。\\n请检查。\");</script>");
		}
	} elseif ($n==3) {
		$bPass=TRUE;
		if ($saveuid=="yes" && $loginname!="" && $password!="") {
			setcookie("SIPUID",$loginname,time()+60*60*24*30,"/",get_cfg_var("SIPWWWHOST"),0);
			setcookie("SIPPWD",md5($loginname.",".$cookiemask.",".$password1),time()+60*60*24*30,"/",get_cfg_var("SIPWWWHOST"),0);
		}
	} elseif ($n==4) {		//不再提示重复登录
		$bPass=TRUE;
	} elseif ($n==5) {				//不管是手工登录还是COOKIE自动登录，都提示
		if (!$bCookieAuth) {		//不是COOKIE验证
			echo("<script>alert(\"<操作失败>\\n您用的登录帐号（房号）已有他人正在使用中，\\n已经超过同时并发在线使用允许人数！\");</script>");
		}
	} elseif ($n==6) {				//不管是手工登录还是COOKIE自动登录，都提示
		if (!$bCookieAuth) {		//不是COOKIE验证
			echo("<script>alert(\"<操作失败>\\n您的帐号当前被暂停上网，\\n请和前台服务员联系！\");</script>");
		}
	} else {
		if (!$bCookieAuth) {		//不是COOKIE验证
			echo("<script>alert(\"<操作失败>\\n必须输入登录帐号（房号）及其密码，不能为空！\\n请检查。\");</script>");
		}
	}
	mysql_close($db);			//关闭数据库连接
	if ($bPass) return 1;	//通过
	else return -1;		//未通过
}

function LogOut()
{
	$db=mysql_pconnect(get_cfg_var("SIPSERVER"),get_cfg_var("SIPUSER"),get_cfg_var("SIPPWD"));
	mysql_select_db(get_cfg_var("SIPDB"),$db);
	$userIP = $_SERVER["REMOTE_ADDR"];			//读取该用户当前使用电脑IP地址
	$rs = mysql_query("select ipaddr from logout where ipaddr='".$userIP."'",$db);		//查找该IP是否已经登出
	if ( ($row = mysql_fetch_array($rs))==FALSE ) {			//还没有登出
		mysql_free_result($rs);
		//向logout表中插入当前用户上网IP地址，以通知监控计费器取消该IP地址连接
		mysql_query( "insert into logout(ipaddr) values('".$userIP."')",$db );
		mysql_query( "delete from contact where ipaddr='".$userIP."'",$db );
	}
	else {
		mysql_free_result($rs);
	}
	mysql_close($db);			//关闭数据库连接
	return FALSE;
}
?>

