<?php
	$db=mysql_pconnect(get_cfg_var("SIPSERVER"),get_cfg_var("SIPUSER"),get_cfg_var("SIPPWD"));
	mysql_select_db(get_cfg_var("SIPDB"),$db);
	$n=0;
	$timestr=strftime("%Y-%m-%d %H:%M:%S");
	$bPass=FALSE;
	$loginname=trim($_REQUEST["loginname"]);
	$password=trim($_REQUEST["password"]);
	$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 ($loginname!="" && $password!="") {						//输入了用户ID
			$rs = mysql_query("select userid,password,type,createtime,cookiemask,gpid,ipaddr,timelength,datalength,daytime,daydata,mac 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"];
				$starttime=$row["createtime"];
				$cookiemask=$row["cookiemask"];
				$gpid = $row["gpid"];
				$allowip = $row["ipaddr"];
				$timelength = $row["timelength"]*3600;
				$datalength = $row["datalength"]*1024;
				$daytime = $row["daytime"]*3600;
				$daydata = $row["daydata"]*1024;
				$mac = $row["mac"];
				mysql_free_result($rs);
				if (is_null($cookiemask)) {
					$cookiemask="1234567890";
				}
				if (is_null($allowip)) {
					$allowip="";
				}
				$maxonline=1;
				$bPass=FALSE;
				if ($password==$password1) {					//比较密码
					$bPass=TRUE;
				}
				if (!$bPass) {					//比较密码
					$n=2;			//密码不对
				}
				else {
					$onlineusers=0;
					$rs = mysql_query("select count(ipaddr) as allcount from login where userid='".$userid."'",$db);		//查找该用户ID是否已经登录过
					if ($row = mysql_fetch_array($rs)) {
						$onlineusers=$row["allcount"];
					}
					mysql_free_result($rs);
					if ($onlineusers<$maxonline) {		//还没有达到用户ID的同时最多在线数限制
						if ($allowip=="") {		//用户没有登录IP地址限制
							$allowip=$userIP;
						}
						if ($allowip==$userIP) {		//客户机登录IP地址就是设定用户使用IP地址
							$remaintime=0;
							$remaindata=0;
							$bPass=FALSE;
							if ($timelength<1 && $datalength<1) {			//无时间和流量限制
								$bPass=TRUE;
							}
							else {							//每月有时间限制，需要检查当月的时间是否已经用完
								$m=DateDiff("m",strtotime($starttime),time());
								$str1="";
								$str2="";
								$tmpday1 = getdate();
								$tmpday2 = getdate(strtotime($starttime));
								if ( $tmpday1["mday"]>=$tmpday2["mday"] ) {		//计算出当月所在的起止时间段
									$tmptime1=strtotime("+".strval($m)." month",strtotime($starttime));
									$tmptime2=strtotime("+".strval($m+1)." month",strtotime($starttime));
								}
								else {
									$tmptime1=strtotime("+".strval($m-1)." month",strtotime($starttime));
									$tmptime2=strtotime("+".strval($m)." month",strtotime($starttime));
								}				//计算出当月所在的起止时间段
								$str1=strftime("%Y-%m-%d %H:%M:%S",$tmptime1);
								$str2=strftime("%Y-%m-%d %H:%M:%S",$tmptime2);
								//计算出当前时刻所在月度时间范围内的已上网时间和流量
								$alltime=0;
								$alldata=0;
								$rs = mysql_query("select sum(usetime) as alltime,sum(datalength) as alldata from history where userid='".$userid."' and starttime>='".$str1."' and starttime<='".$str2."'",$db);
								if ($row = mysql_fetch_array($rs)) {
									$alltime=$row["alltime"];
									$alldata=$row["alldata"];
									if ($timelength>0) {
										if ($alltime>=$timelength) {		//已经超过当月使用小时数的限制
											$n=3;							//本月上网时间已经超过使用小时数的限制
										}
										else {
											$bPass=TRUE;
											$remaintime=$timelength-$alltime;		//本月剩下时间
										}
									}
									else $bPass=TRUE;
									if ($bPass) {
										$bPass=FALSE;
										if ($datalength>0) {
											if ($alldata>=$datalength) {		//已经超过当月使用流量数的限制
												$n=5;							//本月上网时间已经超过使用流量数的限制
											}
											else {
												$bPass=TRUE;
												$remaindata=$datalength-$alldata;		//本月剩下流量
											}
										}
										else $bPass=TRUE;
									}
								}
								else {			//当月还完全没有上过网
									$bPass=TRUE;
									$remaintime=$timelength;
									$remaindata=$datalength;
								}
								mysql_free_result($rs);
								if ($bPass) {
									if ($remaintime>DateDiff("s",time(),strtotime($str2))) {		//本月剩下时间超过现在到本月结束的时间间隔
										$remaintime=DateDiff("s",time(),strtotime($str2));		//剩下时间就取较小者
									}
								}
							}
							if ($bPass && ($daytime>0 || $daydata>0) ) {	//需要每天限制
								$str1=strftime("%Y-%m-%d 00:00:00");
								$str2=strftime("%Y-%m-%d 23:59:59");
								$alltime=0;
								$alldata=0;
								$rs = mysql_query("select sum(usetime) as alltime,sum(datalength) as alldata from history where userid='".$userid."' and starttime>='".$str1."' and starttime<='".str2."'",$db);
								if ($row = mysql_fetch_array($rs)) {
									$alltime=$row[0];
									$alldata=$row[1];
								}
								mysql_free_result($rs);
								if ($daytime>0) {		//要限制每天的上网时间
									$bPass=FALSE;
									if ($alltime>=$daytime) {
										$n=11;	//达到每天限制
									}
									else {
										$remaintime1=$daytime-$alltime;
										if ($timelength>0) {	//有每月限制，取较小的一个
											if ($remaintime1<$remaintime) {
												$remaintime=$remaintime1;
											}
										}
										else {
											$remaintime=$remaintime1;
										}
										if ($remaintime>DateDiff("s",time(),strtotime($str2))) {		//本天剩下时间，最多只能到当天为止
											$remaintime=DateDiff("s",time(),strtotime($str2));		//剩下时间再次取较小者
										}
										if ($remaintime>0) {
											$bPass=TRUE;
										}
										else {
											$n=11;	//达到每天限制
										}
									}
								}
								if ($bPass && $daydata>0) {
									if ($alldata>=$daydata) {
										$bPass=FALSE;
										$n=12;	//达到每天限制
									}
									else {
										$remaindata1=$daydata-$alldata;
										if ($datalength>0) {
											if ($remaindata1<$remaindata) {
												$remaindata=$remaindata1;
											}
										} else {
											$remaindata=$remaindata1;
										}
									}
								}
							}
						}
						else {
							$bPass=FALSE;
							$n=9;			//非法的客户机IP地址
						}
						if ($bPass) {
							//还需要判断用户每天允许上网的时间范围
							$w=intval(strftime("%w"));
							if ($w==0) $w=7;
							$rs = mysql_query("select starttime,endtime from allowtimelist where userid='".$userid."' and (weeknumber=0 or weeknumber=".strval($w).") order by starttime",$db);
							if ($row = mysql_fetch_array($rs)) {		//需要判断是否在每天允许上网的时间范围内
								$bPass=FALSE;
								$datestr=strftime("%Y-%m-%d");
								while ($row) {
									$starttime=$datestr." ".$row["starttime"].":00";
									$endtime=$datestr." ".$row["endtime"].":00";
									if ( DateDiff("s",time(),strtotime($starttime))<=0 and DateDiff("s",time(),strtotime($endtime))>0 ) {		//登录时间大于开始时间，小于结束时间，落在一个允许的时间范围内
										$remaintime=DateDiff("s",time(),strtotime($endtime));	//本次允许的上网时间只持续到该时间范围段结束
										$bPass=TRUE;
										break;
									}
									$row = mysql_fetch_array($rs);
								}
								mysql_free_result($rs);
							}
							else {			//检查其所属组别是否存在每天上网时间段限制
								mysql_free_result($rs);
								if ($gpid>0) {		//存在组别
									$rs = mysql_query("select starttime,endtime from allowtimelist where userid='gp_".strval($gpid)."' and (weeknumber=0 or weeknumber=".strval($w).") order by starttime",$db);
									if ($row = mysql_fetch_array($rs)) {		//组别需要判断是否在每天允许上网的时间范围内
										$bPass=FALSE;
										$datestr=strftime("%Y-%m-%d");
										while ($row) {
											$starttime=$datestr." ".$row["starttime"].":00";
											$endtime=$datestr." ".$row["endtime"].":00";
											if ( DateDiff("s",time(),strtotime($starttime))<=0 and DateDiff("s",time(),strtotime($endtime))>0 ) {		//登录时间大于开始时间，小于结束时间，落在一个允许的时间范围内
												$remaintime=DateDiff("s",time(),strtotime($endtime));	//本次允许的上网时间只持续到该时间范围段结束
												$bPass=TRUE;
												break;
											}
											$row = mysql_fetch_array($rs);
										}
									}
									mysql_free_result($rs);
								}
							}
							if ($bPass) {
								//向登录表中插入当前用户上网新记录
								mysql_query( "insert into login(ipaddr,userid,type,remaintime,remaindata,logintime,maskword,mac) values('".$userIP."','".$userid."','".$usertype."',".strval($remaintime).",".strval($remaindata).",'".$timestr."','n','".$mac."')",$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;
								$n=4;				//登录成功
							}
							else {
								$n=8;				//不在每天允许上网的时间登录
							}
						}
					}
					else {
						$n=6;					//已经达到最多在线数限制
					}
				}
			}
		}
		else {
			$n=10;				//没有输入用户ID
		}
	}
	else {
		$_SESSION["userid"]=$row["userid"];
		mysql_free_result($rs);
		$n=7;					//已经登录
	}
	mysql_close($db);
	if ($n==4||$n==7) {		//登录成功，转到对外主页
		$_SESSION["StartTime"]=$timestr;
		ob_clean();
		header("Location: logout.php");
		exit;
	}
