<?php
/**
* 整合UC的用户类
* @author moufer<moufer@163.com>
* @copyright modoer.com
* @version $Id user_uc.class.php 3 2008-4-17 20 => 02 $
*/
!defined('IN_MUDDER') && exit('Access Denied');
class User_UC_class {

    var $db         = null;
    var $dbpre      = 'modoer_';

    var $uid        = 0;
    var $email      = '';
    var $username   = '';
    var $groupid	= 1;
    var $face       = '';
    var $isLogin    = false;
    var $hash;
	var $coin;
	var $point;
    var $newmsgs;

    var $errmsg;
    var $backurl    = "JavaScript:history.go(-1);";
    var $ucsynlogin;

    var $reg_error = array(
        '-1' => '用户名不合法，请返回修改。',
        '-2' => '包含不允许注册的词语',
        '-3' => '用户名已经存在',
        '-4' => 'Email 格式有误',
        '-5' => 'Email 不允许注册',
        '-6' => '该 Email 已经被注册',
    );
    var $login_error = array(
		'-1' => '用户不存在，或者被删除。',
		'-2' => '密码错误。',
    );
    var $edit_error = array(
        '0'  => '未修改',
        '-1' => '旧密码不正确',
        '-4' => 'Email 格式有误',
        '-5' => 'Email 不允许注册',
        '-6' => '该 Email 已经被注册',
        '-7' => '没有做任何修改',
    );

    function __construct() {
        global $db, $dbpre;
        $this->db = &$db;
        $this->dbpre = &$dbpre;
    }

    function User_UC_class() {
        $this->__construct();
    }

    /**
     * 注册帐户
     *
     */
    function Register($username, $password, $email) {
        global $_config;
        if(uc_get_user($username) && !$res = $this->db->get_value("SELECT uid FROM {$this->dbpre}members WHERE username='$username'")) {
            //判断需要注册的用户如果是需要激活的用户，则需跳转到登录页面验证
            $this->errmsg = '该用户无需注册，请登录并激活该用户。';
            $this->backurl = $_config['siteurl'].'member/login.php';
            return false;
		}
        $result = uc_user_register($username, $password, $email);
        if($result < 0) {
            $this->errmsg = array_key_exists($result, $this->reg_error) ? $this->reg_error[$result] : "{$result}:未定义错误。";
            return false;
        } else {
            $this->Register_for_Local($result, $username, $password, $email);
            return uc_user_synlogin($result).' ';
        }
    }

