<?php
$wind_in='rg';
define('SCR','register');
require_once('global.php');

include_once(D_P."data/bbscache/dbreg.php");
include_once(D_P.'data/bbscache/customfield.php');
@include_once(D_P.'data/bbscache/inv_config.php');
list($rg_regminname,$rg_regmaxname) = explode("\t",$rg_namelen);
list($rg_regminpwd,$rg_regmaxpwd) = explode("\t",$rg_pwdlen);

if (GetGP('vip') == 'activating') {
	InitGP(array('r_uid','pwd'),'G');
	$r_uid = (int)$r_uid;
	$u_db  = $db->get_one('SELECT yz FROM pw_members WHERE uid='.pwEscape($r_uid));
	if ($u_db) {
		if ($pwd == $u_db['yz']) {
			$db->update('UPDATE pw_members SET yz=1 WHERE uid='.pwEscape($r_uid));
			require_once(R_P.'require/header.php');
			require_once(PrintEot('register'));footer();exit;
			Showmsg('reg_jihuo_success');
		} else {
			Showmsg('reg_jihuo_fail');
		}
	} else {
		Showmsg('reg_jihuo_fail');
	}
}
if ($db_pptifopen && $db_ppttype == 'client') {
	Showmsg('passport_register');
}
list($regq) = explode("\t",$db_qcheck);

if (GetGP('action','P') == 'regcheck') {
	InitGP(array('type'),'P');
	if ($type == 'regname') {
		InitGP('username','P');
		if (strlen($username) > $rg_regmaxname || strlen($username) < $rg_regminname) {
			echo 1;
			ajax_footer();
		}
		$S_key = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','%','?');
		foreach ($S_key as $value) {
			if (strpos($username,$value) !== false) {
				echo 2;
				ajax_footer();
			}
		}
		if (!$rg_rglower) {
			for ($asc = 65; $asc <= 90; $asc++) {
				if (strpos($username,chr($asc)) !== false) {
					echo 3;
					ajax_footer();
				}
			}
		}
		$rg_banname = explode(',',$rg_banname);
		foreach ($rg_banname as $value) {
			if ($value && strpos($username,$value) !== false) {
				echo 2;
				ajax_footer();
			}
		}
		$rt = $db->get_one('SELECT uid FROM pw_members WHERE username='.pwEscape($username));
		if ($rt) {
			echo 4;
		} else {
			echo 0;
		}
	} elseif ($type == 'regemail') {
		sleep(1);
		InitGP('email','P');
		if (!$email || !preg_match("/^[-a-zA-Z0-9_\.]+@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,5}$/",$email)) {
			echo 1;
			ajax_footer();
		}
		$rt = $db->get_one('SELECT uid FROM pw_members WHERE email='.pwEscape($email));
		if ($rt) {
			echo 2;
		} else {
			echo 0;
		}
	} elseif ($type == 'reggdcode') {
		InitGP('gdcode','P');
		if (!$gdcode || !SafeCheck(explode("\t",StrCode(GetCookie('cknum'),'DECODE')),strtoupper($gdcode),'cknum',1800)) {
			echo 1;
		} else {
			echo 0;
		}
	} elseif ($type == 'qanswer') {
		InitGP(array('answer','question'),'P');
		if ($db_question && (!isset($db_answer[$question]) || $answer!=$db_answer[$question])) {
			echo 1;
		} else {
			echo 0;
		}
	} elseif ($type == 'invcode') {
		InitGP('invcode','P');
		if (empty($invcode)) {
			echo 1;
		} else {
			$inv_days *= 86400;
			$inv = $db->get_one("SELECT id FROM pw_invitecode WHERE invcode=" . pwEscape($invcode) . " AND ifused<'2' AND createtime>" . pwEscape($timestamp-$inv_days));
			if (!$inv) {
				echo 2;
			} else {
				echo 0;
			}
		}
	}
	ajax_footer();
}
if ($rg_allowregister == 0 || ($rg_registertype == 1 && date('j',$timestamp) != $rg_regmon) || ($rg_registertype == 2 && date('w',$timestamp) != $rg_regweek)) {
	Showmsg($rg_whyregclose);
}
if ($rg_allowsameip && file_exists(D_P.'data/bbscache/ip_cache.php')) {
	$ipdata  = readover(D_P.'data/bbscache/ip_cache.php');
	$pretime = (int)substr($ipdata,13,10);
	if ($timestamp-$pretime>$rg_allowsameip*3600) {
		P_unlink(D_P.'data/bbscache/ip_cache.php');
	} elseif (strpos($ipdata,"<$onlineip>") !== false) {
		Showmsg('reg_limit');
	}
}
InitGP(array('forward')); !$db_pptifopen && $forward = '';
InitGP(array('invcode','step'));

