<?php

/**
 * MainController
 * Feel free to delete the methods and replace them with your own code.
 *
 * @author darkredz
 */
class ApiController extends DooController {

    private $username, $config, $data;

    public function __construct() {
//	parent::__construct();
//	$this->config = pc_base::load_config('system');
//	/* 判断应用字符集和phpsso字符集是否相同，如果不相同，转换用户名为phpsso所用字符集 */
//	$this->username = isset($this->data['username']) ? $this->data['username'] : '';
//
//	if ($this->username && CHARSET != $this->applist[$this->appid]['charset']) {
//	    if ($this->applist[$this->appid]['charset'] == 'utf-8') { //判断应用字符集是否为utf-8编码
//		//应用字符集如果是utf-8，并且用户名是utf-8编码，转换用户名为phpsso字符集，如果为英文，is_utf8返回false，不进行转换
//		if (is_utf8($this->username)) {
//		    $this->username = iconv($this->applist[$this->appid]['charset'], CHARSET, $this->username);
//		}
//	    } else {
//		if (!is_utf8($this->username)) {
//		    $this->username = iconv($this->applist[$this->appid]['charset'], CHARSET, $this->username);
//		}
//	    }
//	}
//	$authstr = $this->authcode($_POST['data']);
////	$authstr = $this->authcode($this->params['authstr']);
//	$ddddd = explode('&', urldecode($authstr));
//	foreach ($ddddd as $k => $v) {
//	    list($key, $val) = explode('=', $v);
//	    $this->$key = $val;
//	}
    }

    /**
     * 用户注册
     * @param string $username 	用户名
     * @param string $password 	密码
     * @param string $email		email
     * @return int {-1:用户名已经存在 ;-2:email已存在;-4:用户名禁止注册;-5:邮箱禁止注册;-6:uc注册失败;int(uid):成功}
     */
    public function register() {
        $this->random = isset($this->data['random']) && !empty($this->data['random']) ? $this->data['random'] : create_randomstr(6);
        $this->password = isset($this->data['password']) ? create_password($this->data['password'], $this->random) : '';
        $this->email = isset($this->data['email']) ? $this->data['email'] : '';
        $this->type = isset($this->appid) ? 'app' : 'connect';
        $this->regip = isset($this->data['regip']) ? $this->data['regip'] : '';
        $this->appid = isset($this->appid) ? $this->appid : '';
        $this->appname = $this->applist[$this->appid]['name'];

        $checkname = $this->checkname(1);
        if ($checkname == -1) {
            exit('-1');
        } elseif ($checkname == -4) {
            exit('-4');
        }

        $checkemail = $this->checkemail(1);
        if ($checkemail == -1) {
            exit('-2');
        } elseif ($checkemail == -5) {
            exit('-5');
        }

        //UCenter会员注册
        $ucuserid = 0;
        if ($this->config['ucuse']) {
            pc_base::load_config('uc_config');
            require_once PHPCMS_PATH . 'api/uc_client/client.php';
            $uid = uc_user_register($this->username, $this->data['password'], $this->email, $this->random);
            if (is_numeric($uid)) {
                switch ($uid) {
                    case '-3':
                        exit('-1');
                        break;
                    case '-6':
                        exit('-2');
                        break;
                    case '-2':
                        exit('-4');
                        break;
                    case '-5':
                        exit('-5');
                        break;
                    case '-1':
                        exit('-4');
                        break;
                    case '-4':
                        exit('-5');
                        break;
                    default :
                        $ucuserid = $uid;
                        break;
                }
            } else {
                exit('-6');
            }
        }

        $data = array(
            'username' => $this->username,
            'password' => $this->password,
            'email' => $this->email,
            'regip' => $this->regip,
            'regdate' => SYS_TIME,
            'lastdate' => SYS_TIME,
            'appname' => $this->appname,
            'type' => $this->type,
            'random' => $this->random,
            'ucuserid' => $ucuserid
        );
        $uid = $this->db->insert($data, 1);
        /* 插入消息队列 */
        $noticedata = $data;
        $noticedata['uid'] = $uid;
        messagequeue::add('member_add', $noticedata);
        exit("$uid"); //exit($uid) 不可以If status is an integer, that value will also be used as the exit status.
    }

