<?php
@ini_set('display_errors',        0);
error_reporting(0);
@header("Content-Type: text/html; charset=utf-8");
if(function_exists('date_default_timezone_set')) date_default_timezone_set('Hongkong');
define('IN_MYMPS',true);
define('WXLOGIN',1);

define('WXLOGINDIR',dirname(__FILE__));
@define('MYMPS_ROOT', str_replace("[/\\]{1,}",'/',substr(WXLOGINDIR,0,-9)));
define('MYMPS_DATA',MYMPS_ROOT.'/data');
define('MYMPS_INC',MYMPS_ROOT.'include');
require MYMPS_DATA.'/config.php';
require MYMPS_DATA.'/config.db.php';
require MYMPS_INC.'/db.class.php';
require MYMPS_INC.'/common.fun.php';
require MYMPS_INC.'/openlogin.fun.php';
require MYMPS_INC.'/cache.fun.php';
require MYMPS_ROOT.'/member/include/common.func.php';

$timestamp = time();
if(!pcclient()){ 
	$_GET['mod'] = 'm';
} else{
	$_GET['mod'] = 'pc';
}

session_save_path (MYMPS_DATA."/sessions");

//$returnurl = mgetcookie('returnurl');
//$returnurl = $returnurl ? urldecode($returnurl) : '';
$code = isset($_GET['code']) ? trim(htmlspecialchars($_GET['code'])) : '';
$actionkey = isset($_GET['actionkey']) ? trim(htmlspecialchars($_GET['actionkey'])) : '';
$data = read_static_cache('wxlogin');
$appid    = $data['appid'];
$appsecret   = $data['appsecret'];
$callback = $data['callback'];
$scope = 'snsapi_userinfo';
$state = 'mymps';

$json_obj = get_wxuser();

$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
$json_obj_more = get_wxuser_more();
$nickname = $json_obj_more['nickname'];
$prelogo = $json_obj_more['headimgurl'];
$logo = $prelogo;

if($openid) $row = $db -> getRow("SELECT userid,userpwd FROM `{$db_mymps}member` WHERE `openid_wx` = '$openid'");

