<?php

/*
 *	W-AGORA 4.2
 *	-----------
 *	$Id: profile.php,v 1.54 2006/05/16 21:45:26 mdruilhe Exp $
 *	Usage:		allows user to edit his profile and to register/unregister new forums
 *	Author:		Markus Inger <privat@markus-inger.de>
 *				Marc Druilhe <mdruilhe@w-agora.net>
 *
 */

	$no_cookie=1;

	if (empty($_GET['showuser']) ) {
		$bn_action="edit_profile";
	} else {
		$bn_action="show_profile";
	}

	$bn_action_mode="R";
	require ("init.inc");

# redirect to the list of sites if none defined
# ---------------------------------------------
	if ($site == "agora") {
		if (!empty($before_access)) include $before_access;
		display_header (LABEL_PROFILE, $header_footer);
		msgForm (ERROR_NO_SITE_SPECIFIED, "$main_page", "");
		display_footer($header_footer);
		exit;
	}

# redirect to the profile page if defined
# ---------------------------------------
	$newURL = $auth->getEditProfileURL();
	if (is_string($newURL)) {
		if (empty($newURL)) {
			if (!empty($before_access)) include $before_access;
			display_header (LABEL_PROFILE, $header_footer);
			msgForm (ERROR_FEATURE_DISABLED, "$WA_SELF", "back");
			display_footer($header_footer);
		} else {
        	header("Location: $newURL");
		}
		exit;
	}

# if showuser is set => displays his profile
# ------------------------------------------
	if (!empty($_GET['showuser']) ) {
		$showuser = strip_magic_quotes($_GET['showuser']);
		$u = $db->getUser($site, $showuser);
		if (is_array($u) ) {
			while ( list( $var, $val ) = each( $u)) {
				if (is_string ($var) && ($var!='password') ) {
					$$var = kill_quotes(stripSlashes($val));
				}
			}
		} else {
			if (!empty($before_access)) include $before_access;
			display_header (LABEL_PROFILE, $header_footer);
			msgForm (sprintf(ERROR_USERID_NOT_FOUND, $showuser), "$main_page", "", ($bn_frames==1)?"_parent":"");
			display_footer($header_footer);
			exit;
		}

		$register_date = formated_date ($unixdate);
		$lastpost_date = ($lastpost>0) ? formated_date ($lastpost) : "";
		$userpriv = $user_privs[$userpriv];
		$homepage_url = "";
		if (!empty($homepage)) {
			if (!eregi ("^https*://[[:alnum:]]+", $homepage)) {
				$homepage = "http://$homepage";
			}
			$homepage_url = "<a href=\"$homepage\" target=\"_blank\" class=\"wa_link\">$homepage</a>";
		}

		$edit_user_url = "admin_user.$ext?site=$site&action=edit&userid=$showuser";

		$form_title = sprintf (LABEL_SHOW_PROFILE_FOR, $showuser);

		$mail_text = LABEL_MAIL;
		$mail_url = "mail.$ext?site=$site&bn=$bn&userid=$showuser&redirect=profile";
		if ($bn_popup) {
			$mail_link = anchorWindow ($mail_url, $mail_text, ALT_PRIVATE_MAIL, $bn_win_width, $bn_win_height);
		} else {
			$mail_link = anchor ($mail_url, $target_frame, $mail_text, ALT_PRIVATE_MAIL);
		}

		$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 (!empty($before_access)) include $before_access;
		display_header (LABEL_PROFILE, $header_footer);

		if (!empty($bn_show_profile) && file_exists("${bn_dir}/${bn_show_profile}") ) {
			include "${bn_dir}/${bn_show_profile}";
		} elseif ( file_exists("${bn_dir_default}/show_profile.$ext") ) {
			include "${bn_dir_default}/show_profile.$ext";
		} else {
			include "${tmpl_dir}/default/agora/show_profile.$ext";
		}
		display_footer($header_footer);
		exit;
	}

	$form_title = ALT_CHANGE_PROFILE;

# Execute before_access program
# -----------------------------
	if (!empty($before_access)) include $before_access;

# Check if the user is authenticated in this site otherwise redirect him to the login form
# ----------------------------------------------------------------------------------------
	if (!$is_authenticated) {
		display_header (LABEL_PROFILE, $header_footer);
		msgForm (sprintf(ERROR_LOGIN_REGISTER, "login.$ext?site=$site&bn=$bn", "register.$ext?site=$site&bn=$bn") , $main_page, "");
		display_footer($header_footer);
		exit;
	}

