<?php
define('THIS_SCRIPT', 'login');
require_once 'global.php';

$lang=load_lang($lang, THIS_SCRIPT);
header("content-Type: text/html; charset=".$charset);

file_exists(CACHE_PATH.'forum_setting.php') && require_once(CACHE_PATH.'forum_setting.php');
$fsetting = $_DCACHE['settings'];
unset($_DCACHE['settings']);

if ( $action == '' ){
	if ( $islogin == 1 ){
		header("Location:index.php");
		exit;
	}else{
		show_loginform();
	}
}elseif( $action == 'logout'){
	//$_SESSION['flag'] = null;
	set_cookie('backend_flag', '');
	if ( $islogin == 1 ){
		if (!is_numeric($logintimeout)) {
			$logintimeout = dv_gmtimestamp($logintimeout);
			if (false === $logintimeout) {
				$logintimeout = time() + date('Z') - getUserTimeZoneOffset() - $systimeout;
			}
		}
		$db->query("Update {$dv}admin Set lastlogin='$logintimeout',mysession='' Where username='$sysusername'");
	}
	set_cookie("sysusername","",-86400 * 365);
	set_cookie("syspassword","",-86400 * 365);
	//cookie_destory();	//	销毁所有的 COOKIE
	header("Location:login.php");
	exit;
}else{
	//$_SESSION['flag'] = null;
	set_cookie('backend_flag', '');
	$psysusername=get_cookie("psysusername");
	if ( strlen($psysusername) == 0 ){
		if ( $rusername == '' || $rpassword == '' ){
			show_loginform($lang['err_str_3']);
			exit;
		}else{
			if($fsetting['logingetcode']) {
				$query=$db->query("Select sessioncode,username,errcount,lastlogin From {$dv}admin Order By lastlogin",array('pageSize'=>1));
				$info=$db->fetch_array($query);
				if ( $info['sessioncode'] == '' ){
					show_loginform($lang['err_str_5']);
					exit;
				}
			}
		}
	}else{
		$query=$db->query("Select sessioncode,username,errcount,lastlogin From {$dv}admin Where adduser='{$psysusername}'");
		$info=$db->fetch_array($query);
	}
	if (false === $info) {	//	后台用户名或密码错误
		onBackendLoginFailure($lastloginip, $membername, false);
		show_loginform($lang['err_str_2']);
		exit;
	}
	$mylastlogins = time() - $info['lastlogin'];
	if ( ($mylastlogins > $systimeout) && $info['errcount'] > 5 ){
		$db->query("Update {$dv}admin Set errcount=0 Where username='".$db->escape_string($info['username'])."'");
		$info['errcount'] = 0;
	}
	if ( $info['errcount'] > 5 ){
		show_loginform($lang['err_str_9']);
		exit;
	}
	if ( $username == '' || $password == '' ){
		show_loginform($lang['err_str_4']);
		exit;
	}
	if ($fsetting['logingetcode'] && ($verifycode == '' || $verifycode != $info['sessioncode']) ){
		show_loginform($lang['err_str_1']);
	}else{
		$loginuser = false;
		if( $query=$db->query("select username,password,id,flag,adduser from {$dv}admin where username='{$username}'") ){
			$loginuser = $db->fetch_array($query);
		}
		if ($loginuser===false){
			onBackendLoginFailure($lastloginip, $db->escape_string($info['username']), false);
			show_loginform($lang['err_str_2']);
		}else{
			$password=md5($password);
			if ( $password == $loginuser['password'] ||substr($password,8,16)== $loginuser['password']){
				if ( $myuserid == 0 ){
					$query=$db->query("Select userid,username,userpassword,usergroupid,truepassword From {$dv}user Where username='$rusername'");
				}else{
					$query=$db->query("Select userid,username,userpassword,usergroupid,truepassword From {$dv}user Where username='$loginuser[adduser]'");
				}
				if ( $headuser = $db->fetch_array($query) ){
					$rpassword=md5($rpassword);
					if ( (($rpassword== $headuser['userpassword']||substr($rpassword,8,16)== $headuser['userpassword']) && $myuserid == 0) || ($myuserid > 0 && strtolower($membername) == strtolower($loginuser['adduser'])) ){
						//判断是否有自定义进入后台权限
						$query=$db->query("Select uc_setting From {$dv}useraccess Where uc_userid=$headuser[userid] And uc_boardid=0");
						if ( $guser = $db->fetch_array($query) ){
							$sysgroupsetting = $guser['uc_setting'];
						}
						if ( $sysgroupsetting == '' ){
							$query=$db->query("Select groupsetting From {$dv}usergroups Where usergroupid=$headuser[usergroupid]");
							if ( $guser = $db->fetch_array($query) ){
								$sysgroupsetting = $guser['groupsetting'];
							}
						}
						if ( $sysgroupsetting == '' ){
							//$db->query("Update {$dv}admin Set lastlogin='".time()."',errcount=errcount+1,lastloginip='{$lastloginip}' Where username='{$loginuser['username']}'");
							onBackendLoginFailure($lastloginip, $db->escape_string($loginuser['username']), false);
							show_loginform($lang['err_str_7']);
							exit;
						}else{
							$sysgroupsetting = explode(',',$sysgroupsetting);
						}
						if ( $sysgroupsetting[70] == 0 ){
							//$db->query("Update {$dv}admin Set lastlogin='".time()."',errcount=errcount+1,lastloginip='{$lastloginip}' Where username='{$loginuser['username']}'");
							onBackendLoginFailure($lastloginip, $db->escape_string($loginuser['username']), false);
							show_loginform($lang['err_str_8']);
							exit;
						}
					}else{
						//$db->query("Update {$dv}admin Set lastlogin='".time()."',errcount=errcount+1,lastloginip='{$lastloginip}' Where username='{$loginuser['username']}'");
						onBackendLoginFailure($lastloginip, $db->escape_string($loginuser['username']), false);
						show_loginform($lang['err_str_6']);
						exit;
					}
				}else{
					//$db->query("Update {$dv}admin Set lastlogin='".time()."',errcount=errcount+1,lastloginip='{$lastloginip}' Where username='{$loginuser['username']}'");
					onBackendLoginFailure($lastloginip, $db->escape_string($loginuser['username']), false);
					show_loginform($lang['err_str_6']);
					exit;
				}

				$_SESSION['MY_SESSION'] = $mysession = Createpass(16);
				set_cookie("sysusername",$loginuser['username'],$systimeout);
				//验证信息和用户IP加密，当用户IP变动后需要重新登录后台
				set_cookie("syspassword",md5($mysession.$lastloginip),$systimeout);
				$db->query("update {$dv}admin set lastlogin='".time()."',lastloginip='$lastloginip',mysession='$mysession',sessioncode='',errcount=0 where id={$loginuser['id']}");
				//$_SESSION['flag'] = $loginuser['flag'];
				set_cookie('backend_flag', $sysinfo['flag']);
				//head();
				//show_msg($lang['page_title'],$lang['suc_str'],1,'','','index.php',$lang['button']);
				//footer();
				header('location:index.php');
			}else{
				//$db->query("Update {$dv}admin Set lastlogin='".time()."',errcount=errcount+1,lastloginip='{$lastloginip}' Where username='{$loginuser['username']}'");
				onBackendLoginFailure($lastloginip, $db->escape_string($loginuser['username']), false);
				show_loginform($lang['err_str_2']);
			}
		}
	}
}

function onBackendLoginFailure($loginip, $loginusername, $addquotes = true)
{
	global $db, $dv;
	if (true === $addquotes) {
		$loginip = $db->escape_string($loginip);
		$loginusername = $db->escape_string($loginusername);
	}
	$db->query("UPDATE {$dv}admin SET lastlogin=".time().", errcount=errcount+1, lastloginip='".$loginip."' WHERE username='".$loginusername."'");
}//end function onBackendLoginFailure

function show_loginform($err_msg=''){
	global $forum_type,$charset,$bodystyle,$lang,$db,$dv,$db_obstart,$myuserid,$membername,$fsetting;
	require_once printout(THIS_SCRIPT);
	$db->close();
	$output = str_replace(array('<!--<!---->','<!---->'),array('',''),ob_get_contents());
	ob_end_clean();
	$db_obstart == 1 ? ob_start('ob_gzhandler') : ob_start();
	echo $output;
	flush;
	exit;
}
?>