    /**
     * 编辑用户，可以不传入旧密码和新密码
     * 如果传入新密码，则修改密码为新密码
     * @param string $username		用户名
     * @param string $password		旧密码
     * @param string $newpassword	新密码
     * @param string $email			email
     * @param string $random		密码随机数
     * @return int {-1:用户不存在;-2:旧密码错误;-3:email已经存在 ;1:成功;0:未作修改}
     */
    public function edit() {
        header("Content-type: text/html; charset=utf-8");
        $authstr = $this->authcode($_POST['data']);
//	var_dump($authstr);
        $ddddd = explode('&', urldecode($authstr));
//	var_dump($ddddd);
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $TmpArray[$key] = $val;
        }
//	debug_zval_dump($TmpArray);
//	比对 旧密码 回答问题
//	getuserinfo
//	$this->email = isset($this->data['email']) ? $this->data['email'] : '';
//	$this->uid = isset($this->data['uid']) ? $this->data['uid'] : '';
//
        $userinfo = $this->__getuserinfo($TmpArray['uid']);
//	var_dump($userinfo);
//	// 不为空
//	string(1) "3" refcount(1)
//	["password"] =>
//	string(6) "dddddd" refcount(1)
//	["newpassword"] =>
//	string(6) "wwwwww" refcount(1)
//	["useranswer"] =>
//	if (isset($TmpArray['password']) && !empty($TmpArray['password'])) {
//
//	}
//	if (isset($TmpArray['newpassword']) && !empty($TmpArray['newpassword'])) {
//	    $this->data['randomstr'] = $this->create_randomstr();
//	    $this->data['newpasswd'] = $this->create_password($TmpArray['newpassword'], $this->data['randomstr']);
//	}
//
//	$this->random = !empty($this->data['random']) ? $this->data['random'] : $userinfo['random'];
//	if (isset($this->data['newpassword']) && !empty($this->data['newpassword'])) {
//	    $this->newpassword = create_password($this->data['newpassword'], $this->random);
//	}
//
        if (!$userinfo) {
            exit('-1');
        }
        $passworld = $this->create_password($TmpArray['password'], $userinfo[0]['salt']);
        if (isset($this->password) && !empty($this->password) && ($passworld != $userinfo[0]['userpasswd'])) {
            exit('-2');
        }
//	echo urldecode($TmpArray['useranswer']) . '|' . $userinfo[0]['useranswer'];
        if ($TmpArray['useranswer'] && ($userinfo[0]['useranswer'] != $TmpArray['useranswer'])) {
            exit('-3');
        }
        $this->data['randomstr'] = $this->create_randomstr();
        $this->data['newpasswd'] = $this->create_password($TmpArray['newpassword'], $this->data['randomstr']);
        Doo::loadModel('users');
        $objuser = new Users();
        $objuser->userpasswd = $this->data['newpasswd'];
        $objuser->salt = $this->data['randomstr'];
        $RetValue = $objuser->update(array('where' => 'id=' . $TmpArray['uid'] . ' AND useranswer=\'' . $TmpArray['useranswer'] . '\''));
        return $RetValue;
//
//	$data = array();
//	$data['appname'] = $this->applist[$this->appid]['name'];
//
//	if (!empty($this->email) && $userinfo['email'] != $this->email) {
//	    $data['email'] = $this->email;
//	}
//
//	if (isset($this->newpassword) && $userinfo['password'] != $this->newpassword) {
//	    $data['password'] = $this->newpassword;
//	    $data['random'] = $this->random;
//	}
    }

    /**
     * 生成随机字符串
     * @param string $lenth 长度
     * @return string 字符串
     */
    function create_randomstr($lenth = 6) {
        return $this->random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    }

    /**
     *
     * @param $password 密码
     * @param $random 随机数
     */
    function create_password($password = '', $random = '') {
        if (empty($random)) {
            $array['random'] = $this->create_randomstr();
            $array['password'] = md5(md5($password) . $array['random']);
            return $array;
        }
        return md5(md5($password) . $random);
    }

    /**
     * 随机字符串函数
     * @param $password 密码
     * @param $random 随机数
     */
    function random($length, $chars = '0123456789') {
        $hash = '';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

    /**
     * 删除用户
     * @param string {$uid:用户id;$username:用户名;$email:email}
     * @return array {-1:删除失败;>0:删除成功}
     */
    public function delete() {
        $this->uid = isset($this->data['uid']) ? $this->data['uid'] : '';
        $this->email = isset($this->data['email']) ? $this->data['email'] : '';

        if ($this->uid > 0 || is_array($this->uid)) {
            $where = to_sqls($this->uid, '', 'uid');

            //ucenter部份
            if ($this->config['ucuse']) {
                pc_base::load_config('uc_config');
                require_once PHPCMS_PATH . 'api/uc_client/client.php';
                $s = $this->db->select($where, 'ucuserid');
                if ($s) {
                    $uc_data = array();
                    foreach ($s as $k => $v) {
                        $uc_data[$k] = $v['ucuserid'];
                    }
                    if (!empty($uc_data))
                        $r = uc_user_delete($uc_data);
                    if (!$r) {
                        exit('-1');
                    }
                } else {
                    exit('-1');
                }
            }

            /* 插入消息队列 */
            $noticedata['uids'] = $this->uid;
            messagequeue::add('member_delete', $noticedata);

            $this->db->delete($where);
            exit('1');
        } elseif (!empty($this->username)) {
            $this->db->delete(array('username' => $this->username));
            exit('2');
        } elseif (!empty($this->email)) {
            $this->db->delete(array('email' => $this->email));
            exit('3');
        } else {
            exit('-1');
        }
    }

    /**
     * 获取用户信息
     * @param string {$uid:用户id;$username:用户名;$email:email}
     * @return array {-1:用户不存在;array(userinfo):用户信息}
     */
    private function __getuserinfo($uid) {
        if ($uid > 0) {
            $r = Doo::db()->find('users', array(
                'where' => 'id=?',
                'param' => array($uid),
                'asArray' => TRUE
                    )
            );
        } elseif (!empty($this->username)) {
            $r = $this->db->get_one(array('username' => $this->username));
        } elseif (!empty($this->email)) {
            $r = $this->db->get_one(array('email' => $this->email));
        } else {
            return false;
        }
        return $r;
    }

    function getuserlist(){
    	
    	$authstr = $this->authcode($_POST['data']);
    	
    	$ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $this->$key = $val;
        }

    	$r = Doo::db()->find('users', array(
    			'select'=>'id,username',
                'where' => 'id in ( '.$this->uid.' )',
                'param' => array($this->uid),
                'asArray' => TRUE
                    )
         );
         exit(json_encode($r));
    }
    
    /**
     * 获取用户信息
     * @param string {$uid:用户id;$username:用户名;$email:email}
     * @return array {-1:用户不存在;array(userinfo):用户信息}
     */
    public function getuserinfo() {
        // TODO:远程字符串解析提取出来做成函数
        $authstr = $this->authcode($_POST['data']);
        $ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $TmpArray[$key] = $val;
            $this->$key = $val;
        }
        $uid = $TmpArray['uid'];
