<?php

/*
 *	W-AGORA 4.2
 *	-----------
 *	$Id: register.php,v 1.48 2005/04/14 12:55:09 mdruilhe Exp $
 *	Usage:		register a new user into a site
 *	Author:		Marc Druilhe <mdruilhe@w-agora.net>
 *
 */

$no_cookie=1;
$bn_action="register";
define("no_auth_required", 1);		// authentication not required to register
require ("init.inc");

# A site must be defined in order to register
# -------------------------------------------
	if ($site == "agora") {
		display_header (ALT_REGISTER_USER, $header_footer);
		msgForm (ERROR_NO_SITE_SPECIFIED, "$main_page", "");
		display_footer($header_footer);
		exit;
	}

# Send to register page if defined
# --------------------------------
	$newURL = $auth->getRegisterURL();
	if (is_string($newURL)) {
		if (empty($newURL)) {
			display_header (ALT_REGISTER_USER, $header_footer);
			msgForm (ERROR_FEATURE_DISABLED, "$WA_SELF", "back");
			display_footer($header_footer);
		} else {
			header("Location: $newURL");
		}
		exit;
	}

# Include mail template
# ---------------------
	if (empty($bn_mail_template) ) {
		include ("$bn_dir_default/mail_template.$ext");
	} else {
		include "$bn_dir/$bn_mail_template";
	}

# gets all forums needing registration (usually only restricted and private forums should be listed here)
# -------------------------------------------------------------------------------------------------------
	$show_forums = "'rest', 'priv'";
	// $show_forums = "'rest'";

	$forums = array();
	$db->query("SELECT S.*, U.username as ownername, U.useraddress as owneraddress FROM $site S, ${site}_users U WHERE S.category!=1 AND S.state!='0' AND S.rank!=0 AND S.type IN ($show_forums) AND U.userid=S.owner");
	while ($db->next_record() ) {
		$_name = ereg_replace ("^${site}_", "", $db->Record["bn_name"]);
		$forums[$_name] = $db->Record;
	}


# Loads user table fields definitions
# -----------------------------------
	if (file_exists("$bn_dir_default/user_fields.$ext") ) {
		include "$bn_dir_default/user_fields.$ext";
	} else {
		include "$tmpl_dir/admin/user_fields.$ext";
	}

# Execute before_access program (set in init.inc)
# -----------------------------------------------
	if (!empty($before_access)) include $before_access;

	$bn_popup = 1;	// to include javascript
	display_header (ALT_REGISTER_USER, $header_footer);

