<?php

/*
 *	W-AGORA 4.2
 *	-----------
 *	$Id: register.php,v 1.51 2005/06/15 14:43:46 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";
	}

# Import all form variable in global scope (we only import variable defined as user variables) 
# magic quotes are stripped accordingly, prevent html in input
# --------------------------------------------------------------------------------------------
	if (isset($_POST['go'])) {
		$go=0;
		foreach($user_var as $var) {
			$$var = getPostVar($var);
			if (!is_null($$var) ) {
				if (@ !empty($user_html_var[$var]) ) {
					$$var = strip_banned_tags($$var);
				} else {
					$$var = htmlspecialchars($$var);
				}
			}
		}
	}

# 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)) {

# Check for a valid email
# -----------------------
	$useraddress = trim($useraddress);
	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)) {
		foreach ($user_bind_var as $field=>$required) {
			if ($required && isset($_POST[$field]) && (strlen(trim($_POST[$field])) == 0) ) {
				$mess = sprintf (ERROR_MISSING_FIELD, $field);
				msgForm ("$mess", "$WA_SELF", "back");
				display_footer($header_footer);
				exit;
			}
		}
	}

#	Check that userid is valid
#	--------------------------
/*
	if (ereg (" ", $userid) ) {
		msgForm (ERROR_SPACE_IN_USERID, "$WA_SELF", "back");
		display_footer($header_footer);
		exit;
	}
*/

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

	$name = trim($name);
	$firstname = trim($firstname);
	$username = trim($username);
	if (empty($username) ) {
		if ( empty($name) && empty($firstname) ) {
			$username = $userid;
		} else {
			$username = $firstname . ' ' . $name;
		}
	}


	$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($_POST['password'])) {
		$self_password = TRUE;
		$password = strip_magic_quotes($_POST['password']);
		if (isset($_POST['password2'])) {
			$password2 = strip_magic_quotes($_POST['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
#	---------------------------
	$homepage = trim($homepage);
	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;
		}
	}

#	format signature and userinfo (details) fields
#	----------------------------------------------
	if (!empty($signature) ) {
		$signature = checkURL ($signature);
		$signature = add_smileys($signature);
		$u_fields['signature'] = nl2br($signature);
	}

	if (!empty($details) ) {
		$details = checkURL ($details);
		$details = add_smileys($details);
		$u_fields['details'] = nl2br($details);
	}

	$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);

?>
