<?php
/* 
 * 微信登录接口 (客户端微信登录默认 新注册用户) ps: 客户端必须有auth否则 客户端多项功能均无法实现
 * ==============================================================
 * @param openid           | 微信用户唯一标示符
 * @param username         | 注册用户名
 * @param 
 * @param 
 * @author                 | zhangxin 
 * ==============================================================
 */
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}


class register_wechat {

	var $showregisterform = 1;

	function register_wechat() {
        
		global $_G;
                //论坛网站关闭
		if($_G['setting']['bbclosed']) {
			if(($_GET['action'] != 'activation' && !$_GET['activationauth']) || !$_G['setting']['closedallowactivation'] ) {
				showmessage('register_disable', NULL, array(), array('login' => 1));
			}
		}

		loadcache(array('modreasons', 'stamptypeid', 'fields_required', 'fields_optional', 'fields_register', 'ipctrl'));
		require_once libfile('function/misc');
		require_once libfile('function/profile');
		if(!function_exists('sendmail')) {
			include libfile('function/mail');
		}
		loaducenter();
	}

	function wechat_register(){
                global $_G;
                //print_r(unserialize($_G['setting']['mobilewechat']));die;
                if(!in_array('wechat', $_G['setting']['plugins']['available'])){
                        //微信插件未安装
                        odz_error('wechat_not_exists');
                }
                if(empty($_GET['openid']) || empty($_GET['username'])){
                        odz_error('openid_or_username_empty');
                }
                $checkusername = DB::fetch_first(' SELECT * FROM '.DB::table('common_member')." WHERE username = '".$_GET['username']."'");
                if($checkusername){
                        odz_error('username_exists');
                }
                $checkopenid = DB::fetch_first(' SELECT * FROM '.DB::table('common_member_wechatmp')." WHERE openid = '".$_GET['openid']."'");
                if($checkopenid){
                        odz_error('openid_exists');
                }
                $ulenth = dstrlen($_GET['username']);
                if($ulength >15 || $ulenth <3){
                        odz_error('username_length_error');
                }
                $chat_setting = isset($_G['setting']['mobilewechat'])?unserialize($_G['setting']['mobilewechat']):odz_error('wechat_not_exists');
		$groupinfo = array();		
		$groupinfo['groupid'] = $chat_setting['wechat_newusergroupid'];		
		$username = isset($_GET['username']) ? $_GET['username'] : '';
		// 执行会员注册流程
		
		$activation = array();
		$profile = $verifyarr = array();
                $questionid = '';
                $answer = '';
                $email = strtolower(random(6)).'@mocuzmail.com';
                $password = 'mocuz123456';
		if(!$activation) {
			$uid = uc_user_register(addslashes($username), $password, $email, $questionid, $answer, $_G['clientip']);
			if($uid <= 0) {
				if($uid == -1) {
					odz_error('profile_username_illegal');
				} elseif($uid == -2) {
					odz_error('profile_username_protect');
				} elseif($uid == -3) {
					odz_error('profile_username_duplicate');
				} elseif($uid == -4) {
					odz_error('profile_email_illegal');
				} elseif($uid == -5) {
					odz_error('profile_email_domain_illegal');
				} elseif($uid == -6) {
					odz_error('profile_email_duplicate');
				} else {
					odz_error('undefined_action');
				}
			}
		} else {
			list($uid, $username, $email) = $activation;
		}
                if($uid){
                        $chatid = DB::insert('common_member_wechatmp', array('uid'=>$uid,'openid'=>$_GET['openid'],'status'=>'0'));
                        if(!$chatid){
                            odz_error('login_failed');
                        }
                }
		$_G['username'] = $username;
		if(getuserbyuid($uid, 1)) {
			if(!$activation) {
				uc_user_delete($uid);
			}
			odz_error('profile_uid_duplicate');
		}
		$password = md5(random(10));
		$secques = $questionid > 0 ? random(8) : '';

		if(isset($_POST['birthmonth']) && isset($_POST['birthday'])) {
			$profile['constellation'] = get_constellation($_POST['birthmonth'], $_POST['birthday']);
		}
		if(isset($_POST['birthyear'])) {
			$profile['zodiac'] = get_zodiac($_POST['birthyear']);
		}

		$init_arr = array('credits' => explode(',', $this->setting['initcredits']), 'profile'=>$profile, 'emailstatus' => $emailstatus);

		C::t('common_member')->insert($uid, $username, $password, $email, $_G['clientip'], $groupinfo['groupid'], $init_arr);
    
		if($verifyarr) {
			$setverify = array(
				'uid' => $uid,
				'username' => $username,
				'verifytype' => '0',
				'field' => serialize($verifyarr),
				'dateline' => TIMESTAMP,
			);
			C::t('common_member_verify_info')->insert($setverify);
			C::t('common_member_verify')->insert(array('uid' => $uid));
		}
		$refreshtime = 3000;
		switch($this->setting['regverify']) {
			case 1:
				$idstring = random(6);
				$authstr = $this->setting['regverify'] == 1 ? "$_G[timestamp]\t2\t$idstring" : '';
				C::t('common_member_field_forum')->update($_G['uid'], array('authstr' => $authstr));
				$verifyurl = "{$_G[baseurl]}member.php?mod=activate&amp;uid={$_G[uid]}&amp;id=$idstring";
				$email_verify_message = lang('email', 'email_verify_message', array(
					'username' => $_G['member']['username'],
					'bbname' => $this->setting['bbname'],
					'siteurl' => $_G['baseurl'],
					'url' => $verifyurl
				));
				if(!sendmail("$username <$email>", lang('email', 'email_verify_subject'), $email_verify_message)) {
					runlog('sendmail', "$email sendmail failed.");
				}
				$message = 'register_email_verify';
				$locationmessage = 'register_email_verify_location';
				$refreshtime = 10000;
				break;
			case 2:
				$message = 'register_manual_verify';
				$locationmessage = 'register_manual_verify_location';
				break;
			default:
				$message = 'register_succeed';
				$locationmessage = 'register_succeed_location';
				break;
		}

        //记录密码尚未被修改（个人中心显示‘设置密码’，不显示‘修改密码’）by zyj at 20170216
        $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 = array();
                $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,username 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 = '".$groupinfo['groupid']."'");
                $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("{$password}\t{$uid}", 'ENCODE', '', 31536000); // 登录令牌有效期(31536000=1年)
                $result_data['iswechat'] = '1';
                $result_data['password_status'] = 1;

				// 登录团购系统
				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_done', 'POST', $e->encrypt(json_encode(array('username'=>odz_encode($regdate['username']),'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);
		
	}
}

$ctl_obj = new register_wechat();
$ctl_obj->setting = $_G['setting'];
$ctl_obj->wechat_register();



?>