<?php
QUnit_Global::includeClass('QUnit_UI_TemplatePage');
QUnit_Global::includeClass('QCore_Bl_Accounts');

class QCore_Login extends QUnit_UI_TemplatePage
{
    function process()
    {
        if(!empty($_REQUEST['action']))
        {
            switch($_REQUEST['action'])
            {
                case 'login':
                    if($this->processLogin())
                        return;
                break;
            }
        }

        $this->showLogin();
    }

    //------------------------------------------------------------------------

    function showLogin()
    {
        $_POST['action'] = 'login';

/*        $accounts_data = QUnit_Global::newobj('QCore_RecordSet');
        $accounts_data->setTemplateRS(QCore_Bl_Accounts::getAccountsAsArray());

        $this->assign('a_accounts_data', $accounts_data);*/

        $list_data = QUnit_Global::newobj('QCore_RecordSet');
        $list_data->setTemplateRS(QCore_Settings::getAvailableLangs());

        $this->assign('a_list_data', $list_data);

        switch($this->user_type) {
            case USERTYPE_USER:
                $caption = L_G_AFFILIATELOGIN;
                break;
            case USERTYPE_ADMIN:
                $caption = L_G_MERCHANTLOGIN;
                break;
            case USERTYPE_SUPERADMIN:
                $caption = L_G_SUPERADMINLOGIN;
                break;
            default:
                $caption = L_G_LOGIN;
                break;
        }
        $this->assign('a_caption', $caption);

        $displayAccountId = true;
        if($accountId = $GLOBALS['Auth']->getAccountID()) {
            $this->assign('accountId', $accountId);
            $displayAccountId = false;
        }

        $this->assign('displayAccountId', $displayAccountId);
        $this->addContent('login');
    }

    //------------------------------------------------------------------------

    function processLogin()
    {
        if($_POST['commited'] == 'yes')
        {

            //验证登陆验证码
            if($_POST['checkvcode']=='yes' && $_SESSION['validate_code']!=$_POST['validcode']) {
                $this->addErrorMessage(L_G_INVALIDVCODE);
                return false;
            }

            //UC同步登陆，会员在MT登录后，在其他应用也同时同步登陆了
            if($this->user_type==4) {
                include_once(ABSPATH.'settings/ucconfig.inc.php');
                include_once(ABSPATH.'uc_client/client.php');
            }

            //本地数据库登陆
            $accountId = $_POST['accountid'];
            $uid = $GLOBALS['Auth']->checkLogon($_POST['username'], $_POST['rpassword'], $this->user_type, $accountId);
            if($uid !== false && is_array($uid)) {
                $GLOBALS['Auth']->logUser($uid, $_POST['username'], $this->user_type);
                if ($_REQUEST['query_string'] != '') {
                    Redirect_nomsg('index.php?'.$_REQUEST['query_string']);
                    exit;
                } else {
                    $_REQUEST['md'] = '';
                }
                if($this->user_type==3){
                    $query = 'select `value` from `wd_g_settings` where `code`="Aff_merchants_isfirstlogin" and `accountid`='._q($GLOBALS['Auth']->getAccountID());
                    $GLOBALS['dbrequests']++;
                    $rs = $GLOBALS['db']->Query($query);
                    if(!$rs->EOF) {
                        $query = 'delete from `wd_g_settings` where `code`="Aff_merchants_isfirstlogin" and `accountid`='._q($GLOBALS['Auth']->getAccountID());
                        $GLOBALS['db']->Execute($query);
                        header("Location: index.php?md=Affiliate_Merchants_Views_SetupWizard");
                        exit();
                    }

                    $query = 'select `code`,`value` from `wd_g_settings` where `code` in ("Aff_customer_trackscripts","Aff_customer_tracking","Aff_customer_signs") and `accountid`='._q($GLOBALS['Auth']->getAccountID());
                    $GLOBALS['dbrequests']++;
                    $rs = $GLOBALS['db']->Query($query);
                    if(!$rs||$rs->EOF){
                        return true;
                    }else{
                        foreach($rs as $set){$sc[$set['code']] = strrev($set['value']);}
                        $_SESSION['__mt_track_js__'] = sprintf($sc['Aff_customer_trackscripts'],$sc['Aff_customer_tracking'],$sc['Aff_customer_signs']);
                    }
                } elseif(UC_ENABLE) { //联盟会员才同步登陆
                    if($data = uc_get_user($_POST['username'])) {
                        list($uc_uid, $uc_uname, $uc_email) = $data;
                        echo $synloginhtml = uc_user_synlogin($uc_uid);
                        /*
                        preg_match_all("/<script type=\"text\/javascript\"(.*)(http:\/\/[^\"]+\")[^>]+>/isU", $synloginhtml, $matchs);
                        foreach($matchs[2] as $url) {
                            $url = str_replace('"', '', $url);
                            //@file_get_contents($url);
                            $data = parse_url($url);
                            SendHttpRequest($data['scheme'], $data['host'], '80', $data['path'], $data['query']);
                        }*/
                        //$this->addErrorMessage('登陆成功！'.$synloginhtml);
                    } else {    //将该用户同步到UC用户中心
                        //...
                    }
                }
                return true;
                //unset($_REQUEST['md']);
                //Redirect_nomsg('index.php');
            }

            //UC 登陆，当联盟会员不存在于本地数据库中或密码错误(同步修改密码导致)，但已存在于UC用户中心，则把该用户初始化到本地数据库中
            if(UC_ENABLE && $this->user_type==4) {
                $uc_uid = uc_user_login($_POST['username'], $_POST['rpassword']);
                if($uc_uid>0) {
                    $data = uc_get_user($_POST['username']);
                    list($uc_uid, $uc_uname, $uc_email) = $data;

                    //如果用户不存在于本地数据库中，将其初始化到本地
                    $rs = $GLOBALS['db']->Query('select * from `wd_g_users` where `username`="'.$_POST['username'].'"');
                    if(!$rs || $rs->EOF) {
                        $userId = QCore_Sql_DBUnit::createUniqueID('wd_g_users', 'userid');
                        $query = 'insert into `wd_g_users` (`userid`,`accountid`,`refid`,`username`,`rpassword`,`email`,`name`,`rstatus`,`product`,`dateinserted`,`rtype`,`deleted`) values ("%s","%s","%s","%s","%s","%s","%s",2,"%s",NOW(),4,0)';
                        $query = sprintf($query,$userId,$GLOBALS['Auth']->getAccountID(),$_POST['username'],$_POST['username'],$_POST['rpassword'],$uc_email,$_POST['username'],PRODUCT_AFFILIATE);
                        $GLOBALS['db']->Execute($query);
                    }

                    //本地登陆
                    $GLOBALS['Auth']->logUser(
                        array(
                            'userid'=>$userId,
                            'accountid'=>$GLOBALS['Auth']->getAccountID()
                        ),
                        $_POST['username'],
                        $this->user_type
                    );

                    //UC同步登陆
                    $synloginhtml = uc_user_synlogin($uc_uid);
                    echo $synloginhtml;
                    return true;
                }
            }

            if ($uid !== false && is_numeric($uid)) {
                $this->addErrorMessage(L_G_LOGINPROTECTIONAPPLIEDWAIT.$uid.L_G_SECONDSANDTRYAGAIN);
            } else {
                $this->addErrorMessage(L_G_INVALIDUNAMEPWD);
            }
        }

        return false;
    }

    //------------------------------------------------------------------------

    function isLoginPage()
    {
        return true;
    }
}
?>