    /**
     * 激活帐户
     *
     */
    function Activation($activation) {
        if($activeuser = uc_get_user($activation)) {
            list($uid, $username, $email) = $activeuser;
            if($username) {
            	$this->Register_for_Local($uid, $username, '', $email);
            	$this->Remember_Login($uid, $username, true);
                set_Cookie('loginuser', '', -86400 * 365);
                set_Cookie('activationauth', '', -86400 * 365);
                return uc_user_synlogin($uid).' ';
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 登录帐户
     *
     */
    function Login($username, $password, $savelogin = false) {
        global $timestamp,$onlineip,$_config;
        
        list($uid, $username, $password, $email) = uc_user_login($username, $password);

        if($uid > 0) {
            if(!$res = $this->db->get_one("SELECT * FROM {$this->dbpre}members WHERE uid='$uid'")) {
			    //判断用户是否存在于用户表，不存在则跳转到激活页面
			    $auth = rawurlencode(uc_authcode("$username\t".time(), 'ENCODE'));
                $this->backurl = $_config['siteurl'].'member/reg.php?action=activation&auth='.$auth;
                $this->errmsg = '您需要需要激活该帐号，才能进入网站。';
                return false;
            }
            $this->Remember_Login($uid, $username, $savelogin);
            $ucsynlogin = uc_user_synlogin($uid).' ';
            $this->db->update("UPDATE {$this->dbpre}members SET logintime='$timestamp', loginip='$onlineip', logincount=logincount+1 WHERE uid='$uid'");
            $this->isLogin = true;
            return $ucsynlogin;
        } else {
            $this->errmsg = array_key_exists($uid, $this->login_error) ? $this->login_error[$uid] : '未知错误。';
            return false;
        }
    }

    /**
     * 自定登陆
     *
     */
    function Auto_Login() {
    	global $_DCOOKIE;
    	$myauth = $_DCOOKIE['myauth'];
		if(!empty($myauth)) {
			list($uid, $username) = explode("\t", uc_authcode($myauth, 'DECODE'));
			if($data = uc_get_user($username)) {
				list($this->uid, $this->username, $this->email) = $data;
				$this->hash = $myauth;
				$this->isLogin = true;
				$this->Get_Baseinfo(); //读取基本信息
			} else {
				$this->errmsg = '会员不存在.';
				$this->Loginout_login();
				return -1;
			}
		} else {
			//$this->Loginout_login(false);
			return false;
		}
    }

    /**
     * 同步系统帐户
     *
     */
    function Register_for_Local($uid, $username, $password, $email) {
        global $timestamp, $onlineip, $_webtotal, $_config, $_space, $_expleve;

        $password = md5($password);
        $this->db->query("INSERT INTO {$this->dbpre}members (uid,username,password,email,regdate,logintime,loginip,logincount,groupid) VALUES ('$uid','$username','','$email','$timestamp','$timestamp','$onlineip','1','10')");

        // 注册会员增加积分;
        $uppoint = intval(addslashes($_expleve['reg']['point']));
        $upcoin = intval(addslashes($_expleve['reg']['coin']));
        if($uppoint != 0 && $upcoin != 0) {
            $this->db->update("UPDATE {$this->dbpre}members SET point=point+$uppoint,coin=coin+$upcoin WHERE uid='$uid'");
        }

        // 创建个人空间
        $rp = array("\$sitename", "\$username", "\$time");
        $sm = array($_config['sitename'], $username, date("Y-m-d H:i:s", $timestamp));

        $spacename = $_space['spacename'];
        $spacedescribe = $_space['spacedescribe'];
        if(empty($_space['spacename'])) {
            $spacename = '$username的个人空间';
        }
        if(empty($_space['spacedescribe'])) {
            $spacedescribe = "读万卷书，行万里路。";
        }
        $spacename = str_replace($rp, $sm, $spacename);
        $spacedescribe = str_replace($rp, $sm, $spacedescribe);
        $this->db->query("INSERT INTO {$this->dbpre}spaces(uid,space_styleid,spacename,spacedescribe,pageview) VALUES('$uid','{$_config['space_styleid']}','$spacename','$spacedescribe','0')");

        if($_config['salutatory']) {
            $subject = '欢迎注册'.$_config['sitename'].'会员';
            if(!$_config['salutatory_msg']) {
                $content = "敬爱的会员：$username\r\n欢迎您注册成为".$_config['sitename']."会员。\r\n\r\n".$_config['sitename']."\r\n".date("Y-m-d H:i:s",$timestamp);
            } else {
                $content = str_replace($rp, $sm, $_config['salutatory_msg']);
            }
            uc_pm_send(0,$uid,$subject,$content);
        }
        //更新统计缓存
        $_webtotal['totalmember'] ++;
        update_webtotal();
    }
    
    /**
     * 记住登录（Cookie）
     *
     * @param integer $uid 用户ID
     * @param string $username 会员名
     */
    function Remember_Login($uid, $username, $savelogin) {
        global $timestamp;
    	$life = $savelogin ? 3600 * 24 * 30 : ''; //Cookie保存1个月
    	$myauth = uc_authcode($uid."\t".$username, 'ENCODE');
    	set_Cookie('myauth', $myauth, $life);
    	set_Cookie("logintime", $timestamp, $life);
    	set_Cookie("remembertime", $timestamp + $life, $life);
    }
    
    /**
     * 退出登录
     *
     */
    function Loginout_login($synlogout = true) {
    	del_cookie(array("myauth", "logintime", "remembertime", "loginuser", "activationauth"));
        return $synlogout ? uc_user_synlogout() : true;
    }
    
    /**
     * 清除Cookie
     *
     */
    function Clear_Cookie() {
    	$this->Loginout_login();
    }
    
    /**
     * 取得帐户的基本信息
     *
     */
    function Get_Baseinfo(){
    	if(!$this->isLogin || !$this->uid) return false;
    	$row = $this->db->get_one("SELECT * FROM {$this->dbpre}members WHERE uid='{$this->uid}'");
    	$this->groupid = $row['groupid'];
    	$this->coin = $row['coin'];
    	$this->point = $row['point'];
    	$this->newmsgs = uc_pm_checknew($this->uid);
        $this->face = UC_API.'/avatar.php?uid='.$this->uid.'&size=small';
    	unset($row);
    }

    /**
     * 修改密码
     *
     */
     function Modfily_Password($newpw, $oldpw, $ignoreoldpw = false) {
        $result = uc_user_edit($this->username, $oldpw, $newpw, '', $ignoreoldpw);
        if($result == 1) {
            return true;
        } else {
            $this->errmsg = array_key_exists("$result", $this->edit_error) ? $this->edit_error[$result] : "{$result}:未定义错误。";
            return false;
        }
     }

    /**
     * 取得短信列表
     *
     */
    function Get_Pmlist($page, $pagesize = '10', $folder = 'inbox', $filter = '') {
        $row = uc_pm_list($this->uid, $page, $pagesize, $folder, $filter);
        $result = array();
        foreach($row['data'] as $key=>$val){
            $result[$key]['pmid'] = $val['pmid'];
            $result[$key]['subject'] = $val['subject'];
            if($folder == 'inbox') {
                $result[$key]['uid'] = $val['msgfromid'];
                $result[$key]['username'] = $val['msgfrom'];
            } else {
                $result[$key]['uid'] = $val['msgtoid'];
                $result[$key]['username'] = $this->db->get_value("SELECT username FROM {$this->dbpre}members WHERE uid='{$val['msgtoid']}'");
            }
            $result[$key]['new'] = $val['new'];
            $result[$key]['posttime'] = date('Y-m-d H:i:s',$val['dateline']);
        }
        $row['result'] = $result;
        unset($row['data']);
        return $row;
    }

    /**
     * 取得好友列表
     *
     */
    function Get_Friendlist($page, $pagesize = '10', $direction = 0) {
        $totalnum = uc_friend_totalnum($this->uid, $direction);
        $totalnum > 0 && $row = uc_friend_ls($this->uid, $page, $pagesize, $totalnum, $direction);
        if(!$totalnum || !$row) return array(0,array());
        $result = array();
        foreach($row as $key => $val) {
            $result[$key]['fid'] = $val['friendid'];
            $result[$key]['uid'] = $val['friendid'];
            $result[$key]['username'] = $val['username'];
            $result[$key]['direction'] = $val['direction'];
            $result[$key]['point'] = 'n/a';
            $result[$key]['reviews'] = 'n/a';
            $result[$key]['addtime'] = 'n/a';
            $result[$key]['logintime'] = 'n/a';
        }
        unset($row);
        return array('total' => $totalnum, 'result' => $result);
    }

    /**
     * 加某人为好友
     *
     */
    function Add_Friend($firendid) {
        return uc_friend_add($this->uid, $firendid);
    }

    /**
     * 删除好友
     *
     */
    function Delete_Friend($firendids) {
        return uc_friend_delete($this->uid, $firendids);
    }
}


class Member_Base_class {

    var $uid        = 0;        //UID
    var $username   = '';
    var $face       = '';
    var $point      = 0;
    var $coin       = 0;
    var $reviews    = 0;
    var $flowers    = 0;
    var $rank       = '';        //积分等级

    function __construct() {
    }

    function Member_Base_class() {
        $this->__construct();
    }

    function Set_Row($row) {

        $this->uid = $row['uid'];
        $this->username = $row['username'];
        $this->face = UC_API.'/avatar.php?uid='.$this->uid.'&size=small';
        $this->point = $row['point'];
        $this->coin = $row['coin'];
        $this->reviews = $row['reviews'];
        $this->flowers = $row['flowers'];
        $this->rank = get_userrank($row['point']);

    }

    function ToArray() {
        $array = array(
            'uid' => $this->uid,
            'username' => $this->username,
            'face' => $this->face,
            'point' => $this->point,
            'coin' => $this->coin,
            'reviews' => $this->reviews,
            'rank' => $this->rank,
        );

        return $array;
    }

}
?>