?>


</html>

<html>

<head>
<title>User Login</title>

<script language="javascript">
document.oncontextmenu=mymenu;

function mymenu()
{
	window.event.returnValue=false;
}

function myload() 
{
<?php
	//登录未成功，显示原因
	if ($n==1) {
		echo("alert(".Chr(34)."There don't exist this UserID!".Chr(34).");");
	}
	elseif ($n==2) {
		echo("alert(".chr(34)."Password is incorrect!".chr(34).");");
	}
	elseif ($n==3) {
		echo("alert(".chr(34)."User's time  is over in this month!".chr(34).");");
	}
	elseif ($n==5) {
		echo("alert(".chr(34)."User's flow  is over in this month!".chr(34).");");
	}
	elseif ($n==6) {
		echo("alert(".chr(34)."UserID is used by another!\\r\\nThere can exist only one login at one time for one UserID!".chr(34).");");
	}
	elseif ($n==8) {
		echo("alert(".chr(34)."Forbid to be on line at current time!".chr(34).");");
	}
	elseif ($n==9) {
		echo("alert(".chr(34)."Client computer ip address is wrong!".chr(34).");");
	}
	elseif ($n==10) {
		//echo("alert(".chr(34)."You must input the userid and password!".chr(34).");");
	}
	elseif ($n==11) {
		echo("alert(".chr(34)."User's time  is over in this day!".chr(34).");");
	}
	elseif ($n==12) {
		echo("alert(".chr(34)."User's flow  is over in this day!".chr(34).");");
	}
	elseif ($n==13) {
		echo("alert(".chr(34)."You should to check-out!".chr(34).");");
	}
	else {
		echo("authentication is not successful!");
	}
?>
}
</script>

