<?php

/*
	[DISCUZ!] register.php - new member registration
	This is NOT a freeware, use is subject to license terms

	Version: 4.0.0
	Web: http://www.comsenz.com
	Copyright: 2001-2005 Comsenz Technology Ltd.
	Last Modified: 2005-3-31 18:24
*/

require_once './include/common.inc.php';
require_once DISCUZ_ROOT.'./forumdata/cache/cache_profilefields.php';

$discuz_action = 5;

if($discuz_uid) {
	showmessage('login_succeed', 'index.php');
}

if(!$regstatus) {
	showmessage('register_disable');
}

$query = $db->query("SELECT * FROM {$tablepre}settings WHERE variable IN ('doublee', 'bbrules', 'bbrulestxt', 'welcomemsg', 'welcomemsgtxt')");
while($setting = $db->fetch_array($query)) {
	$$setting['variable'] = $setting['value'];
}

$query = $db->query("SELECT groupid, allownickname, allowcstatus, allowavatar, allowcusbbcode, allowsigbbcode, allowsigimgcode, maxsigsize FROM {$tablepre}usergroups WHERE ".($regverify ? "groupid='8'" : "creditshigher<=".intval($initcredits)." AND ".intval($initcredits)."<creditslower LIMIT 1"));
$groupinfo = $db->fetch_array($query);

//get secure code checking status (pos. -1)
$seccodecheck = substr(sprintf('%05b', $seccodestatus), -1, 1);

