<?php
class login
{
	var $cache_user = false;
	function login(){$this->__construct();}
	function __construct(){
		global $_SET;
		$this->cache_user = intval($_SET['cache_user']) ? true : false;
	}

	function check($username)
	{
		$username = trim($username);
		if (strlen($username) < 2 || strlen($username) > 20){
			return array('status'=>417, 'message'=>'用户名程度必须在2-20之间');
		}
		$badwords = array("\\", '&', ' ', '　', "'", '"', '/', '*', ',', '<', '>', "\r", "\t", "\n", '#', "\$", "%");
		foreach($badwords as $value){
			if (strpos($username, $value) !== false){
				return array('status'=>417, 'message'=>'用户名中不得包含非法字符');
			}
		}
		return array('status' => 200);
	}

	function checkOnly($username){
		$sql = "select count(*) as num from ".TABLEPRE."user where username='$username' limit 1";
		return qdb::queryAlone($sql);
	}

	function checkEmail($email){
		$sql = "select count(*) as num from ".TABLEPRE."user where email='{$email}' and email_verify = 1 limit 1";
		return qdb::queryAlone($sql);
	}

	function checkIp(){
		$ip = qbase::get_ip();
		$sql = "select max(regtime) from ".TABLEPRE."user where regip='{$ip}' limit 1";
		return intval(qdb::queryAlone($sql));
	}

	function checkPassword($username, $password){
		$sql = "select uid from ".TABLEPRE."user where username='{$username}' and password = '{$password}' limit 1";
		return qdb::queryAlone($sql);
	}

	function loginAc( $username, $password, $cookietime = 86400, $encode = 0){
		global $_SET;
		$uc_user = U_C ? uc_user_login($username, $password) : array(1);
		if($uc_user[0] > 0){
			if(!$enode) $password = md5($password);
			$checkInfo = $this->check($username);
			if( $checkInfo['status'] != 200) return $checkInfo;
			$uid = $this->checkPassword( $username, $password);
			if (empty($uid)) return array('status'=>417, 'message'=>'用户不存在或者密码不正确!');
			$info = qdb::queryFirst("select u.*, e.* from ".TABLEPRE."user as u left join ".TABLEPRE."user_extend as e on u.uid = e.uid where u.uid = '{$uid}' ");
			if($info['unallowed'] == 1) return array('status'=>417, 'message'=>'你已经被管理员禁止，有疑问联系管理员');
			if($_SET['mail_verify'] && $info['email_verify'] == 0) return array('status'=>302, 'message'=>"user.php?ac=mail_verify&uid={$uid}&session={$info['session']}&auto=1");
			if($info['gid'] == 1) return array('status'=>302, 'message'=>"user.php?ac=user_verify&uid={$uid}&session={$info['session']}");

			$ip = qbase::get_ip();
			$session = substr(md5(qbase::random(6) . $ip . $uid), 0, 12);

			qdb::query("update ".TABLEPRE."user set loginip='{$ip}',logintime='{$_SERVER['REQUEST_TIME']}',logintimes=logintimes+1, session = '{$session}' where uid='{$uid}' limit 1");
			$user_info =array(
				'u' => $uid,
				's'=> $session
			);
			$user_info['hash'] = substr(md5(qbase::array2string($user_info) . $_SET['passport_key']), 0, 12);
			$user_info_string = qbase::authcode(qbase::array2string($user_info), "ENCODE");
			qbase::phpsetcookie("qmecms_auth", $user_info_string, $cookietime);
			qbase::phpsetcookie("qmecms_name", $username, $cookietime);
			$this->delete_user_cache($uid);
			return array('status'=>200, 'uc'=>U_C ? uc_user_synlogin($uc_user[0]) : '');
		}elseif($uc_user[0] == -1) {
			return array('status'=>417, 'message'=>'用户不存在,或者被删除!');
		} elseif($uc_user[0] == -2) {
			return array('status'=>417, 'message'=>'密码不正确!');
		} else {
			return array('status'=>417, 'message'=>'系统似乎出了点问题，请重试!');
		}
	}

	function checkSession(){
		global $_SET;
		$user_info_temp = $user_info = array();
		if(empty($_COOKIE['qmecms_auth'])) return $user_info;
		parse_str(qbase::authcode(trim($_COOKIE['qmecms_auth']), "DECODE"), $user_info_temp);
		if(isset($user_info_temp['u']) && isset($user_info_temp['s']) && isset($user_info_temp['hash'])){
			$verify_hash = $user_info_temp['hash'];
			unset($user_info_temp['hash']);
			if($verify_hash != substr(md5(qbase::array2string($user_info_temp) . $_SET['passport_key']), 0, 12)){
				$user_info['uid'] = 0;
				$user_info['username'] = '';
				$this->loginOut();
			}else{
				$user_info_temp['uid'] = intval($user_info_temp['u']);
				$user_info_temp['session'] = addslashes($user_info_temp['s']);
				$user_info = $this->get_user_info($user_info_temp['uid'], $user_info_temp['session']);
				if(empty($user_info)){
					$user_info['uid'] = 0;
					$user_info['username'] = '';
					$this->loginOut($user_info_temp['uid'] );
				}else{
					if($user_info['unallowed'] == 1){
						$this->loginOut($user_info_temp['uid'] );
						qbase::showmsg("你已经被管理员禁止登录");
					}else if(($user_info['email_verify'] == 0 && $_SET['mail_verify'] == 1)){
						$this->loginOut($user_info_temp['uid'] );
						qbase::showmsg("您的Email需要验证后才能登录", $_SET['skin'], "user.php?ac=mail_verify&uid={$user_info['uid']}&session={$user_info['session']}");
					}else if($user_info['gid'] == 1){
						$this->loginOut($user_info_temp['uid'] );
						qbase::showmsg("您需要在管理员认证后才能登录", $_SET['skin'], "user.php?ac=user_verify&uid={$user_info['uid']}&session={$user_info['session']}");
					}
				}
			}
		}else{
			$user_info['uid'] = 0;
			$user_info['username'] = '';
		}
		return $user_info;
	}
	function get_user_info($uid, $session = ''){
		$key = $this->_get_key($uid);
		if($this->cache_user == false || false === ($user = cache::get($key))){
			$user = qdb::queryFirst("select u.*, e.* from ".TABLEPRE."user as u left join ".TABLEPRE."user_extend as e on u.uid = e.uid where u.uid = '{$uid}' ");
			if($this->cache_user == true && !empty($user)) cache::set($key, $user, 3600 * 24);
		}
		if(empty($user) || ($session && $user['session'] != $session)) return array();
		return $user;
	}

	function loginOut($uid = 0){
		$uid = intval($uid);
		if($uid > 0) $this->delete_user_cache($uid);
		qbase::phpsetcookie('qmecms_auth', '', 1);
	}
	
	function delete_user_cache($uid){
		cache::delete($this->_get_key($uid));
	}
	
	function _get_key($uid){
		return 'uid_' . $uid; 
	}
}
?>