# If Creation form have been submitted
# ------------------------------------
if (isset($go)) {

	$go=0;

	foreach($HTTP_POST_VARS as $var=>$val) {
		$$var = strip_magic_quotes($val);
	}

# Check for a valid email
# -----------------------
	if (!validate_email ($useraddress, MAIL_CHECK_DNS)) {
		msgForm (ERROR_INVALID_EMAIL, "$WA_SELF", "back");
		display_footer($header_footer);
		exit;
	}

#	Check for required fields
#	-------------------------
	if (is_array ($user_bind_var)) {
		reset($user_bind_var);
		while (list($field, $required) = each($user_bind_var)) {
			if ($required && isset($HTTP_POST_VARS[$field]) && ($$field=="") ) {
				$mess = sprintf (ERROR_MISSING_FIELD, $field);
				msgForm ("$mess", "$WA_SELF", "back");
				display_footer($header_footer);
				exit;
			}
		}
	}

#	Check that userid is valid (no spaces in it)
#	--------------------------------------------
	$userid = trim($userid);	// remove spaces at beginning and end
	if (ereg (" ", $userid) ) {
		msgForm (ERROR_SPACE_IN_USERID, "$WA_SELF", "back");
		display_footer($header_footer);
		exit;
	}

#	Check if users already exists
#	-----------------------------
	$u = $db->getUser($site, $userid);
	if (is_array($u)) {
		msgForm (sprintf(ERROR_USER_ALREADY_EXISTS, $userid), "$WA_SELF", "back");
		display_footer($header_footer);
		exit;
	}

	if (!isset($username) ) {
		if(isset($name)) {
			$username = (isset($firstname)) ? "$firstname $name" : $name;
		} elseif(isset($firstname)) {
			$username = $firstname;
		} else {
			$username = $userid;
		}
	}

	$u = $db->getUser($site, $username);
	if (is_array($u)) {
		msgForm (sprintf(ERROR_USER_ALREADY_EXISTS, $username), "$WA_SELF", "back");
		display_footer($header_footer);
		exit;
	}

	$u = $db->getUser($site, $useraddress, "useraddress");
	if (is_array($u)) {
		msgForm (sprintf(ERROR_EMAIL_ALREADY_EXISTS, $useraddress), "$WA_SELF", "back");
		display_footer($header_footer);
		exit;
	}

# Password handling
# -----------------
	if (!empty($HTTP_POST_VARS['password'])) {
		$self_password = TRUE;
		$password = strip_magic_quotes($HTTP_POST_VARS['password']);
		if (isset($HTTP_POST_VARS['password2'])) {
			$password2 = strip_magic_quotes($HTTP_POST_VARS['password2']);
			if ($password != $password2) {
				MsgForm (LABEL_NEW_PASSWORD_TWICE, "$WA_SELF", 'back');
				display_footer ($header_footer);
				exit;
			}
		}
	} else {
		$self_password = FALSE;
		//No password set in the register form => generate a random password which can be sent by email
		$password = $auth->genPassword();
	}

# -------------------------------------------------------------------
# Create user privileges (user->forums relation) for each forum
# -------------------------------------------------------------------

# initialize default values
# --------------------------
	$uf_fields["unixdate"]  = $now;
	$uf_fields["userid"]    = $userid;
	$uf_fields["lastlogin"] = 0;
	$uf_fields["lastpost"]  = 0;
	$uf_fields["listpriv"]  = 1;
	$uf_fields["readpriv"]  = 1;
	$uf_fields["writepriv"] = 1;
	$uf_fields["modpriv"]   = 0;

# Backward compatibility with old templates that use subscribeforums[] instead of {register_forums_list}
# ------------------------------------------------------------------------------------------------------
if (is_array($subscribeforums)) {
	$register_forums = $subscribeforums;
}

# Initialize the moderators list and the list of forums to be included in the email
# ---------------------------------------------------------------------------------
	$moderators = array();
	$registered_forums = '';

# For each registered/restricted forum in this site
# -------------------------------------------------
	if (is_array ($forums) && is_array($register_forums)) {
		foreach($forums as $_name=>$_forum) {
			// if user has applied to this forum
			if (!empty($register_forums[$_name])) {
				$registered_forums .= "  [ $_name ] " . $_forum['bn_title'] . "\t [*]\n";
				$moderators[] = $_forum['owneraddress'];
				$uf_fields["bn_name"] = $_forum['bn_name'];
				$uf_fields["state"] = "P";
				$ret = $db->insertPrivs ($site, $_forum['bn_name'], $userid, $uf_fields);
				if ($ret < 0) {
					msgForm (sprintf (ERROR_INSERT_USER, $userid), "$WA_SELF?site=$site", "back");
					display_footer($header_footer);
					exit;
				}
			}
		}
	}


#	format Home page URL if set
#	---------------------------
	if (!empty($homepage) && !eregi ("^https*://[[:alnum:]]+", $homepage)) {
		$homepage = "";
	}

#  insert this user in users table
#  -------------------------------

	foreach($user_var as $field) {
		if (isset ($$field) ) {
			if (is_array($$field)){
				$$field = implode(",", $$field);
			}
			$u_fields[$field] = $$field;
		}
	}

#	Strip HTML tags in signature
#	----------------------------
	if (!empty($signature) ) {
		$signature = checkURL ($signature);
		$signature = add_smileys($signature);
		// $u_fields['signature'] = strip_banned_tags($signature);
		$u_fields['signature'] = nl2br(strip_tags($signature));
	}
	$u_fields["password"] = md5($password);
	$u_fields["userpriv"] = "user";
	$u_fields["lastlogin"] = 0;
	$u_fields["unixdate"] = $now;
 	if ($bn_registration_mode == REG_ADMIN_APPROVAL) {
		$u_fields["state"] = 'P';		// pending
	} else {
		$u_fields["state"] = '1';		// Active
	}

	$ret = $db->insertUser ($site, $u_fields);

	if ($ret < 0) {
		msgForm (sprintf (ERROR_INSERT_USER, $userid), "$WA_SELF?site=$site", "back");
		display_footer($header_footer);
		exit;
	}


# send mail back to the user and to moderators
# --------------------------------------------

	include "$inc_dir/mail.$ext";
	
	$bn_registration_mode = (isset($bn_registration_mode)) ? $bn_registration_mode : REG_NO_CONTROL;
	switch ($bn_registration_mode) {
		case REG_NO_CONTROL:
			$reg_msg = ($self_password) ? sprintf (MSG_USER_REGISTERED, $userid) : sprintf (MSG_USER_RESERVED, $userid);
		break;
		case REG_ADMIN_APPROVAL:
			$admins = $db->getAdministrators($site);
			foreach($admins as $admin) {
				$moderators[] = $admin['useraddress'];
			}
			$reg_msg = 	sprintf (MSG_USER_APPROVAL, $userid);
		break;
	}

	if (is_array($moderators)) {
		$moderators = array_unique($moderators);
	}
	mail_profile ($userid, $password, $u_fields, $moderators);

	if (!$bn_no_stats) {
		$db->addLogEntry ($bn, 'register', $userid);
	}

# Now display the confirmation then exit
# --------------------------------------
	if (empty($redirect_url) ) {
		$redirect_url = "$main_page?site=$site";
	}

	msgForm ($reg_msg, $redirect_url, "", ($bn_frames==1) ? "_parent" : "", "post");
	display_footer($header_footer);

	exit;
} // End $go