$step != 'finish' && $groupid != 'guest' && Showmsg('reg_repeat');

if (!$step && $step != 2) {

	!$rg_timestart && $rg_timestart=1960;
	!$rg_timeend && $rg_timeend=2000;
	$img = @opendir("$imgdir/face");
	while ($imagearray = @readdir($img)) {
		if ($imagearray!="." && $imagearray!=".." && $imagearray!="" && $imagearray!="none.gif") {
			$imgselect.="<option value='$imagearray'>$imagearray</option>";
		}
	}
	@closedir($img);
	require_once(R_P.'require/header.php');
	$custominfo = unserialize($db_union[7]);
	require_once(PrintEot('register'));footer();

} elseif ($step == 2) {

	PostCheck(0,$db_gdcheck & 1,$regq,0);
	InitGP(array('regreason','regname','regpwd', 'regemail','customdata', 'regemailtoall','rgpermit'),'P');
	InitGP(array('question','customquest','answer'),'P');
	$sRegpwd		= $regpwd;
	$userstatus		= 0;
	$regemailtoall && setstatus($userstatus,7);

	if ($inv_open == '1') {
		if (empty($invcode)) {
			Showmsg('invcode_empty');
		} else {
			$inv_days *= 86400;
			$inv = $db->get_one("SELECT id,uid FROM pw_invitecode WHERE invcode=" . pwEscape($invcode) . " AND ifused<'2' AND createtime>" . pwEscape($timestamp-$inv_days));
			!$inv && Showmsg('illegal_invcode');
		}
	}
	if ($rg_ifcheck && !$regreason) {
		Showmsg('reg_reason');
	}
	if (strlen($regname)>$rg_regmaxname || strlen($regname)<$rg_regminname) {
		Showmsg('reg_username_limit');
	}
	if (strlen($regpwd)<$rg_regminpwd) {
		Showmsg('reg_password_minlimit');
	} elseif ($rg_regmaxpwd && strlen($regpwd)>$rg_regmaxpwd) {
		Showmsg('reg_password_maxlimit');
	} elseif ($rg_npdifferf && $regpwd==$regname) {
		Showmsg('reg_nameuptopwd');
	}
	$S_key = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','%','?');
	if (str_replace($S_key,'',$regname) != $regname) {
		Showmsg('illegal_username');
	} elseif ($regpwd!=$regname && str_replace($S_key,'',$regpwd) != $regpwd) {
		Showmsg('illegal_password');
	}
	
	if ($rg_pwdcomplex) {
		$arr_rule = array();
		$arr_rule = explode(',',$rg_pwdcomplex);
		foreach ($arr_rule as $value) {
			$value = (int)$value;
			if (!$value) continue;
			switch ($value){
				case 1:
					if (!preg_match('/[a-z]/',$regpwd)) {
						Showmsg('reg_password_lowstring');
					}
					break;
				case 2:
					if (!preg_match('/[A-Z]/',$regpwd)) {
						Showmsg('reg_password_upstring');
					}
					break;
				case 3:
					if (!preg_match('/[0-9]/',$regpwd)) {
						Showmsg('reg_password_num');
					}
					break;
				case 4:
					if (!preg_match('/[^a-zA-Z0-9]/',$regpwd)) {
						Showmsg('reg_password_specialstring');
					}
					break;
			}
		}
	}
	$safecv = '';
	if ($db_ifsafecv) {
		require_once(R_P.'require/checkpass.php');
		$safecv = questcode($question,$customquest,$answer);
	}
	if (!$rg_rglower) {
		for ($asc = 65; $asc <= 90; $asc++) {
			if (strpos($regname,chr($asc)) !== false) {
				Showmsg('username_limit');
			}
		}
	}
	
	$regpwd = md5($regpwd);
	
	require_once(D_P.'data/bbscache/level.php');
	@asort($lneed);
	$rg_memberid = key($lneed);

	if (strpos($regpwd,"\r")!==false || strpos($regpwd,"\t")!==false || strpos($regpwd,"|")!==false || strpos($regpwd,"<")!==false || strpos($regpwd,">")!==false) {
		Showmsg('illegal_password');
	}
	if (empty($regemail) || !ereg("^[-a-zA-Z0-9_\.]+\@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,5}$",$regemail)) {
		Showmsg('illegal_email');
	} else {
		if ($rg_email) {
			$e_check = 0;
			$e_limit = explode(',',$rg_email);
			foreach ($e_limit as $key => $val) {
				if (strpos($regemail,"@".$val)!==false) {
					$e_check=1;
					break;
				}
			}
			$e_check==0 && Showmsg('email_check');
		}
		$email_check = $db->get_one('SELECT COUNT(*) AS count FROM pw_members WHERE email=' . pwEscape($regemail));
		if ($email_check['count']) {
			Showmsg('reg_email_have_same');
		}
	}
	if ($regname !== Sql_cv($regname)) {
		Showmsg('illegal_username');
	}
	$rs = $db->get_one('SELECT COUNT(*) AS count FROM pw_members WHERE username='.pwEscape($regname));
	if ($rs['count'] > 0) {
		Showmsg('username_same');
	}

	CkInArray(strtolower($regname),array('guest','system')) && Showmsg('illegal_username');
	$rg_banname = explode(',',$rg_banname);
	foreach ($rg_banname as $value) {
		if ($value && strpos($regname,$value) !== false) {
			Showmsg('illegal_username');
		}
	}
	
	
	if ($rg_ifcheck == '1') {
		$rg_groupid = '7';//後台控制是否需要驗證
	} else {
		$rg_groupid = '-1';
	}

	if ($rg_emailcheck == 1) {
		$rg_yz = '1'.num_rand(9);
	} else {
		$rg_yz = 1;
	}

	$upmeminfo = array();
	if ($customfield) {
		foreach ($customfield as $key => $val) {
			$field  = "field_".(int)$val['id'];
			InitGP(array($field),'P');
			if ($val['required'] && !$$field) {
				Showmsg('field_empty');
			}
			if ($val['maxlen'] && strlen($$field) > $val['maxlen']) {
				Showmsg('field_lenlimit');
			}
			$upmeminfo[$field] = $$field;
		}
	}
	$pwSQL = pwSqlSingle(array(
		'username'	=> $regname,		'password'	=> $regpwd,
		'safecv'	=> $safecv,			'email'		=> $regemail,
		'groupid'	=> $rg_groupid,		'memberid'	=> $rg_memberid,
		'regdate'	=> $timestamp,		'icq'		=> '',				
		'yz'		=> $rg_yz,			'userstatus'=> $userstatus,
	));
	$db->update("INSERT INTO pw_members SET $pwSQL");
	$winduid = $db->insert_id();

	require_once(R_P.'require/credit.php');
	$credit->addLog('reg_register',$rg_regcredit,array(
		'uid'		=> $winduid,
		'username'	=> stripslashes($regname),
		'ip'		=> $onlineip
	));
	$credit->sets($winduid,$rg_regcredit,false);
	if ($regsql = $credit->runsql($winduid)) {
		$regsql.= ',';
	}
	$pwSQL = pwSqlSingle(array(
		'postnum'	=> 0,
		'lastvisit'	=> $timestamp,
		'thisvisit'	=> $timestamp,
		'onlineip'	=> $onlineip
	));
	$db->update("INSERT INTO pw_memberdata SET uid=".pwEscape($winduid).",$regsql $pwSQL ");

	if ($rg_ifcheck) {
		$upmeminfo['regreason'] = $regreason;
	}
	$db_union	= explode("\t",stripslashes($db_union));
	$custominfo	= unserialize($db_union[7]);
	if ($custominfo && $customdata) {
		foreach ($customdata as $key => $val) {
			$key = Char_cv($key);
			$customdata[stripslashes($key)] = stripslashes($val);
		}
		$upmeminfo['customdata'] = addslashes(serialize($customdata));
	}
	$db->update("UPDATE pw_bbsinfo SET newmember=".pwEscape($regname).",totalmember=totalmember+1 WHERE id='1'");
	if ($upmeminfo) {
		$db->update("REPLACE INTO pw_memberinfo SET uid=".pwEscape($winduid).','.pwSqlSingle($upmeminfo));
	}
	if ($inv_open == '1') {
		$db->update("UPDATE pw_invitecode SET " . pwSqlSingle(array('receiver' => $regname, 'usetime' => $timestamp, 'ifused' => 2)) . ' WHERE id=' . pwEscape($inv['id']));
		if ($inv['uid'] == 0) {
			$db->update("UPDATE pw_clientorder SET uid=" . pwEscape($winduid) . " WHERE type='4' AND uid='0' AND paycredit=" . pwEscape($inv['id']));
		}
	}
	$windid  = $regname;
	$windpwd = $regpwd;
	//$iptime=$timestamp+86400;
	//Cookie("ifregip",$onlineip,$iptime);
	if ($rg_allowsameip) {
		if (file_exists(D_P.'data/bbscache/ip_cache.php')) {
			writeover(D_P.'data/bbscache/ip_cache.php',"<$onlineip>","ab");
		} else {
			writeover(D_P.'data/bbscache/ip_cache.php',"<?php die;?><$timestamp>\n<$onlineip>");
		}
	}
	//addonlinefile();
	if (GetCookie('userads') && $db_ads == '2') {
		list($u,$a)=explode("\t",GetCookie('userads'));
		if (is_numeric($u) || ($a && strlen($a)<16)) {
			require_once(R_P.'require/userads.php');
		}
	}
	if (GetCookie('o_invite') && $db_modes['o']['ifopen']==1) {
		list($o_u,$hash,$app)=explode("\t",GetCookie('o_invite'));
		if (is_numeric($o_u) && strlen($hash)==18) {
			require_once(R_P.'require/o_invite.php');
		}
	}
	if ($rg_yz == 1) {
		Cookie("winduser",StrCode($winduid."\t".PwdCode($windpwd)."\t".$safecv));
		Cookie("ck_info",$db_ckpath."\t".$db_ckdomain);
		Cookie('lastvisit','',0);//將$lastvist清空以將剛注冊的會員加入今日到訪會員中
	}
	//發送短消息
	if ($rg_regsendmsg) {
		require_once(R_P.'require/msg.php');
		$rg_welcomemsg = str_replace('$rg_name',$regname,$rg_welcomemsg);
		$messageinfo   = array(
			'toUser'	=> $windid,
			'subject'	=> "Welcome To[{$db_bbsname}]!",
			'content'	=> $rg_welcomemsg
		);
		pwSendMsg($messageinfo);
	}

	//發送郵件
	

	if ($rg_emailcheck) {
		$verifyhash = GetVerify();
		require_once(R_P.'require/sendemail.php');
		$sendinfo = sendemail($regemail,'email_check_subject','email_check_content','email_additional');
		if ($sendinfo === true) {
			ObHeader("$db_registerfile?step=finish&email=$regemail&verify=$verifyhash");
		} else {
			Showmsg(is_string($sendinfo) ? $sendinfo : 'reg_email_fail');
		}
	} elseif ($rg_regsendemail) {
		require_once(R_P.'require/sendemail.php');
		sendemail($regemail,'email_welcome_subject','email_welcome_content','email_additional');
	}
	//發送結束

	//passport
	if ($db_pptifopen && $db_ppttype == 'server' && ($db_ppturls || $forward)) {
		$action = 'login';
		$jumpurl = $forward ? $forward : $db_ppturls;
		empty($forward) && $forward = $db_bbsurl;
		require_once(R_P.'require/passport_server.php');
	}
	//passport

	$verifyhash = GetVerify($winduid);
	ObHeader("$db_registerfile?step=finish&verify=$verifyhash");
} elseif ($step == 'finish') {
	InitGP(array('email'),'G');
	InitGP(array('option'));
	require_once(R_P.'require/header.php');
	
	PostCheck();
	
	if ($email && $rg_emailcheck) {
		list(,$emailurl) = explode('@',$email);
		$emailurl = 'http://mail.'.$emailurl;
		if ($_GET['r']) {
			require_once(R_P.'require/sendemail.php');
			$sendinfo = sendemail($email,'email_check_subject','email_check_content','email_additional');
			if ($sendinfo === true) {
				ObHeader("$db_registerfile?step=finish&email=$email&verify=$verifyhash");
			} else {
				Showmsg(is_string($sendinfo) ? $sendinfo : 'reg_email_fail');
			}
		}
	}
	if (!$rg_emailcheck) {
		!$winduid && Showmsg('illegal_request');
	}
	if ($option == '2') {
		InitGP(array('reghomepage','regfrom','regintroduce','regsign','regsex','regbirthyear','regbirthmonth','regbirthday','regoicq'),'P');
		
		
		$regsex = (int)$regsex;
		$regsex = $regsex ? $regsex : "0";
		$rg_birth = (!$regbirthyear || !$regbirthmonth || !$regbirthday) ? '0000-00-00' : $regbirthyear."-".$regbirthmonth."-".$regbirthday;
		if ($regoicq && !ereg("^[0-9]{5,}$",$regoicq)) {
			Showmsg('illegal_OICQ');
		}

		if ($regsign != '') {
			if (file_exists(D_P."data/groupdb/group_$rg_memberid.php")) {
				require_once Pcv(D_P."data/groupdb/group_$rg_memberid.php");
			} else {
				$_G['signnum'] = 50;
			}
			if (strlen($regsign) > $_G['signnum']) {
				Showmsg('sign_limit');
			}
			require_once(R_P.'require/bbscode.php');
			$lxsign = convert($regsign,$db_windpic,2);

			if ($lxsign <> $regsign) {
				setstatus($userstatus,9);
			}
		}

		if (@include_once(D_P."data/bbscache/wordsfb.php")) {
			$wordsfb = $wordsfb + $replace;
			foreach ($wordsfb as $key => $value) {
				$banword = (string) stripslashes($key);
				if (strpos($regsign,$banword) !== false || strpos($regintroduce,$banword) !== false) {
					Showmsg('sign_wordsfb');
				}
			}
		}
		if (strlen($regintroduce)>100) Showmsg('introduce_limit');
		
		$db->update("UPDATE pw_members SET " . pwSqlSingle(array('gender' => $regsex, 'bday' => $rg_birth, 'location' => $regfrom, 'oicq' => $regoicq, 'site' => $reghomepage, 'signature' => $regsign, 'introduce' => $regintroduce)) . ' WHERE uid=' . pwEscape($winduid));

	} elseif ($option == '3') {
		InitGP(array('proicon','facetype'),'P');
		require_once(R_P.'require/postfunc.php');
		require_once(R_P.'require/showimg.php');

		//user icon
		list($iconurl,,$iconwidth,$iconheight,$iconfile,$iconpig) = showfacedesign('',true);
	
		if ($_G['allowportait'] && $facetype == 2) {
			$httpurl = $_POST['httpurl'];
			if (strncmp($httpurl[0],'http',4) != 0 || strrpos($httpurl[0],'|') !== false) {
				Showmsg('illegal_customimg');
			}
			$httpurl[1] = (int)$httpurl[1];
			$httpurl[2] = (int)$httpurl[2];
			$iconfile = $httpurl[0];
			if (empty($httpurl[1]) && empty($httpurl[2])) {
				list($iconwidth,$iconheight) = getimagesize($iconfile);
			} else {
				list($iconwidth,$iconheight) = getfacelen($httpurl[1],$httpurl[2]);
			}
			unset($httpurl);
			
		} elseif ($db_ifupload && $_G['upload'] && $facetype == 3 && is_array($_POST['uploadurl'])) {
			UploadIcon($_POST['uploadurl']);
		}
		
		$usericon = GetIcon($proicon);
		
		pwFtpClose($ftp);

		$db->update("UPDATE pw_members SET icon=".pwEscape($usericon,false)."WHERE uid=".pwEscape($winduid));

		refreshto("./$db_bfn",'reg_success');
	} elseif ($option == 'ajaxface') {
		require_once(R_P.'require/postfunc.php');
		require_once(R_P.'require/showimg.php');
		define('AJAX',true);
		$facetype = $_POST['facetype'];
		list($iconurl,,$iconwidth,$iconheight,$iconfile,$iconpig) = showfacedesign('',true);
		$iconfile = addslashes($iconfile);
		if ($facetype == 3 && $db_ifupload && $_G['upload'] && is_array($_POST['uploadurl'])) {
			UploadIcon($_POST['uploadurl']);
			pwFtpClose($ftp);
			$usericon = GetIcon();
			$db->update("UPDATE pw_members SET icon=".pwEscape($usericon,false)."WHERE uid=".pwEscape($winduid));
			if ($iconpig) {
				$iconurl = "$imgpath/pig.gif";
			} elseif ($db_ftpweb && !file_exists("$attachdir/upload/$iconfile")) {
				$iconurl = "$db_ftpweb/upload/";
			} else {
				$iconurl = "$attachpath/upload/";
			}
			$showmsg = 'success';
		} else {
			$showmsg = 'undefined_action';
		}
		echo "<script language=\"JavaScript1.2\">parent.facepath('$iconurl','$iconfile','$showmsg','$iconwidth','$iconheight');</script>";exit;

	}
	
	require_once(PrintEot('register'));footer();

} else {
	Showmsg('undefined_action');
}