</head>

<body background="../bkg.bmp" onload="javascript:myload();">

<p align="center"><font size="5"><b>User Login</b></font></p>
<hr color="#999966">
<p></p>
<div align="center">
  <center>
  <form name="form1" method="POST" action="login.php">
  <table border="1" width="342" height="146" bordercolor="#008080" cellspacing="0" cellpadding="0">
    <tr>
      <td width="100" align="right" height="44">User ID</td>
      <td width="228" align="center" height="44">
          <input type="text" name="loginname" size="20">
        </td>
    </tr>
    <tr>
      <td width="100" align="right" height="44">Password</td>
      <td width="228" align="center" height="44">
          <input type="password" name="password" size="20">
        </td>
    </tr>
    <tr>
      <td colspan="2" width="334" align="center" height="52"><input type="submit" value="Login" name="B1"></td>
    </tr>
  </table>
  </form>
  </center>
</div>
<p></p>
<hr>
<p align="center">SIPMonitor System</p>

</body>

</html>

<?php
function DateDiff($opertype,$starttime,$endtime)
{
	if ($starttime>=$endtime) return 0;	//starttime在endtime之后，返回0
	$n=0;
	if ($opertype=="d") {
		if ( strftime("%Y-%m-%d",$starttime)==strftime("%Y-%m-%d",$endtime) ) return 0;	//同一天
		while (TRUE) {
			$n++;
			if ( strftime("%Y-%m-%d",strtotime("+".strval($n)." day",$starttime))==strftime("%Y-%m-%d",$endtime) ) {
				//年月日部分已经相同
				break;
			}
		}
	}
	elseif ($opertype=="m") {
		if ( strftime("%Y-%m",$starttime)==strftime("%Y-%m",$endtime) ) return 0;	//同一月
		while (TRUE) {
			$n++;
			if ( strftime("%Y-%m",strtotime("+".strval($n)." month",$starttime))==strftime("%Y-%m",$endtime) ) {
				//年月部分已经相同
				break;
			}
		}
	}
	elseif ($opertype=="yyyy") {
		if ( strftime("%Y",$starttime)==strftime("%Y",$endtime) ) return 0;	//同一年
		while (TRUE) {
			$n++;
			if ( strftime("%Y",strtotime("+".strval($n)." year",$starttime))==strftime("%Y",$endtime) ) {
				//年部分已经相同
				break;
			}
		}
	}
	elseif ($opertype=="s") {
		$n=$endtime-$starttime;
	}
	else {
		$n=0;
	}
	return $n;
}
?>