#  -------------------------------------------
#  Initialize default values then display FORM
#  -------------------------------------------

	$userid = (isset($userid)) ? $userid : "";
	$username = (isset($username)) ? $username : "";
	$useraddress = (isset($useraddress)) ? $useraddress : "";
	$homepage = (empty($homepage)) ? 'http://' : $homepage;
	$details = (isset($details)) ? $details : "";
	$mailok = (isset($mailok)) ? $mailok : "Y";

	$input_userid = getTextField ('userid', $userid);

	$form_title = ALT_REGISTER_USER;
?>

<script type="text/javascript" language="JavaScript">
<!-- // Hide for old browsers
function CheckForm(form) {
<?php
	// Check for required fields
	if (is_array($user_bind_var)) {
		foreach($user_bind_var as $field=>$required) {
			if ($required) {
				printf ("  if ((form.%s) && (form.%s.value.length == 0)) {\n", $field, $field);
				$alert = sprintf (ERROR_MISSING_FIELD, $field);
				print  ("    alert (\"$alert\");\n");
				printf ("    form.%s.focus();\n", $field);
				print  ("    return false;\n  }\n");
			}
		}
	}

	// Check if email is valid (simple but effective)
	$alert = ERROR_INVALID_EMAIL;
	print ("  if ( (form.useraddress) && (form.useraddress.value.length > 0) ) {\n");
	print ("    var mail = form.useraddress.value;\n");
	print ("    if ( ( (mail.length - mail.lastIndexOf(\".\")) < 3) || (mail.indexOf(\"@\") < 1) ) {\n");
	print ("      alert (\"$alert\");\n");
	print ("      form.useraddress.focus();\n");
	print ("      return false;\n    }\n  }\n");

	// Check password
	$alert = LABEL_NEW_PASSWORD_TWICE;
	print ("  if ((form.password) && (form.password2) && (form.password.value != form.password2.value)) {\n");
	print ("    alert (\"$alert\");\n");
	print ("    form.password.focus();\n");
	print ("    return false;\n  }\n");

?>
  return true;
}