//	var_dump($uid);
        if ($uid > 0) {
            $r = Doo::db()->find('users', array(
                'where' => 'id=?',
                'param' => array($uid),
                'asArray' => TRUE
                    )
            );
        } elseif (!empty($this->username)) {
            $r = Doo::db()->find('users', array(
                'where' => 'username=?',
                'param' => array($this->username),
                'asArray' => TRUE
                    )
            );
        } elseif (!empty($this->email)) {
            $r = $this->db->get_one(array('email' => $this->email));
        } else {
            return false;
        }
        if ($this->username) {
            exit(json_encode($r));
        } else {
            exit(json_encode($r));
        }
    }

    function isMail($mail) {
        // if (preg_match("/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9\-\.])+/", $mail))
		if (filter_var($mail, FILTER_VALIDATE_EMAIL)){
            return true;
        }else{
            return false;
		}
    }

    public function checkauth(){
    	$authstr = $this->authcode($_POST['data']);
    	$ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $this->$key = $val;
        }
        $k=explode('_', $this->auth);
        $userinfo = Doo::db()->find('users', array(
               'select' => 'id,keys_auth',
               'where' => 'id=?',
               'param' => array($k[0]),
                   ));
        if(empty($userinfo[0]->keys_auth)){
        	echo '2';die;           
        }
        
		$dd = explode('_', $userinfo[0]->keys_auth);
		
		Doo::loadModel('users');
	    $users = new Users();
		
		if(!isset($dd[1])){
			
	        $users->keys_auth=$k[1]."_1";
	        $users->update(array('where' => 'id=?', 'param' => array($k[0])));
			
		}else{
			//过程认证完成           
			if(isset($k[2])){
	            $users->keys_auth="";
	            $users->update(array('where' => 'id=?', 'param' => array($k[0])));
			}
		}           
        if($dd[0]==$k[1]){
        	echo '1';die;
        }else{
        	echo '2';die;
        }
    }
    
    /**
     * 用户登录
     * @param string $username	用户名
     * @param string $password	密码
     * @return array {-2;密码错误;-1:用户不存在;array(userinfo):用户信息}
     */
    public function login() {
        $authstr = $this->authcode($_POST['data']);
        $ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $this->$key = $val;
        }
        if ($this->isMail($this->email)) {
            $userinfo = Doo::db()->find('users', array(
                'select' => 'id,username,userpasswd,useremail,salt,actstate,bank,keys_auth',
                'where' => 'useremail=?',
                'param' => array($this->email),
                    ));
        }
        if ($this->username) {
            $userinfo = Doo::db()->find('users', array(
                'select' => 'id,username,userpasswd,useremail,salt,actstate,bank,keys_auth',
                'where' => 'username=?',
                'param' => array($this->username),
                    ));
        }
        if (empty($userinfo))
            exit('-22');
        if (!empty($userinfo) && $userinfo[0]->userpasswd == $this->create_password($this->userpasswd, $userinfo[0]->salt)) {
            //登录成功更新用户最近登录时间和ip
            Doo::loadModel('users');
            $users = new Users();
            $key=$this->random_k(8);
            $users->keys_auth=$key;
            $users->lastloginip = ip2long($this->clientIP());
            $users->lastlogintime = time();
            $users->update(array('where' => 'id=?', 'param' => array($userinfo[0]->id)));
            $userinfo[0]->keys_auth=$key;
//	    $this->LoginSetCookie($userinfo);
//            $res = '<script type="text/javascript" src="http://192.168.1.140:8012/zhsso/api/synlogin/' . $userinfo[0]->username . '"></script>';\
            Doo::loadModel('userswitch');
            $userswitch = new UserSwitch();
            $usArray = $userswitch->getOne(array('select' => 'actime', 'where' => 'uid=?', 'param' => array($userinfo[0]->id), 'asArray' => TRUE));
            if (!$usArray['actime'])
                exit('-3');
            echo json_encode($userinfo);
            die();
        } else {
            exit('-2');
        }
    }

    public function scLogin(){
    	$authstr = $this->authcode($_POST['data']);
        $ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $this->$key = $val;
        }
        if ($this->isMail($this->email)) {
            $userinfo = Doo::db()->find('users', array(
                'select' => 'id,username,userpasswd,useremail,salt,actstate,keys_auth',
                'where' => 'useremail=?',
                'param' => array($this->email),
                    ));
        }
        if ($this->username) {
            $userinfo = Doo::db()->find('users', array(
                'select' => 'id,username,userpasswd,useremail,salt,actstate,keys_auth',
                'where' => 'username=?',
                'param' => array($this->username),
                    ));
        }
        if (empty($userinfo))
            exit('-22');
        if (!empty($userinfo) && $userinfo[0]->userpasswd == $this->create_password($this->userpasswd, $userinfo[0]->salt)) {
            //登录成功更新用户最近登录时间和ip
            Doo::loadModel('users');
            $users = new Users();
            $key=$this->random_k(8);
            $users->keys_auth=$key;
            $users->lastloginip = ip2long($this->clientIP());
            $users->lastlogintime = time();
            $users->update(array('where' => 'id=?', 'param' => array($userinfo[0]->id)));
            $userinfo[0]->keys_auth=$key;
//	    $this->LoginSetCookie($userinfo);
//            $res = '<script type="text/javascript" src="http://192.168.1.140:8012/zhsso/api/synlogin/' . $userinfo[0]->username . '"></script>';\
            Doo::loadModel('userswitch');
            Doo::loadModel('scUser');
            $scUser=new scUser();
            $userswitch = new UserSwitch();
            $usArray = $userswitch->getOne(array('select' => 'actime', 'where' => 'uid=?', 'param' => array($userinfo[0]->id), 'asArray' => TRUE));
            $scU=$scUser->find(array('where' => 'uid='.$userinfo[0]->id, 'asArray' => TRUE));
            $scU[0]['userName']=$userinfo[0]->username;$scU[0]['userpasswd']=$userinfo[0]->userpasswd;$scU[0]['useremail']=$userinfo[0]->useremail;
            if (!$usArray['actime'])
                exit('-3');
            echo json_encode($scU);
            die();
        } else {
            exit('-2');
        }
    }
    
    /**
     * 同步登陆
     * @param string $uid	用户id
     * @return string javascript用户同步登陆js
     */
    public function synlogin() {
        //判断本应用是否开启同步登陆
        if ($this->applist[$this->appid]['synlogin']) {
            $this->uid = isset($this->data['uid']) ? $this->data['uid'] : '';
            $this->password = isset($this->data['password']) ? $this->data['password'] : '';

            $res = '';
            //ucenter登陆部份
            if ($this->config['ucuse']) {
                pc_base::load_config('uc_config');
                require_once PHPCMS_PATH . 'api/uc_client/client.php';
                $r = $this->db->get_one(array('uid' => $this->uid), "ucuserid");
                if ($r['ucuserid'])
                    $res .= uc_user_synlogin($r['ucuserid']);
            }

            foreach ($this->applist as $v) {
                if (!$v['synlogin'])
                    continue;
                if ($v['appid'] != $this->appid) {
                    $tmp_s = strstr($v['url'] . $v['apifilename'], '?') ? '&' : '?';
                    $res .= '<script type="text/javascript" src="' . $v['url'] . $v['apifilename'] . $tmp_s . 'time=' . SYS_TIME . '&code=' . urlencode(sys_auth('action=synlogin&username=' . $this->username . '&uid=' . $this->uid . '&password=' . $this->password . "&time=" . SYS_TIME, 'ENCODE', $v['authkey'])) . '" reload="1"></script>';
                }
            }
            exit($res);
        } else {
            exit('0');
        }
    }

    /**
     * 同步退出
     * @return string javascript用户同步退出js
     */
    public function synlogout() {
        if ($this->applist[$this->appid]['synlogin']) {
            $res = '';
            //ucenter登陆部份
            if ($this->config['ucuse']) {
                pc_base::load_config('uc_config');
                require_once PHPCMS_PATH . 'api/uc_client/client.php';
                $res .= uc_user_synlogout();
            }
            foreach ($this->applist as $v) {
                if (!$v['synlogin'])
                    continue;
                if ($v['appid'] != $this->appid) {
                    $tmp_s = strstr($v['url'] . $v['apifilename'], '?') ? '&' : '?';
                    $res .= '<script type="text/javascript" src="' . $v['url'] . $v['apifilename'] . $tmp_s . 'time=' . SYS_TIME . '&code=' . urlencode(sys_auth('action=synlogout&time=' . SYS_TIME, 'ENCODE', $v['authkey'])) . '" reload="1"></script>';
                }
            }
            exit($res);
        } else {
            exit;
        }
    }

    /**
     * 获取应用列表
     */
    public function getapplist() {
        $applist = getcache('applist', 'admin');
        exit(serialize($applist));
    }

    /**
     * 获取积分兑换规则
     */
    public function getcredit($return = '') {
        $creditcache = getcache('creditlist', 'admin');
        foreach ($creditcache as $v) {
            if ($v['fromid'] == $this->appid) {
                $creditlist[$v['from'] . '_' . $v['to']] = $v;
            }
        }
        if ($return) {
            return $creditlist;
        } else {
            exit(serialize($creditlist));
        }
    }

    /**
     * 兑换积分
     * @param int $uid			phpssouid
     * @param int $from			本系统积分类型id
     * @param int $toappid 		目标系统应用appid
     * @param int $to			目标系统积分类型id
     * @param int $credit		本系统扣除积分数
     * @return bool 			{1:成功;0:失败}
     */
    public function changecredit() {
        $this->uid = isset($this->data['uid']) ? $this->data['uid'] : exit('0');
        $this->toappid = isset($this->data['toappid']) ? $this->data['toappid'] : exit('0');
        $this->from = isset($this->data['from']) ? $this->data['from'] : exit('0');
        $this->to = isset($this->data['to']) ? $this->data['to'] : exit('0');
        $this->credit = isset($this->data['credit']) ? $this->data['credit'] : exit('0');
        $this->appname = $this->applist[$this->appid]['name'];
        $outcredit = $this->getcredit(1);
        //目标系统积分增加数
        $this->credit = floor($this->credit * $outcredit[$this->from . '_' . $this->to]['torate'] / $outcredit[$this->from . '_' . $this->to]['fromrate']);

        /* 插入消息队列 */
        $noticedata['appname'] = $this->appname;
        $noticedata['uid'] = $this->uid;
        $noticedata['toappid'] = $this->toappid;
        $noticedata['totypeid'] = $this->to;
        $noticedata['credit'] = $this->credit;
        messagequeue::add('change_credit', $noticedata);
        exit('1');
    }

    /**
     * 检查用户名
     * @param string $username	用户名
     * @return int {-4：用户名禁止注册;-1:用户名已经存在 ;1:成功}
     */
    public function checkname($is_return = 0) {
        if (empty($this->username)) {
            if ($is_return) {
                return -1;
            } else {
                exit('-1');
            }
        }
        //非法关键词判断
        $denyusername = $this->settings['denyusername'];
        if (is_array($denyusername)) {
            $denyusername = implode("|", $denyusername);
            $pattern = '/^(' . str_replace(array('\\*', ' ', "\|"), array('.*', '', '|'), preg_quote($denyusername, '/')) . ')$/i';
            if (preg_match($pattern, $this->username)) {
                if ($is_return) {
                    return -4;
                } else {
                    exit('-4');
                }
            }
        }

        //UCenter部分
        if ($this->config['ucuse']) {
            pc_base::load_config('uc_config');
            require_once PHPCMS_PATH . 'api/uc_client/client.php';
            $rs = uc_user_checkname($this->username);
            if ($rs < 1) {
                exit('-4');
            }
        }

        $r = $this->db->get_one(array('username' => $this->username));
        if ($is_return) {
            return !empty($r) ? -1 : 1;
        } else {
            echo!empty($r) ? -1 : 1;
            exit;
        }
    }

    /**
     * 检查email
     * @param string $email	email
     * @return int {-1:email已经存在 ;-5:邮箱禁止注册;1:成功}
     */
    public function checkemail($is_return = 0) {
        $this->email = isset($this->email) ? $this->email : isset($this->data['email']) ? $this->data['email'] : '';
        if (empty($this->email)) {
            if ($is_return) {
                return -1;
            } else {
                exit('-1');
            }
        }
        //非法关键词判断
        $denyemail = $this->settings['denyemail'];
        if (is_array($denyemail)) {
            $denyemail = implode("|", $denyemail);
            $pattern = '/^(' . str_replace(array('\\*', ' ', "\|"), array('.*', '', '|'), preg_quote($denyemail, '/')) . ')$/i';
            if (preg_match($pattern, $this->email)) {
                if ($is_return) {
                    return -5;
                } else {
                    exit('-5');
                }
            }
        }

        //UCenter部分
        if ($this->config['ucuse']) {
            pc_base::load_config('uc_config');
            require_once PHPCMS_PATH . 'api/uc_client/client.php';
            $rs = uc_user_checkemail($this->email);
            if ($rs < 1) {
                exit('-5');
            }
        }

        $r = $this->db->get_one(array('email' => $this->email));
        if ($is_return) {
            return !empty($r) ? -1 : 1;
        } else {
            !empty($r) ? exit('-1') : exit('1');
        }
    }

    /**
     *  上传头像处理
     *  传入头像压缩包，解压到指定文件夹后删除非图片文件
     */
    public function uploadavatar() {
        //根据用户id创建文件夹
        $encodestr = $this->authcode(rawurldecode($this->params['authstr']));
        if (isset($encodestr)) {
            $this->uid = $encodestr;
        } else {
            exit('0');
        }
        $dir1 = ceil($this->uid / 10000);
        $dir2 = ceil($this->uid % 10000 / 1000);
        //创建图片存储文件夹
        $avatarfile = 'data/avatar/';
        $dir = $avatarfile . $dir1 . '/' . $dir2 . '/' . $this->uid . '/';
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        //存储flashpost图片
        $this->data['avatardata'] = $GLOBALS['HTTP_RAW_POST_DATA'];
        $filename = Doo::conf()->SITE_PATH . $dir . $this->uid . '.zip';
        file_put_contents($filename, $this->data['avatardata']);

        //解压缩文件
        Doo::loadClass('pclzip.lib');
//	pc_base::load_app_class('pclzip', 'phpsso', 0);
        $archive = new PclZip($filename);
        if ($archive->extract(PCLZIP_OPT_PATH, $dir) == 0) {
            die("Error : " . $archive->errorInfo(true));
        }
        // 判断文件安全，删除压缩包和非jpg图片
        $avatararr = array('180x180.jpg', '30x30.jpg', '45x45.jpg', '90x90.jpg');
        if ($handle = opendir($dir)) {
            while (false !== ($file = readdir($handle))) {
                if ($file !== '.' && $file !== '..') {
                    if (!in_array($file, $avatararr)) {
                        @unlink($dir . $file);
                    } else {
                        $info = @getimagesize($dir . $file);
                        if (!$info || $info[2] != 2) {
                            @unlink($dir . $file);
                        }
                    }
                }
            }
            closedir($handle);
        }
//	$this->db->update(array('avatar' => 1), array('uid' => $this->uid));
        exit('1');
    }

    /**
     *  存储支付方式
     *
     */
    public function setPayWay() {

        $authstr = $this->authcode($_POST['data']);
//	var_dump($authstr);
        $ddddd = explode('&', urldecode($authstr));
//	var_dump($ddddd);
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode(' = ', $v);
            $TmpArray[$key] = $val;
        }