if(!submitcheck('regsubmit', 0, $seccodecheck)) {

	if($bbrules && !submitcheck('rulesubmit')) {

		$bbrulestxt = nl2br("\n$bbrulestxt\n\n");

	} else {

		$enctype = $groupinfo['allowavatar'] == 3 ? 'enctype="multipart/form-data"' : NULL;

		$censoremail = str_replace("\r\n", '/', $censoremail);

		$styleselect = $dayselect = '';
		$query = $db->query("SELECT styleid, name FROM {$tablepre}styles WHERE available='1'");
		while($styleinfo = $db->fetch_array($query)) {
			$styleselect .= '<option value="'.$styleinfo['styleid'].'">'.$styleinfo['name'].'</option>'."\n";
		}

		for($num = 1; $num <= 31; $num++) {
			$dayselect .= '<option value="'.$num.'">'.$num.'</option>';
		}

		$dateformatorig = $dateformat;
		$dateformatorig = str_replace('n', 'mm', $dateformatorig);
		$dateformatorig = str_replace('j', 'dd', $dateformatorig);
		$dateformatorig = str_replace('y', 'yy', $dateformatorig);
		$dateformatorig = str_replace('Y', 'yyyy', $dateformatorig);

	}

	if($seccodecheck) {
		$seccode = random(4, 1);
	}

	include template('register');

} else {

	require_once DISCUZ_ROOT.'./include/discuzcode.func.php';
	include_once DISCUZ_ROOT.'./forumdata/cache/cache_bbcodes.php';

	$email = trim($email);
	$username = trim($username);
	$alipay = trim($alipay);

	if(strlen($username) > 15) {
		showmessage('profile_username_toolang');
	}

	if($password != $password2) {
		showmessage('profile_passwd_notmatch');
	}
	
	// Regular Expression for "Guest" of different languages
	$guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';

	$censorexp = '/^('.str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($censoruser = trim($censoruser)), '/')).')$/i';
	if(preg_match("/^\s*$|^c:\\con\\con$|[%,\*\"\s\t\<\>\&]|$guestexp/is", $username) || ($censoruser && @preg_match($censorexp, $username))) {
		showmessage('profile_username_illegal');
	}
	if($censoruser && (@preg_match($censorexp, $nickname) || @preg_match($censorexp, $cstatus))) {
		showmessage('profile_nickname_cstatus_illegal');
	}

	if(!$password || $password != addslashes($password)) {
		showmessage('profile_passwd_illegal');
	}

	$censorexp = '/('.str_replace("\r\n", '|', preg_quote($censoremail, '/')).')$/i';
	if(!isemail($email) || ($censoremail && preg_match($censorexp, $email))) {
		showmessage('profile_email_illegal');
	}

	if($alipay && !isemail($alipay)) {
		showmessage('profile_alipay_illegal');
	}

	$fieldadd1 = $fieldadd2 = '';
	foreach(array_merge($_DCACHE['fields_required'], $_DCACHE['fields_optional']) as $field) {
		$field_key = 'field_'.$field['fieldid'];
		$field_val = ${'field_'.$field['fieldid'].'new'};
		if($field['required'] && trim($field_val) == '') {
			showmessage('profile_required_info_invalid');
		} elseif($field['selective'] && $field_val != '' && !isset($field['choices'][$field_val])) {
			showmessage('undefined_action', NULL, 'HALTED');
		} else {
			$fieldadd1 .= ", $field_key";
			$fieldadd2 .= ", '".dhtmlspecialchars($field_val)."'";
		}
	}

	if($regverify == 2 && !trim($regmessage)) {
		showmessage('profile_required_info_invalid');
	}

	if($groupinfo['maxsigsize']) {
		if(strlen($signature) > $groupinfo['maxsigsize']) {
			$maxsigsize = $groupinfo['maxsigsize'];
			showmessage('profile_sig_toolang');
		}
	} else {
		$signature = '';
	}

	if($ipregctrl) {
		foreach(explode("\n", $ipregctrl) as $ctrlip) {
			if(preg_match("/^(".preg_quote(($ctrlip = trim($ctrlip)), '/').")/", $onlineip)) {
				$ctrlip = $ctrlip.'%';
				$regctrl = 72;
				break;
			}
		}
	} else {
		$ctrlip = $onlineip;
	}
				
	if($regctrl) {
		$query = $db->query("SELECT ip FROM {$tablepre}regips WHERE ip LIKE '$ctrlip' AND count='-1' AND dateline>$timestamp-'$regctrl'*3600 LIMIT 1");
		if($db->num_rows($query)) {
			showmessage('register_ctrl', NULL, 'HALTED');
		}
	}

	$query = $db->query("SELECT uid FROM {$tablepre}members WHERE username='$username'");
	if($db->num_rows($query)) {
		showmessage('profile_username_duplicate');
	}

	if(!$doublee) {
		$query = $db->query("SELECT uid FROM {$tablepre}members WHERE email='$email' LIMIT 1");
		if($db->num_rows($query)) {
			showmessage('profile_email_duplicate');
		}
	}

	if(($groupinfo['allowavatar'] == 2 || $groupinfo['allowavatar'] == 3) && $avatar) {
		$avatar = dhtmlspecialchars($avatar);
		$avatarext = strtolower(fileext($avatar));
		if(!preg_match("/^((customavatars\/\d+\.[a-z]+)|(images\/avatars\/.+?)|(http:\/\/.+?))$/i", $avatar)
			|| !in_array($avatarext, array('gif', 'jpg', 'png'))) {
			showmessage('profile_avatar_invalid');
		}
	} elseif($groupinfo['allowavatar'] == 3 && $_FILES['customavatar']) {
		if(disuploadedfile($_FILES['customavatar']['tmp_name']) && $_FILES['customavatar']['tmp_name'] != 'none' && $_FILES['customavatar']['tmp_name'] && trim($_FILES['customavatar']['name'])) {
			$_FILES['customavatar']['name'] = daddslashes($_FILES['customavatar']['name']);
			$avatarext = strtolower(fileext($_FILES['customavatar']['name']));
			if(!in_array($avatarext, array('gif', 'jpg', 'png'))) {
				showmessage('profile_avatar_invalid');
			}
		} else {
			$_FILES['customavatar'] = array();
		}
	} else {
		$avatar = '';
	}

	if($regfloodctrl) {
		$query = $db->query("SELECT count FROM {$tablepre}regips WHERE ip='$onlineip' AND count>'0' AND dateline>'$timestamp'-86400");
		if($regattempts = $db->result($query, 0)) {
			if($regattempts >= $regfloodctrl) {
				showmessage('register_flood', NULL, 'HALTED');
			} else {
				$db->query("UPDATE {$tablepre}regips SET count=count+1 WHERE ip='$onlineip' AND count>'0'");
			}
		} else {
			$db->query("INSERT INTO {$tablepre}regips (ip, count, dateline)
				VALUES ('$onlineip', '1', '$timestamp')");
		}
	}

	$password = md5($password);
	$secques = quescrypt($questionid, $answer);

	$tppnew = in_array($tppnew, array(10, 20, 30)) ? $tppnew : 0;
	$pppnew = in_array($pppnew, array(5, 10, 15)) ? $pppnew : 0;

	if($dateformatnew) {
		$dateformatnew = str_replace('mm', 'n', $cdateformatnew);
		$dateformatnew = str_replace('dd', 'j', $dateformatnew);
		$dateformatnew = str_replace('yyyy', 'Y', $dateformatnew);
		$dateformatnew = str_replace('yy', 'y', $dateformatnew);
	} else {
		$dateformatnew = '';
	}

	$dateformatnew = str_replace('mm', 'n', $dateformatnew);
	$dateformatnew = str_replace('dd', 'j', $dateformatnew);
	$dateformatnew = str_replace('yyyy', 'Y', $dateformatnew);
	$dateformatnew = str_replace('yy', 'y', $dateformatnew);

	$icq = preg_match("/^([0-9]+)$/", $icq) && strlen($icq) >= 5 && strlen($icq) <= 12 ? $icq : '';
	$qq = preg_match("/^([0-9]+)$/", $qq) && strlen($qq) >= 5 && strlen($qq) <= 12 ? $qq : '';
	$bday = ($month && $day) ? (empty($year) ? '0000' : $year)."-$month-$day" : '';

	$avatar = dhtmlspecialchars($avatar);
	$yahoo = dhtmlspecialchars($yahoo);
	$msn = dhtmlspecialchars($msn);
	$taobao = dhtmlspecialchars($taobao);
	$email = dhtmlspecialchars($email);
	$alipay = dhtmlspecialchars($alipay);
	$bday = dhtmlspecialchars($bday);

	$signature = censor($signature);
	$sigstatus = $signature ? 1 : 0;
	$sightml = addslashes(discuzcode(stripslashes($signature), 1, 0, 0, 0, ($groupinfo['allowsigbbcode'] ? ($groupinfo['allowcusbbcode'] ? 2 : 1) : 0), $groupinfo['allowsigimgcode'], 0));

	$bio = censor(dhtmlspecialchars($bio));
	$site = dhtmlspecialchars(trim(preg_match("/^https?:\/\/.+/i", $site) ? $site : ($site ? 'http://'.$site : '')));

	$locationnew = cutstr(censor(dhtmlspecialchars($locationnew)), 30);
	$nickname = $groupinfo['allownickname'] ? cutstr(censor(dhtmlspecialchars($nickname)), 30) : '';
	$cstatus = $groupinfo['allowcstatus'] ? cutstr(censor(dhtmlspecialchars($cstatus)), 30) : '';

	$invisiblenew = $invisiblenew && $groupinfo['allowinvisible'] ? 1 : 0;

	$idstring = random(6);
	$authstr = $regverify == 1 ? "$timestamp\t2\t$idstring" : '';

	$db->query("INSERT INTO {$tablepre}members (username, password, secques, gender, adminid, groupid, regip, regdate, lastvisit, lastactivity, posts, credits, extcredits1, extcredits2, extcredits3, extcredits4, extcredits5, extcredits6, extcredits7, extcredits8, email, bday, sigstatus, tpp, ppp, styleid, dateformat, timeformat, pmsound, showemail, newsletter, invisible, timeoffset)
		VALUES ('$username', '$password', '$secques', '$gendernew', '0', '$groupinfo[groupid]', '$onlineip', '$timestamp', '$timestamp', '$timestamp', '0', $initcredits, '$email', '$bday', '$sigstatus', '$tppnew', '$pppnew', '$styleidnew', '$dateformatnew', '$timeformatnew', '$pmsoundnew', '$showemail', '$newsletter', '$invisiblenew', '$timeoffsetnew')");
	$uid = $db->insert_id();

	$db->query("INSERT INTO {$tablepre}memberfields (uid, nickname, site, icq, qq, yahoo, msn, taobao, alipay, location, bio, signature, sightml, customstatus, authstr $fieldadd1)
		VALUES ('$uid', '$nickname', '$site', '$icq', '$qq', '$yahoo', '$msn', '$taobao', '$alipay', '$locationnew', '$bio', '$signature', '$sightml', '$cstatus', '$authstr' $fieldadd2)");

	if($regctrl || $regfloodctrl) {
		$db->query("DELETE FROM {$tablepre}regips WHERE dateline<='$timestamp'-".($regctrl > 72 ? $regctrl : 72)."*3600", 'UNBUFFERED');
		if($regctrl) {
			$db->query("INSERT INTO {$tablepre}regips (ip, count, dateline)
				VALUES ('$onlineip', '-1', '$timestamp')");
		}
	}

	if($regverify == 2) {
		$db->query("REPLACE INTO {$tablepre}validating (uid, submitdate, moddate, admin, submittimes, status, message, remark)
			VALUES ('$uid', '$timestamp', '0', '', '1', '0', '$regmessage', '')");
	}

	if($avatar || $_FILES['customavatar']) {
		if($_FILES['customavatar']) {
			$avatar = 'customavatars/'.$uid.'.'.$avatarext;
			$avatartarget = DISCUZ_ROOT.'./'.$avatar;
			if(!@copy($_FILES['customavatar']['tmp_name'], $avatartarget)) {
				@move_uploaded_file($_FILES['customavatar']['tmp_name'], $avatartarget);
			}
			$avatarimagesize = @getimagesize($avatartarget);
			if(!$avatarimagesize) {
				@unlink($avatartarget);
				showmessage('profile_avatar_invalid');
			} elseif($maxavatarsize && filesize($avatartarget) > $maxavatarsize) {
				@unlink($avatartarget);
				showmessage('profile_avatar_toobig');
			}
		}

		if($avatarwidth == '*' || $avatarheight == '*') {
			$avatarwidth = $avatarheight = 80;
			@list($avatarwidth, $avatarheight) = $avatarimagesize;
		}
		$maxsize = max($avatarwidth, $avatarheight);
		if($maxsize > $maxavatarpixel) {
			$avatarwidth = $avatarwidth * $maxavatarpixel / $maxsize;
			$avatarheight = $avatarheight * $maxavatarpixel / $maxsize;
		}

		$db->query("UPDATE {$tablepre}memberfields SET avatar='$avatar', avatarwidth='$avatarwidth', avatarheight='$avatarheight' WHERE uid='$uid'");
	}

	if($welcomemsg && !empty($welcomemsgtxt)) {
		$welcomtitle = "Welcome to $bbname!";
		$welcomemsgtxt = addslashes($welcomemsgtxt);
		$db->query("INSERT INTO {$tablepre}pms (msgfrom, msgfromid, msgtoid, folder, new, subject, dateline, message)
			VALUES ('System Message', '0', '$uid', 'inbox', '1', '$welcomtitle', '$timestamp','$welcomemsgtxt')");
		$db->query("UPDATE {$tablepre}members SET newpm='1' WHERE uid='$uid'");
	}

	require_once DISCUZ_ROOT.'./include/cache.func.php';
	updatecache('settings');

	$discuz_uid = $uid;
	$discuz_user = $username;
	$discuz_userss = stripslashes($discuz_user);
	$discuz_pw = $password;
	$discuz_secques = $secques;
	$groupid = $groupinfo['groupid'];
	$styleid = $styleid ? $styleid : $_DCACHE['settings']['styleid'];

	switch($regverify) {
		case 1:
			sendmail($email, 'email_verify_subject', 'email_verify_message');
			showmessage('profile_email_verify');
			break;
		case 2:
			showmessage('register_manual_verify', 'memcp.php');
			break;
		default:
			showmessage('register_succeed', dreferer());
			break;
	}

}

?>