<?php
define('IN_ECTOUCH', true);
require ('config.php');
require ('cls_mysql.php');
require ('lib_common.php');
$db = new cls_mysql($db_host, $db_user, $db_pass, $db_name);
$user = & init_users();
if($_GET['code']){
    $wxch_config = $db -> getRow("SELECT * FROM `wxch_config` WHERE `id` = 1");
    $appid = $wxch_config['appid'];
    $appsecret = $wxch_config['appsecret'];

    $code = !empty($_GET['code']) ? $_GET['code'] : '';
	$openid = !empty($_GET['openid']) ? $_GET['openid'] : '';
	$oid = !empty($_GET['oid']) ? $_GET['oid'] : '';
	$access_token=!empty($_GET['access_token']) ? $_GET['access_token'] : '';
   // $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
   // $ret_oa_json = curl_get_contents($url);
    //$ret_oa = json_decode($ret_oa_json);
    if(strlen($openid) == 28){
        $thistable = 'ecs_users';
        $w_openid = $db -> getOne("SELECT `wxid` FROM `go_member` WHERE `wxid` = '$openid'");
        $time = time();
        if(empty($w_openid)){
            if(!empty($openid)){
                $db -> query("INSERT INTO `go_member` ( `wxid` , `dateline`) VALUES ('$openid','$time') ");
            }
        }
        $wxch_user_name_sql = "SELECT `user_name` FROM `$thistable` WHERE `wxch_bd`='ok' AND `wxid` = '$openid'";
        $wxch_user_name = $db -> getOne($wxch_user_name_sql);
        $wxch_user_wxid_sql = "SELECT `wxid` FROM `$thistable` WHERE `wxid`=`user_name` AND `wxid` = '$openid'";
        $wxch_user_wxid = $db -> getOne($wxch_user_wxid_sql);
        if(empty($wxch_user_wxid)){
            if(empty($wxch_user_name)){
                $wxch_nobd_wxid_sql = "SELECT `wxid` FROM `$thistable` WHERE `wxch_bd`='no' AND `wxid` = '$openid'";
                $wxch_nobd_wxid = $db -> getOne($wxch_nobd_wxid_sql);
                if(empty($wxch_nobd_wxid)){
                    $wxch_user_sql = "INSERT INTO `$thistable` ( `user_name`,`password`,`wxid`,`user_rank`,`wxch_bd`) VALUES ('$openid','$ec_pwd','$openid','99','no')";
                    $db -> query($wxch_user_sql);
                    $ecs_user_id = $db -> insert_id();
                    $ecs_user_name = 'wx' . $ecs_user_id;
                    $ecs_update = " UPDATE `$thistable` SET `user_name` = '$ecs_user_name' WHERE `user_id` = '$ecs_user_id'";
                    $db -> query($ecs_update);
                }
            }
            $sns_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
            $ret_sns_json = curl_get_contents($sns_url);
            $ret_sns = json_decode($ret_sns_json);
            if($openid == $ret_sns -> openid){
                $w_sql = "UPDATE  `go_member` SET  `nickname` =  '$ret_sns->nickname',`sex` =  '$ret_sns->sex',`city` =  '$ret_sns->city',`country` = '$ret_sns->country',`headimgurl` =  '$ret_sns->headimgurl',`username` =  '$ret_sns->nickname' WHERE `wxid` = '$openid';";
                $db -> query($w_sql);
            }
        }
        if(empty($ecs_user_name)){
            $ecs_user_name = $db -> getOne("SELECT `user_name` FROM `$thistable` WHERE `wxid` = '$openid'");
        }
        $is_login = 0;
        if(!empty($ecs_user_name)){
            $user -> set_session($ecs_user_name);
            $user -> set_cookie($ecs_user_name);
            //update_user_info();
            //recalculate_price();
            $is_login = 1;
        }
        if($is_login == 0){
            $user -> set_session($ecs_user_name);
            $user -> set_cookie($ecs_user_name);
            //update_user_info();
            //recalculate_price();
        }
        $_SESSION['wxoauth'] = 'true';
    }
}elseif(!$_SESSION['user_id']){
    if (strpos($_SERVER["HTTP_USER_AGENT"], "MicroMessenger")){
        if($_SESSION['wxoauth'] != 'true'){
            $wxch_config = $db -> getRow("SELECT * FROM `wxch_config` WHERE `id` = 1");
            $appid = $wxch_config['appid'];
            $appsecret = $wxch_config['appsecret'];
            $_SESSION['wxoauth'] = 'false';
            $back_url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
            $state = 'wechat';
            $scope = 'snsapi_userinfo';
            $redirect_uri = urlencode($back_url);
            $oauth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
            goheader($oauth_url);
        }
    }
}

