<?php

/**
 * Description of M
 *
 * @author zongheng
 */
class UserController extends DooController {

    private $cashlimit = 100; // 充值金额奖励底限
    private $perlimit = 0.05; // 奖励百分比
    private $salelimit = 0.2; // 销售人员提成
    public $data;
    private $theme = null;
    public $errorMsg;       //错误信息
    public $QArray = array(1 => '您父亲的名字是?', 2 => '您母亲的名字是?', 3 => '您的英文名字是?', 4 => '您身份证最后6位数字是?', 5 => '您就读的第一所学校全称是?');

    function __construct() {
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->data['rootUrl_JS'] = Doo::conf()->APP_JS_URL;
        $this->data['rootUrl_IMG'] = Doo::conf()->APP_IMG_URL;
        $this->data['rootUrl_CSS'] = Doo::conf()->APP_CSS_URL;
        $this->theme = Doo::conf()->APP_THEME;
    }

    /**
     * 管理登入
     */
    function login() {
        $forward = isset($this->params['forward']) ? $this->params['forward'] : 'profile';
        $session = Doo::session("sso");
        if ($session->user['id']) {
            if ($forward == 'deposit') {
                return Doo::conf()->APP_URL . 'msg/login';
            } 
        }
        $this->data['messages'] = null;
        if (isset($_POST['zhusername']) && isset($_POST['zhuserpasswd'])) {
            $username = trim($_POST['zhusername']);
            $password = trim($_POST['zhuserpasswd']);
            if (!empty($username) && !empty($password)) {
                if ($this->checkMail($username)) {
                    $user = Doo::db()->find('users', array(
                        'select' => 'id,username,userpasswd,useranswer,useremail,actstate,defquestion,userquestion,regdate,salt,intime,mobile',
                        'where' => 'useremail=?',
                        'param' => array($username),
                            )
                    );
                }elseif($this->checkMobile($username)){
                    $user = Doo::db()->find('users', array(
                            'select' => 'id,username,userpasswd,useranswer,useremail,actstate,defquestion,userquestion,regdate,salt,intime,mobile',
                            'where' => 'mobile=?',
                            'param' => array($username),
                        )
                    );
                } else {
                    $user = Doo::db()->find('users', array(
                        'select' => 'id,username,userpasswd,useranswer,salt,actstate,defquestion,userquestion,regdate,useremail,intime,mobile',
                        'where' => 'username=?',
                        'param' => array($username),
                            )
                    );
                }
                Doo::loadModel('userswitch');
                $userswitch = new UserSwitch();
                $usArray = $userswitch->getOne(array('select' => 'actime', 'where' => 'uid=?', 'param' => array($user[0]->id), 'asArray' => TRUE));
                if (!empty($user)) {
                    if ($user[0]->userpasswd == $this->create_password($password, $user[0]->salt)) {
                        $session = Doo::session("sso");
                        unset($session->user);
                        $session->user = array(
                            'id' => $user[0]->id,
                            'username' => $user[0]->username,
                            'password' => $user[0]->userpasswd,
                            'answer' => $user[0]->useranswer,
                            'regdate' => $user[0]->regdate,
                            'email' => $user[0]->useremail,
                            'mobile' => $user[0]->mobile,
                            'salt' => $user[0]->salt,
                            'status' => $usArray['actime'],
                            'defquestion' => $user[0]->defquestion,
                            'userquestion' => $user[0]->userquestion,
                        );
                        setcookie(Doo::conf()->COOKIEPRE . 'auth', $this->authcode($user[0]->id . "\t" . $this->clientIP(), 'ENCODE'), 0, '/', Doo::conf()->APP_URL, 0);
                        setcookie(Doo::conf()->COOKIEPRE . '_userid', $this->authcode($user[0]->id, 'ENCODE'), 0, '/', Doo::conf()->APP_URL, 0);
                        setcookie(Doo::conf()->COOKIEPRE . '_username', $this->authcode($user[0]->username, 'ENCODE'), 0, '/', Doo::conf()->APP_URL, 0);
                        if (empty($user[0]->userquestion) && empty($user[0]->mobile))
                            return Doo::conf()->APP_URL . 'safe';
                        if ($forward == 'deposit') {
                            return Doo::conf()->APP_URL . 'msg/login';
                        } 
                        // else {
                        //     return Doo::conf()->APP_URL . 'profile';
                        // }
                    } else {
                        $this->data['messages'] = '账号或者密码错误';
                    }
                } else {
                    $this->data['messages'] = '无此用户';
                }
            }
        }
        $this->data['userid'] = $session->user['id'];
        $this->data['username'] = $session->user['username'];   
        $this->render($this->theme.'login', $this->data,true);
    }
    
