<?php
require_once(dirname(__FILE__)."/config.php");

$pp_hash = $cfg_cookie_encode;
if(!$cfg_pp_isopen || !$cfg_pp_regurl){
	ShowMsg('系统没有开启通行证功能！','-1');exit();
}
if(md5($action.$userdb.$forward.$pp_hash) != $verify){
	ShowMsg('安全检验失败，请检查通行证设置是否正确！','-1');exit();
}

parse_str(StrCode($userdb,'DECODE'),$userdb);
if (!$forward || strpos($forward,'index_do.php') !== false) {
	$forward = $cfg_indexurl;
}
$timestamp = time();
$loginip = GetIP();
if($action=='login'){
	foreach($userdb as $key=>$val){
		$userdb[$key] = addslashes($val);
	}
	if(!$userdb['time'] || !$userdb['username'] || !$userdb['password']){
		ShowMsg('数据检验失败，缺少参数！lack_data');exit();
	}
	if($timestamp > $userdb['time']+3600){
		ShowMsg('数据检验失败，无效数据！expired_error');exit();
	}

	if(!TestStringSafe($userdb['username']) || !TestStringSafe($userdb['password'])){
		ShowMsg("用户名或密码不合法！","-1",0,2000);exit();
	}
	$dsql = new DedeSql(false);
	$row = $dsql->GetOne("SELECT ID,pwd,uname FROM #@__member WHERE userid='$userdb[username]' ");
	if(!is_array($row)){
		$inQuery = "INSERT INTO `#@__member` (`userid` , `pwd` , `type` , `uname` , `membertype` , `uptime` , `exptime` ,`money` , `email` , `jointime` , `joinip` , `logintime` , `loginip` ,`c1` , `c2` , `c3` , `matt` , `guestbook` , `spaceshow` , `pageshow` , `spacestyle` ,`spacename` , `spaceimage` , `news` , `mybb` , `listnum` , `scores` ) VALUES ('$userdb[username]', '$userdb[password]', '0', '$userdb[username]', '10', '0', '0','0', '', '$timestamp', '$loginip', '$timestamp', '$loginip','0', '0', '0', '0', '0', '0', '0', '','', '', '', '', '20', '1000');";
		$dsql->ExecuteNoneQuery($inQuery);
		$ID = $dsql->GetLastID();
		if($ID){
			$inQuery = "INSERT INTO `#@__member_perinfo` (`id`, `uname` , `sex` , `birthday` , `weight` ,`height` , `job` , `province` , `city` , `myinfo` ,`tel` , `oicq` , `homepage` , `showaddr` ,`address` , `fullinfo`) VALUES ('$ID','$userdb[username]', '', '0000-00-00', '0','0', '0','0', '0', '0' , '0' , '0' , '0' ,'0','0','');";
			$dsql->ExecuteNoneQuery($inQuery);
		}
	}else{
		$ID = $row['ID'];
		$sqladd = '';
		if ($row['userid'] != $userdb['username']){
			$sqladd .= " userid='$userdb[username]',";
		}
		if ($row['pwd'] != $userdb['password']){
			$sqladd .= " pwd='$userdb[password]', ";
		}
		$dsql->ExecuteNoneQuery("UPDATE #@__member SET $sqladd logintime='$timestamp',loginip='$loginip' WHERE ID='$ID' ");
	}
	$dsql->Close();
	$cfg_ml->PutLoginInfo($ID);
	$cfg_ml->FushCache();
	header("Location:$forward");exit();
} elseif($action=='quit'){
	$cfg_ml->ExitCookie();
	header("Location:$forward");exit();
}

function StrCode($string,$action='ENCODE'){
	$action != 'ENCODE' && $string = base64_decode($string);
	$code = '';
	$key  = substr(md5($_SERVER['HTTP_USER_AGENT'].$GLOBALS['pp_hash']),8,18);
	$keylen = strlen($key);
	$strlen = strlen($string);
	for ($i=0;$i<$strlen;$i++) {
		$k		= $i % $keylen;
		$code  .= $string[$i] ^ $key[$k];
	}
	return ($action!='DECODE' ? base64_encode($code) : $code);
}
?>