# 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;
	}

# Force userid (cannot be changed here)
# -------------------------------------
	$userid = $auth->userid;
	$input_userid = $userid;

# If Creation form have been submitted
# ------------------------------------
if (isset($_POST['go'])) {

	$go=0;

# 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
# --------------------------------------------------------------------------------------------
	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);
			}
		}
	}

#	Check for required fields
#	-------------------------
	$user_bind_var["username"] = 1;
	$user_bind_var["useraddress"] = 1;

	foreach($user_bind_var as $field=>$required) {
		if ($required && isset($_POST[$field]) && (strlen(trim($_POST[$field])) == 0) ) {
			$mess = sprintf (ERROR_MISSING_FIELD, $field);
			display_header (LABEL_PROFILE, $header_footer);
			msgForm ("$mess", "$WA_SELF?site=$site", "back");
			display_footer($header_footer);
			exit;
		}
	}

# Password change handling
# ------------------------
	$password_changed = false;
	if (!empty($_POST['password'])) {
		$password = strip_magic_quotes($_POST['password']);
		if (isset($_POST['password2'])) {
			$password2 = strip_magic_quotes($_POST['password2']);
			if ($password != $password2) {
				display_header (LABEL_PROFILE, $header_footer);
				msgForm (LABEL_NEW_PASSWORD_TWICE, "$WA_SELF", 'back');
				display_footer ($header_footer);
				exit;
			}
			$password_changed = true;
		}
	} else {
		// Make sure it will not be used later
		unset($password);
	}

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

#	Initialize user array with form values
#	--------------------------------------

	// Get all user variables that can be changed by the user
	$profile_vars = array_diff ($user_var, array('unixdate','userid', 'userpriv', 'state', 'totallogins', 'lastlogin', 'totalposts', 'lastpost', 'lastforumpost') );
		
	foreach($profile_vars as $field) {
		if (isset ($$field) ) {
			if (is_array($$field)){
				$$field = implode(",", $$field);
			}
			$u_fields[$field] = $$field;
		}
	}

	if ($password_changed) {
		$u_fields['password'] = md5($password);
	}

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

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

# If email has been changed
# -------------------------
	if ($useraddress != $auth->user["useraddress"]) {

		// Check that the new email address is not already used
		$tmp = $db->getUser($site, $useraddress, "useraddress");
		if (is_array($tmp)) {
			display_header (LABEL_PROFILE, $header_footer);
			msgForm (sprintf(ERROR_EMAIL_ALREADY_EXISTS, $useraddress), "$WA_SELF", "back");
			display_footer ($header_footer);
			exit;
		}

		// Check that the email is valid
		if (!validate_email ($useraddress, MAIL_CHECK_DNS)) {
			display_header (LABEL_PROFILE, $header_footer);
			msgForm (ERROR_INVALID_EMAIL, "$WA_SELF", "back");
			display_footer($header_footer);
			exit;
		}
	}

# If username has been changed
# ----------------------------
	if ($username != $auth->user["username"]) {
		$query = "SELECT 1 FROM ${site}_users WHERE userid<>'". $db->preserveQuotes($auth->userid). "' AND username='". $db->preserveQuotes($username) . "'";
		$db->query($query);
		if ($db->next_record() ) {
			display_header (LABEL_PROFILE, $header_footer);
			msgForm (sprintf(ERROR_USER_ALREADY_EXISTS, $username), "$WA_SELF", "back");
			display_footer ($header_footer);
			exit;
		}
	}

#  Update user infos for this user in the users table
#  --------------------------------------------------

#	1. for the current site
#	-----------------------
	$ret = $db->updateUser ($site, $auth->userid, $u_fields);

	if ($ret < 0) {
		display_header (LABEL_PROFILE, $header_footer);
		msgForm ("could not change profile for the user $userid, please contact the administrator", "$WA_SELF?site=$site", "back");
		display_footer($header_footer);
		exit;
	}

#	2. then the main site for administrators.
#	-----------------------------------------
// FIXME: to be re-written, deal with multiple DBs + better sysadmin management
	if ($auth->level >= ADMIN) {
		$tmp = $db->setHaltOnError("no");
		$db->updateUser ("agora", $auth->userid, $u_fields);
		$db->setHaltOnError($tmp);
	}