    // 账户名称检测只能由中文、大小写字母、数字组成
    private function checkUserName($username){
        if (preg_match('/^[A-Za-z0-9\x{4e00}-\x{9fa5}]{3,15}$/u', $username)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    // 检测手机验证码和验证手机是否符合
    private function checkSmsCode($mobile,$code){
        $now = time();
        $old = $now-900;
        Doo::loadModel('mobilecode');
        $mobilecode = new mobilecode();
        $user = $mobilecode->find(array(
            'select' => 'id',
            'where' => 'mobile='.$mobile.' and code='.$code.' and time between '.$old.' and '.$now,
            'desc' => 'id',
            'limit' => 1,
            'asArray' => true
        ));
        if ($user) {
            $mobilecode->mobile=$mobile;
            $mobilecode->delete();
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function reg() {
    	$this->data['soft']=$this->params['soft']?$this->params['soft']:false;
    	$web=isset($_POST['web'])?$_POST['web']:2;
    	
    	if($web==1)
    		if(empty($_POST['realName'])||empty($_POST['PhoneNum'])||empty($_POST['Company'])||empty($_POST['MobileNum']))
    			$this->render($this->theme.'register', $this->data);
    	
    	
        if (!empty($_POST['zhuser']) && !empty($_POST['zhemail']) && filter_var($_POST['zhemail'], FILTER_VALIDATE_EMAIL) && !empty($_POST['zhq']) && !empty($_POST['zhanswer']) && ($_POST['zhuser'] != $_POST['zhemail'])) {
            if(!$this->checkUserName($_POST['zhuser'])){
                return Doo::conf()->APP_URL . 'error/UserName';
            }
            // if(!$this->checkMail($_POST['zhemail'])){
            //     return Doo::conf()->APP_URL . 'error/UserEmail';
            // }
            $strSalt = $this->create_randomstr();
            $stractstate = sha1(substr(uniqid(rand()), 0, 6)); // 旧激活功能代码
            $strpasswd = $this->create_password($_POST['zhpwdrepeat'], $strSalt);
            $nowtime = time();
            $items = array(
                'username' => $_POST['zhuser'],
                'useremail' => $_POST['zhemail'],
                'mobile' => '',
                'userpasswd' => $strpasswd,
                'salt' => $strSalt,
                'regip' => $this->clientIP(),
                'userquestion' => htmlspecialchars($_POST['zhq']),
                'defquestion' => addslashes(htmlspecialchars($_POST['defq'])),
                'useranswer' => addslashes(htmlspecialchars($_POST['zhanswer'])),
                'actstate' => $stractstate, // 旧激活功能代码
                'intime' => $nowtime,
                'regdate' => $nowtime,
            );
            doo::loadModel('users');
            $users = new Users();
            $RetValue = $users->_insertAttributes('users', $items);
            //插入网络版信息
            doo::loadModel('scUser');
            $scuser = new scUser();
            $scuser->uid=$RetValue;
            $scuser->Name=$_POST['realName'];
            $scuser->MobileNum=$_POST['MobileNum'];
            $scuser->Company=$_POST['Company'];
            $scuser->PhoneNum=$_POST['AreaCode'].'-'.$_POST['PhoneNum'];
            $scuser->QQ=$_POST['QQ'];
            $scuser->Province=$_POST['Province'];
            $scuser->Address=$_POST['Address'];
            $scuser->KnowFrom=$_POST['KnowFrom'];
            if($_POST['KnowFrom']==9)
            	$scuser->KnowOther='其他';
            $scuser->insert();	
            // 新注册用户加入待激活列表
            $rndcode = $this->create_randomstr();
            $acode = md5($RetValue . $rndcode);
            Doo::loadModel('userswitch');
            $UserSwitch = new UserSwitch();
            $UserSwitch->userAdd($RetValue, $acode, $rndcode);
            // End
            if ($RetValue) {
                $session = Doo::session("sso");
                unset($session->user);
                $session->user = array(
                    'id' => $RetValue,
                    'username' => $_POST['zhuser'],
                    'password' => $strpasswd,
                    'answer' => $_POST['zhanswer'],
                    'email' => $_POST['zhemail'],
                    'salt' => $strSalt,
                    'status' => $stractstate,
                    'defquestion' => addslashes(htmlspecialchars($_POST['defq'])),
                    'userquestion' => addslashes(htmlspecialchars($_POST['zhq'])),
                    'regdate' => $nowtime,
                );
            }
            $StrSubject = '纵横通行帐号-请激活您的帐号';
            $StrContent = '<table style="width:100%">
			<tbody>
				<tr><td>
					<p>感谢您注册成为纵横通行帐号的会员。在使用我们提供的服务之前，请点击以下链接，或将以下链接复制到浏览器的地址栏中打开，以激活您的帐户：</p>
					<p style="width:600px"><br><a href="' . Doo::conf()->APP_URL . 'actuser/' . $acode . '">' . Doo::conf()->APP_URL . 'actuser/' . $acode . '</a></p>
					<p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
					<p><br>纵横通行帐号与你共成长！</p>
					<p>' . date('Y年m月d日', time()) . '</p>
					<p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
				</td></tr>
			</tbody>
		</table>';
            @$this->SMail($_POST['zhemail'], $StrSubject, $StrContent);
            return Doo::conf()->APP_URL . 'sec';
        }
        $this->render($this->theme.'register', $this->data);
    }

    function smsreg(){
        $this->data['soft']=$this->params['soft']?$this->params['soft']:false;
        $web=isset($_POST['web'])?$_POST['web']:2;

        if($web==1)
            if(empty($_POST['realName'])||empty($_POST['PhoneNum'])||empty($_POST['Company'])||empty($_POST['MobileNum']))
                $this->render($this->theme.'register', $this->data);


        if (!empty($_POST['zhmuser']) && !empty($_POST['zhmobile']) && !empty($_POST['zhsmscode']) && !empty($_POST['zhmpasswd'])) {
            if(!$this->checkUserName($_POST['zhmuser'])){
                return Doo::conf()->APP_URL . 'error/UserName';
            }
            if(!$this->checkSmsCode($_POST['zhmobile'],$_POST['zhsmscode'])){
                return Doo::conf()->APP_URL . 'error/mobile';
            }
            $strSalt = $this->create_randomstr();
            $stractstate = sha1(substr(uniqid(rand()), 0, 6)); // 旧激活功能代码
            $strpasswd = $this->create_password($_POST['zhmpasswd'], $strSalt);
            $nowtime = time();
            $items = array(
                'username' => $_POST['zhmuser'],
                'mobile' => $_POST['zhmobile'],
                'useremail' => '',
                'userpasswd' => '',
                'userquestion' => '',
                'useranswer' => '',
                'userpasswd' => $strpasswd,
                'salt' => $strSalt,
                'regip' => $this->clientIP(),
                'actstate' => $stractstate, // 旧激活功能代码
                'intime' => $nowtime,
                'regdate' => $nowtime,
            );
            doo::loadModel('users');
            $users = new Users();
            $RetValue = $users->_insertAttributes('users', $items);

            //插入网络版信息
            doo::loadModel('scUser');
            $scuser = new scUser();
            $scuser->uid=$RetValue;
//            $scuser->Name=$_POST['realName'];
//            $scuser->MobileNum=$_POST['MobileNum'];
//            $scuser->Company=$_POST['Company'];
//            $scuser->PhoneNum=$_POST['AreaCode'].'-'.$_POST['PhoneNum'];
//            $scuser->QQ=$_POST['QQ'];
//            $scuser->Province=$_POST['Province'];
//            $scuser->Address=$_POST['Address'];
//            $scuser->KnowFrom=$_POST['KnowFrom'];
//            if($_POST['KnowFrom']==9)
//                $scuser->KnowOther='其他';
            $scuser->insert();

            if ($RetValue) {
                $session = Doo::session("sso");
                unset($session->user);
                $session->user = array(
                    'id' => $RetValue,
                    'username' => $_POST['zhmuser'],
                    'password' => $strpasswd,
                    'answer' => '',
                    'email' => '',
                    'mobile' => $_POST['zhmobile'],
                    'salt' => $strSalt,
                    'status' => $stractstate,
                    'defquestion' => '',
                    'userquestion' => '',
                    'regdate' => $nowtime,
                );
            }
            $this->data['username'] = $_POST['zhmuser'];
            $this->data['mobile'] = $_POST['zhmobile'];
            if(isset($_POST['mobilereg'])){
                $this->render($this->theme.'registerMobile-success', $this->data);
            }else{
                $this->render($this->theme.'successM', $this->data);
            }
            die();
        }else{
            if(isset($_POST['mobilereg'])) {
                $this->render($this->theme.'registerMobile', $this->data);
            }else{
                $this->render($this->theme.'register', $this->data);
            }
        }
    }

    /**
     * 生成随机字符串
     * @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;
    }

    function setpasswd() {
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        $StrEncode = $this->authcode(base64_decode($this->params['AuthStr']), 'DECODE');
        if (empty($StrEncode))
            exit('error');
        list($userid, $useremail, $timetemp) = explode('|', $StrEncode);
        if ((time() - $timetemp) > 86400) {
            exit('error');
        }
        $user = Doo::db()->find('users', array(
            'select' => 'id,salt',
            'where' => 'useremail=?',
            'param' => array($useremail),
                )
        );
        if (empty($user)) {
            exit('error');
        }
        if ($userid != $user[0]->id) {
            exit('error!');
        }
        $this->data['messages'] = null;
        if (!empty($_POST['answer']) && !empty($_POST['newpasswd']) && !empty($_POST['repeatnew']) && ($_POST['newpasswd'] == $_POST['repeatnew'])) {
            $useranswer = htmlspecialchars($_POST['answer']);
            $userrepeatnew = $_POST['repeatnew'];
            Doo::loadModel('users');
            $objuser = new Users();
            $objuser->userpasswd = $this->create_password($userrepeatnew, $user[0]->salt);
            $RetValue = $objuser->update(array('where' => 'id=' . $userid . ' AND useremail=\'' . $useremail . '\' AND useranswer=\'' . $useranswer . '\''));
            if ($RetValue)
                $this->data['messages'] = '密码重置成功';
            return Doo::conf()->APP_URL;
        }
        $this->data['defquestion'] = null;
        $session = Doo::session("sso");
        if (!empty($session->user['defquestion']) || ($session->user['userquestion'] == 6))
            $this->data['defquestion'] = htmlspecialchars_decode($session->user['defquestion']);
        if (!empty($session->user['userquestion']) && ($session->user['userquestion'] != 6))
            $this->data['defquestion'] = $this->QArray[$session->user['userquestion']];
        $this->data['StrAuth'] = $this->params['AuthStr'];
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->render($this->theme.'getPassword2', $this->data);
    }

    function getpasswd() {
//            $flash = new DooFlashMessenger();
//            $flash->addMessage("This is just test message");
//            $this->data['messages'] = $flash->displayMessages();
        $gpemail = isset($_POST['email']) ? $_POST['email'] : NULL;
        if (!empty($gpemail) && isset($_POST['emailsubmit'])) {
            if ($this->checkMail($gpemail)) {
                $user = Doo::db()->find('users', array(
                    'select' => 'id,salt,username,useremail',
                    'where' => 'useremail=?',
                    'param' => array($gpemail),
                        )
                );
            } else {
                $user = Doo::db()->find('users', array(
                    'select' => 'id,salt,username,useremail',
                    'where' => 'username=?',
                    'param' => array($gpemail)
                        )
                );
            }
            if (!empty($user)) {
                // TODO：重新设置密码过程
                $newPasswdStr = $this->create_randomstr();
                $newPasswd = $this->create_password($newPasswdStr, $user[0]->salt);
                $usersObj = Doo::loadModel('users', TRUE);
                $usersObj->id = $user[0]->id;
                $usersObj->userpasswd = $newPasswd;
                if ($usersObj->update()) {
                    $StrSubject = '纵横通行帐号提醒您：您的帐号修改了新密码';
                    $StrContent = '<table style="width:100%">
			<tbody>
				<tr><td>
					<p>尊敬的' . $user[0]->username . ':</p>
					<p><br>您的通行帐号修改了新的密码（区分大小写）：<b style="font-size:18px">' . $newPasswdStr . '</b></p>
					<p><br>请妥善保管您的新密码，及时登陆纵横通行证进行更新。</p>
					<p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
					<p><br>纵横通行帐号与你共成长！</p>
					<p>' . date('Y年m月d日', time()) . '</p>
					<p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
				</td></tr>
			</tbody>
		</table>';
                    if ($this->SMail($user[0]->useremail, $StrSubject, $StrContent)) {
                        $this->data['messages'] = '密码找回完成，请查收您的邮箱';
                        header('refresh:2;url=' . Doo::conf()->APP_URL);
                        $this->render($this->theme.'getPConfirm', $this->data, TRUE);
                        exit();
                    }
                }
            } else {
                $this->data['messages'] = '账号或邮箱有误，请重新输入';
            }
        }
        if(isset($_POST['mobilesubmit'])){
            if($this->checkSmsCode($_POST['zhmobile'],$_POST['zhsmscode'])){
                $user = Doo::db()->find('users', array(
                        'select' => 'id,salt,username,mobile',
                        'where' => 'mobile=?',
                        'param' => array($_POST['zhmobile'])
                    )
                );
                if(!empty($user)){
                    // TODO：重新设置密码过程
                    $newPasswdStr = $_POST['password'];
                    $newPasswd = $this->create_password($newPasswdStr, $user[0]->salt);
                    $usersObj = Doo::loadModel('users', TRUE);
                    $usersObj->id = $user[0]->id;
                    $usersObj->userpasswd = $newPasswd;
                    if ($usersObj->update()) {
                        return Doo::conf()->APP_URL . 'notic/repwdmobile';
                        exit();
                    }else{
                        $this->data['messages2'] = '新密码有误，请重新输入';
                    }
                } else {
                    $this->data['messages2'] = '手机号有误，请重新输入';
                }
            }else{
                $this->data['messages2'] = '验证码过期或不一致，请重新获取';
            }
        }
        $this->data['messages'] = isset($this->data['messages']) ? $this->data['messages'] : NULL;
        $this->data['messages2'] = isset($this->data['messages2']) ? $this->data['messages2'] : NULL;
        $this->render($this->theme.'getPassword', $this->data);
    }

    function ActEmail() {
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if (empty($this->params['AuthStr'])) {
            return Doo::conf()->APP_URL . 'error/actemail';
        }
        $StrEncode = $this->authcode(base64_decode($this->params['AuthStr']), 'DECODE');
        if (empty($StrEncode))
            return Doo::conf()->APP_URL . 'error/actemail';
        if (!empty($session->user['status'])) {
            if (empty($session->user['status'])) {
                $this->data['name'] = $session->user['username'];
                $this->data['rootUrl'] = Doo::conf()->APP_URL;
                $this->render($this->theme.'success', $this->data);
                exit();
            }
            list($userid, $userstatus, $uemail, $timetemp) = explode('|', $StrEncode);
            if ($session->user['email'] != $uemail) {
                return Doo::conf()->APP_URL . 'error/actemail';
            }
            if ((time() - $timetemp) > 86400) {
                return Doo::conf()->APP_URL . 'error/actemail';
            }
            if (empty($userstatus)) {
                return Doo::conf()->APP_URL . 'error/actemail';
            }
            if ($userid != $session->user['id']) {
                return Doo::conf()->APP_URL . 'error/actemail';
            }
            Doo::loadModel('users');
            $objuser = new Users();
            $objuser->actstate = 0;
            $RetValue = $objuser->update(array('where' => 'id=' . $session->user['id']));
            if ($RetValue)
                $session->user['status'] = null;
        }
        $this->data['name'] = $session->user['username'];
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->render($this->theme.'success', $this->data);
    }

    function activeUserDo() {
        $accode = $this->params['AuthStr'];
        if (empty($accode)) {
            return Doo::conf()->APP_URL . 'error/actUserError';
        }
        // 检测账号激活状态
        Doo::loadModel('userswitch');
        $userswitch = new UserSwitch();
        $usArray = $userswitch->getOne(array('where' => 'actcode=?', 'param' => array($accode), 'asArray' => TRUE));
        // $checkActCode = md5($usArray['uid'] . $usArray['rndcode']);
        if (!empty($usArray)) {
            if (!self::isUserActive($usArray['uid'])) {
                $userswitch->actime = time();
                $userswitch->update(array('where' => 'uid=?', 'param' => array($usArray['uid'])));
                Doo::loadModel('users');
                $user = new Users();
                $name = $user->getOne(array('select' => 'username,useremail', 'where' => 'id=?', 'param' => array($usArray['uid']), 'asArray' => TRUE));
            } else {
                return Doo::conf()->APP_URL . 'error/actived';
            }
        } else {
            return Doo::conf()->APP_URL . 'error/actUserError';
        }
        $this->data['name'] = $name['username'];
        $this->data['email'] = $name['useremail'];
        $this->render($this->theme.'success', $this->data);
    }

    function CheckNewEMail() {
//        ini_set('display_errors', on);
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if (empty($session->user['userquestion'])) {
            return Doo::conf()->APP_URL . 'safe';
        }
        $password = isset($_POST['password']) ? $_POST['password'] : NULL;
        $email = isset($_POST['email']) ? $_POST['email'] : NULL;
        if (!empty($email) && !empty($password) && $this->checkMail($email)) {
            if ($session->user['email'] == $_POST['email']) {
                $this->data['message'] = '邮箱已被注册';
            } else {
                if (!$this->checkExsitmail($email)) {
                    $this->data['message'] = '请尝试其他邮箱';
                    exit;
                }
                if ($session->user['password'] != $this->create_password($_POST['password'], $session->user['salt'])) {
                    $this->data['message'] = '请重新确认您输入的密码';
                    exit;
                }
                if ($this->sendmail($session->user['id'] . '|' . $_POST['email'] . '|' . time(), $_POST['email'])) {
                    $this->data['email'] = $_POST['email'];
                    $this->render($this->theme.'changeMail2', $this->data, TRUE);
                    die();
                } else {
                    $this->data['message'] = '发送失败，请联系管理员~';
                }
            }
        }
        $this->data['message'] = isset($this->data['message']) ? $this->data['message'] : NULL;
        $this->data['email'] = $session->user['email'];
        $this->data['name'] = $session->user['username'];
        $this->render($this->theme.'changeMail', $this->data, TRUE);
    }

    function CheckNewMobile() {
//        ini_set('display_errors', on);
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        $password = isset($_POST['password']) ? $_POST['password'] : NULL;
        $mobile = isset($_POST['zhmobile']) ? $_POST['zhmobile'] : NULL;
        $code = isset($_POST['zhsmscode']) ? $_POST['zhsmscode'] : NULL;
        if (!empty($mobile) && !empty($password) && !empty($code) && $this->checkMobile($mobile)) {
            if ($session->user['mobile'] == $_POST['zhmobile']) {
                $this->data['message'] = '该手机号码已被注册';
                return Doo::conf()->APP_URL . 'error/hadmobile';
                exit;
            } else {
                if (!$this->checkExsitMobile($mobile)) {
                    $this->data['message'] = '请尝试其他手机号';
                    return Doo::conf()->APP_URL . 'error/hadmobile';
                    exit;
                }
                if ($session->user['password'] != $this->create_password($_POST['password'], $session->user['salt'])) {
                    $this->data['message'] = '请重新确认您输入的密码';
                    return Doo::conf()->APP_URL . 'error/mima';
                    exit;
                }
                if(!$this->checkSmsCode($mobile,$code)){
                    $this->data['message'] = '验证码过期或不一致，请重新获取';
                    return Doo::conf()->APP_URL . 'error/mobile';
                    exit();
                }
                Doo::loadModel('users');
                $objuser = new Users();
                $objuser->mobile = $mobile;
                $RetValue = $objuser->update(array('where' => 'id=' . $session->user['id']));
                if ($RetValue){
                    $session->user['mobile'] = $mobile;
                    $this->data['mobile'] = $mobile;
                    $this->render($this->theme.'changeMobile2', $this->data, TRUE);
                    die();
                }else{
                    $this->data['message'] = '修改失败，请重试';
                    return Doo::conf()->APP_URL . 'error';
                    exit;
                }
            }
        }
        $this->data['message'] = isset($this->data['message']) ? $this->data['message'] : NULL;
        $this->data['mobile'] = $session->user['mobile'];
        $this->data['name'] = $session->user['username'];
        $this->render($this->theme.'changeMobile', $this->data, TRUE);
    }

    function AddMail(){
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if(!empty($_POST['email']) && !empty($_POST['password'])){

            if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
                $this->data['message'] = '邮箱格式出错';
                return Doo::conf()->APP_URL . 'error/erroremail';
                exit;
            }
            if (!$this->checkExsitmail($_POST['email'])) {
                $this->data['message'] = '邮箱已被注册';
                return Doo::conf()->APP_URL . 'error/userdemail';
                exit;
            }
            if ($session->user['password'] != $this->create_password($_POST['password'], $session->user['salt'])) {
                $this->data['message'] = '请重新确认您输入的密码';
                return Doo::conf()->APP_URL . 'error/mima';
                exit;
            }

            $userquestion = htmlspecialchars($_POST['zhq']);
            $defquestion = addslashes(htmlspecialchars($_POST['defq']));
            $useranswer = addslashes(htmlspecialchars($_POST['zhanswer']));
            Doo::loadModel('users');
            $users = new Users();
            $users->useremail = $_POST['email'];
            $users->userquestion = $userquestion;
            $users->defquestion = $defquestion;
            $users->useranswer = $useranswer;
            $RetValue = $users->update(array('where' => 'id=' . $session->user['id']));
            // 新注册用户加入待激活列表
            $rndcode = $this->create_randomstr();
            $acode = md5($session->user['id'] . $rndcode);
            Doo::loadModel('userswitch');
            $UserSwitch = new UserSwitch();
            $UserSwitch->userAdd($session->user['id'], $acode, $rndcode);
            if ($RetValue){
                $session->user['defquestion'] = $defquestion;
                $session->user['userquestion'] = $userquestion;
                $session->user['answer'] = $useranswer;
                $session->user['email'] = $_POST['email'];
            }

            $StrSubject = '纵横通行帐号-请激活您的帐号';
            $StrContent = '<table style="width:100%">
			<tbody>
				<tr><td>
					<p>感谢您注册成为纵横通行帐号的会员。在使用我们提供的服务之前，请点击以下链接，或将以下链接复制到浏览器的地址栏中打开，以激活您的帐户：</p>
					<p style="width:600px"><br><a href="' . Doo::conf()->APP_URL . 'actuser/' . $acode . '">' . Doo::conf()->APP_URL . 'actuser/' . $acode . '</a></p>
					<p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
					<p><br>纵横通行帐号与你共成长！</p>
					<p>' . date('Y年m月d日', time()) . '</p>
					<p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
				</td></tr>
			</tbody>
		</table>';
            @$this->SMail($_POST['email'], $StrSubject, $StrContent);
            $this->data['email'] = $_POST['email'];
            $this->render($this->theme.'changeMail2', $this->data, TRUE);
            die();

        }
        $this->data['name'] = $session->user['username'];
        $this->data['message'] = isset($this->data['message']) ? $this->data['message'] : NULL;
        $this->render($this->theme.'addMail', $this->data, TRUE);
    }

    function AddMobile(){
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        $password = isset($_POST['password']) ? $_POST['password'] : NULL;
        $mobile = isset($_POST['zhmobile']) ? $_POST['zhmobile'] : NULL;
        $code = isset($_POST['zhsmscode']) ? $_POST['zhsmscode'] : NULL;
        if (!empty($mobile) && !empty($password) && !empty($code) && $this->checkMobile($mobile)) {
            if ($session->user['mobile'] == $_POST['zhmobile']) {
                $this->data['message'] = '该手机号码已被注册';
                return Doo::conf()->APP_URL . 'error/hadmobile';
                exit;
            } else {
                if (!$this->checkExsitMobile($mobile)) {
                    $this->data['message'] = '请尝试其他手机号';
                    return Doo::conf()->APP_URL . 'error/hadmobile';
                    exit;
                }
                if ($session->user['password'] != $this->create_password($_POST['password'], $session->user['salt'])) {
                    $this->data['message'] = '请重新确认您输入的密码';
                    return Doo::conf()->APP_URL . 'error/mima';
                    exit;
                }
                if(!$this->checkSmsCode($mobile,$code)){
                    $this->data['message'] = '验证码过期或不一致，请重新获取';
                    return Doo::conf()->APP_URL . 'error/mobile';
                    exit();
                }
                Doo::loadModel('users');
                $objuser = new Users();
                $objuser->mobile = $mobile;
                $RetValue = $objuser->update(array('where' => 'id=' . $session->user['id']));
                if ($RetValue){
                    $session->user['mobile'] = $mobile;
//                    $this->data['mobile'] = $mobile;
                    return Doo::conf()->APP_URL . 'notic/addmobile';
//                    $this->render($this->theme.'addMobile2', $this->data, TRUE);
                    die();
                }else{
                    $this->data['message'] = '修改失败，请重试';
                    return Doo::conf()->APP_URL . 'error';
                    exit;
                }
            }
        }
        $this->data['name'] = $session->user['username'];
        $this->data['message'] = isset($this->data['message']) ? $this->data['message'] : NULL;
        $this->render($this->theme.'addMobile', $this->data, TRUE);
    }

// Email发送函数
    function sendmail($StrEncodeAuth, $toemail) {
        Doo::loadClass('class.phpmailer');
        $mail = new PHPMailer();
        $mail->From = "websupport@smartcost.com.cn"; //发送邮箱全名
        $mail->FromName = "=?UTF-8?B?" . base64_encode("纵横知道·通行证") . "?="; //发送人昵称
        $mail->Username = "postmaster@websupport.sendcloud.org"; //用户名
        $mail->Password = "cDO1GjtY1seH"; //密码
        $mail->CharSet = "UTF8";
        $mail->SMTPAuth = true;
        $mail->Host = "smtpcloud.sohu.com"; //邮件主机的smtp地址
        $mail->Port = 25;
        $mail->Mailer = "smtp";
        $mail->Subject = "=?UTF-8?B?" . base64_encode('纵横通行帐号-修改邮箱确认') . "?=";
        $tmplate = '
            <table style="width:100%">
			<tbody>
				<tr><td>
					<p>您对通行帐号进行了修改邮箱操作，请点击以下链接，或将以下链接复制到浏览器的地址栏中打开，以验证您的新邮箱：</p>
					<p style="width:600px"><br><a href="' . Doo::conf()->APP_URL . 'ChangEmail/' . base64_encode($this->authcode($StrEncodeAuth, 'ENCODE')) . '">' . Doo::conf()->APP_URL . 'ChangEmail/' . base64_encode($this->authcode($StrEncodeAuth, 'ENCODE')) . '</a></p>
					<p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
					<p><br>纵横通行帐号与你共成长！</p>
					<p>' . date('Y年m月d日', time()) . '</p>
					<p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
				</td></tr>
			</tbody>
		</table>';
        $mail->MsgHTML($tmplate);
        $mail->AddAddress($toemail);
        $mail->CharSet = "UTF-8";
        return $mail->Send();
    }

// Email发送函数
    function SMail($toemail, $subject, $contents) {
        Doo::loadClass('class.phpmailer');
        $mail = new PHPMailer();
        $mail->From = "websupport@smartcost.com.cn"; //发送邮箱全名
        $mail->FromName = "=?UTF-8?B?" . base64_encode("纵横知道·通行证") . "?="; //发送人昵称
        $mail->Username = "postmaster@websupport.sendcloud.org"; //用户名
        $mail->Password = "cDO1GjtY1seH"; //密码
        $mail->CharSet = "UTF8";
        $mail->SMTPAuth = true;
        $mail->Host = "smtpcloud.sohu.com"; //邮件主机的smtp地址
        $mail->Mailer = "smtp";
        $mail->Port = 25;
        $mail->Subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";
        $mail->MsgHTML($contents);
        $mail->AddAddress($toemail);
        $mail->CharSet = "UTF-8";
        return $mail->Send();
    }

// 变更邮箱第二步
    function ChangEmail() {
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if (empty($session->user['userquestion'])) {
            return Doo::conf()->APP_URL . 'safe';
        }
        $StrEncode = $this->authcode(base64_decode($this->params['AuthStr']), 'DECODE');
        if (empty($StrEncode))
            return Doo::conf()->APP_URL . 'error/actemail';
        list($userid, $useremail, $timetemp) = explode('|', $StrEncode);
        if ((time() - $timetemp) > 86400) {
            return Doo::conf()->APP_URL . 'error/actemail';
        }
        if (!$this->checkMail($useremail)) {
            return Doo::conf()->APP_URL . 'error/actemail';
        }
        if ($userid != $session->user['id']) {
            return Doo::conf()->APP_URL . 'error/actemail';
        }
        if ($useremail == $session->user['email']) {
            return Doo::conf()->APP_URL . 'error/actemail';
        }
        Doo::loadModel('users');
        $objuser = new Users();
        $objuser->useremail = $useremail;
        $RetValue = $objuser->update(array('where' => 'id=' . $session->user['id']));
        if ($RetValue)
            $session->user['email'] = $useremail;
        $this->data['email'] = $useremail;
        $this->render($this->theme.'changeMail3', $this->data);
    }

    function secmail() {
        // TODO:切换新邮箱未发送此激活邮箱的激活邮件
        // TODO:检测已存在邮箱与
        $session = Doo::session("sso");
        if ($session->user['status'] == 0) {
            return Doo::conf()->APP_URL;
        }
        if (!empty($_POST['sendsubmit'])) {
            $StrSubject = '纵横通行帐号-修改邮箱确认';
            $StrContent = '<table style="width:100%">
			<tbody>
				<tr>
                                    <td>
                                            <p>您对通行帐号进行了修改邮箱操作，请点击以下链接，或将以下链接复制到浏览器的地址栏中打开，以验证您的新邮箱：</p>
                                            <p style="width:600px"><br><a href="' . Doo::conf()->APP_URL . 'ActEmail/' . base64_encode($this->authcode($session->user['id'] . '|' . $session->user['status'] . '|' . $session->user['email'] . '|' . time(), 'ENCODE')) . '">' . Doo::conf()->APP_URL . 'ActEmail/' . base64_encode($this->authcode($session->user['id'] . '|' . $session->user['status'] . '|' . $session->user['email'] . '|' . time(), 'ENCODE')) . '</a></p>
                                            <p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
                                            <p><br>纵横通行帐号与你共成长！</p>
                                            <p>' . date('Y年m月d日', time()) . '</p>
                                            <p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
                                    </td>
                                </tr>
			</tbody>
		</table>';
            $this->SMail($session->user['email'], $StrSubject, $StrContent);
//                return Doo::conf()->APP_URL . 'sec';
        }
        if (!empty($_POST['email']))
            if ($this->checkMail($_POST['email']) && !empty($_POST['email']) && ($_POST['email'] != $session->user['email'])) {
                Doo::loadModel('users');
                $objuser = new Users();
                $objuser->useremail = $_POST['email'];
                $RetValue = $objuser->update(array('where' => 'id=' . $session->user['id']));
                if ($RetValue)
                    $session->user['email'] = $_POST['email'];
                $StrSubject = '纵横通行帐号-修改邮箱确认';
                $StrContent = '<table style="width:100%">
			<tbody>
				<tr>
                                    <td>
                                            <p>您对通行帐号进行了修改邮箱操作，请点击以下链接，或将以下链接复制到浏览器的地址栏中打开，以验证您的新邮箱：</p>
                                            <p style="width:600px"><br><a href="' . Doo::conf()->APP_URL . 'ActEmail/' . base64_encode($this->authcode($session->user['id'] . '|' . $session->user['status'] . '|' . $session->user['email'] . '|' . time(), 'ENCODE')) . '">' . Doo::conf()->APP_URL . 'ActEmail/' . base64_encode($this->authcode($session->user['id'] . '|' . $session->user['status'] . '|' . $session->user['email'] . '|' . time(), 'ENCODE')) . '</a></p>
                                            <p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
                                            <p><br>纵横通行帐号与你共成长！</p>
                                            <p>' . date('Y年m月d日', time()) . '</p>
                                            <p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
                                    </td>
                                </tr>
			</tbody>
		</table>';
                if ($this->SMail($session->user['email'], $StrSubject, $StrContent)) {
                    return Doo::conf()->APP_URL . 'sec';
                }
            }
        $this->data['email'] = isset($session->user['email']) ? $session->user['email'] : NULL;
        $this->render($this->theme.'register2', $this->data);
    }

    function profile() {
        $session = Doo::session("sso");
        if (!isset($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if ($this->checkUserQuestion($session->user['id']) && (!isset($session->user['mobile']) && empty($session->user['mobile'])))
            return Doo::conf()->APP_URL . 'safe';
        if (!empty($_POST['sendsubmit'])) {
            if (self::isUserActive($session->user['id']))
                return Doo::conf()->APP_URL . 'error/actuser';
            Doo::loadModel('userswitch');
            $UserSwitch = new UserSwitch();
            $usArray = $UserSwitch->getOne(array('where' => 'uid=?', 'param' => array($session->user['id']), 'asArray' => TRUE));
            $StrSubject = '纵横通行帐号-请激活您的帐号';
            $StrContent = '<table style="width:100%">
			<tbody>
				<tr>
                                    <td>
                                            <p>感谢您注册成为纵横通行帐号的会员。在使用我们提供的服务之前，请点击以下链接，或将以下链接复制到浏览器的地址栏中打开，以激活您的帐户：</p>
                                            <p style="width:600px"><br><a href="' . Doo::conf()->APP_URL . 'actuser/' . $usArray['actcode'] . '">' . Doo::conf()->APP_URL . 'actuser/' . $usArray['actcode'] . '</a></p>
                                            <p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
                                            <p><br>纵横通行帐号与你共成长！</p>
                                            <p>' . date('Y年m月d日', time()) . '</p>
                                            <p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
                                    </td>
                                </tr>
			</tbody>
		</table>';
            if ($this->SMail($session->user['email'], $StrSubject, $StrContent)) {
                return Doo::conf()->APP_URL . 'error/isact';
            }
        }
        Doo::loadModel('users');
        $users = new Users();
        $valuebank = $users->getRowByUid($session->user['id']);
        $this->data['bank'] = isset($valuebank[0]['bank']) ? $valuebank[0]['bank'] : 0;
        $this->data['name'] = $session->user['username'];
//        $this->data['avatar'] = $this->url_exists($this->ps_getavatar($session->user['id'])) ? $this->ps_getavatar($session->user['id']) : Doo::conf()->APP_URL . 'global/img/avatra48.png';
		if(isset($session->user['id'])){
            $this->data['avatar'] = $this->ps_getavatar($session->user['id']);
		}else{
            $this->data['avatar'] = Doo::conf()->APP_URL . 'global/img/avatra48.png';
		}
        $this->data['regdate'] = $session->user['regdate'];
        $this->data['email'] = $session->user['email'];
        $this->data['mobile'] = $session->user['mobile'];
//        $this->data['status'] = $session->user['status'];
        $this->data['status'] = self::isUserActive($session->user['id']);
        $this->data['FUN'] =  __FUNCTION__;
        $this->render($this->theme.'profile', $this->data, TRUE);
    }

    private function url_exists($url) {
        $h = get_headers($url);
        if (!$h || !isset($h[0]))
            return false;
        $status = $h[0];
        return preg_match("/.*200\s{1}OK/i", $status) ? true : false;
    }


    function chpasswd() {
        // TODO:变更密码后更新SESSION中数据
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if (empty($session->user['userquestion']) && empty($session->user['mobile'])) {
            return Doo::conf()->APP_URL . 'safe';
        }
        $this->data['erroT']="";
        $this->data['erroTxt']='';
        $this->data['aerroT']="";
        $this->data['aerroTxt']='';
        $this->data['defquestion'] = null;
        $this->data['mobile'] = !empty($session->user['mobile']) ? $session->user['mobile'] : '';
        $this->data['userquestion'] = !empty($session->user['userquestion']) ? $session->user['userquestion'] : '';
        $this->data['name'] = $session->user['username'];
        if (!empty($session->user['defquestion']) || ($session->user['userquestion'] == 6))
            $this->data['defquestion'] = $session->user['defquestion'];
        if (!empty($session->user['userquestion']) && ($session->user['userquestion'] != 6))
            $this->data['defquestion'] = $this->QArray[$session->user['userquestion']];
        if (!empty($_POST['subchpwd'])) {
            if(isset($_POST['answer']) && !empty($_POST['answer'])){
                if($session->user['answer'] == $_POST['answer']){
                    $action = 1;
                }else{
                    $this->data['erroT']="";
                    $this->data['erroTxt']='';
                    $this->data['aerroT']="erroT";
                    $this->data['aerroTxt']='<span for="oldpwd" generated="true" class="erroT" style="">输入的答案错误</span>';
                    $this->render($this->theme.'changePassword', $this->data);die;
                }
            }elseif(isset($_POST['zhsmscode']) && !empty($_POST['zhsmscode'])){
                if($this->checkSmsCode($session->user['mobile'],$_POST['zhsmscode'])){
                    $action = 2;
                }else{
                    $this->data['erroT']="";
                    $this->data['erroTxt']='';
                    $this->data['aerroT']="erroT";
                    $this->data['aerroTxt']='<span for="oldpwd" generated="true" class="erroT" style="">验证码过期或不一致，请重新获取</span>';
                    $this->render($this->theme.'changePassword', $this->data);die;
                }
            }else{
                $this->data['erroT']="";
                $this->data['erroTxt']='';
                $this->data['aerroT']="erroT";
                $this->data['aerroTxt']='<span for="oldpwd" generated="true" class="erroT" style="">请输入密保答案或手机验证码</span>';
                $this->render($this->theme.'changePassword', $this->data);die;
            }
            if (($session->user['password'] == $this->create_password($_POST['oldpwd'], $session->user['salt']))) {
                Doo::loadModel('users');
                $objuser = new Users();
//                $objuser->id = $session->user['id'];
                $objuser->userpasswd = $this->create_password($_POST['newpwd'], $session->user['salt']);
//                $objuser->useranswer = $session->user['password'];
//                $AryUser[] = $objuser;
                $objuser->update(array('where' => 'useranswer=\'' . $session->user['answer'] . '\' and id=' . $session->user['id']));
                if($action == 1){
                    $StrSubject = '纵横通行帐号提醒您：您的帐号修改了新密码';
                    $StrContent = '<table style="width:100%">
                        		<tbody>
                        			<tr><td>
                        				<p>尊敬的' . $session->user['username'] . ':</p>
                        				<p><br>您的通行帐号修改了新的密码</p>
                        				<p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
                        				<p><br>纵横通行帐号与你共成长！</p>
                        				<p>' . date('Y年m月d日', time()) . '</p>
                        				<p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
                        			</td></tr>
                            		</tbody>
                            	</table>';
                    $this->SMail($session->user['email'], $StrSubject, $StrContent);
                }elseif($action == 2){

                }
                setcookie(Doo::conf()->COOKIEPRE . 'auth');
                $session->user = array();
                return $this->logout('msgRelogin');
            }elseif($session->user['password'] != $this->create_password($_POST['oldpwd'], $session->user['salt'])){
            	$this->data['erroT']="erroT";
            	$this->data['erroTxt']='<span for="oldpwd" generated="true" class="erroT" style="">输入密码有误</span>';
            	$this->data['aerroT']="";
            	$this->data['aerroTxt']='';
            	$this->render($this->theme.'changePassword', $this->data);die;
            }

//            echo $session->user['id'];
        }
        $this->render($this->theme.'changePassword', $this->data);
    }


// 加密
    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));
        }
    }

    /**
     * 管理登出
     */
    function logout($msg=null) {
        $session = Doo::session("sso");
        unset($session->user);
        session_destroy();
        setcookie(Doo::conf()->COOKIEPRE . 'auth', null, 0, '/', Doo::conf()->APP_URL, 0);
        setcookie(Doo::conf()->COOKIEPRE . '_userid', null, 0, '/', Doo::conf()->APP_URL, 0);
        setcookie(Doo::conf()->COOKIEPRE . '_username', null, 0, '/', Doo::conf()->APP_URL, 0);
        if(!empty($msg)){
            return Doo::conf()->APP_URL . 'notic/relogin';
        }else{
            return Doo::conf()->APP_URL . 'msg/logout';
        }
    }
    // 检测Email格式
    function checkMail($email) {
        //if (strlen($email) > 6 && preg_match('/^([\w-]+\.?)*\w+@[\w-]+\.[a-z]{2,6}$/', $email)) {
                if (filter_var($email, FILTER_VALIDATE_EMAIL)){
            return TRUE;
        } else {
            return FALSE;
        }
    }
    // 检测手机格式
    function checkMobile($mobile) {
        if(preg_match("/^1[34578]{1}\d{9}$/",$mobile)){
            return TRUE;
        } else {
            return FALSE;
        }
    }
    function checkhadmobile() {
        // TODO:检测手机号是否已注册通行账号
        if (!empty($_POST['zhmobile'])){

        }
    }

    function checkuser() {
        if (!empty($_POST['zhemail']))
            $checkemail = $_POST['zhemail'];
        if (!empty($_POST['zhuser']))
            $checkuser = $_POST['zhuser'];
        if(!empty($_POST['zhmobile']))
            $checkmobile = $_POST['zhmobile'];
        if(!empty($_POST['zhsmscode']))
            $checkcode = $_POST['zhsmscode'];
        if (!empty($_POST['zhmuser']))
            $checkuser = $_POST['zhmuser'];
        if (!empty($_POST['password']))
            $checkpassword = $_POST['password'];
        if (!empty($checkemail))
            if ($this->checkMail($checkemail)) {
                $user = Doo::db()->find('users', array(
                    'select' => 'id',
                    'where' => 'useremail=?',
                    'param' => array($checkemail),
                        )
                );
                if (empty($user)) {
                    exit('true');
                } else {
                    exit('false');
                }
            }
        if (!empty($checkuser))
            if ($checkuser) {
                // TODO:判断是否符合账号规则
                $user = Doo::db()->find('users', array(
                    'select' => 'id',
                    'where' => 'username=?',
                    'param' => array($checkuser),
                        )
                );
                if (empty($user)) {
                    exit('true');
                } else {
                    exit('false');
                }
            }
        if(!empty($checkcode) && !empty($checkmobile)){
            //TODO:检测验证码
            if($checkmobile && $checkcode) {
                $now = time();
                $old = $now-1800;
                Doo::loadModel('mobilecode');
                $mobilecode = new mobilecode();
                $code = $mobilecode->find(array(
                    'select' => 'id',
                    'where' => 'mobile='.$checkmobile.' and code='.$checkcode.' and time between '.$old.' and '.$now,
                    'desc' => 'id',
                    'limit' => 1,
                    'asArray' => true
                ));
                if ($code) {
                    exit('true');
                } else {
                    exit('false');
                }
            }
        }
        if(!empty($checkmobile)){
            if($checkmobile) {
                // TODO:判断是否符合电话并且未注册
                $user = Doo::db()->find('users', array(
                        'select' => 'id',
                        'where' => 'mobile=?',
                        'param' => array($checkmobile),
                    )
                );
                if (empty($user)) {
                    exit('true');
                } else {
                    exit('false');
                }
            }
        }
        if(!empty($checkpassword)){
            if($checkpassword) {
                $session = Doo::session("sso");
                if ($session->user['password'] == $this->create_password($checkpassword, $session->user['salt'])) {
                    exit('true');
                }else{
                    exit('false');
                }
            }
        }
    }

    function checkphone(){
        if(!empty($_POST['zhmobile']))
            $checkmobile = $_POST['zhmobile'];
        if(!empty($checkmobile)){
            if($checkmobile) {
                // TODO:判断是否符合电话并且已注册
                $user = Doo::db()->find('users', array(
                        'select' => 'id',
                        'where' => 'mobile=?',
                        'param' => array($checkmobile),
                    )
                );
                if (!empty($user)) {
                    exit('true');
                } else {
                    exit('false');
                }
            }
        }
    }

    public function checkemail() {
        //TODO:其实检测唯一性就已经检测了当前用户Email
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        $newEmail = isset($_POST['email']) ? $_POST['email'] : NULL;
        if (!empty($newEmail) && $this->checkMail($newEmail)) {
            $session = Doo::session("sso");
            if ($newEmail == $session->user['email']) {
                exit('false');
            }
            if (!$this->checkExsitmail($newEmail)) {
                exit('false');
            }
        }
        exit('true');
    }

    public function alipay(){
     	$session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
    	if (!empty($_POST['remark2'])) {
			Doo::loadModel('m/sale');
            $saleObj = new Sale();
            $rowNumber = $saleObj->count(array('where'=>'promocode=?','param' => array($_POST['remark2']),'asArray'=>TRUE));
            if($rowNumber){
                $this->data['remark2'] = $_POST['remark2'];
            }else{
                $this->data['remark2'] = NULL;
            }
        } else {
            $this->data['remark2'] = NULL;
        }
    	
    	require_once(Doo::conf()->SITE_PATH."protected/class/alipay/alipay.config.php");
		require_once(Doo::conf()->SITE_PATH."protected/class/alipay/lib/alipay_submit.class.php");
    	
		$alipaySubmit = new AlipaySubmit($alipay_config);
		
        $payment_type = "1";
        $notify_url = Doo::conf()->APP_URL."api/smartcost/sso/notify_url.php";
        $return_url = Doo::conf()->APP_URL."api/smartcost/sso/return_url.php";
        
        //商户订单号
        $sn=$this->create_sn();
        $out_trade_no = $sn;
        $subject = '纵横通行账户充值';
     	$extra_common_param=$this->data['remark2']; //用户自定义回传参数
        //付款金额
        $p_amount=trim($_POST['p_amount']);
        $total_fee = $p_amount;
        $body = '';
        $show_url = '';
    
        //防钓鱼时间戳
        $anti_phishing_key = $alipaySubmit->query_timestamp();
        $exter_invoke_ip = $this->clientIP();
		
		
		//构造要请求的参数数组，无需改动
		$parameter = array(
				"service" => "create_direct_pay_by_user",
				"partner" => trim($alipay_config['partner']),
				"seller_email" => trim($alipay_config['seller_email']),
				"payment_type"	=> $payment_type,
				"notify_url"	=> $notify_url,
				"return_url"	=> $return_url,
				"out_trade_no"	=> $out_trade_no,
				"subject"	=> $subject,
				"total_fee"	=> $total_fee,
				"body"	=> $body,
				"show_url"	=> $show_url,
				"anti_phishing_key"	=> $anti_phishing_key,
				"exter_invoke_ip"	=> $exter_invoke_ip,
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
				"extra_common_param"=> $extra_common_param
		);
		
		//建立请求
		
		$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "加载中");
		
		// 生成订单
        Doo::loadModel('pay');
        $pay = new Pay();
        $array = array('trade_sn' => $sn, 
        		'userid' => $session->user['id'], 
        		'username' => $session->user['username'], 
        		'telephone' => $this->data['remark2'], 
        		'money' => $p_amount, 
        		'addtime' => time(), 
        		'usernote' => $session->user['username'] . '[' . $sn . ']', 
        		'pay_type' => 'alipay', 
        		'payment' => '支付宝', 
        		'ip' => $this->clientIP(), 
        		'status' => 'unpay'
        		);
        $pay->add($array);
		header("Content-type: text/html; charset=utf-8"); 
		echo $html_text;
    }
    
    function returnAlipay(){
     	$session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
    	require_once(Doo::conf()->SITE_PATH."protected/class/alipay/alipay.config.php");
		require_once(Doo::conf()->SITE_PATH."protected/class/alipay/lib/alipay_notify.class.php");

		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyReturn();
		if($verify_result) {
			$v_oid = $_GET['out_trade_no'];	//商户订单号
			$trade_no = $_GET['trade_no'];			//支付宝交易号
			$trade_status = $_GET['trade_status'];	//交易状态
			$v_amount=$_GET['total_fee'];			//交易金额
			$remark2 = $_GET['extra_common_param']; 
			
		    if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
		    	
		    	$pay = Doo::loadModel('pay', TRUE);
                $callbackData = $pay->getRowsBySN($v_oid);
                if ($callbackData['status'] == 'unpay') {
                    if ($callbackData['money'] == $v_amount) {
                        $pay->trade_sn = $v_oid;
                        $comment = $pay->find(array('limit' => 1, 'select' => 'id', 'asArray' => TRUE));
                        $pay->id = $comment['id'];
                        $pay->paytime = time();
                        $pay->status = 'succ';
                        $succvalue = $pay->update();

                        if ($succvalue) {
                            // 增加销售人员提成与折扣
                            if(!empty($remark2)&&($v_amount>=$this->cashlimit)){
                                $salerGet = floor($v_amount*$this->salelimit); // 计算销售人员获得的提成
                                $v_amount += floor($v_amount*$this->perlimit); // 计算输入优惠码的最终充值金额
                                Doo::loadModel('m/sale');
                                $saleObj = new Sale();
                                $saleObj->total = new DooDbExpression('total+' . $salerGet);
                                $saleObj->update(array('where'=>'promocode=?','param'=>array($remark2)));
                            }
                            Doo::loadModel('users');
                            $users = new Users();
                            $moneyValue = $users->updateBank($callbackData['userid'], $v_amount);
                            if ($moneyValue) {
                                $this->data['msg'] = '充值完成';
                                header('refresh:3;url=/');
                            }
                            //发送邮件
					        include ('./protected/class/email_templete.file.php');
					        
					        //获取文档  $callbackData['userid']
						    $userinfo=$users->getRowByUid( $callbackData['userid']);
					        //$v_amount , $v_oid
					        $templete_email=$this->format_email_content($email_file['RECHARGE_SUCCESS'], "RECHARGE_SUCCESS",$v_amount,$userinfo,$v_oid);
					        	
					        //$templete_email['toemail']="cpthought@vip.qq.com";
					        if(filter_var($templete_email['toemail'], FILTER_VALIDATE_EMAIL))
					        	$this->_mail($templete_email['templete'],$templete_email['subject'],$templete_email['toemail']);
                        }
                    } 
                } else {
                    $this->data['msg'] = '已充值完毕，操作无效';
                    header('refresh:3;url=/');
                }
		    }
		}else {
		    $this->data['msg'] = '充值故障';
            header('refresh:3;url=/');
		}
		$this->render($this->theme.'recharge_msg', $this->data, TRUE);
    }
    
	function notifyAlipay(){
    	require_once(Doo::conf()->SITE_PATH."protected/class/alipay/alipay.config.php");
		require_once(Doo::conf()->SITE_PATH."protected/class/alipay/lib/alipay_notify.class.php");

		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if($verify_result) {
			$v_oid = $_POST['out_trade_no'];	//商户订单号
			$trade_no = $_POST['trade_no'];			//支付宝交易号
			$trade_status = $_POST['trade_status'];	//交易状态
			$v_amount=$_POST['total_fee'];			//交易金额
			$remark2 = $_POST['extra_common_param']; 
			
		    if($_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS') {
		    	
		    	$pay = Doo::loadModel('pay', TRUE);
                $callbackData = $pay->getRowsBySN($v_oid);
                if ($callbackData['status'] == 'unpay') {
                    if ($callbackData['money'] == $v_amount) {
                        $pay->trade_sn = $v_oid;
                        $comment = $pay->find(array('limit' => 1, 'select' => 'id', 'asArray' => TRUE));
                        $pay->id = $comment['id'];
                        $pay->paytime = time();
                        $pay->status = 'succ';
                        $succvalue = $pay->update();
                        if ($succvalue) {
                            // 增加销售人员提成与折扣
                            if(!empty($remark2)&&($v_amount>=$this->cashlimit)){
                                $salerGet = floor($v_amount*$this->salelimit); // 计算销售人员获得的提成
                                $v_amount += floor($v_amount*$this->perlimit); // 计算输入优惠码的最终充值金额
                                Doo::loadModel('m/sale');
                                $saleObj = new Sale();
                                $saleObj->total = new DooDbExpression('total+' . $salerGet);
                                $saleObj->update(array('where'=>'promocode=?','param'=>array($remark2)));
                            }
                            Doo::loadModel('users');
                            $users = new Users();
                            $moneyValue = $users->updateBank($callbackData['userid'], $v_amount);
                            if ($moneyValue) {
                                Doo::loadModel('income_pay');
                                $incomepay = new IncomePay();
                                $incomepay->uid = $callbackData['userid'];
                                $incomepay->money = $v_amount;
                                $incomepay->type = 1;
                                $incomepay->comefrom = '支付宝';
                                $incomepay->addtime = time();
                                $incomepay->insert();
                                echo "success"; die;
                            }
                            //发送邮件
					        include ('./protected/class/email_templete.file.php');
					        
					        //获取文档  $callbackData['userid']
						    $userinfo=$users->getRowByUid( $callbackData['userid']);
					        //$v_amount , $v_oid
					        $templete_email=$this->format_email_content($email_file['RECHARGE_SUCCESS'], "RECHARGE_SUCCESS",$v_amount,$userinfo,$v_oid);
					        	
					        //$templete_email['toemail']="cpthought@vip.qq.com";
					        if(filter_var($templete_email['toemail'], FILTER_VALIDATE_EMAIL))
					        	$this->_mail($templete_email['templete'],$templete_email['subject'],$templete_email['toemail']);
                        }
                    } 
                } 
		    }
		    echo "success";
		}else {
		    echo "fail";
		}
    }
    
    public function deposit2() {
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        $sn = $this->create_sn();
        if (isset($_POST['isubmit']) && isset($_POST['ibank']) && is_numeric($_POST['ibank'])) {
            $money = intval($_POST['ibank']);
//            if (preg_match('/^1[3458][0-9]{9}$/', $_POST['remark2'])) {
	        if (!empty($_POST['remark2'])) {
                Doo::loadModel('m/sale');
                $saleObj = new Sale();
                $rowNumber = $saleObj->count(array('where'=>'promocode=?','param' => array($_POST['remark2']),'asArray'=>TRUE));
                if($rowNumber){
                    $this->data['remark2'] = $_POST['remark2'];
                }else{
                    $this->data['remark2'] = NULL;
                }
            } else {
                $this->data['remark2'] = NULL;
            }
            Doo::loadModel('pay');
            $pay = new Pay();
            $array = array('trade_sn' => $sn, 'userid' => $session->user['id'], 'username' => $session->user['username'], 'money' => $money, 'telephone' => $this->data['remark2'], 'addtime' => time(), 'pay_type' => 'offline', 'payment' => '银行转账', 'ip' => $this->clientIP(), 'status' => 'waitting');
            $pay->add($array);
            $this->data['money'] = $money;
            // header('refresh:2;url=' . Doo::conf()->APP_URL . 'deposit');
            $this->render($this->theme.'bankConfirm', $this->data, TRUE);
            die();
        }
        Doo::loadModel('users');
        $users = new Users();
        $valuebank = $users->getRowByUid($session->user['id']);
        $this->data['bank'] = isset($valuebank[0]['bank']) ? $valuebank[0]['bank'] : 0;
        $this->data['sn'] = $sn;
        $this->data['usercat'] = NULL;
        $this->data['extmenu'] = 0;
        $this->data['FUN'] =  __FUNCTION__;
		if($session->user['id']){
		        $this->data['avatar'] = $this->ps_getavatar($session->user['id']);
		}else{
		        $this->data['avatar'] = Doo::conf()->APP_URL . 'global/img/avatra48.png';
		}
        $this->data['name'] = $session->user['username'];
        $this->render($this->theme.'recharge', $this->data, TRUE);
    }

    public function deposit3() {
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        $bankArray = array(
            /*'1025' => 'https://pay3.chinabank.com.cn/i/bank_gsyh2.gif',
            '308' => 'https://pay3.chinabank.com.cn/i/bank_zsyh2.gif',
            '105' => 'https://pay3.chinabank.com.cn/i/bank_jsyh2.gif',
            '103' => 'https://pay3.chinabank.com.cn/i/bank_nyyh2.gif',
            '104' => 'https://pay3.chinabank.com.cn/i/bank_zgyh2.gif',
            '301' => 'https://pay3.chinabank.com.cn/i/bank_jtyh.gif',
            '311' => 'https://pay3.chinabank.com.cn/i/bank_hxyh.gif',
            '309' => 'https://pay3.chinabank.com.cn/i/bank_xyyh.gif',
            '305' => 'https://pay3.chinabank.com.cn/i/bank_msyh2.gif',
            '306' => 'https://pay3.chinabank.com.cn/i/bank_gdfz.gif',
            '307' => 'https://pay3.chinabank.com.cn/i/bank_szfz.gif',
            '314' => 'https://pay3.chinabank.com.cn/i/bank_pfyh.gif',
            '313' => 'https://pay3.chinabank.com.cn/i/bank_zxyh.gif',
            '312' => 'https://pay3.chinabank.com.cn/i/bank_gdyh.gif',
            '316' => 'https://pay3.chinabank.com.cn/i/bank_njyh.gif',
            '317' => 'https://pay3.chinabank.com.cn/i/bank_bhyh.gif',
            '3279' => 'https://pay3.chinabank.com.cn/i/bank_psbc.gif',
            '327' => 'https://pay3.chinabank.com.cn/i/bank_unionpay.gif'*/
			'1025'=>'http://bank-logo.qiniudn.com/bank_gsyh2.gif',     
'308'=>'http://bank-logo.qiniudn.com/bank_zsyh2.gif',
'105'=>'http://bank-logo.qiniudn.com/bank_jsyh2.gif',
'103'=>'http://bank-logo.qiniudn.com/bank_nyyh2.gif',
'104'=>'http://bank-logo.qiniudn.com/bank_zgyh2.gif',
'301'=>'http://bank-logo.qiniudn.com/bank_jtyh.gif',
'311'=>'http://bank-logo.qiniudn.com/bank_hxyh.gif',
'309'=>'http://bank-logo.qiniudn.com/bank_xyyh.gif',
'305'=>'http://bank-logo.qiniudn.com/bank_msyh2.gif',
'306'=>'http://bank-logo.qiniudn.com/bank_gdfz.gif',
'307'=>'http://bank-logo.qiniudn.com/bank_payh.gif',
'314'=>'http://bank-logo.qiniudn.com/bank_pfyh.gif',
'313'=>'http://bank-logo.qiniudn.com/bank_zxyh.gif',
'312'=>'http://bank-logo.qiniudn.com/bank_gdyh.gif',
'316'=>'http://bank-logo.qiniudn.com/bank_njyh.gif',
'3230'=>'http://bank-logo.qiniudn.com/bank_psbc.gif',
'324'=>'http://bank-logo.qiniudn.com/bank_hangzhou.jpg', 
'302'=>'http://bank-logo.qiniudn.com/bank_nbyh.gif', 
'310'=>'http://bank-logo.qiniudn.com/bank_bj.gif',  
'342'=>'http://bank-logo.qiniudn.com/bank_CQRCB.gif', 
'343'=>'http://bank-logo.qiniudn.com/bank_SRCB.gif', 
'335'=>'http://bank-logo.qiniudn.com/bank_BJRCB.gif', 
'3341'=>'http://bank-logo.qiniudn.com/bank_QDCCB.gif', 
'336'=>'http://bank-logo.qiniudn.com/bank_BOCD.gif',
		);
        $banKey = array_keys($bankArray);
        if (isset($_POST['v_amount']) && isset($_POST['bank']) && in_array($_POST['bank'], $banKey)) {
            $this->data['v_amount'] = $_POST['v_amount'];
            $this->data['bankid'] = $_POST['bank'];
            $this->data['bankinfo'] = $bankArray[$this->data['bankid']];
        } else {
            return Doo::conf()->APP_URL . 'depositnew';
        }
        $this->data['usercat'] = NULL;
        $this->data['extmenu'] = 0;
        Doo::loadModel('users');
        $users = new Users();
        $valuebank = $users->getRowByUid($session->user['id']);
        $this->data['bank'] = isset($valuebank[0]['bank']) ? $valuebank[0]['bank'] : 0;
        $this->data['FUN'] =  __FUNCTION__;
		if($session->user['id']){
		        $this->data['avatar'] = $this->ps_getavatar($session->user['id']);
		}else{
		        $this->data['avatar'] = Doo::conf()->APP_URL . 'global/img/avatra48.png';
		}
        $this->render($this->theme.'recharge2', $this->data, TRUE);
    }

    /**
     * 生成流水号
     */
    function create_sn() {
        mt_srand((double) microtime() * 1000000);
        return date("YmdHis") . str_pad(mt_rand(1, 99999), 5, "0", STR_PAD_LEFT);
    }

    public function send() {
        // TODO：20130312
        // TODO：没有检验金额，是否额定
        // TODO：请求链接来源验证
        // TODO：防止暴力提交订单
        // TODO：检测是否存在为支付订单，防止重复提交
        // TODO：增加销售人员手机号作为优惠码20130503
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        $this->data['v_oid'] = $this->create_sn();
        $this->data['v_mid'] = '22544863';            // 商户号，这里为测试商户号1001，替换为自己的商户号(老版商户号为4位或5位,新版为8位)即可
        $this->data['v_url'] = 'http://sso.smartcost.com.cn/Receive'; // 请填写返回url,地址应为绝对路径,带有http协议
        $this->data['v_return'] = 'http://sso.smartcost.com.cn'; // 请填写返回url,地址应为绝对路径,带有http协议
        $this->data['key'] = 'smartcost@)!@onlinepaychinabank';            // 如果您还没有设置MD5密钥请登陆我们为您提供商户后台，地址：https://merchant3.chinabank.com.cn/
        $this->data['v_amount'] = trim($_POST['v_amount']);                   //支付金额
        $this->data['v_moneytype'] = "CNY";                                            //币种
        $this->data['text'] = $this->data['v_amount'] . $this->data['v_moneytype'] . $this->data['v_oid'] . $this->data['v_mid'] . $this->data['v_url'] . $this->data['key'];        //md5加密拼凑串,注意顺序不能变
        $this->data['v_md5info'] = strtoupper(md5($this->data['text']));                             //md5函数加密并转化成大写字母
        if (isset($_POST['bank'])) {
            $this->data['bank'] = trim($_POST['bank']);                             //md5函数加密并转化成大写字母
        } else {
            $this->data['bank'] = NULL;
        }
         // $this->data['remark2'] =  isset($_POST['remark2']) ? trim($_POST['remark2']) : NULL; //备注字段2
//        if (preg_match('/^1[3458][0-9]{9}$/', $_POST['remark2'])) {
		if (!empty($_POST['remark2'])) {
			Doo::loadModel('m/sale');
            $saleObj = new Sale();
            $rowNumber = $saleObj->count(array('where'=>'promocode=?','param' => array($_POST['remark2']),'asArray'=>TRUE));
            if($rowNumber){
                $this->data['remark2'] = $_POST['remark2'];
            }else{
                $this->data['remark2'] = NULL;
            }
        } else {
            $this->data['remark2'] = NULL;
        }
        // 生成订单
        Doo::loadModel('pay');
        $pay = new Pay();
        $array = array('trade_sn' => $this->data['v_oid'], 'userid' => $session->user['id'], 'username' => $session->user['username'], 'telephone' => $this->data['remark2'], 'money' => $this->data['v_amount'], 'addtime' => time(), 'usernote' => $session->user['username'] . '[' . $this->data['v_oid'] . ']', 'pay_type' => 'recharge', 'payment' => '网银在线', 'ip' => $this->clientIP(), 'status' => 'unpay','pay_id'=>$this->data['bank']);
        $pay->add($array);
        $this->data['remark1'] = $this->getUserName() . '[' . $this->data['v_oid'] . ']';      //备注字段1
        $this->data['v_rcvname'] = isset($_POST['v_rcvname']) ? trim($_POST['v_rcvname']) : NULL;  // 收货人
        $this->data['v_rcvaddr'] = isset($_POST['v_rcvaddr']) ? trim($_POST['v_rcvaddr']) : NULL;  // 收货地址
        $this->data['v_rcvtel'] = isset($_POST['v_rcvtel']) ? trim($_POST['v_rcvtel']) : NULL;  // 收货人电话
        $this->data['v_rcvpost'] = isset($_POST['v_rcvpost']) ? trim($_POST['v_rcvpost']) : NULL;  // 收货人邮编
        $this->data['v_rcvemail'] = isset($_POST['v_rcvemail']) ? trim($_POST['v_rcvemail']) : NULL;  // 收货人邮件
        $this->data['v_rcvmobile'] = isset($_POST['v_rcvmobile']) ? trim($_POST['v_rcvmobile']) : NULL;  // 收货人手机号

        $this->data['v_ordername'] = isset($_POST['v_ordername']) ? trim($_POST['v_ordername']) : NULL; // 订货人姓名
        $this->data['v_orderaddr'] = isset($_POST['v_orderaddr']) ? trim($_POST['v_orderaddr']) : NULL; // 订货人地址
        $this->data['v_ordertel'] = isset($_POST['v_ordertel']) ? trim($_POST['v_ordertel']) : NULL; // 订货人电话
        $this->data['v_orderpost'] = isset($_POST['v_orderpost']) ? trim($_POST['v_orderpost']) : NULL; // 订货人邮编
        $this->data['v_orderemail'] = isset($_POST['v_orderemail']) ? trim($_POST['v_orderemail']) : NULL; // 订货人邮件
        $this->data['v_ordermobile'] = isset($_POST['v_ordermobile']) ? trim($_POST['v_ordermobile']) : NULL; // 订货人手机号
        $this->render($this->theme.'send', $this->data, TRUE);
    }
    // 手动对账
    public function receive() {
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        $key = 'smartcost@)!@onlinepaychinabank';
        $v_oid = isset($_POST['v_oid']) ? trim($_POST['v_oid']) : NULL;       // 商户发送的v_oid定单编号
        $v_pmode = isset($_POST['v_pmode']) ? trim($_POST['v_pmode']) : NULL;    // 支付方式（字符串）
        $v_pstatus = isset($_POST['v_pstatus']) ? trim($_POST['v_pstatus']) : NULL;   //  支付状态 ：20（支付成功）；30（支付失败）
        $v_pstring = isset($_POST['v_pstring']) ? trim($_POST['v_pstring']) : NULL;   // 支付结果信息 ： 支付完成（当v_pstatus=20时）；失败原因（当v_pstatus=30时,字符串）；
        $v_amount = isset($_POST['v_amount']) ? trim($_POST['v_amount']) : NULL;     // 订单实际支付金额
        $v_moneytype = isset($_POST['v_moneytype']) ? trim($_POST['v_moneytype']) : NULL; //订单实际支付币种
        $remark1 = isset($_POST['remark1']) ? trim($_POST['remark1']) : NULL;      //备注字段1
        $remark2 = isset($_POST['remark2']) ? trim($_POST['remark2']) : NULL;     //备注字段2
        $v_md5str = isset($_POST['v_md5str']) ? trim($_POST['v_md5str']) : NULL;   //拼凑后的MD5校验值
//        echo $v_oid . '|' . $v_pstatus . '|' . $v_amount . '|' . $v_moneytype . '|' . $key;
        /**
         * 重新计算md5的值
         * // 增加优惠信息
         */
        $md5string = strtoupper(md5($v_oid . $v_pstatus . $v_amount . $v_moneytype . $key)); //拼凑加密串
        if ($v_md5str == $md5string) {
            if ($v_pstatus == '20') {
                $pay = Doo::loadModel('pay', TRUE);
                $callbackData = $pay->getRowsBySN($v_oid);
                if ($callbackData['status'] == 'unpay') {
                    if ($callbackData['money'] == $v_amount) {
                        $pay->trade_sn = $v_oid;
                        $comment = $pay->find(array('limit' => 1, 'select' => 'id', 'asArray' => TRUE));
                        $pay->id = $comment['id'];
                        $pay->paytime = time();
                        $pay->status = 'succ';
                        $succvalue = $pay->update();

                        Doo::loadModel('income_pay');
                        $incomepay = new IncomePay();
                        $incomepay->uid = $session->user['id'];
                        $incomepay->money = $v_amount;
                        $incomepay->type = 1;
                        $incomepay->comefrom = '网银在线';
                        $incomepay->addtime = time();
                        $incomepay->insert();
                        if ($succvalue) {
                            // 增加销售人员提成与折扣
                            if(!empty($remark2)&&($v_amount>=$this->cashlimit)){
                                $salerGet = floor($v_amount*$this->salelimit); // 计算销售人员获得的提成
                                $v_amount += floor($v_amount*$this->perlimit); // 计算输入优惠码的最终充值金额
                                Doo::loadModel('m/sale');
                                $saleObj = new Sale();
                                $saleObj->total = new DooDbExpression('total+' . $salerGet);
                                $saleObj->update(array('where'=>'promocode=?','param'=>array($remark2)));
                            }
                            Doo::loadModel('users');
                            $users = new Users();
                            $moneyValue = $users->updateBank($callbackData['userid'], $v_amount);
                            if ($moneyValue) {
                                $this->data['msg'] = '充值完成';
                                header('refresh:3;url=/');
                            }
                            //发送邮件
					        include ('./protected/class/email_templete.file.php');
					        
					        //获取文档  $callbackData['userid']
						    $userinfo=$users->getRowByUid( $callbackData['userid']);
					        //$v_amount , $v_oid
					        $templete_email=$this->format_email_content($email_file['RECHARGE_SUCCESS'], "RECHARGE_SUCCESS",$v_amount,$userinfo,$v_oid);
					        	
					        //$templete_email['toemail']="cpthought@vip.qq.com";
					        if(filter_var($templete_email['toemail'], FILTER_VALIDATE_EMAIL))
					        	$this->_mail($templete_email['templete'],$templete_email['subject'],$templete_email['toemail']);
                        }
                    } 
                } else {
                    $this->data['msg'] = '已充值完毕，操作无效';
                    header('refresh:3;url=/');
                }
            }
        } else {
            $this->data['msg'] = '充值故障';
            header('refresh:3;url=/');
        }
        $this->render($this->theme.'recharge_msg', $this->data, TRUE);
    }

    /**
     * 判断email格式是否正确
     * @param $string email
     */
    public function getUserID() {
        $userid = self::get_cookie('_userid');
        if ($userid) {
            return $userid;
        } else {
            return FALSE;
        }
    }

    public function getUserName() {
        $username = self::get_cookie('_username');
        if ($username) {
            return $username;
        } else {
            return FALSE;
        }
    }

    public function get_cookie($var, $default = '') {
        $varvar = Doo::conf()->COOKIEPRE . $var;
        return isset($_COOKIE[$varvar]) ? $this->authcode($_COOKIE[$varvar], 'DECODE') : $default;
    }

    public function issafe() {
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if ($this->checkUserQuestionExs($session->user['id'])) {
            return Doo::conf()->APP_URL . 'profile';
        }
        if (!empty($_POST['isubmit'])) {
            $userquestion = htmlspecialchars($_POST['zhq']);
            $defquestion = addslashes(htmlspecialchars($_POST['defq']));
            $useranswer = addslashes(htmlspecialchars($_POST['zhanswer']));
            if (in_array($userquestion, array(1, 2, 3, 4, 5, 6))) {
                Doo::loadModel('users');
                $users = new Users();
                if (($userquestion == 6) && !empty($defquestion)) {
                    $users->defquestion = $defquestion;
                }
                $users->userquestion = $userquestion;
                $users->useranswer = $useranswer;
                $users->update(array('where' => 'id=' . $session->user['id']));
                $session->user['userquestion'] = $userquestion;
                return Doo::conf()->APP_URL . 'profile';
            }
        }
        $this->data['avatar'] = $this->url_exists($this->ps_getavatar($session->user['id'])) ? $this->ps_getavatar($session->user['id']) : Doo::conf()->APP_URL . 'global/img/avatra48.png';
        $this->data['qArray'] = $this->QArray;
        $this->render($this->theme.'oldAunRe', $this->data, TRUE);
    }

    public function saveSafe() {
//        $data = array('str' => '你好测试一下好不好用', 1 => 2, 2 => 3);
////        var_dump($data);
//// serialize
//        $msg = msgpack_pack($data);
//
//// hexadecimal
//        $str = unpack('H*', $msg);
//        var_dump($str);
//// deserialize
////        $ret = msgpack_unpack($msg);
////        var_dump($ret);
        $this->data['qArray'] = $this->QArray;
        $this->render($this->theme.'oldAunRe', $this->data, TRUE);
    }

    public function pay() {
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        Doo::loadModel('users');
        $users = new Users();
        $valuebank = $users->getRowByUid($session->user['id']);
        $this->data['bank'] = isset($valuebank[0]['bank']) ? $valuebank[0]['bank'] : 0;
        $this->data['name'] = $session->user['username'];
        $this->data['avatar'] = $this->url_exists($this->ps_getavatar($session->user['id'])) ? $this->ps_getavatar($session->user['id']) : Doo::conf()->APP_URL . 'global/img/avatra48.png';
        $this->render($this->theme.'toCash2', $this->data, TRUE);
    }

    public function ps_getavatar($uid) {
        $dir1 = ceil($uid / 10000);
        $dir2 = ceil($uid % 10000 / 1000);
        $url = Doo::conf()->APP_URL . 'data/avatar/' . $dir1 . '/' . $dir2 . '/' . $uid . '/';
        $avatar = array('180' => $url . '180x180.jpg', '90' => $url . '90x90.jpg', '45' => $url . '45x45.jpg', '30' => $url . '30x30.jpg');
        return $avatar['45'];
    }

// Not activated 未激活状态更改邮箱
    public function nactChangMail() {
        $session = Doo::session("sso");
        $this->data['name'] = $session->user['username'];
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if (self::isUserActive($session->user['id']))
            return Doo::conf()->APP_URL . 'error/actuser';
        if (isset($_POST['isubmit'])) {
            $ismail = $this->checkMail($_POST['nactmail']);
            if (!$ismail)
                return Doo::conf()->APP_URL . 'error/erroremail';
            $isok = $this->checkExsitmail($_POST['nactmail']);
            if (!$isok || ($session->user['useremail'] == $_POST['nactmail']))
                return Doo::conf()->APP_URL . 'error/userdemail';
            $users = Doo::loadModel('users', true);
            $users->id = $session->user['id'];
            $users->useremail = $_POST['nactmail'];
            $succvalue = $users->update();
            if ($succvalue) {
                Doo::loadModel('userswitch');
                $UserSwitch = new UserSwitch();
                $usArray = $UserSwitch->getOne(array('where' => 'uid=?', 'param' => array($session->user['id']), 'asArray' => TRUE));
                $StrSubject = '纵横通行帐号-请激活您的帐号';
                $StrContent = '<table style="width:100%">
			<tbody>
				<tr>
                                    <td>
                                            <p>感谢您注册成为纵横通行帐号的会员。在使用我们提供的服务之前，请点击以下链接，或将以下链接复制到浏览器的地址栏中打开，以激活您的帐户：</p>
                                            <p style="width:600px"><br><a href="' . Doo::conf()->APP_URL . 'actuser/' . md5($session->user['id'] . $usArray['rndcode']) . '">' . Doo::conf()->APP_URL . 'actuser/' . md5($session->user['id'] . $usArray['rndcode']) . '</a></p>
                                            <p><br>您之所以收到这封邮件，是因为您曾经注册成为纵横通行帐号的用户。我们保证仅向您发送关于纵横通行帐号的电子邮件。我们尊重并保护您的隐私。</p>
                                            <p><br>纵横通行帐号与你共成长！</p>
                                            <p>' . date('Y年m月d日', time()) . '</p>
                                            <p>&copy;2012 <a href="http://smartcost.com.cn">珠海纵横创新软件有限公司</a></p>
                                    </td>
                                </tr>
			</tbody>
		</table>';
                $this->SMail($_POST['nactmail'], $StrSubject, $StrContent);
                $this->data['nowmail'] = $session->user['email'] = $_POST['nactmail'];
                $this->render($this->theme.'mailConfirm', $this->data, TRUE);
                exit();
            } else {
                $this->render($this->theme.'newMailch', $this->data, TRUE);
                exit();
            }
        }
        $this->render($this->theme.'newMailch', $this->data, TRUE);
    }

    public function regMobile(){
        $this->render($this->theme.'registerMobile', $this->data, TRUE);
    }

    public function getPWMobile(){
        $this->render($this->theme.'getPassword-mobile', $this->data, TRUE);
    }

    public function setPWMobile() {
        if($this->checkSmsCode($_POST['zhmobile'],$_POST['zhsmscode'])){
            $user = Doo::db()->find('users', array(
                    'select' => 'id,salt,username,mobile',
                    'where' => 'mobile=?',
                    'param' => array($_POST['zhmobile'])
                )
            );
            if(!empty($user)){
                $this->data['userid'] = $user[0]->id;
                $this->data['usersalt'] = $user[0]->salt;
                $this->render($this->theme.'getPassword-mobile2', $this->data, TRUE);
                die;

            } else {
                $this->data['messages'] = '手机号有误，请重新输入';
            }
        }else{
            $this->data['messages'] = '验证码过期或不一致，请重新获取';
        }
        $this->render($this->theme.'getPassword-mobile', $this->data, TRUE);
    }

    public function successPW(){
        if(isset($_POST['userid'])){
            // TODO：重新设置密码过程
            $newPasswdStr = $_POST['password'];
            $newPasswd = $this->create_password($newPasswdStr, $_POST['usersalt']);
            $usersObj = Doo::loadModel('users', TRUE);
            $usersObj->id = $_POST['userid'];
            $usersObj->userpasswd = $newPasswd;
            if ($usersObj->update()) {
                $this->render($this->theme . 'getPassword-mobile-success', $this->data, TRUE);
                die;
            }else{
                $this->data['messages'] = '新密码有误，请重新输入';
                $this->data['userid'] = $_POST['userid'];
                $this->data['usersalt'] = $_POST['usersalt'];
                $this->render($this->theme.'getPassword-mobile2', $this->data, TRUE);
                die;
            }
        }
        return '/mobile/getpasswd';
    }

    public function Voucher(){
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        Doo::loadModel('voucher');
        Doo::loadModel('users');
        $voucher = new Voucher();
        if(isset($_POST['code'])){
            $vinfo = $voucher->getRowbyCode($_POST['code']);
            if(!empty($vinfo) && isset($vinfo['vstarttime']) && $vinfo['vstarttime'] <= time()){
                Doo::loadModel('users_voucher');
                $usersvoucher = new UsersVoucher();
                $hadnum = $usersvoucher->count(array('where' => 'vid='.$vinfo['id']));
                if($vinfo['vendtime'] < time() || ($vinfo['vcount'] != 0 && $hadnum >= $vinfo['vcount'])){
                    $this->data['pnote'] = '领取码"'.$_POST['code'].'"的活动已结束';
                }else{
                    $checktake = $usersvoucher->checkuser($session->user['id'],$vinfo['id']);
                    if(!$checktake){
                        $this->data['pnote'] = '领取码"'.$_POST['code'].'"的活动您已参加，不可再次领取';
                    }else{
                        $usersvoucher->userid = $session->user['id'];
                        $usersvoucher->vid = $vinfo['id'];
                        $usersvoucher->vmoney = $vinfo['vcost'];
                        $usersvoucher->addtime = time();
                        $usersvoucher->vname = $vinfo['vname'];
                        $usersvoucher->insert();

                        Doo::loadModel('pay');
                        $pay = new Pay();
                        $array = array(
                            'trade_sn' => $this->create_sn(),
                            'userid' => $session->user['id'],
                            'username' => $session->user['username'],
                            'money' => $vinfo['vcost'],
                            'addtime' => time(),
                            'usernote' => $session->user['username'] . '[' . $this->create_sn() . ']',
                            'pay_type' => 'voucher',
                            'payment' => $vinfo['vname'],
                            'ip' => $this->clientIP(),
                            'status' => 'succ'
                        );
                        $pay->add($array);

                        $user = new Users();
                        $k=$user->updateBank($session->user['id'], $vinfo['vcost']);
                        if($k){
                            Doo::loadModel('income_pay');
                            $incomepay = new IncomePay();
                            $incomepay->uid = $session->user['id'];
                            $incomepay->money = $vinfo['vcost'];
                            $incomepay->type = 1;
                            $incomepay->comefrom = '代金券';
                            $incomepay->description = $vinfo['vname'];
                            $incomepay->addtime = time();
                            $incomepay->insert();
                            $this->data['pnote'] = '您成功领取了"'.$_POST['code'].'"领取码的活动';
                        }
                    }
                }
            }else{
                $this->data['pnote'] = '没有"'.$_POST['code'].'"领取码的活动';
            }
        }

        Doo::loadModel('users_voucher');
        $uvou = new UsersVoucher();
        $this->data['uvounum'] = $uvou->count(array('where' => 'userid='.$session->user['id'], 'asArray' => TRUE));
        $uvoulist = $uvou->getvoucher($session->user['id'],20);
        if(!empty($uvoulist)){
            $this->data['uvoulist'] = $uvoulist;
        }

        $users = new Users();
        $valuebank = $users->getRowByUid($session->user['id']);
        $this->data['bank'] = isset($valuebank[0]['bank']) ? $valuebank[0]['bank'] : 0;
        $this->data['name'] = $session->user['username'];
//        $this->data['avatar'] = $this->url_exists($this->ps_getavatar($session->user['id'])) ? $this->ps_getavatar($session->user['id']) : Doo::conf()->APP_URL . 'global/img/avatra48.png';
        if(isset($session->user['id'])){
            $this->data['avatar'] = $this->ps_getavatar($session->user['id']);
        }else{
            $this->data['avatar'] = Doo::conf()->APP_URL . 'global/img/avatra48.png';
        }
        $this->data['FUN'] = 'voucher';
        $this->render($this->theme.'voucher', $this->data, TRUE);
    }

    public function getVoucherMsg(){
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if(isset($this->params['pindex']) && is_numeric($this->params['pindex'])) {
            Doo::loadModel('users_voucher');
            $uvou = new UsersVoucher();
            $limit = ($this->params['pindex']*20).',20';
            $uvoulist = $uvou->getvoucher($session->user['id'], $limit);
            if (!empty($uvoulist)) {
                $uvounum = $uvou->count(array('where' => 'userid='.$session->user['id'], 'asArray' => TRUE));
                $num = 0;
                if($this->params['pindex']*20+20 < $uvounum){
                    $num = $this->params['pindex']+1;
                };
                foreach($uvoulist as $k => $v){
                    $uvoulist[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                }
                echo json_encode(array('code' => 200, 'uvoulist' => $uvoulist, 'num' => $num));
                exit;
            }
        }
        echo json_encode(array('code' => 400));
        exit;
    }

    public function Order(){
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }

        Doo::loadModel('income_pay');
        $incomepay = new IncomePay();
        $this->data['incomepaynum'] = $incomepay->count(array('where' => 'uid='.$session->user['id'], 'asArray' => TRUE));
        $incomepaylist = $incomepay->get_listbyuid($session->user['id'],20);

        if(!empty($incomepaylist)){
            $this->data['incomepaylist'] = $incomepaylist;
        }

        Doo::loadModel('users');
        $users = new Users();
        $valuebank = $users->getRowByUid($session->user['id']);
        $this->data['bank'] = isset($valuebank[0]['bank']) ? $valuebank[0]['bank'] : 0;
        $this->data['name'] = $session->user['username'];
//        $this->data['avatar'] = $this->url_exists($this->ps_getavatar($session->user['id'])) ? $this->ps_getavatar($session->user['id']) : Doo::conf()->APP_URL . 'global/img/avatra48.png';
        if(isset($session->user['id'])){
            $this->data['avatar'] = $this->ps_getavatar($session->user['id']);
        }else{
            $this->data['avatar'] = Doo::conf()->APP_URL . 'global/img/avatra48.png';
        }
        $this->data['FUN'] = '';
        $this->render($this->theme.'order', $this->data, TRUE);
    }

    public function getOrderMsg(){
        $session = Doo::session("sso");
        if (empty($session->user['id'])) {
            return Doo::conf()->APP_URL . 'error/loginFail';
        }
        if(isset($this->params['pindex']) && is_numeric($this->params['pindex'])) {
            Doo::loadModel('income_pay');
            $incomepay = new IncomePay();
            $limit = ($this->params['pindex']*20).',20';
            $incomepaylist = $incomepay->get_listbyuid($session->user['id'], $limit);
            if (!empty($incomepaylist)) {
                $incomepaynum = $incomepay->count(array('where' => 'uid='.$session->user['id'], 'asArray' => TRUE));
                $num = 0;
                if($this->params['pindex']*20+20 < $incomepaynum){
                    $num = $this->params['pindex']+1;
                };
                foreach($incomepaylist as $k => $v){
                    $incomepaylist[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                }
                echo json_encode(array('code' => 200, 'incomepaylist' => $incomepaylist, 'num' => $num));
                exit;
            }
        }
        echo json_encode(array('code' => 400));
        exit;
    }


    private function checkExsitmail($email) {
        $users = Doo::loadModel('users', true);
        $arruser = $users->getOne(array('select' => 'id', 'where' => 'useremail=?', 'param' => array($email), 'asArray' => TRUE));
        if (empty($arruser)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    private function checkExsitMobile($mobile) {
        $users = Doo::loadModel('users', true);
        $arruser = $users->getOne(array('select' => 'id', 'where' => 'mobile=?', 'param' => array($mobile), 'asArray' => TRUE));
        if (empty($arruser)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    private function checkUserQuestion($uid) {
        $ddd = Doo::loadModel('users', true);
        $arruser = $ddd->getOne(array('select' => 'userquestion', 'where' => 'id=?', 'param' => array($uid), 'limit' => '1', 'asArray' => TRUE));
        if (empty($arruser['userquestion'])) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    private function checkUserQuestionExs($uid) {
        $ddd = Doo::loadModel('users', true);
        $arruser = $ddd->getOne(array('select' => 'userquestion', 'where' => 'id=?', 'param' => array($uid), 'limit' => '1', 'asArray' => TRUE));
        if ($arruser['userquestion']) {
            return TRUE;
        }
    }

    private static function isUserActive($uid) {
        Doo::loadModel('userswitch');
        $userswitch = new UserSwitch();
        return $userswitch->checkUserStatus($uid);
    }

    
/**
	 * 发送email
	 * @param unknown_type $html_templete
	 * @param unknown_type $subject
	 * @param unknown_type $toemail
	 */
	function _mail( $html_templete = "",$subject="",$toemail=""){
		
		require_once  './protected/class/class.pop3.php';
		
		require_once  './protected/class/class.smtp.php';
		
		require_once  './protected/class/class.phpmailer.php';
	
		$mail             = new PHPMailer();
		
		$body             = $html_templete;
		
		$mail->IsSMTP(); // telling the class to use SMTP
		
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		//$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
		$mail->Host       = "smtp.exmail.qq.com";      // sets GMAIL as the SMTP server
		//$mail->Port       = 465;                   // set the SMTP port for the GMAIL server
		
		//$mail->CharSet = "UTF8";
		
		$mail->Username   = "websupport@smartcost.com.cn";  // GMAIL username
		$mail->Password   = "smartcost2010";            // GMAIL password
		
		$mail->From = "websupport@smartcost.com.cn";
		
		$mail->FromName   = "=?UTF-8?B?" . base64_encode('纵横知道·问答') . "?=";
		
		$mail->Subject    = $subject;
		
		$mail->MsgHTML($body);
		
		$mail->AddAddress($toemail);
		
		$mail->Send();
	}
    
	/**
	 * 实现接口
	 * (non-PHPdoc)
	 * @see BaseLogic::format_email_content()
	 */
	protected function format_email_content($html_templete, $templete_name, $postArray = 0, $user = 0,$v_oid) {
		
		if ($templete_name == "RECHARGE_SUCCESS") { 			//纵横通行帐号提醒您：您的帐号成功充值了一笔金额
			
			$str = str_replace ( "%username%",$user[0]['username'] , $html_templete );
			
			$str = str_replace ( "%price%",$postArray , $str );
			
			$str = str_replace ( "%oder%", $v_oid, $str );
			
			$str = str_replace ( "%time%", date('Y-m-d H:i:s', time()), $str );
			
			$result ['templete'] = $str;
			
			$result ['subject'] = "=?UTF-8?B?" . base64_encode ( '纵横通行帐号提醒您：您的帐号成功充值了一笔金额' ) . "?=";
			
			$result ['toemail'] = $user [0]['useremail'];
			
			return $result;
		}  
	}

    /**
     * ajax短信验证码调用接口
     */
    public function checkSms(){
        if(isset($_POST['zhmobile'])){
            $mobile = trim($_POST['zhmobile']);
        }else{
            exit(json_encode(array('code' => -1, 'msg' => '请输入手机号')));
        }
        if(preg_match("/^1[34578]{1}\d{9}$/",$mobile)){
            Doo::loadModel('users');
            $user = new Users();
            $checkuser = $user->getOne(array('where' => 'mobile='.$mobile, 'asArray' => true));
            if(!empty($checkuser)){
                exit(json_encode(
                    array('code' => -1, 'msg' => '该手机号码已被注册！')
                ));
            }
            Doo::loadModel('mobilecode');
            $mobilecode = new mobilecode();
            $code = $this->getRandomCheckCode();
            $now = time();
            $checkresult = $mobilecode->find(array('where' => 'mobile='.$mobile, 'desc' => 'id', 'limit' => 1,'asArray' => true));
            if(!empty($checkresult)){
                $old = $checkresult['time'];
                if($now-$old >= 60){
                    $sendresult = $this->sendSms($mobile,$code);
//                    $sendresult = true;
                    if($sendresult){
                        $mobilecode->mobile = $mobile;
                        $mobilecode->code = $code;
                        $mobilecode->time = $now;
                        $mobilecode->insert();
                        exit(json_encode(
                            array('code' => 1, 'msg' => '发送成功')
                        ));
                    }else{
                        exit(json_encode(
                            array('code' => -1, 'msg'=> $this->errorMsg)
                        ));
                    }
                }else{
                    exit(json_encode(
                        array('code' => -1, 'msg' => '60s内无法再次发送验证码')
                    ));
                }
            }else{
                $sendresult = $this->sendSms($mobile,$code);
//                $sendresult = true;
                if($sendresult){
                    $mobilecode->mobile = $mobile;
                    $mobilecode->code = $code;
                    $mobilecode->time = $now;
                    $mobilecode->insert();
                    exit(json_encode(
                        array('code' => 1, 'msg' => '发送成功')
                    ));
                }else{
                    exit(json_encode(
                        array('code' => -1, 'msg'=> $this->errorMsg)
                    ));
                }
            }
        }else{
            exit(json_encode(
               array('code' => -1, 'msg' => '请正确填写您的手机号码')
            ));
        }
    }
    /**
     * ajax短信修改密码验证码调用接口
     */
    function chpwdsms(){
        if(isset($_POST['zhmobile'])){
            $mobile = trim($_POST['zhmobile']);
        }else{
            exit(json_encode(array('code' => -1, 'msg' => '请输入手机号')));
        }
        if(preg_match("/^1[34578]{1}\d{9}$/",$mobile)){
            Doo::loadModel('mobilecode');
            $mobilecode = new mobilecode();
            $code = $this->getRandomCheckCode();
            $now = time();
            $checkresult = $mobilecode->find(array('where' => 'mobile='.$mobile, 'desc' => 'id', 'limit' => 1,'asArray' => true));
            if(!empty($checkresult)){
                $old = $checkresult['time'];
                if($now-$old >= 60){
                    $sendresult = $this->sendSms($mobile,$code);
//                    $sendresult = true;
                    if($sendresult){
                        $mobilecode->mobile = $mobile;
                        $mobilecode->code = $code;
                        $mobilecode->time = $now;
                        $mobilecode->insert();
                        exit(json_encode(
                            array('code' => 1, 'msg' => '发送成功')
                        ));
                    }else{
                        exit(json_encode(
                            array('code' => -1, 'msg'=> $this->errorMsg)
                        ));
                    }
                }else{
                    exit(json_encode(
                        array('code' => -1, 'msg' => '60s内无法再次发送验证码')
                    ));
                }
            }else{
                $sendresult = $this->sendSms($mobile,$code);
//                $sendresult = true;
                if($sendresult){
                    $mobilecode->mobile = $mobile;
                    $mobilecode->code = $code;
                    $mobilecode->time = $now;
                    $mobilecode->insert();
                    exit(json_encode(
                        array('code' => 1, 'msg' => '发送成功')
                    ));
                }else{
                    exit(json_encode(
                        array('code' => -1, 'msg'=> $this->errorMsg)
                    ));
                }
            }
        }else{
            exit(json_encode(
                array('code' => -1, 'msg' => '请正确填写您的手机号码')
            ));
        }
    }
    function checkgetpwdsms(){
        if(isset($_POST['zhmobile'])){
            $mobile = trim($_POST['zhmobile']);
        }else{
            exit(json_encode(array('code' => -1, 'msg' => '请输入手机号')));
        }
        if(preg_match("/^1[34578]{1}\d{9}$/",$mobile)){
            Doo::loadModel('users');
            $user = new Users();
            $checkuser = $user->getOne(array('where' => 'mobile='.$mobile, 'asArray' => true));
            if(empty($checkuser)){
                exit(json_encode(
                    array('code' => -1, 'msg' => '该手机号码未在纵横通行账号注册！')
                ));
            }
            Doo::loadModel('mobilecode');
            $mobilecode = new mobilecode();
            $code = $this->getRandomCheckCode();
            $now = time();
            $checkresult = $mobilecode->find(array('where' => 'mobile='.$mobile, 'desc' => 'id', 'limit' => 1,'asArray' => true));
            if(!empty($checkresult)){
                $old = $checkresult['time'];
                if($now-$old >= 60){
                    $sendresult = $this->sendSms($mobile,$code);
//                    $sendresult = true;
                    if($sendresult){
                        $mobilecode->mobile = $mobile;
                        $mobilecode->code = $code;
                        $mobilecode->time = $now;
                        $mobilecode->insert();
                        exit(json_encode(
                            array('code' => 1, 'msg' => '发送成功')
                        ));
                    }else{
                        exit(json_encode(
                            array('code' => -1, 'msg'=> $this->errorMsg)
                        ));
                    }
                }else{
                    exit(json_encode(
                        array('code' => -1, 'msg' => '60s内无法再次发送验证码')
                    ));
                }
            }else{
                $sendresult = $this->sendSms($mobile,$code);
//                $sendresult = true;
                if($sendresult){
                    $mobilecode->mobile = $mobile;
                    $mobilecode->code = $code;
                    $mobilecode->time = $now;
                    $mobilecode->insert();
                    exit(json_encode(
                        array('code' => 1, 'msg' => '发送成功')
                    ));
                }else{
                    exit(json_encode(
                        array('code' => -1, 'msg'=> $this->errorMsg)
                    ));
                }
            }
        }else{
            exit(json_encode(
                array('code' => -1, 'msg' => '请正确填写您的手机号码')
            ));
        }
    }

    /**
     * 实现短信验证码接口
     *
     */
    protected function sendSms($number,$code){
        $send = array(
            'apikey' => 'fb5ef483e44b9556512a9febef376051',
            'mobile' => $number,
            'text'   => '【纵横通行账号】您的验证码是'.$code.'，15分钟内有效。'
        );

        $data = http_build_query($send);
        $res = json_decode($this->_httpClient($data));
        $resArr = $this->objectToArray($res);

        if (!empty($resArr) && $resArr["code"] == 0) return true;
        else {
            if (empty($this->errorMsg)) $this->errorMsg = isset($resArr["msg"]) ? $resArr["msg"] : '未知错误';
            return false;
        }
    }

    //对象转数组,使用get_object_vars返回对象属性组成的数组
    function objectToArray($array){
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->objectToArray($value);
            }
        }
        return $array;
    }

    /**
     * POST方式访问短信接口
     * @param string $data
     * @return mixed
     */
    private function _httpClient($data) {
        $sms_api_url = 'http://sms.haotingyun.com/v2/sms/single_send.json';
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded','charset=utf-8'));
            curl_setopt($ch, CURLOPT_URL,$sms_api_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $res = curl_exec($ch);
            curl_close($ch);
            return $res;
        } catch (Exception $e) {
            $this->errorMsg = $e->getMessage();
            return false;
        }
    }

    /**
     * 随机生成验证码
     */
    function getRandomCheckCode() {
        $chars = '0123456789';
        mt_srand((double)microtime()*1000000*getmypid());
        $CheckCode="";
        while(strlen($CheckCode)<6)
            $CheckCode.=substr($chars,(mt_rand()%strlen($chars)),1);
        return $CheckCode;
    }



//    private static function isUserActive($uid) {
//        Doo::loadModel('userswitch');
//        $userswitch = new UserSwitch();
//        return $userswitch->checkUserStatus($uid);
//    }
}

?>
