<?php
        require_once DISCUZ_ROOT.'/source/function/function_home.php';
        require_once './includes/functions/bbcode.php';
        date_default_timezone_set('Asia/Chongqing');
	$timestamp = time();
        if(!$_G['setting']['connect']['allow']) {
            view_showmessage('qqconnect_closed');
        }

        define('CURMODULE', $mod);
       // runhooks();
        $connectService = Cloud::loadClass('Service_Connect');
        try {
                $connectOAuthClient = Cloud::loadClass('Service_Client_ConnectOAuth');
        } catch(Exception $e) {
                view_showmessage('connect_app_invalid');
        }
        $op = !empty($_GET['op']) ? $_GET['op'] : '';
        $referer = dreferer();
        $QQLoginBaseUrl = $_G['baseurl'] . $_G['mocuz_config']['mocuz_type'].'/index.php';
        $_G['connect']['callback_url'] = $QQLoginBaseUrl . '?mod=connect&op=qq_callback';
        $_G['setting']['connect']['oauth2']=1;
	if($op == 'qq_redirect') {
                    if($_G['member']['conisbind'] && $_GET['reauthorize']) {
                        if($_GET['formhash'] == FORMHASH) {
                            $connectService->connectMergeMember();
                        } else {
                            view_showmessage('submit_invalid');
                        }
                    }
                    $callback = $_G['connect']['callback_url'] . '&referer=' . urlencode($_GET['referer']) . (!empty($_GET['isqqshow']) ? '&isqqshow=yes' : '');
                    if(!$_G['setting']['connect']['oauth2']) {
                        dsetcookie('con_request_token');
                        dsetcookie('con_request_token_secret');
                        try {
                            $response = $connectOAuthClient->connectGetRequestToken($callback);
                        } catch(Exception $e) {
                            view_showmessage('connect_get_request_token_failed_code', $referer, array('codeMessage' => getErrorMessage($e->getmessage()), 'code' => $e->getmessage()));
                        }
                        $request_token = $response['oauth_token'];
                        $request_token_secret = $response['oauth_token_secret'];
                        dsetcookie('con_request_token', $request_token);
                        dsetcookie('con_request_token_secret', $request_token_secret);
                        $redirect = $connectOAuthClient->getOAuthAuthorizeURL($request_token);
                        if(defined('IN_MOBILE') || $_GET['oauth_style'] == 'mobile') {
                            $redirect .= '&oauth_style=mobile';
                        }
                    } else {
                        try {
                            dsetcookie('con_request_uri', $callback);
                            $redirect = $connectOAuthClient->getOAuthAuthorizeURL_V2($callback);
                            $redirect .= '&display=mobile';
                        } catch(Exception $e) {
                            view_showmessage('connect_get_request_token_failed_code', $referer, array('codeMessage' => getErrorMessage($e->getmessage()), 'code' => $e->getmessage()));
                        }
                }
             dheader('Location:' . $redirect);
	}else if($op=='qq_callback') {

		$params = $_GET;
                $isqqshow = !empty($_GET['isqqshow']) ? 1 : 0;
		if(!$_G['setting']['connect']['oauth2']) {
                    try {
                        $response = $connectOAuthClient->connectGetAccessToken($params, $_G['cookie']['con_request_token_secret']);
                    } catch(Exception $e) {
                        view_showmessage('connect_get_request_token_failed_code', $referer, array('codeMessage' => getErrorMessage($e->getmessage()), 'code' => $e->getmessage()));
                    }

                    dsetcookie('con_request_token');
                    dsetcookie('con_request_token_secret');

                    $conuin = $response['oauth_token'];
                    $conuinsecret = $response['oauth_token_secret'];
                    $conopenid = strtoupper($response['openid']);
                    if(!$conuin || !$conuinsecret || !$conopenid) {
                        view_showmessage('connect_get_request_token_failed_code', $referer);
                    }
                } else {
//                    if($_GET['state'] != md5(FORMHASH)){
//                        view_showmessage('qqconnect:connect_get_access_token_failed', $referer);
//                    }
                    try {
                        $response = $connectOAuthClient->connectGetOpenId_V2($_G['cookie']['con_request_uri'], $_GET['code']);
                    } catch(Exception $e) {
                        view_showmessage('connect_get_request_token_failed_code', $referer, array('codeMessage' => getErrorMessage($e->getmessage()), 'code' => $e->getmessage()));
                    }


                    dsetcookie('con_request_token');
                    dsetcookie('con_request_token_secret');

                    $conuintoken = $response['access_token'];
                    $conopenid = strtoupper($response['openid']);
                    if(!$conuintoken || !$conopenid) {
                        view_showmessage('connect_get_request_token_failed_code', $referer);
                    }
                }
 
		setcookie('con_request_token', '', $timestamp - 86400);
		setcookie('con_request_token_secret', '', $timestamp - 86400);
		$conuin = $response['oauth_token'];
		$conuin_secret = $response['oauth_token_secret'];
		$conopenid = strtoupper($response['openid']);
                $conuintoken = $response['access_token'];
                if($params['uin']) {
                        $old_conuin = $params['uin'];
                }
   
                $connect_member = array();
                $fields = array('uid', 'conuin', 'conuinsecret', 'conopenid');
                if($old_conuin) {
                        $connect_member = C::t('#qqconnect#common_member_connect')->fetch_fields_by_openid($old_conuin, $fields);
                }
                if(empty($connect_member)) {
                        $connect_member = C::t('#qqconnect#common_member_connect')->fetch_fields_by_openid($conopenid, $fields);
                }
    
                if(!empty($connect_member)) {
                            $uid=$connect_member['uid'];
                            $user= DB::fetch_first('SELECT *  FROM '.DB::table('common_member')." as u LEFT JOIN "
                                .DB::table('common_usergroup')." as g ON u.groupid = g.groupid   WHERE uid = '$uid'");
                            $result_data = array(
                                    'uid' => $uid,
                                    'code'=>0,
                                    'username' => $user['username'],
                                    'avatar' => avatar($uid, 'middle', true),
                                    'auth' => authcode("{$user[password]}\t{$uid}", 'ENCODE', '', 31536000), // ��¼������Ч��(31536000=1��)
                                    'credits'=>$user['credits'], //����
                                    'grouptitle'=>$user['grouptitle'] //ͷ��
                             );
                             // tuangou
                            $ttauth = '';
                            $result_data['ttauth'] = $ttauth;
                            $user_info = DB::fetch_first('SELECT gender,mobile,affectivestatus,birthyear,birthmonth,birthday FROM '.DB::table('common_member_profile').' WHERE uid='.$uid);
                            $sightml= DB::fetch_first('SELECT sightml FROM '.DB::table('common_member_field_forum').' WHERE uid = '.$uid);
                            $regdate = DB::fetch_first('SELECT regdate FROM '.DB::table('common_member').' WHERE uid = '.$uid);
                            $mobiles  = DB::fetch_first('SELECT mobile FROM '.DB::table('mocuz_mobile').' WHERE uid = '.$uid);
                            $result_data['regdate'] = date('Y-m-d',$regdate['regdate']);
                            $result_data['sightml'] = $sightml['sightml']?addslashes(parse_html($sightml['sightml'])):odz_lang('no_message_left');
                            $result_data['mobile']  = $mobiles['mobile']?$mobiles['mobile']:odz_lang('no_binding');
                            $result_data['gender'] = (string)$user_info['gender'];
                            $result_data['affectivestatus'] = $user_info['affectivestatus']?$user_info['affectivestatus']:odz_lang('secrect');
                            $result_data['birth'] = $user_info['birthyear'].'-'.add_num_zero($user_info['birthmonth']).'-'.add_num_zero($user_info['birthday']);
                            $result_data['isperfect'] = "1";
                       odz_stats(array('typeid'=>3, 'action'=>'login'));
                }

                if(empty($result_data)){
                    $result_data['code']=1;
                    $result_data['qq_openid']=$conopenid;
                    $result_data['con_request_conuin']=$conuin;
                    $result_data['con_request_conuin_secret']=$conuin_secret;
                    $result_data['con_request_conuintoken']=isset($conuintoken)?$conuintoken:'';
                    $result_data['con_request_isqqshow']=$isqqshow;
                }
                foreach ( $result_data as $key => $value ) { 
                        $value= strip_tags($value);//去除签名中的标签
                        $result_data [$key] = urlencode ( $value ); 
                } 
                $params= urldecode ( json_encode ( $result_data ) ); 

             
$html = <<<EOF
<script type="text/javascript">
var MocuzMobile = {
	Android: function() {
		return /Android/i.test(navigator.userAgent);
	},
	BlackBerry: function() {
		return /BlackBerry/i.test(navigator.userAgent);
	},
	iOS: function() {
		return /iPhone|iPad|iPod/i.test(navigator.userAgent);
	},
	Windows: function() {
		return /IEMobile/i.test(navigator.userAgent);
	},
	any: function() {
		return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
	}
};

function qqconnect() {
	if (MocuzMobile.Android()) {
                var str = '{$params}';
		window.myjs.qqconnect(str);
	} 
}

window.onload = qqconnect();
</script>
EOF;
echo $html;
        }
?>