//	var_dump($TmpArray);
        Doo::loadModel('users_payway');
        $upayway = new UsersPayway();
        $upayway->uid = $TmpArray['uid'];
        $upayway->idbank = $TmpArray['idbank'];
        $upayway->idalipay = $TmpArray['alipay'];
        $upayway->idtenpay = $TmpArray['tenpay'];
        if ($upayway->insert())
            exit('1');
    }

    /**
     *  实名认证
     *
     */
    public function setVerify() {
        Doo::loadModel('users_verify');
    }

    /**
     *  删除用户头像
     *  @return {0:失败;1:成功}
     */
    public function deleteavatar() {
        //根据用户id创建文件夹
        if (isset($this->data['uid'])) {
            $this->uid = $this->data['uid'];
        } else {
            exit('0');
        }

        $dir1 = ceil($this->uid / 10000);
        $dir2 = ceil($this->uid % 10000 / 1000);

        //图片存储文件夹
        $avatarfile = pc_base::load_config('system', 'upload_path') . 'avatar/';
        $dir = $avatarfile . $dir1 . '/' . $dir2 . '/' . $this->uid . '/';
        $this->db->update(array('avatar' => 0), array('uid' => $this->uid));
        if (!file_exists($dir)) {
            exit('1');
        } else {
            if ($handle = opendir($dir)) {
                while (false !== ($file = readdir($handle))) {
                    if ($file !== '.' && $file !== '..') {
                        @unlink($dir . $file);
                    }
                }
                closedir($handle);
                @rmdir($dir);
                exit('1');
            }
        }
    }

    /**
     *
     * @param type $string
     * @param type $operation
     * @param type $key
     * @param type $expiry
     * @return string
     */
    function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
        $ckey_length = 4;
        $key = md5($key != '' ? $key : Doo::conf()->AUTHKEY);
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace(' = ', '', base64_encode($result));
        }
    }

    public function LoginSetCookie() {
//        if (empty($this->params['username']))
//            return FALSE;
        $user = Doo::db()->find('users', array(
            'where' => 'username = ?',
            'param' => array($this->params['username']),
                ));
//        if (empty($user))
//            return FALSE;
        header('P3P: CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"');
//        header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
//        setcookie(Doo::conf()->COOKIEPRE . 'auth', '', 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE . '_userid', '', 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE . '_username', '', 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WK . 'auth', '', 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WK . '_userid', '', 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WK . '_username', '', 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WD . 'auth', '', 0, '/', '192.168.1.106', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WD . '_userid', '', 0, '/', '192.168.1.106', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WD . '_username', '', 0, '/', '192.168.1.106', 0);
        // 通行证
        setcookie(Doo::conf()->COOKIEPRE . 'auth', $this->authcode($user[0]->id . "\t" . $this->clientIP(), 'ENCODE'), 0, '/', '192.168.1.140', 0);
        setcookie(Doo::conf()->COOKIEPRE . '_userid', $this->authcode($user[0]->id, 'ENCODE'), 0, '/', '192.168.1.140', 0);
        setcookie(Doo::conf()->COOKIEPRE . '_username', $this->authcode($user[0]->username, 'ENCODE'), 0, '/', '192.168.1.140', 0);
        // 文库
//        setcookie(Doo::conf()->COOKIEPRE_WK . 'auth', $this->authcode($user[0]->id . "\t" . $this->clientIP(), 'ENCODE'), 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WK . '_userid', $this->authcode($user[0]->id, 'ENCODE'), 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WK . '_username', $this->authcode($user[0]->username, 'ENCODE'), 0, '/', '192.168.1.140', 0);
        // 问答
//        setcookie(Doo::conf()->COOKIEPRE_WD . 'auth', $this->authcode($user[0]->id . "\t" . $this->clientIP(), 'ENCODE'), 0, '/', 'local_zhask.com', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WD . '_userid', $this->authcode($user[0]->id, 'ENCODE'), 0, '/', 'local_zhask.com', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WD . '_username', $this->authcode($user[0]->username, 'ENCODE'), 0, '/', 'local_zhask.com', 0);
//        setcookie("test", 'sdfsdfsdfsdf', time() + 3600, '/', '192.168.1.106');
    }

