<?php
/* 
 * 微信登录检测 
 * ==============================================================
 * @param openid           | 微信用户唯一标示符
 * @param username         | 注册用户名
 * @param 
 * @param 
 * @author                 | zhangxin 
 * ==============================================================
 */
/*
    [uid] => 1
    [username] => admin
    [avatar] => http://192.168.100.252/discuz/uc_server/avatar.php?uid=1&size=middle&random=1448241241
    [auth] => 71a2nT/PxglE+esJUnJJDQiODRdj/nnHtN/aHp+7W188fMXSX1R5D/RWPs8/8u6H2zyW3tcEm/oftMIqSjmp
    [credits] => 466
    [grouptitle] => 管理员
    [regdate] => 2015-07-14
    [sightml] => 阿达大大大
    [mobile] => 18362935563
    [gender] => 2
    [affectivestatus] => 未婚
    [birth] => 1999-04-30
    [isperfect] => 1
    [ttauth] => 
    [errcode] => 0
    [errmsg] => 
 */
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

global $_G;
$profile = array();
$openid = trim($_GET['openid']);
if(!in_array('wechat', $_G['setting']['plugins']['available'])){
        //微信插件未安装
        odz_error('wechat_not_exists');
}
if(empty($openid)){
        odz_error('openid_not_exists');
}
$chat_setting = isset($_G['setting']['mobilewechat'])?unserialize($_G['setting']['mobilewechat']):odz_error('wechat_not_exists');
$result_data = array();
//$result_data['tag']为0表示新用户，为1表示已存在用户
$result_data['tag'] = 0;
//判断此微信用户是否已注册
$result  = DB::fetch_first(' SELECT * FROM '.DB::table('common_member_wechatmp')." WHERE openid = '".$openid."'");
if(!empty($result['uid'])){
    $member = DB::fetch_first('SELECT count(*) FROM '.DB::table('common_member').' WHERE uid = '.$result['uid']);
    if(empty($member)){
            DB::delete('common_member_wechatmp', array('uid'=>$result['uid']));
    }
}
if (!empty($result) && !empty($member)) {
    $result_data['tag'] = 1;
} else {
    //判断此微信用户是否已绑定add by zyj at 20170217
    $result  = DB::fetch_first(" SELECT * FROM mocuz_common_member_wechat_bind WHERE openid = '".$openid."'");
    if (!empty($result['uid']) && !empty($result['uid'])) {
        $result_data['tag'] = 1;
    }
}

if($result_data['tag'] === 1){
    //配置用户信息
    $ttauth = '';
    $uid = $result['uid'];
    $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,username,password FROM '.DB::table('common_member').' WHERE uid = '.$uid);
   // $mobiles	= DB::fetch_first('SELECT mobile FROM '.DB::table('mocuz_mobile').' WHERE uid = '.$uid);
    $group          = DB::fetch_first('SELECT grouptitle FROM '.DB::table('common_usergroup')." WHERE groupid = '".$chat_setting['wechat_newusergroupid']."'");
    $result_data['regdate'] = date('Y-m-d',$regdate['regdate']);
    $result_data['sightml'] =  !empty($sightml['sightml'])?(strip_tags($sightml['sightml'])?strip_tags($sightml['sightml']):odz_lang('no_message_left')):odz_lang('no_message_left');
    $result_data['mobile']	= !empty($user_info['mobile'])?$user_info['mobile']:odz_lang('no_binding');
    $result_data['gender'] = (string)$user_info['gender'];
    $result_data['affectivestatus'] = !empty($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['grouptitle'] = strip_tags($group['grouptitle']);//头衔
    $result_data['credits']  = (string)$_G['member']['credits'];//积分
    $result_data['avatar']  = avatar($uid, 'middle', true);//头像
    $result_data['uid'] = (string)$uid;//用户id
    $result_data['isperfect'] = "1";
    $result_data['ttauth'] = '';
    $result_data['username'] = $regdate['username'];
    $result_data['auth'] = authcode("{$regdate['password']}\t{$uid}", 'ENCODE', '', 31536000); // 登录令牌有效期(31536000=1年)
    $result_data['iswechat'] = 1;

    //查询是否设置过密码(老的微信用户没有添加此表) add by zyj at 20170217
    $ret = DB::fetch_first('SELECT password_status FROM mocuz_member_password_status WHERE uid='.$uid);
    if (empty($ret)) {
        $sql = "INSERT INTO mocuz_member_password_status (`uid`, `login_type`, `password_status`)
                        VALUES ('" . $uid . "', '3', '1')";
        $rs = DB::query($sql);
        /*DB::insert(
            'member_password_status',
            array(
                'uid' => $uid,
                'login_type' => 3,
                'password_status' => 1
            )
        );*/
        $result_data['password_status'] = 1;
    } else {
        $result_data['password_status'] = $ret['password_status'];
    }

 				// 登录团购系统
				
				if(defined('ODZ_TUANGOU_API')) {
					// 加密登录参数
					require_once 'includes/Mcrypt3Des.php';
					$e = new Mcrypt3Des();
					//$token 
					
					$token = md5('abcd123@!&');
					$ttresult = odz_http_request(ODZ_TUANGOU_API.'mocuz_api.php?mod=index&code=Login_username', 'POST', $e->encrypt(json_encode(array('username'=>odz_encode($regdate['username']), 'token'=>$token,'password'=>'mocuz123456'))));
                    
					is_string($ttresult) && $ttresult = json_decode($e->dencrypt($ttresult), true);

					if(!isset($ttresult['code']) || $ttresult['code'] != '0') {
						odz_error('teambuy_login_failed');
					}
				}
			if(isset($ttresult) && isset($ttresult['res'])) {
				$ttauth = $ttresult['res']['ttauth'];
			}
			$result_data['ttauth'] = $ttauth; 
}
	
odz_result($result_data);


?>