$back_url = $db->getOne("SELECT `contents` FROM `wxch_oauth` WHERE `oid` = '$oid'");
$affiliate_id = $db->getOne("SELECT `affiliate` FROM `go_member` WHERE `wxid` = '$openid'");

if($affiliate_id>=1) 
{
	$affiliate = '&u='.$affiliate_id;
	$back_url = $back_url.$affiliate;
}
$update_sql = "UPDATE `wxch_oauth` SET `count` = `count` + 1 WHERE `oid` = $oid; ";
$db->query($update_sql);
if(!empty($openid) && strlen($openid) == 28)
{



	$wxch_ecs = 'ecs_users';

	$w_res = $db->getRow("SELECT * FROM  ".$wxch_ecs." WHERE  `wxid` = '$openid'");
	$_SESSION['wxid'] = $openid;
	$huiyuan = $db->getRow("SELECT uid,password,mobile,email,img FROM  ".'go_member'." WHERE  `wxid` = '$openid'");
		
	$s1 = _setcookie("uid",_encrypt($huiyuan['uid']),60*60*24*7);			
		$s2 = _setcookie("ushell",_encrypt(md5($huiyuan['uid'].$huiyuan['password'].$huiyuan['mobile'].$huiyuan['email'])),60*60*24*7);
	/*
	if ($is_login == 0) 
	{
		$user->login($w_res['user_name'], null, true);
		update_user_info();
		recalculate_price();
		$is_login = 1;
	}*/
	//if ($user->login($w_res['user_name'], null, true)) 
	//{
		//update_user_info();
		//recalculate_price();
	//}
}

header("HTTP/1.1 301 Moved Permanently");
header("Location: $back_url");
exit;

function curl_get_contents($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
    curl_setopt($ch, CURLOPT_REFERER, _REFERER_);
    @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}
function goheader($oauth_url){
    header('Expires: 0');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cahe, must-revalidate');
    header('Cache-Control: post-chedk=0, pre-check=0', false);
    header('Pragma: no-cache');
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: $oauth_url");
    exit;
}
function _encrypt($string, $operation = 'ENCODE', $key = '', $expiry = 0){
	if($operation == 'DECODE') {
		$string =  str_replace('_', '/', $string);
	}
	$key_length = 4;
	if(1){
			$key = md5($key != '' ? $key : 'lrbrary.taobao.com');
	}else{
			$key = md5($key != '' ? $key : YYS_LOCAL_PATH);
	}
	$fixedkey = md5($key);
	$egiskeys = md5(substr($fixedkey, 16, 16));
	$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
	$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
	$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));

	$i = 0; $result = '';
	$string_length = strlen($string);
	for ($i = 0; $i < $string_length; $i++){
		$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
	}
	if($operation == 'ENCODE') {
		$retstrs =  str_replace('=', '', base64_encode($result));
		$retstrs =  str_replace('/', '_', $retstrs);
		return $runtokey.$retstrs;
	} else {	
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	}
}

function _setcookie($name,$value,$time=0,$path='/',$yuming=''){		
	if(empty($name)){return false;}
	$_COOKIE[$name]=$value;				//及时生效
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	if(!$time){
		return setcookie($name,$value,0,$path,$yuming,$s);
	}else{
		return setcookie($name,$value,time()+$time,$path,$yuming,$s);
	}
}
?>