function UploadIcon($uploadurl) {
	global $db_uploadfiletype,$db_imgsize,$iconfile,$iconwidth,$iconheight,$facetype,$winduid;
	$db_uploadfiletype = array();
	$db_uploadfiletype['gif'] = $db_uploadfiletype['jpg'] = $db_uploadfiletype['bmp'] = $db_uploadfiletype['png'] = $db_imgsize;
	$uploadurl[1] = (int)$uploadurl[1];
	$uploadurl[2] = (int)$uploadurl[2];
	$uploaddb = UploadFile($winduid,'face',"1\t1");
	if (!empty($uploaddb)) {
		$attachurl = str_replace('upload/','',$uploaddb[0]['attachurl']);
		$iconfile = $attachurl;
		$uploadurl[1] > $uploaddb[0]['img_w'] && $uploadurl[1] = $uploaddb[0]['img_w'];
		$uploadurl[2] > $uploaddb[0]['img_h'] && $uploadurl[2] = $uploaddb[0]['img_h'];
		if (!$uploadurl[1] && !$uploadurl[2]) {
			$uploadurl[1] = $uploaddb[0]['img_w'];
			$uploadurl[2] = $uploaddb[0]['img_h'];
		}
		list($iconwidth,$iconheight) = getfacelen($uploadurl[1],$uploadurl[2]);
	} else {
		if (!$uploadurl[1] || !$uploadurl[2]) {
			global $iconurl;
			require_once(R_P.'require/imgfunc.php');
			$srcdata = GetImgSize($iconurl);
			$iconwidth = $srcdata['width'];
			$iconheight = $srcdata['height'];
		} else {
			list($iconwidth,$iconheight) = getfacelen($uploadurl[1],$uploadurl[2]);
		}
	}
}
function GetIcon($proicon = null) {
	global $iconfile,$iconwidth,$iconheight,$iconpig,$facetype,$db_imgheight,$db_imgwidth;
	if ($facetype == 1) {
		global $imgdir;
		if (!file_exists("$imgdir/face/$proicon")) {
			$proicon = 'none.gif';
		}
	
		if (!empty($proicon)) {
			if (strlen($proicon)>20 || !preg_match('/^[0-9A-Za-z]+\.[A-Za-z]{2,5}$/',$proicon)) {
				Showmsg('undefined_action');
			}
			$iconfile = $proicon;
		}
		$iconwidth = $iconheight = 0;
	} elseif ($facetype == 3 && $proicon) {
		$iconfile = $proicon;
	}
	
	$iconwidth < 1 && $iconwidth = '';
	$iconheight < 1 && $iconheight = '';
	$usericon = "$iconfile|$facetype|$iconwidth|$iconheight";
	$iconpig && $usericon .= "|$iconpig";
	strlen($usericon)>100 && Showmsg('illegal_customimg');
	return $usericon;
}
?>