require MYMPS_INC."/member.class.php";
if(is_array($row)){

	$userid = $row['userid'];
	$userpwd = $row['userpwd'];
	$db -> query("UPDATE `{$db_mymps}member` SET logintime='$timestamp' WHERE userid = '$userid' ");
	if(PASSPORT_TYPE == 'phpwind'){
		require MYMPS_ROOT.'/pw_client/uc_client.php';
		$user_login = uc_user_login($userid,$userpwd,0);
		$member_log -> in($userid,$userpwd,'off','noredirect');
		echo $user_login['synlogin'];
	} elseif(PASSPORT_TYPE == 'ucenter'){
		$member_log -> in($userid,$userpwd,'off','noredirect');
		require MYMPS_ROOT.'/uc_client/client.php';
		list($uid, $username, $password, $email) = uc_user_login($userid, $userpwd);
		echo uc_user_synlogin($uid);
	} else {
		$member_log -> in($userid,$userpwd,'off','noredirect');
	}
	
	$db->query("INSERT INTO `{$db_mymps}member_wx` (`actionkey`,`openid`,`userid`,`userpwd`)VALUES ('$actionkey','$openid','$userid','$userpwd')");
	
	if(!pcclient() && $view != 'pc'){
		$mayimobile = get_mobile_settings();
		$mayimobile['mobiledomain'] = $mayimobile['mobiledomain']?$mayimobile['mobiledomain']:$mymps_global['SiteUrl'].'/m';
		$returnurl=$returnurl?$returnurl:$mayimobile['mobiledomain'].'/?mod=member';
		echo mymps_goto($returnurl);
	} else{
		echo mymps_goto($mymps_global['SiteUrl'].'/member/?frame=on');
	}
} else{
	
	$nickname = $charset == 'gbk' ? iconv("UTF-8", "GBK", matchname($nickname)) : matchname($nickname);
	$nickname = cutstr($nickname,15);
	$userid = !reusername($nickname) ? $nickname : $nickname.random(6);
	$userid = !reusername($userid) ? $userid : $userid.random(6);
	$userid = 'lei_'.$timestamp.rand(0,100);
	$userpwd = md5(random());
	$invite = mgetcookie('invite');
	
	if($db->getOne("SELECT COUNT(id) FROM `{$db_mymps}member` WHERE userid = '$userid'") < 1){
		
		$email = random().'@qq.com';
		if(PASSPORT_TYPE == 'phpwind'){
			require MYMPS_ROOT.'/pw_client/uc_client.php';
			$checkuser = uc_check_username($userid);
			if($checkuser == -2){
				write_msg('用户名重复，请换一个用户名注册');
			} elseif($checkuser == -1){
				write_msg('用户名不符合规范，请换一个用户名注册');
			} elseif($checkuser == 1){
			
			} else {
				write_msg('未知错误，请换一个用户名注册');
			}
			
			if($email){
				$checkemail = uc_check_email($email);
				$checkemail == -3 && write_msg('Email格式不正确，请填写正确的Email');
				$checkemail == -4 && write_msg('该Email地址已重复，请更换一个Email地址');
			}
			
			uc_user_register($userid,md5($userpwd),$email);
			$user_login = uc_user_login($userid,$userpwd,0);
			echo $user_login['synlogin'];
			
		} elseif(PASSPORT_TYPE == 'ucenter'){
			require MYMPS_ROOT.'/uc_client/client.php';
			if($activation && ($activeuser = uc_get_user($activation))) {
				list($uid, $userid) = $activeuser;
			} else {
				$user = $db -> getRow("SELECT id,userid FROM `{$db_mymps}member` WHERE userid = '$userid'");
				if(uc_get_user($userid) && !$user['userid']) {
					write_msg("该用户无需注册，请重新登录",$mymps_global[SiteUrl]."/".$mymps_global['cfg_member_logfile']);
				}
				$uid = uc_user_register($userid,$userpwd, $email);
				if($uid <= 0) {
					if($uid == -1) {
						write_msg('用户名不合法');
					} elseif($uid == -2) {
						write_msg( '包含不允许注册的词语');
					} elseif($uid == -3) {
						write_msg( '用户名已经存在');
					} elseif($uid == -4) {
						write_msg( 'Email 格式有误');
					} elseif($uid == -5) {
						write_msg( 'Email 不允许注册');
					} elseif($uid == -6) {
						write_msg( '该 Email 已经被注册');
					} else {
						write_msg( '未定义');
					}
				} else {
					$userid  = trim($userid);
					$userpwd = trim($userpwd);
					$email 	 = trim($email);
				}
				
				list($uid, $username, $password, $email) = uc_user_login($userid, $userpwd);
				echo uc_user_synlogin($uid);
			}
			
		}
		
		member_reg($userid,$userpwd,'','','','','',1,$openid,$logo,$prelogo,$invite);
	}
	
	$member_log -> in($userid,$userpwd,'off','noredirect');
	
	$db->query("INSERT INTO `{$db_mymps}member_wx` (`actionkey`,`openid`,`userid`,`userpwd`)VALUES ('$actionkey','$openid','$userid','$userpwd')");
	
	if(!pcclient() && $view != 'pc'){
		$mayimobile = get_mobile_settings();
		$mayimobile['mobiledomain'] = $mayimobile['mobiledomain']?$mayimobile['mobiledomain']:$mymps_global['SiteUrl'].'/m';
		$returnurl=$returnurl?$returnurl:$mayimobile['mobiledomain'].'/?mod=member';
		echo mymps_goto($returnurl);
	} else{
		echo mymps_goto($mymps_global['SiteUrl'].'/member/?frame=on');
	}
}


function get_wxuser()
{
	global $appid,$appsecret,$code;
    $graph_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
	$str  = get_url_contents($graph_url);
    $user = json_decode($str);
    if (isset($user->errcode))
    {
        echo "<h3>error:</h3>" . $user->errcode;
        echo "<h3>msg  :</h3>" . $user->errmsg;
        exit;
    }
    $userarr['openid'] = $user->openid;
	$userarr['access_token'] = $user->access_token;
	return $userarr;
}

function get_wxuser_more(){
	global $access_token,$openid;
	$graph_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; 
	$str  = get_url_contents($graph_url);
	
    $user = json_decode($str);
    if (isset($user->errcode))
    {
        echo "<h3>error:</h3>" . $user->errcode;
        echo "<h3>msg  :</h3>" . $user->errmsg;
        exit;
    }
    $userarr['openid'] = $user->openid;
	$userarr['nickname'] = $user->nickname;
	$userarr['sex'] = $user->sex;
	$userarr['province'] = $user->province;
	$userarr['city'] = $user->city;
	$userarr['country'] = $user->country;
	$userarr['headimgurl'] = $user->headimgurl;
	$userarr['privilege'] = $user->privilege;
	$userarr['unionid'] = $user->unionid;
	return $userarr;
	
}

function reusername($userid){
	global $db,$db_mymps;
	$ifreuser = $db->getOne("SELECT COUNT(id) FROM `{$db_mymps}member` WHERE userid = '$userid'");
	if($ifreuser > 0)
	{
		return true;
	}else{
		return false;
	}
}

function matchname($chars,$encoding='utf8')
{
	$chars=trim($chars);
	$pattern =($encoding=='utf8')?'/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u':'/[\x80-\xFF]/';
	preg_match_all($pattern,$chars,$result);
	$temp =join('',$result[0]);
	return $temp;
}
?>