<?php

class Member
{
	/**
	 * 数据引用
	 */
	var $pbdb;
	
	/**
	 * 用户信息
	 */
	var $customer;
	
	/**
	 * 用户ID
	 */
	var $uids = array();
	
	/**
	 * 操作类型
	 */
	var $action = NULL;
	
	/**
	 * 语言包
	 */
	var $lang = '';
	var $newuser = array();

	function __construct()
	{
		global $DB, $customer, $func_message;
		$this->pbdb = $DB;
		$this->customer = $customer;
		$this->lang = $func_message;
	}
	
	function Member()
	{
		$this->__construct();
	}
	function setUID($uid)
	{
		$this->uids = $this->ckuid($uid);
	}
	function setNewUser($newuser)
	{
		$this->newuser = $newuser;
	}
	function getNewUser()
	{
		return $this->newuser;
	}
	function ckuid($uids)
	{
		if (!is_array($uids)) (array)$uids;
		foreach ($uids as $k => $uid)
		{
			if ($uid <= 0)
			{
				unset($uids[$k]);
			}
			else
			{
				$uids[$k] = (int)$uid;
			}
		}
		if (!count($uids)) showMsg($this->lang['member_nouid']);
		return $uids;
	}
	function Action($action, $data = '')
	{
		global $func_message;
		$this->action = $action;
		switch ($this->action)
		{
			case 'add':
				$this->add($data);
				break;
			case 'del':
				$this->del();
				break;
			case 'mod':
				$this->mod($data);
				break;
			case 'check':
				$this->check($data);
				break;
			default:
				showMsg($this->lang['unknow_action']);
		}
	}