//    public function nsetcookie($name) {
//        $user = Doo::db()->find('users', array(
//            'where' => 'username = ?',
//            'param' => array($name),
//                ));
//        setcookie(Doo::conf()->COOKIEPRE . 'auth', $this->authcode($user[0]->id . "\t" . $this->clientIP(), 'ENCODE'), 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE . '_userid', $this->authcode($user[0]->id, 'ENCODE'), 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE . '_username', $this->authcode($user[0]->username, 'ENCODE'), 0, '/', '192.168.1.140', 0);
//        // 文库
//        setcookie(Doo::conf()->COOKIEPRE_WK . 'auth', $this->authcode($user[0]->id . "\t" . $this->clientIP(), 'ENCODE'), 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WK . '_userid', $this->authcode($user[0]->id, 'ENCODE'), 0, '/', '192.168.1.140', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WK . '_username', $this->authcode($user[0]->username, 'ENCODE'), 0, '/', '192.168.1.140', 0);
//        // 问答
//        setcookie(Doo::conf()->COOKIEPRE_WD . 'auth', $this->authcode($user[0]->id . "\t" . $this->clientIP(), 'ENCODE'), 0, '/', 'local_zhask.com', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WD . '_userid', $this->authcode($user[0]->id, 'ENCODE'), 0, '/', 'local_zhask.com', 0);
//        setcookie(Doo::conf()->COOKIEPRE_WD . '_username', $this->authcode($user[0]->username, 'ENCODE'), 0, '/', 'local_zhask.com', 0);
//    }
    public function getBank() {
        // TODO:远程字符串解析提取出来做成函数
        $authstr = $this->authcode($_POST['data']);
        $ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $TmpArray[$key] = $val;
            $this->$key = $val;
        }
        $uid = $TmpArray['uid'];
        if ($uid > 0) {
            $r = Doo::db()->find('users', array(
                'select' => 'bank',
                'where' => 'id=?',
                'param' => array($uid),
                'asArray' => TRUE
                    )
            );
        }
        exit(json_encode(array($r[0]['bank'])));
    }

    public function getPayOrder() {
        // TODO:远程字符串解析提取出来做成函数
        $authstr = $this->authcode($_POST['data']);
        $ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $TmpArray[$key] = $val;
            $this->$key = $val;
        }
        $uid = $TmpArray['uid'];
        if ($uid > 0) {
            $r = Doo::db()->find('pay', array(
                'where' => 'userid=?',
                'param' => array($uid),
                'asArray' => TRUE
                    )
            );
        }
        exit(json_encode($r));
    }

    public function madd() {
        // TODO:认证，变量判断
        $authstr = $this->authcode($_POST['data']);
        $ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $TmpArray[$key] = $val;
            $this->$key = $val;
        }
        $uid = $TmpArray['uid'];
        if ($uid > 0) {
            $usersArray = Doo::db()->find('users', array(
                'where' => 'id=?',
                'param' => array($uid),
                'asArray' => TRUE
                    )
            );
            if (empty($usersArray)) {
                exit('0');
            } else {
                $usersObject = Doo::loadModel('users', TRUE);
                $usersObject->id = $usersArray[0]['id'];
                $usersObject->bank = new DooDbExpression('bank+' . $this->bank);
                if ($usersObject->update()) {
                    //TODO:写入日志
                    exit('1');
                } else {
                    exit('0');
                }
            }
        } else {
            exit('0');
        }
    }

    public function msub() {
        // TODO:远程字符串解析提取出来做成函数
        $authstr = $this->authcode($_POST['data']);
        $ddddd = explode('&', urldecode($authstr));
        foreach ($ddddd as $k => $v) {
            list($key, $val) = explode('=', $v);
            $TmpArray[$key] = $val;
            $this->$key = $val;
        }
        $uid = $TmpArray['uid'];
        if ($uid > 0) {
            $usersArray = Doo::db()->find('users', array(
                'where' => 'id=?',
                'param' => array($uid),
                'asArray' => TRUE
                    )
            );
            if (empty($usersArray)) {
                exit('0');
            } else {
                if ($usersArray[0]['bank'] < $this->bank) {
                    exit('-1');
                }
                $usersObject = Doo::loadModel('users', TRUE);
                $usersObject->id = $usersArray[0]['id'];
                $usersObject->bank = new DooDbExpression('bank-' . $this->bank);
                if ($usersObject->update()) {
                    //TODO:写入日志
                    exit('1');
                } else {
                    exit('0');
                }
            }
        } else {
            exit('0');
        }
    }

/**
	 * random 获取字符串
	 * @param int $length
	 * @return string $hash
	 */
	public function random_k($length = 6, $type = 0) {
		$hash = '';
		$chararr = array ('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz', '0123456789', '23456789ABCDEFGHJKLMNPQRSTUVWXYZ' );
		$chars = $chararr [$type];
		$max = strlen ( $chars ) - 1;
		PHP_VERSION < '4.2.0' && mt_srand ( ( double ) microtime () * 1000000 );
		for($i = 0; $i < $length; $i ++) {
			$hash .= $chars [mt_rand ( 0, $max )];
		}
		return $hash;
	}
    
}

?>