<?php
session_start();
require( dirname(__FILE__) . '/../../../wp-load.php' );
define('QQ_APPID',_ceo('qq_app_id'));//appkey
define('QQ_APPSECRET',_ceo('qq_app_key'));//appsecret
header('Content-Type: text/html; charset=utf-8');
    if($_SERVER['REQUEST_METHOD'] == 'GET')
    {
        if (isset($_GET['code']))
        {
            if (!empty($_GET ['state']) && $_GET ['state'] == $_SESSION ['state']) {
				$code = $_GET['code'];

				$token_url = "https://graph.qq.com/oauth2.0/token?client_id=" . QQ_APPID . "&client_secret=" . QQ_APPSECRET . "&grant_type=authorization_code&redirect_uri=".urlencode (home_url())."&code=".$code;
                $response = get_url_contents ( $token_url );
                if (strpos ( $response, "callback" ) !== false) {
                    $lpos = strpos ( $response, "(" );
                    $rpos = strrpos ( $response, ")" );
                    $response = substr ( $response, $lpos + 1, $rpos - $lpos - 1 );
                    $msg = json_decode ( $response );
                    if (isset ( $msg->error )) {
                        echo "<h3>错误代码:</h3>" . $msg->error;
                        echo "<h3>信息  :</h3>" . $msg->error_description;
                        exit ();
                    }
                }
                $params = array ();
                parse_str ( $response, $params );
                $qq_access_token = $params ["access_token"];} else {
                echo ("呃……好像哪里不对，请关闭页面，刷新之后请重试一次？依旧不行请联系站长，谢谢~");
                exit;
            }
            $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $qq_access_token;
            $str = get_url_contents ( $graph_url );
            if (strpos ( $str, "callback" ) !== false) {
                $lpos = strpos ( $str, "(" );
                $rpos = strrpos ( $str, ")" );
                $str = substr ( $str, $lpos + 1, $rpos - $lpos - 1 );
            }
            $user = json_decode ( $str );
            if (isset ( $user->error )) {
                echo "<h3>错误代码:</h3>" . $user->error;
                echo "<h3>信息  :</h3>" . $user->error_description;
                exit ();
            }
            $qq_openid = $user->openid;

			$get_user_info = "https://graph.qq.com/user/get_user_info?" . "access_token=" . $qq_access_token . "&oauth_consumer_key=" . QQ_APPID . "&openid=" . $qq_openid . "&format=json";
			$data = get_url_contents ( $get_user_info );
			$str  = json_decode($data , true);

			$custom_avatar = $str['figureurl_qq_2'];
            if(empty($qq_openid)){
                //wp_redirect(home_url('/?3'.$qq_openid));//授权错误跳转
                wp_die('抱歉，服务器响应错误，请重试。');
            }
            if(is_user_logged_in()){
                $this_user = wp_get_current_user();
                update_user_meta($this_user->ID ,"qq_openid",$qq_openid);
                update_user_meta($this_user->ID ,"qq_access_token",$qq_access_token);
				update_user_meta($this_user->ID ,"avatarurl",$custom_avatar);
                //wp_redirect(get_field("tizipu_menber_link","option"));//已登录授权

                if(!empty($_SESSION ['ref'])){
                    wp_redirect($_SESSION ['ref']);
                }else{
                    wp_redirect( home_url(user_trailingslashit('/user')) );
                }

            }else{
                $user_fb = get_users(array("meta_key "=>"qq_openid","meta_value"=>$qq_openid));
                if(is_wp_error($user_fb) || !count($user_fb)){
                    $username = $str['nickname'];
					$custom_avatar = $str['figureurl_qq_2'];
     //                $login_name = wp_create_nonce($qq_openid);
     //                $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
     //                $userdata=array(
     //                    'user_login' => $login_name,
     //                    'display_name' => $username,
     //                    'user_pass' => $random_password,
     //                    'nickname' => $username
     //                );
     //                $user_id = wp_insert_user( $userdata );
     //                wp_signon(array("user_login"=>$login_name,"user_password"=>$random_password),false);
     //                update_user_meta($user_id ,"qq_openid",$qq_openid);
     //                update_user_meta($user_id ,"qq_access_token",$qq_access_token);
					// update_user_meta($user_id ,"custom_avatar",$custom_avatar);

                    $_SESSION['qq_openid'] = $qq_openid;
                    $_SESSION['qq_access_token'] = $qq_access_token;
                    $_SESSION['avatarurl'] = $custom_avatar;
                    $_SESSION['display_name'] = $username;
                    $_SESSION['sf'] = 'qq';

                    //直接注册账号
                    global $wpdb;
                    $max_id = $wpdb->get_var( "SELECT ID FROM $wpdb->users ORDER BY ID DESC LIMIT 0,1" );
                    $user_login = 'CEO' . $max_id . date('His', time()) . ($max_id + 1);
                    $user_id = wp_create_user($user_login, md5(time()), $user_login . '@ceo.com');

                    if( $user_id ){

                        wp_set_current_user($user_id);
                        wp_set_auth_cookie($user_id);
                        //add_user_meta( $user_id , 'verifymail' , 1 );


//                        if( $sf == 'qq' ){
                        if( true ){

                            $qq_openid = $_SESSION['qq_openid'];
                            $qq_access_token = $_SESSION['qq_access_token'];
                            $custom_avatar = $_SESSION['avatarurl'];
                            $display_name = $_SESSION['display_name'];

                            update_user_meta($user_id ,"qq_openid",$qq_openid);
                            update_user_meta($user_id ,"qq_access_token",$qq_access_token);
                            update_user_meta($user_id ,"avatarurl",$custom_avatar);
                            $ret=wp_update_user( array( 'ID' => $user_id, 'display_name' => $display_name ) );
                            if($ret){
                                $redirect_url=home_url(user_trailingslashit('/user'));
                            }else{
                                $redirect_url=user_trailingslashit('/user/binding');
                            }
                        }

                        $redirect_url=home_url(user_trailingslashit('/user'));
                    }
//                    var_dump($user_login, md5(time()), $user_login . '@ceotheme.com');
//                    exit($redirect_url);
                    wp_redirect( $redirect_url );

                }else{
                    wp_set_auth_cookie($user_fb[0]->ID);
                    //wp_redirect(home_url('/?2'));//已授权用户登录跳转
//					wp_redirect( home_url(user_trailingslashit('/user')) );
                    if(!empty($_SESSION ['ref'])){
                        wp_redirect($_SESSION ['ref']);
                    }else{
                        wp_redirect( home_url(user_trailingslashit('/user')) );
                    }
                }
            }
        }
    }


?>