	/**
	 * 添加用户
	 * 
	 * @param Array $member array('username'=>'用户名', 'password'=>'密码', 'email'=>'电子邮件', 'groupid'=>'等级', 'ignore'=>'忽略用户名检查', 'exp'=>array())
	 */
	function add($member)
	{
		global $timestamp, $grouplevel, $pb_ucenable, $db_prefix, $_SUPERMANAGER, $_PBDEV, $Cache;

		require(PBDIGG_ROOT.'data/cache/cache_reg.php');
		@extract($_REGCONFIG);
		$username = $password = $email = $groupid = $ignore = $exp = $uc_login = '';
		$uc_uid = 0;
		@extract($member, EXTR_OVERWRITE);
		unset($_REGCONFIG, $member);
		if (!$username || !$password || !$email || !$groupid) showMsg($this->lang['member_field_halfbaked']);
		$name_length = strlen($username);
		if ($name_length < $reg_minname || $name_length > $reg_maxname)
		{
			showMsg($this->lang['username_length_error']);
		}
		$ck = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','%');
		foreach ($ck as $v)
		{
			if (strpos($username, $v) !== FALSE) showMsg($this->lang['username_fchar_exist']);
			if (strpos($password, $v) !== FALSE) showMsg($this->lang['password_fchar_exist']);
		}
		if ($reg_bannames && !$ignore && (strpos($reg_bannames, $username) !== FALSE))
		{
			showMsg($this->lang['username_banword_exist']);
		}
		if ($rpassword && ($password != $rpassword)) showMsg($this->lang['password_not_same']);
		if (strlen($password) < 6) showMsg($this->lang['password_less_six']);
		$md5password = md5($password);
		if (!preg_match('/^[A-Za-z0-9]+([._\-\+]*[A-Za-z0-9]+)*@([A-Za-z0-9]+[-A-Za-z0-9]*[A-Za-z0-9]+\.)+[A-Za-z0-9]+$/', $email)) showMsg($this->lang['email_format_error']);
		if (!array_key_exists($groupid, $grouplevel) || $groupid == '7')
		{
			$groupid = '-1';
		}
		if ($groupid == '1' || $groupid == '2')
		{
			if ($_SUPERMANAGER)
			{
				$adminid = $groupid;
			}
			else
			{
				$groupid = '-1';
				$adminid = 0;
			}
		}
		else
		{
			$adminid = 0;
		}
		$rs = $this->pbdb->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}members WHERE username = '".$username."' OR email = '".$email."'");
		if ($rs['num'])
		{
			showMsg($this->lang['username_registerd']);
		}
		if ($pb_ucenable)
		{
			$uc_uid = $message = '';
			$uc_uid = uc_user_register($username, $password, $email);
			switch ($uc_uid)
			{
				case -1:
					$message = 'username_error';
					break;
				case -2:
					$message = 'username_banword_exist';
					break;
				case -3:
					$message = 'username_registerd';
					break;
				case -4:
					$message = 'email_format_error';
					break;
				case -5:
					$message = 'email_noallowed';
					break;
				case -6:
					$message = 'email_exist';
					break;
			}
			$message && showMsg($this->lang[$message]);
			$uc_login =  uc_user_synlogin($uc_uid);
		}
		if ($exp && is_array($exp))
		{
			$i_field = $v_field = '';
			foreach ($exp as $k => $v)
			{
				$i_field .= $k.',';
				$v_field .= "'$v'".',';
			}
			if ($i_field) $i_field = ','.substr($i_field, 0, -1);
			if ($v_field) $v_field = ','.substr($v_field, 0, -1);
		}
		$this->pbdb->db_query("INSERT INTO {$db_prefix}members (username, password, email, adminid, groupid, publicemail, regip, regdate) VALUES ('".$username."', '".$md5password."', '".$email."', '$adminid', '".$groupid."', 0, '".$_PBDEV['PB_IP']."', '$timestamp')");
		$autoid = $this->pbdb->db_insertID();
		$this->pbdb->db_query("INSERT INTO {$db_prefix}memberexp (uid $i_field) VALUES ($autoid $v_field)");
		$this->pbdb->db_query("INSERT INTO {$db_prefix}memberdata (uid, currency, lastip, currentip, lastvisit, ucuid) VALUES ($autoid, ".intval($reg_credit).", '".$_PBDEV['PB_IP']."', '".$_PBDEV['PB_IP']."', $timestamp, $uc_uid)");
		$this->pbdb->db_query("UPDATE {$db_prefix}sitestat SET newmember = '$username', membernum = membernum + 1 WHERE id = 1");
		$Cache->sitestat();
		$this->setNewUser(array($autoid,$username,$password,$md5password,$email,'uc_login'=>$uc_login));
	}
	
	/**
	 * 删除会员
	 */
	function del()
	{
		global $_SUPERMANAGER, $customer, $pb_ucenable, $db_prefix,$Cache;
		if (!$this->uids) return FALSE;
		$suid = implode(',', $this->uids);
		foreach ($this->uids as $value)
		{
			$rs = $this->pbdb->db_fetch_one_array("SELECT groupid, username FROM {$db_prefix}members WHERE uid = $value");
			if (($rs['groupid'] == '1' && !$_SUPERMANAGER) || ($value == $customer['uid'])) return FALSE;
			if ($pb_ucenable)
			{
				uc_user_delete($rs['username']);
			}
		}
		$this->pbdb->db_query("DELETE FROM {$db_prefix}members WHERE uid IN ($suid)");
		$this->pbdb->db_query("DELETE FROM {$db_prefix}memberdata WHERE uid IN ($suid)");
		$this->pbdb->db_query("DELETE FROM {$db_prefix}memberexp WHERE uid IN ($suid)");
		$this->pbdb->db_query("DELETE FROM {$db_prefix}tdata WHERE uid IN ($suid)");
		$this->pbdb->db_query("DELETE FROM {$db_prefix}cdata WHERE uid IN ($suid)");
		$this->pbdb->db_query("DELETE FROM {$db_prefix}friends WHERE uid IN ($suid) OR fuid IN ($suid)");
		$this->pbdb->db_query("DELETE FROM {$db_prefix}message WHERE (tuid IN ($suid) AND type = 'r') OR (fuid IN ($suid) AND type = 's')");
		$this->pbdb->db_query("UPDATE {$db_prefix}threads SET author = '', uid = '0' WHERE uid IN ($suid)");
		$rs = $this->pbdb->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}members");
		$membernum = (int)$rs['num'];
		$newmember = $this->pbdb->db_fetch_one_array("SELECT username FROM {$db_prefix}members ORDER BY uid DESC LIMIT 1");
		$this->pbdb->db_query("UPDATE {$db_prefix}sitestat SET newmember = '$newmember', membernum = '$membernum' WHERE id = 1");
		$Cache->sitestat();
	}
	
	/**
	 * 激活用户
	 */
	function check($pass = TRUE)
	{
		global $db_prefix;
		if (!$this->uids) return FALSE;
		$suid = implode(',', $this->uids);
		$groupid = $pass ? -1 : 6;
		$this->pbdb->db_query("UPDATE {$db_prefix}members SET groupid = '$groupid' WHERE uid IN ($suid)");
	}
	
	/**
	 * 编辑用户
	 * 
	 * @param Array $member array('uid'=>'用户ID', 'username'=>'用户名', 'password'=>'密码', 'rpassword'=>'重复密码', 
	 * 'email'=>'电子邮件', 'publicemail'=>'是否公开电子邮件', 'groupid'=>'等级', 'ignore'=>'忽略用户名检查', 'exp'=>array())
	 */
	function mod($member)
	{
		global $grouplevel, $pb_ucenable, $db_prefix, $_SUPERMANAGER, $cp_message, $a_message, $customer, $siteFounder;
		require (PBDIGG_ROOT.'data/cache/cache_reg.php');
		@extract($_REGCONFIG);
		$uid = $username = $password = $email = $groupid = $ignore = $ignoreusername = $sql = $exp = $self = $realname = '';
		@extract($member, EXTR_OVERWRITE);
		unset($_REGCONFIG, $member);
		$rt = $this->pbdb->db_fetch_one_array("SELECT username, adminid FROM {$db_prefix}members WHERE uid = '$uid'");
		if (!$rt) showMsg($this->lang['member_illegal_uid']);
		$realname = addslashes($rt['username']);
		($customer['uid'] == $uid) && $self = '1';
		if (in_array($rt['adminid'], array('1', '2')) && !$_SUPERMANAGER && !$self) showMsg($this->lang['action_nopermission']);
		if (!$username)
		{
			$username = $realname;
			$ignoreusername = 1;
		}
		//开启uc整合不允许修改用户名
		if (!$ignoreusername && !$pb_ucenable)
		{
			$name_length = strlen($username);
			if ($name_length < $reg_minname || $name_length > $reg_maxname)
			{
				showMsg($this->lang['username_length_error']);
			}
			$ck = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','%');
			foreach ($ck as $v)
			{
				if (strpos($username, $v) !== FALSE) showMsg($this->lang['username_fchar_exist']);
			}
			if ($reg_bannames && !$ignore && (strpos($reg_bannames, $username) !== FALSE))
			{
				showMsg($this->lang['username_banword_exist']);
			}
			$rt = $this->pbdb->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}members WHERE username = '$username' AND uid <> '$uid'");
			if ($rt['num']) showMsg($this->lang['username_registerd']);
			$sql .= "username = '$username',";
		}
		if ($password)
		{
			if (!$rpassword || ($password != $rpassword)) showMsg($this->lang['password_not_same']);
			if (strlen($password) < 6) showMsg($this->lang['password_less_six']);
			$ck = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','%');
			foreach ($ck as $v)
			{
				if (strpos($password, $v) !== FALSE) showMsg($this->lang['password_fchar_exist']);
			}
			$sql .= "password = '".md5($password)."',";
		}
		if (!preg_match('/^[A-Za-z0-9]+([._\-\+]*[A-Za-z0-9]+)*@([A-Za-z0-9]+[-A-Za-z0-9]*[A-Za-z0-9]+\.)+[A-Za-z0-9]+$/', $email)) showMsg($this->lang['email_format_error']);
		$rt = $this->pbdb->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}members WHERE email = '$email' AND uid <> '$uid'");
		if ($rt['num']) showMsg($this->lang['email_exist']);
		$sql .= "email = '$email',";
		if (defined('IN_ADMIN') && ($siteFounder['username'] != $realname))
		{
			if (!array_key_exists($groupid, $grouplevel) || $groupid == '7') 
			{
				$groupid = '-1';
			}
			
			if ($groupid == '1' || $groupid == '2')
			{
				
				if ($_SUPERMANAGER)
				{
					$adminid = $groupid;
				}
				else
				{
					$groupid = -1;
					$adminid = 0;
				}
			}
			else
			{
				$adminid = 0;
			}
			$sql .= "groupid = '$groupid', adminid = '$adminid',";
		}
		$sql .= "publicemail = '".$publicemail."',";
		if ($pb_ucenable)
		{
			$message = '';
			$uc_uid = uc_user_edit($username, '', $password, $email, 1);
			switch ($uc_uid)
			{
				case -4:
					$message = 'email_format_error';
					break;
				case -5:
					$message = 'email_noallowed';
					break;
				case -6:
					$message = 'email_exist';
					break;
			}
			$message && showMsg($this->lang[$message]);
		}
		if ($exp && is_array($exp))
		{
			$expsql = '';
			foreach ($exp as $k => $v)
			{
				$expsql .= "$k = '$v',";
			}
			if ($expsql) $this->pbdb->db_query("UPDATE {$db_prefix}memberexp SET ".substr($expsql, 0, -1)." WHERE uid = $uid"); 
		}
		$this->pbdb->db_query("UPDATE {$db_prefix}members SET ".substr($sql, 0, -1)." WHERE uid = $uid");
		if (defined('IN_ADMIN') && $_SUPERMANAGER && $password && $uid == $customer['uid'])
		{
			$str = "<?php\r\n/** ".$cp_message['super_manager']." **/\r\nif (!defined('IN_PBDIGG'))\r\n{\r\n\texit('Access Denied!');\r\n}\r\n\$siteFounder = array(\r\n\t\t'username' => '$username',\r\n\t\t'password' => '".md5($password)."'\r\n);\r\n?>";
			PWriteFile(PBDIGG_ROOT.'data/manager.inc.php', $str, 'wb');
			redirect($a_message['mod_member_success'], 'admincp.php?action=logout');
		}
	}
}
?>