<?php
// 会员模型
class MemberModel extends Model {
	public $L = array();
	public $C = array();
	protected function _initialize() {
		$this -> L = L('');
		$this -> C = C('', 0, 'member');
		$configFile = JXCMS_ROOT . 'uc_client/config.php';
		if ($this -> C['enablepassport'] && $this -> C['passportfile'] == 'uc' && file_exists($configFile)) {
			include_once $configFile;
		}
	}
	// 获取用户权限ID
	public function getRole($userid) {
		$rows = $this -> field('roleid') -> table('member_role') -> where("userid=$userid") -> select();
		$role = array();
		if (is_array($rows)) {
			$tmp = Cache :: read('role', '', 0, 'Data');
			foreach($rows as $row) $role[] = $tmp[$row['roleid']];
		}
		return $role;
	}
	public function login($username, $password) {
		if (!$this -> checkCaptcha($this -> C['captcha_login'])) {
			return false;
		}
		$username = trim($username);
		if (!$this -> checkUsername($username, 0)) {
			return false;
		}
		$password = trim($password);
		$field = array('userid', 'username', 'password', 'email', 'lastdate', 'groupid');
		$where = array('username' => $username);
		$r = $this -> field($field) -> where($where) -> find();
		$synLogin = true; //同步登录代码初始化
		$ucLogin = false;
		if ($this -> C['enablepassport'] && $this -> C['passportfile'] == 'uc') {
			include_once JXCMS_ROOT . 'uc_client/client.php';
			// 通过接口判断登录帐号的正确性，返回值为数组
			list($uid, $username, $password, $email) = uc_user_login($username, $password);
			if ($uid) {
				if (!$r) {
					$r = array('userid' => $uid, 'username' => $username, 'password' => md5($password), 'email' => $email, 'groupid' => 6, 'regdate' => TIME, 'regip' => IP, 'lastdate' => TIME);
					$this -> create($r) -> add();
				}
				// 生成同步登录的代码
				$synLogin = uc_user_synlogin($uid);
				$ucLogin = true;
			} elseif ($uid == -1) {
				$this -> error = $this -> L['USERNAME_IS_NOT_EXIST'];
				return false;
			} elseif ($uid == -2) {
				$this -> error = $this -> L['PASSWORD_ERROR'];
				return false;
			} else {
				$this -> error = $this -> L['unknow'];
				return false;
			}
		}
		if ($r) {
			if ($r['password'] == md5($password)) {
				$this -> setLogin($r, R('cookietime'));
				return $synLogin;
			} elseif ($ucLogin) {
				$this -> setFields(array('password' => md5($password)), 'userid', $r['userid']);
				$this -> setLogin($r, R('cookietime'));
				return $synLogin;
			} else {
				$this -> error = $this -> L['PASSWORD_ERROR'];
				return false;
			}
		} else $this -> error = $this -> L['USERNAME_IS_NOT_EXIST'];
		return false;
	}
	public function reg() {
		if (!$this -> checkCaptcha($this -> C['captcha_reg'])) {
			return false;
		}
		$info = R('info', 'post');
		$info['username'] = trim($info['username']);
		if (!($this -> checkUsername($info['username']) && $this -> checkEmail($info['email']) && $this -> checkPassword($info['password']))) {
			return false;
		}
		defined('IN_ADMIN') or $info['groupid'] = $this -> C['ischeck']?5:6;
		if (isset($info['userid'])) unset($info['userid']);
		if ($this -> C['enablepassport'] && $this -> C['passportfile'] == 'uc') {
			include_once JXCMS_ROOT . 'uc_client/client.php';
			$uid = uc_user_register($info['username'], $info['password'], $info['email']);
			if ($uid) {
				$info['userid'] = $uid; //与uc ID 保持一致
			} else {
				if ($uid == -1) {
					$this -> error = $this -> L['USERNAME_ILLEGAL'];
					return false;
				} elseif ($uid == -2) {
					$this -> error = $this -> L['USERNAME_PROTECT'];
					return false;
				} elseif ($uid == -3) {
					$this -> error = $this -> L['USERNAME_DUPLICATE'];
					return false;
				} elseif ($uid == -4) {
					$this -> error = $this -> L['EMAIL_FORMAT_ERROR'];
					return false;
				} elseif ($uid == -5) {
					$this -> error = $this -> L['EMAIL_DOMAIN_ILLEGAL'];
					return false;
				} elseif ($uid == -6) {
					$this -> error = $this -> L['EMAIL_EXIST'];
					return false;
				} else {
					$this -> error = $this -> L['UNKNOW'];
					return false;
				}
			}
		}
		$info['regip'] = IP;
		$info['regdate'] = TIME;
		$info['password'] = md5($info['password']);
		return $this -> create($info) -> add();
	}
	public function edit() {
		$info = R('info', 'post');
		$info['userid'] = intval($info['userid']);
		if (!$info['userid']) {
			$this -> error = $this -> L['NOPARAM'];
			return false;
		}
		$data = $this -> find($info['userid']);
		if (empty($data)) {
			$this -> error = $this -> L['USER_IS_NOT_EXIST'];
			return false;
		}
		$info['userid'] == get_cookie('userid') or show_error($this -> L['NO_PERMISSION']);
		$info['birthday'] = R('birthyear') . '-' . R('birthmonth') . '-' . R('birthday');
		return $this -> create($info) -> update();
	}
	public function password() {
		if (!$this -> checkCaptcha($this -> C['captcha_password'])) {
			return false;
		}
		$info = R('info', 'post');
		$info['userid'] = intval($info['userid']);
		if (!$info['userid']) {
			$this -> error = $this -> L['NOPARAM'];
			return false;
		}
		$data = $this -> find($info['userid']);
		if (empty($data)) {
			$this -> error = $this -> L['USER_IS_NOT_EXIST'];
			return false;
		}
		$info['password'] = trim($info['password']);
		if ($info['password']) {
			if (!$this -> checkPassword($info['password'])) {
				return false;
			}
			if (!defined('IN_ADMIN')) {
				$pwdconfirm = trim(R('pwdconfirm'));
				if ($pwdconfirm != $info['password']) {
					$this -> error = $this -> L['PASSWORD_CONFIRM_ERROR'];
					return false;
				}
			}
			$newPassword = $info['password'];
			$info['password'] = md5($info['password']);
		} else {
			$newPassword = '';
			unset($info['password']);
		}
		if (defined('IN_ADMIN')) {
			$ignoreOldpw = 1;
			$oldPassword = '';
			$checkEmail = empty($info['email'])?0:1;
		} else {
			$info['userid'] == get_cookie('userid') or show_error($this -> L['NO_PERMISSION']);
			$ignoreOldpw = 0;
			$oldPassword = R('oldpassword');
			if ($data['password'] != md5($oldPassword)) {
				$this -> error = $this -> L['PASSWORD_OLD_ERROR'];
				return false;
			}
			$checkEmail = 1;
		}
		if ($checkEmail && !$this -> checkEmail($info['email'], 1, $info['userid'])) {
			return false;
		}
		if (empty($info['question'])) {
			$info['question'] = $data['question'];
			$info['answer'] = $data['answer'];
		}
		if ($this -> C['enablepassport'] && $this -> C['passportfile'] == 'uc') {
			include_once JXCMS_ROOT . 'uc_client/client.php';
			$ucResult = uc_user_edit($data['username'], $oldPassword, $newPassword, $info['email'], $ignoreOldpw, $info['question'], $info['answer']);
			if ($ucResult == -1) {
				$this -> error = $this -> L['PASSWORD_ERROR'];
				return false;
			} elseif ($ucResult == -4) {
				$this -> error = $this -> L['EMAIL_FORMAT_ERROR'];
				return false;
			} elseif ($ucResult == -5) {
				$this -> error = $this -> L['EMAIL_DOMAIN_ILLEGAL'];
				return false;
			} elseif ($ucResult == -6) {
				$this -> error = $this -> L['EMAIL_EXIST'];
				return false;
			}
		}
		$rs = $this -> create($info) -> update();
		$field = array('userid', 'username', 'password', 'email', 'lastdate', 'groupid');
		$r = $this -> field($field) -> find($info['userid']);
		$this -> setLogin($r);
		return $rs;
	}
	public function del($userid) {
		if (is_array($userid)) {
			foreach($userid as $k => $v) {
				$v = intval($v);
				if ($v != $this -> loginInfo['userid']) $userid[$k] = intval($v);
				else unset($userid[$k]);
			}
			$where = 'userid IN (' . implode(', ', $userid) . ')';
		} else {
			$userid = intval($userid);
			if ($userid != $this -> loginInfo['userid']) $where = "userid = $userid";
			else $userid = 0;
		}
		if (empty($userid)) return false;
		if ($this -> C['enablepassport'] && $this -> C['passportfile'] == 'uc') {
			include_once JXCMS_ROOT . 'uc_client/client.php';
			uc_user_delete($userid);
		}
		return $this -> where($where) -> delete();
	}
	/**
	 * 检查用户名
	 */
	public function checkUsername($username, $isExist = 1) {
		$banwords = explode(',', strtolower($this -> C['fbname']));
		$_username = strtolower($username);
		$len = strlen($_username);
		if ($len > $this -> C['regmaxname'] || $len < $this -> C['regminname']) {
			$this -> error = $this -> L['USERNAME_LENGTH_ERROR'];
			return false;
		}
		if (!preg_match("/^[\x{4e00}-\x{9fa5}a-z0-9_]+$/u", C('APP_CHARSET', 1) == 'utf-8'?$_username:iconv(C('APP_CHARSET', 1), 'utf-8', $_username))) {
			$this -> error = $this -> L['USERNAME_ILLEGAL'];
			return false;
		}
		if ($isExist) {
			if (is_array($banwords)) {
				foreach ($banwords as $value) {
					if (strpos($_username, $value) !== false) {
						$this -> error = $this -> L['USERNAME_PROTECT'];
						return false;
					}
				}
			}
			if ($this -> where("username=$username") -> count()) {
				$this -> error = $this -> L['USERNAME_DUPLICATE'];
				return false;
			} else {
				if ($this -> C['enablepassport'] && $this -> C['passportfile'] == 'uc') {
					include_once JXCMS_ROOT . 'uc_client/client.php';
					$ucresult = uc_user_checkname($username);
					if ($ucresult > 0) {
						return true;
					} elseif ($ucresult == -1) {
						$this -> error = $this -> L['USERNAME_ILLEGAL'];
						return false;
					} elseif ($ucresult == -2) {
						$this -> error = $this -> L['USERNAME_PROTECT'];
						return false;
					} elseif ($ucresult == -3) {
						$this -> error = $this -> L['USERNAME_DUPLICATE'];
						return false;
					}
				}
			}
		}
		return true;
	}
	private function checkCaptcha($isCheck = 0) {
		if ($isCheck && !defined('IN_ADMIN')) {
			$captcha = new Captcha();
			if (!$captcha -> check(trim($_POST['captcha']))) {
				$this -> error = $this -> L['CAPTCHA_ERROR'];
				return false;
			}
		}
		return true;
	}
	/**
	 * 检查邮箱
	 */
	public function checkEmail($email, $isExist = 1, $userid = 0) {
		if ($email == '') {
			$this -> error = $this -> L['EMAIL_EMPTY'];
			return false;
		}
		if (!preg_match('/^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i', $email)) {
			$this -> error = $this -> L['EMAIL_FORMAT_ERROR'];
			return false;
		}
		$userid or $userid = get_cookie('userid');
		if ($isExist) {
			$userid = intval($userid);
			$where = $userid?array("userid!=$userid", "email='$email'"):"email='$email'";
			if ($this -> where($where) -> find()) {
				$this -> error = $this -> L['EMAIL_EXIST'];
				return false;
			} else {
				if ($this -> C['enablepassport'] && $this -> C['passportfile'] == 'uc') {
					include_once JXCMS_ROOT . 'uc_client/client.php';
					$ucresult = uc_user_checkemail($email);
					if ($ucresult > 0) {
						return true;
					} elseif ($ucresult == -4) {
						$this -> error = $this -> L['email_format_error'];
						return false;
					} elseif ($ucresult == -5) {
						$this -> error = $this -> L['email_domain_illegal'];
						return false;
					} elseif ($ucresult == -6) {
						$this -> error = $this -> L['email_exist'];
						return false;
					}
				}
			}
		}
		return true;
	}
	public function checkPassword($password) {
		$fc = array ("\r", "\t", "\n", "'", "\"", "\\");
		if ($password == '') {
			$this -> error = $this -> L['PASSWORD_EMPTY'];
			return false;
		}
		if (strlen($password) < 6) {
			$this -> error = $this -> L['PASSWORD_FORMAT_ERROR'];
			return false;
		}
		foreach ($fc as $value) {
			if (strpos($password, $value) !== false) {
				$this -> error = $this -> L['PASSWORD_FORMAT_ERROR'];
				return false;
			}
		}
		return true;
	}
	public function isLogin() {
		$userid = get_cookie('userid');
		$username = get_cookie('username');
		if (empty($username) or empty($userid)) return false;
		$data = $this -> find($userid);
		$auth = get_cookie('auth');
		if ($username != $data['username'] or $auth != sha1($data['password'] . $username . $this -> C['sid'])) {
			$this -> setLogout();
			return false;
		}
		return true;
	}
	public function setLogin($userInfo, $cookieTime = 0) {
		$cookieTime or $cookieTime = 86400;
		set_cookie('userid', $userInfo['userid'], $cookieTime);
		set_cookie('username', $userInfo['username'], $cookieTime);
		set_cookie('auth', sha1($userInfo['password'] . $userInfo['username'] . $this -> C['sid']), $cookieTime);
		set_cookie('groupid', $userInfo['groupid'], $cookieTime);
		set_cookie('email', $userInfo['email'], $cookieTime);
		set_cookie('lastdate', $userInfo['lastdate'], $cookieTime);
		$info = array('userid' => $userInfo['userid'], 'lastip' => IP, 'lastdate' => TIME, 'logintimes' => 'logintimes+1');
		if (date('Y-m-d', $userInfo['lastdate']) != date('Y-m-d', TIME)) $info['point'] = 'point+10';
		return $this -> create($info) -> update();
	}
	public function logout() {
		$this -> setLogout();
		$synlogout = '';
		if ($this -> C['enablepassport'] && $this -> C['passportfile'] == 'uc') {
			include_once JXCMS_ROOT . 'uc_client/client.php';
			$synlogout = uc_user_synlogout();
		}
		return $synlogout;
	}
	public function setLogout() {
		set_cookie('userid', '', -1);
		set_cookie('username', '', -1);
		set_cookie('auth', '', -1);
		set_cookie('groupid', '', -1);
		set_cookie('email', '', -1);
		set_cookie('lastdate', '', -1);
	}
}