# ----------------------------------------------------------
# Now register / unregister the users to the selected forums
# ----------------------------------------------------------

# initialize default values
# -------------------------
	$uf_fields["unixdate"]  = $now;
	$uf_fields["userid"]    = $auth->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;

# For each registered/restricted forum in this site
# -------------------------------------------------
	$registered_forums = "";

	if ( is_array($forums) && is_array($register_forums) ) {
		foreach($forums as $_name=>$forum_infos) {
			$forum = $forum_infos["bn_name"];

			// check if user already subscribed to this forum
			$privs = $db->getPrivs ($site, $forum, $auth->userid);
			if (is_array ($privs) ) {

				// user already subscribed to this forum, check if checkbox was unchecked
				if (empty($register_forums[$_name]) ) {
					$ret = $db->deletePrivs ($site, $forum, $auth->userid);
					if ($ret < 0) {
						display_header (LABEL_PROFILE, $header_footer);
						msgForm ("Sorry, could not unsubscribe $auth->userid to forum $_name, try again or contact the site administrator", "$WA_SELF?site=$site", "back");
						display_footer($header_footer);
						exit;
					}
				}

			} else {
				if ( !empty($register_forums[$_name]) ) {

					// add permission -> insert into userforum
					$uf_fields["bn_name"]=$forum;
					$uf_fields["state"] = 'P';
					$ret = $db->insertPrivs ($site, $forum, $auth->userid, $uf_fields);
					if ($ret < 0) {
						display_header (LABEL_PROFILE, $header_footer);
						msgForm ("Sorry, could not subscribe $auth->userid to forum $_name, try again or contact the site administrator", "$WA_SELF?site=$site", "back");
						display_footer($header_footer);
						exit;
					}

					// add owner address on the recipient list in order to send them an email
					$registered_forums .= "  [ $_name ] " . $forum_infos["bn_title"] . "\t [*]\n";
					$owner = $forum_infos['owneraddress'];
					if (!isset($owners[$owner]) ) {
						$owners[$owner] = 1;
						$moderators[] = $owner;
					}
				}
			}
		}
	}

# Re-authenticate the user if password has been changed
# -----------------------------------------------------
	if ($password_changed) {
		$auth->authenticate ($auth->userid, $password);
	}

# --------------------------------------------
# send mail back to the user and to moderators
# --------------------------------------------
	include "$inc_dir/mail.$ext";
	mail_profile ($auth->userid, $password, $u_fields, $moderators);

# and display the message
# -----------------------
	if (empty($redirect_url) ) {
		$redirect_url = "$main_page?site=$site";
	}

	display_header (LABEL_PROFILE, $header_footer);
	msgForm (MSG_PROFILE_CHANGED, $redirect_url, "", ($bn_frames==1) ? "_parent" : "", "post");
	display_footer ($header_footer);
	exit;

}
	$bn_popup = 1; // for browse_avatar
	display_header (LABEL_PROFILE, $header_footer);

	#  evaluate all fields from $user
	#  ------------------------------

	while ( list( $var, $val ) = each( $auth->user)) {
		if (is_string ($var) && ($var!='password') ) {
			if ($var=='signature') {
				$val = strip_smileys($val);
				$val = strip_url($val);
			}
			$$var = kill_quotes(stripSlashes($val));
		}
	}

    $homepage = (empty($homepage)) ? "http://" : $homepage;

?>
<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 id="register_form" name="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) ) {
		// add a dummy forum subscription entry => so that register_forums[] is always set 
		// even if no checkbox has been checked
		$register_forums_list .= getHiddenField ("register_forums[]", "1");
		$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) {
			$privs = $db->getPrivs ($site, $_forum['bn_name'], $userid);
			$checked = (is_array ($privs)) ? '1' : '0';
			$type = $_forum['type'];
			$register_forums_list .= sprintf ('<tr><td valign="middle">%s</td><td>%s</td></tr>', getCheckBox ('register_forums['.$_name.']', '1', $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
# --------------------------------------------
	$label_avatar = "";
	$show_picture = "";
	$label_change_avatar = "";
	$choose_picture_field = "";
	if($bn_browse_avatar || $bn_avatar_remote) {
		$label_avatar = LABEL_AVATAR;
		$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);
?>