// End of script -->
</script>

<form name="register_form" id="register_form" method="post" action="<?php echo $WA_SELF?>" onsubmit="return CheckForm(this);" >

<?php
	hiddenField ("site", $site);
	hiddenField ("bn", $bn);
	hiddenField ("go", "1");

# Set the forums list that is displayed to the user to apply to restricted forums
#     -> use {register_forums_list} in register_form
# -------------------------------------------------------------------------------
	$register_forums_list = '';
	if (is_array($forums) && (count($forums)>0) ) {
		$register_forums_list = '<table align="center">';
		$register_forums_list .= '<tr><th colspan="2">'.COLUMN_CHOOSE_FORUM_TO_REGISTER.'</th></tr>';
		$register_forums_list .= '<tr><th align="left">'.COLUMN_FORUM.'</th><th align="left">'.COLUMN_FORUM_ACCESS.'</th></tr>';
		foreach($forums as $_name=>$_forum) {
			$default_checked = '1';
			$type = $_forum['type'];
			$register_forums_list .= sprintf ('<tr><td valign="top">%s</td><td valign="top">%s</td></tr>', getCheckBox ('register_forums['.$_name.']', '1', $default_checked, $_forum['bn_title']), $forum_types[$type]);
		}
		$register_forums_list .= '</table>';
	}

# Set mail opt IN option
# ----------------------
	$mail_opt_in_box = LABEL_EMAIL_QUESTION . '&nbsp;';
	$mail_opt_in_box .= getRadioButton ('mailok', 'Y', $mailok, LABEL_YES);
	$mail_opt_in_box .= '&nbsp;'. getRadioButton ('mailok', 'N', $mailok, LABEL_NO);

# Register Help Url
# -----------------
	if (file_exists("help/$lang/register_help.htm") ) {
		$register_help_url = "help/$lang/register_help.htm";
	} else {
		$register_help_url = "help/en/register_help.htm";
	}
	$register_help_text = join('', file($register_help_url));

# Set the avatar image, label and input fields
# --------------------------------------------
	$choose_picture_field = "";
	$label_avatar = "";
	$show_picture = "";
	if($bn_browse_avatar || $bn_avatar_remote) {
		$label_avatar = LABEL_AVATAR;
		$picture = trim($picture);
		$show_picture = (empty($picture)) ? "<img id=\"show_picture\" src=\"$img_dir/none.gif\" class=\"avatar\">" : "<img id=\"show_picture\" src=\"$picture\" class=\"avatar\">";
		if($bn_avatar_remote) {
			$label_change_avatar = LABEL_CHANGE_AVATAR;
			$choose_picture_field = getTextField ('picture', $picture, 30, 255);
		} else {
			$choose_picture_field = getHiddenField ('picture', $picture, 30, 255);		
		}
		if($bn_browse_avatar) {
			$choose_picture_field .= ' '. getButton ('browse', BUTTON_BROWSE_AVATAR, "OpenWindow('browse_avatar.$ext?site=$site','gallery',$bn_win_width,$bn_win_height);");
		}
	}

# Displays the form from template
# -------------------------------

	if (!empty($bn_register_form) && file_exists("${bn_dir}/${bn_register_form}") ) {
		include "${bn_dir}/${bn_register_form}";
	} elseif ( file_exists("${bn_dir_default}/register_form.$ext") ) {
		include "${bn_dir_default}/register_form.$ext";
	} else {
		include "${tmpl_dir}/default/agora/register_form.$ext";
	}

	echo "</form>";
	display_footer($header_footer);

?>
