<?php

/*
 *  W-AGORA 4.1
 *  -----------
 *  $Id: admin_user.php,v 1.42 2005/06/03 14:47:14 mdruilhe Exp $
 *  Usage:      Edit a user
 *  Author:     Marc Druilhe <mdruilhe@w-agora.net>
 */

require	("init_admin.inc");

# Display header
# ---------------
if ( empty($bn)) {
	display_header (str_replace("{SITE}", $site, TITLE_SITE_USER_ADMIN));
} else {
	$name = ereg_replace ("^${site}_", "", $bn);
	display_header (str_replace("{FORUM}", $name, TITLE_FORUM_USER_ADMIN));
}

# Load site administration configuration
# --------------------------------------
require	("$site_cfg_file");
if (empty($bn_msgs) ) {
	include ("$bn_dir_default/site_msgs.$ext");
} else {
	include "$bn_dir/$bn_msgs";
}

function title_list() {
	global $site, $bn, $user_states;
	global $selection, $pattern, $letter, $period, $activity, $unit, $userstate;

// return "Résultat de la sélection";

	$in = (empty($bn))? sprintf(LABEL_REG_USERS_SITE, $site) : sprintf(LABEL_REG_USERS_FORUM, $bn);
	if ($selection == "name") {
		if (!empty($letter)||$letter=='all') {
			return sprintf(LABEL_USERS_BEGINING, $letter) . $in;
		} else {
			return sprintf(LABEL_USERS_BEGINING, $pattern) . $in;
		}
	}

	if ($activity == "never_post") {
		return LABEL_USERS_NEVER_POST . $in;
	}
	if ($activity == "never_login") {
		return LABEL_USERS_NEVER_LOGIN . $in;
	}
	$period_units = array (
		"1" => LABEL_DAYS,
		"7" => LABEL_WEEKS,
		"30" => LABEL_MONTHS
	);
	if ($activity == "didnt_post") {
		return sprintf(LABEL_USERS_DIDNT_POST, $period, $period_units[$unit]) . $in;
	}
	if ($activity == "didnt_login") {
		return sprintf(LABEL_USERS_DIDNT_LOGIN, $period, $period_units[$unit]) . $in;
	}
	if ($activity == "in_state") {
		return sprintf(LABEL_USERS_IN_STATE, $user_states[$userstate]) . $in;
	}
	return LABEL_USERS . " $in";
}

function subscribe_user($userid, $gosubscribe, $keepthreads) {
	global $site, $bn, $db,$WA_SELF;
	global $action, $keepthreads;
	$user=$db->getUser($site,$userid);
	$useraddress=$user['useraddress'];
	if ($gosubscribe==1) {
		$ret=$db->subscribeUser ($site, $bn, $useraddress, 0);
		return 1;
	} else {
		$ret=$db->unsubscribeUser ($site, $bn, $useraddress, 0, $keepthreads);
		return 0;
	}
}

# Display form and alphabet to select a user
# -------------------------------------------
function form_user ($title) {
	global $site, $bn, $WA_SELF, $user_states, $db;
	global $selection, $pattern, $period, $activity, $unit, $userstate, $letter, $search_field;

	$period_units = array (
		"1" => LABEL_DAYS,
		"7" => LABEL_WEEKS,
		"30" => LABEL_MONTHS
	);
	$period = (!empty($period)) ? $period : 3;
	$dsp_activity = (!empty($activity))? $activity : "never_post";
	$userstate = (!empty($userstate)) ? $userstate : "P";

?>
<script	language="JavaScript">
<!--
  function CheckMe(idx,whichform) {
	whichform.activity[idx].checked = true;
  }
//-->
</script>
<?php

	table_header($title);
	beginForm($WA_SELF, "post");
	echo "<FIELDSET><LEGEND>".LABEL_BY_NAME . "</LEGEND>";


	$alpha = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P','Q','R','S','T','U','V','W','X','Y','Z');
	echo "<br><br>".LABEL_CHOOSE_USERID_INIT ." : <font size=1>";
	reset($alpha);
	while (list($k,$let) = each($alpha)) {
		if ($let == $letter) {
			echo "[$let] ";
		} else {
			echo "<a href=\"$WA_SELF?site=$site&bn=$bn&letter=$let&action=list&selection=name\">[$let]</a> ";
		}
	}

	if (empty($letter) || ($letter == "all")) {
		echo LABEL_ALL_USERS;
	} else {
		echo "<a href=\"$WA_SELF?site=$site&bn=$bn&action=list&selection=name\">[".LABEL_ALL_USERS."]</a>";
	}
	echo "</font><br><br>";

	echo "<table><tr><td align=\"right\"><b>".LABEL_OR."</b> ". LABEL_SEARCH . " </td><td>";
	textField ("pattern", $pattern, 20);
	echo "</td></tr><tr><td align=\"right\"> ". LABEL_SEARCH_IN . " </td><td>";
	checkBox("search_field[userid]", "1", "1", LABEL_USERNAME);
	echo "&nbsp;";
	checkBox("search_field[useraddress]", "1", "1", LABEL_EMAIL_ADDRESS);
	echo "&nbsp;";
	checkBox("search_field[username]", "1", "1", LABEL_FULL_NAME);
	echo "</font></td></tr>";
	echo "</td></tr></table>";

	echo "<br><div align=center>";
	hiddenField("selection","name");
	submitButton ("list", LABEL_SEARCH);
	echo "</div></form>";

	echo "</FIELDSET>";

	// echo "<hr noshade>";

	echo "<br><FIELDSET><LEGEND>".LABEL_BY_ACTIVITY . "</LEGEND>";

	beginForm($WA_SELF, "post");

	echo "<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	radioButton("activity","never_post",$dsp_activity, LABEL_SHOW_NO_POST);
	echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	radioButton("activity","never_login",$dsp_activity, LABEL_SHOW_NO_LOGIN);
	echo "<hr noshade width=400>";

	echo "<table border=0 width='100%' cellspacing=0 cellpadding=0><tr><td>";
	echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	radioButton("activity","didnt_post", $dsp_activity, LABEL_SHOW_DIDNT_POST);
	echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	radioButton("activity","didnt_login", $dsp_activity, LABEL_SHOW_DIDNT_LOGIN);
	echo "</td><td>";
	textField ("period", $period, 2);
	listBox ("unit", $period_units, $unit);
	echo "</td></tr></table>";
	if (!empty($bn)) {
		echo "<hr noshade width=400><br>&nbsp;&nbsp;&nbsp;<b>". sprintf(LABEL_REG_USERS_FORUM, $bn)."</b><br>";
		$db->query("select type from $site where bn_name='$bn'");
		if ($db->next_record()) {
			$type = $db->f('type');
			if ( ($type == "rest") || ($type=="priv") ) {
				$user_states['none'] = LABEL_NOT_REGISTERED;
				echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
				radioButton("activity","in_state",$dsp_activity," " . LABEL_SHOW_IN_STATE);
				// listBox ("state", $user_states, $state, 0, "document.forms[1].activity[4].checked=true;");
				listBox ("userstate", $user_states, $userstate, 0, "CheckMe('4',this.form);");
			}
		}
		echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		radioButton("activity","subscribed",$dsp_activity, LABEL_SUBSCRIBED_USERS);
		echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		radioButton("activity","unsubscribed",$dsp_activity, LABEL_UNSUBSCRIBED_USERS);
		echo "<br>";
	} else {
		echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		radioButton("activity","in_state",$dsp_activity," " . LABEL_SHOW_IN_STATE);
		// listBox ("state", $user_states, $state, 0, "document.forms[1].activity[4].checked=true;");
		listBox ("userstate", $user_states, $userstate, 0, "CheckMe('4',this.form);");
	}
	echo "<br><center>";
	submitButton ("list", LABEL_SHOW);
	hiddenField ("action", "list");
	hiddenField ("selection", "activity");
	echo "</center></form></FIELDSET>";

	table_footer();
}

# Displays form to confirm users deleting
# ---------------------------------------
function confirm_delete_form ($users) {
	global $site, $bn, $WA_SELF;
	global $selection, $pattern, $activity, $sort, $unit, $period, $userstate;

	table_header(LABEL_CONFIRM_USER_DELETE);

	beginForm($WA_SELF, "post");
	hiddenField("selection",$selection);
	hiddenField("pattern",$pattern);
	hiddenField("activity",$activity);
	hiddenField("period",$period);
	hiddenField("unit",$unit);
	hiddenField("userstate",$userstate);
	hiddenField("sort",$sort);
	hiddenField("action","delete");
	echo "<ul>";
	while (list(,$userid) = each($users)) {
		$userid = strip_magic_quotes($userid);
		echo "<li>$userid</li>";
		hiddenField("del_users[]", $userid);
	}
	echo "</ul>";
	submitButton("confirm_delete", LABEL_DELETE_THESE_USERS);
	echo "&nbsp;";
	submitButton("cancel_delete", BUTTON_CANCEL);
	echo "</form>";
	table_footer();
}

function confirm_subscribe_form ($users) {
	global $site, $bn, $WA_SELF;
	global $selection, $pattern, $activity, $sort, $unit, $period, $userstate, $gosubscribe;

	$gosubscribe = (isset($gosubscribe)) ? $gosubscribe : 1;

	table_header(LABEL_SUBSCRIBE_USER);

	beginForm($WA_SELF, "post");
	hiddenField("selection",$selection);
	hiddenField("pattern",$pattern);
	hiddenField("activity",$activity);
	hiddenField("period",$period);
	hiddenField("unit",$unit);
	hiddenField("userstate",$userstate);
	hiddenField("sort",$sort);
	hiddenField("action","subscribe");

	echo "<ul>";
	while (list(,$userid) = each($users)) {
		echo "<li>$userid</li>";
		hiddenField("del_users[]",$userid);
	}
	echo "</ul>";
	radioButton("gosubscribe", "1", $gosubscribe, LABEL_SUBSCRIBE);
	echo " / ";
	radioButton("gosubscribe", "0", $gosubscribe, LABEL_UNSUBSCRIBE);
	echo "<hr>";

	checkBox("keepthreads", "1", "0", LABEL_KEEP_THREADS);
	echo "<br>";
	checkBox("mail_user_subscribe", "1", "1", LABEL_MAIL_USER_SUBSCRIBE);
	echo "<hr><div align=center>";
	submitButton("confirm_subscribe", LABEL_VALIDATE);
	echo "&nbsp;";
	submitButton("cancel_delete", BUTTON_CANCEL);
	echo "</div></form>";
	table_footer();
}

function confirm_register_form ($users) {
	global $site, $bn, $WA_SELF;
	global $selection, $pattern, $activity, $sort, $unit, $period, $userstate, $goregister;

	$goregister = (isset($goregister)) ? $goregister : 1;

	table_header("Inscrire un/des utilisateur(s)");

	beginForm($WA_SELF, "post");
	hiddenField("selection",$selection);
	hiddenField("pattern",$pattern);
	hiddenField("activity",$activity);
	hiddenField("period",$period);
	hiddenField("unit",$unit);
	hiddenField("userstate",$userstate);
	hiddenField("sort",$sort);
	hiddenField("action","register");

	echo "<ul>";
	while (list(,$userid) = each($users)) {
		echo "<li>$userid</li>";
		hiddenField("del_users[]",$userid);
	}
	echo "</ul>";
	radioButton("goregister", "1", $goregister, "<b>Inscrire</b>");

	echo '<TABLE border="1" WIDTH="70%" align="center">';
	caption (sprintf(LABEL_USER_GRANT_PRIVILEGES, $bn));
	echo "<tr><th>" . COLUMN_CAN_LIST . "</th><th>" . COLUMN_CAN_READ . "</th><th>" . COLUMN_CAN_WRITE . "</th>";
	printf ("</tr><tr align=center><td>");
	checkBox ("listpriv", "1", "1");
	print ("</td><td>");
	checkBox ("readpriv", "1", "1");
	print ("</td><td>");
	checkBox ("writepriv", "1", "1");
	print ("</td></tr>");
	echo " </TABLE>";

	radioButton("goregister", "0", $goregister, "<b>Désinscrire</b>");

	echo "<hr noshade><div align=center>";
	submitButton("confirm_register", LABEL_VALIDATE);
	echo "&nbsp;";
	submitButton("cancel_register", BUTTON_CANCEL);
	echo "</div></form>";
	table_footer();
}

function confirm_status_form ($users,$state) {
	global $site, $bn, $WA_SELF;
	global $selection, $pattern, $activity, $sort, $unit, $period, $userstate, $user_states;

	table_header(LABEL_CHANGE_STATUS." ".$user_states[$state]);

	beginForm($WA_SELF, "post");
	hiddenField("selection",$selection);
	hiddenField("pattern",$pattern);
	hiddenField("activity",$activity);
	hiddenField("period",$period);
	hiddenField("unit",$unit);
	hiddenField("state",$state);
	hiddenField("sort",$sort);
	hiddenField("userstate",$userstate);
	hiddenField("action","status");

	echo "<ul>";
	while (list(,$userid) = each($users)) {
		echo "<li>$userid</li>";
		hiddenField("del_users[]",$userid);
	}
	echo "</ul>";
	echo "<hr>";

	checkBox("mail_user_status", "1", "1", LABEL_MAIL_USER_STATUS);
	echo "<hr><div align=center>";
	submitButton("confirm_status", LABEL_VALIDATE);
	echo "&nbsp;";
	submitButton("cancel_delete", BUTTON_CANCEL);
	echo "</div></form>";
	table_footer();
}

function display_sort_link($field, $label, $sort, $dsp_par) {
	global $WA_SELF, $site, $bn, $img_dir, $icon_dir;

	$t_sort = explode(" ", $sort);
	if ($t_sort[0] != $field) {
		$sort = $field;
		$arrow = "<img src='$img_dir/none.gif' border=0 align=absmiddle width=8 height=7>";
	} elseif ($t_sort[1] == "desc"){
		$sort = $field;
		$arrow = "<img src='$icon_dir/sort_down.gif' border=0 align=absmiddle width=8 height=7>";
	} else {
		$sort = "$field+desc";
		$arrow = "<img src='$icon_dir/sort_up.gif' border=0 align=absmiddle width=8 height=7>";
	}

	displayUrl ("$WA_SELF?site=$site&bn=$bn&sort=$sort&action=list&$dsp_par", "", $label, "");
	echo "&nbsp;&nbsp; $arrow";
}

# Displays all selected users
# ---------------------------
function list_users (&$users, $action="", $first=0, $last=0) {
	global $site, $bn, $db, $WA_SELF, $bn_date_format, $bn_tz_offset;
	global $formuser, $user_states, $user_privs;
	global $icon_dir, $img_dir;
	global $nb_users_list;
	global $selection, $letter, $sort, $pattern, $activity, $unit, $period, $userstate, $search_field;

?>
<script	language="JavaScript">
<!--
function setCheckboxes(val)
{
	var elts      = document.forms['listForm'].elements['del_users[]'];
	var elts_cnt  = (typeof(elts.length) != 'undefined') ? elts.length : 0;

	if (elts_cnt) {
		for (var i = 0; i < elts_cnt; i++) {
			elts[i].checked = val;
		} // end for
	} else {
		elts.checked = val;
	} // end if... else

	return true;
} // end of the 'setCheckboxes()' function

//-->
</script>

<?php

	$dsp_par = "selection=$selection&letter=$letter&pattern=$pattern&activity=$activity&unit=$unit&period=$period&userstate=$userstate";
	if (is_array($search_field) ) {
		foreach($search_field as $key=>$val) {
			if ($search_field[$key]==1) {
				$dsp_par .= "&search_field[$key]=1";
			}
		}
	}

	$total_users = count($users);

	if ($last == 0) {
		$last = $total_users - 1;
	}

	if (empty($action) ) {
		$action = $WA_SELF;
	}

	if (is_array($users)) {
		$sort_col = explode(" ", $sort);
		echo "<form name='listForm' method='post' action='$WA_SELF'>";
		$bgcolor = ($sort_col[0] == "userid")? "bgcolor=#e0eaf6" : "";
		echo "<table width='100%' CELLPADDING='4' CELLSPACING='1'>";
		echo "<tr><td nowrap>&nbsp;</td>";

		$bgcolor = ($sort_col[0] == "userid")? "bgcolor=#e0eaf6" : "";
		echo "<td class=\"s_label\" $bgcolor nowrap>";
		display_sort_link("userid", COLUMN_USER_ID, $sort, $dsp_par);

		$bgcolor = ($sort_col[0] == "name")? "bgcolor=#e0eaf6" : "";
		echo "</td><td class=\"s_label\" $bgcolor nowrap>";
		display_sort_link("name", COLUMN_USER_NAME, $sort, $dsp_par);

		//$bgcolor = ($sort_col[0] == "useraddress")? "bgcolor=#e0eaf6" : "";
		//echo "</td><td class=\"s_label\" $bgcolor nowrap>";
		//display_sort_link("useraddress", COLUMN_USER_EMAIL, $sort, $dsp_par);

		$bgcolor = ($sort_col[0] == "unixdate")? "bgcolor=#e0eaf6" : "";
		echo "</td><td class=\"s_label\" $bgcolor nowrap>";
		display_sort_link("unixdate", COLUMN_USER_REGISTERED, $sort, $dsp_par);

		$bgcolor = ($sort_col[0] == "lastlogin")? "bgcolor=#e0eaf6" : "";
		echo "</td><td class=\"s_label\" $bgcolor nowrap>";
		display_sort_link("lastlogin", COLUMN_USER_LAST_LOGIN, $sort, $dsp_par);

		$bgcolor = ($sort_col[0] == "lastpost")? "bgcolor=#e0eaf6" : "";
		echo "</td><td class=\"s_label\" $bgcolor nowrap>";
		display_sort_link("lastpost", COLUMN_USER_LAST_POST, $sort, $dsp_par);

		if (empty($bn)) {
			$bgcolor = ($sort_col[0] == "userstate")? "bgcolor=#e0eaf6" : "";
			echo "</td><td class=\"s_label\" $bgcolor nowrap>";
			display_sort_link("state", LABEL_STATUS, $sort, $dsp_par);
		}

		echo "</td><td>".COLUMN_ACTION;

		echo "</td></tr>\n";

		reset ($users);

		// skip first records
		$i = 0;     // $i # users displayed
		while (($i < $first) && (list(,$user) = each ($users) )) {
			$i++;
		}

		while (($i <= $last) && (list(,$user) = each ($users) )) {

			$ch_box = getCheckBox("del_users[]",$user["userid"],"");
			$userid_color = ($user["userid"] == "admin")? "<FONT COLOR='red'><b>admin</b></FONT>": $user["userid"];

			$edit_url = "$WA_SELF?action=edit&site=$site&bn=$bn&sort=$sort&$dsp_par&userid=". urlencode(stripslashes($user["userid"]));
			$edit_icon = "<a href=\"$edit_url\"><img src=\"images/icons/profile.gif\" width=15 height=15 border=0 alt=\"".LABEL_EDIT_THIS_USER."\" align=absmiddle></a>";
			$edit_link = "<a href=\"$edit_url\">$userid_color</a>";

			if ( ($user["userid"] =='admin') || ($user["userid"] =='guest') ) {
				$del_icon = '&nbsp;';
			} else {
			$del_icon = "<a href='$WA_SELF?site=$site&bn=$bn&action=ask_delete&sort=$sort&$dsp_par&del_user=" . urlencode(stripslashes($user["userid"]))	. "'><img src='$icon_dir/delete.gif' align=absmiddle border=0 alt=\"".LABEL_DELETE."\"></a>";
			}

			$mail_icon = "<a href='$WA_SELF?site=$site&bn=$bn&action=ask_mail&sort=$sort&$dsp_par&del_users[]=" . urlencode(stripslashes($user["userid"]))	. "'><img src='$icon_dir/email.gif' align=absmiddle border=0 alt=\"".LABEL_MAIL_USER."\"></a>";

			if (!empty($bn)) {
				$is_subscribed = $db->checkSubscribedUser ($site, $bn, $user['useraddress'],0);
				$sub_icon = ($is_subscribed)
							? "<a href='$WA_SELF?site=$site&bn=$bn&action=ask_subscribe&gosubscribe=0&sort=$sort&$dsp_par&del_user="	. urlencode(stripslashes($user["userid"])) . "'><img src='$icon_dir/subscribe.gif' align=absmiddle	border=0 alt=\"".LABEL_UNSUBSCRIBE."\"></a>"
							: "<a href='$WA_SELF?site=$site&bn=$bn&action=ask_subscribe&gosubscribe=1&sort=$sort&$dsp_par&del_user="	. urlencode(stripslashes($user["userid"])) . "'><img src='$icon_dir/unsubscribe.gif' align=absmiddle	border=0 alt=\"".LABEL_SUBSCRIBE."\"></a>";

			}
			$username = stripslashes($user["username"]);
			$useraddress = $user["useraddress"];
			$priv = $user["userpriv"];
			$user_priv = $user_privs[$priv];

			$created = formated_date($user["unixdate"]);
			$totallogins = (empty($user["totallogins"]))? "-" : $user["totallogins"];
			$lastlogin = ($user["lastlogin"] > 0) ? formated_date($user["lastlogin"]): "-";
			$totalposts = (empty($user["totalposts"]))? "-" : $user["totalposts"];
			$lastpost = ($user["lastpost"] > 0) ? formated_date($user["lastpost"]): "-";

			$state = $user["state"];

			$line = "<tr class=\"mouseout\" onmouseout=\"changeclass(this,'mouseout')\" onmouseover=\"changeclass(this,'mouseover')\">";
			$line .= "<td nowrap=\"nowrap\" class=\"s_label\">$ch_box</td>";
			$line .= "<td nowrap=\"nowrap\" class=\"s_label\" nowrap>$edit_link</td>";
			$line .= "<td nowrap=\"nowrap\" class=\"s_label\">$username</td>";
			// $line .= "<td NOWRAP class=\"s_label\">$useraddress</td>";
			$line .= "<td nowrap=\"nowrap\" class=\"s_label\" >$created</td>";
			$line .= "<td nowrap=\"nowrap\" class=\"s_label\" >$lastlogin</td>";
			$line .= "<td nowrap=\"nowrap\" class=\"s_label\" >$lastpost</td>";
			if (empty($bn)) $line .= "<td nowrap=\"nowrap\" class=\"s_label\" >$user_states[$state]</td>";
			$line .= "<td nowrap=\"nowrap\" class=\"s_label\">$mail_icon $edit_icon $sub_icon $del_icon</td>";
			print $line;
			$i++;
		}
		hiddenField("action","ask_delete_mail");
		hiddenField("bn",$bn);
		hiddenField("site",$site);
		hiddenField("selection",$selection);
		hiddenField("pattern",$pattern);
		hiddenField("activity",$activity);
		hiddenField("period",$period);
		hiddenField("unit",$unit);
		hiddenField("userstate",$userstate);
		hiddenField("sort",$sort);
		$del_button = getSubmitButton("delete",LABEL_DELETE);
		$mail_button = getSubmitButton("mail",LABEL_MAIL_USER);

		if (!empty($bn)) {
			$subscribe_button = getSubmitButton("subscribe", LABEL_SUBSCRIBE."/".LABEL_UNSUBSCRIBE);
			$register_button  = getSubmitButton("register", LABEL_ADD_USER);
		} else {
			$status_button = getSubmitButton("status", "OK");
			$status_list = LABEL_CHANGE_STATUS.getListbox("state",$user_states,"1");
		}
		$set_button = "<a href=\"$action?site=$site&bn=$bn&userstate=$userstate&sort=$sort&first=$first&last=$last&action=list&$dsp_par&checkall=1\"	onClick=\"setCheckboxes(true);return false;\">".LABEL_SELECT_ALL."</a>";
		$unset_button = "<a href=\"$action?site=$site&bn=$bn&userstate=$userstate&sort=$sort&first=$first&last=$last&action=list&$dsp_par\"	onClick=\"setCheckboxes(false);return false;\">".LABEL_UNSELECT."</a>";

		echo "<tr><td colspan=7 nowrap><img src='$img_dir/arrow.gif' border=0>$set_button / $unset_button</td><tr>";
		echo "<tr><td colspan=7 class=label><hr noshade></td></tr>";
		echo "<tr><td colspan=7>". LABEL_WITH_SELECTED ."</td></tr>";
		echo "<tr><td colspan=7 nowrap align=center> $mail_button $del_button $subscribe_button $register_button $status_list$status_button</td></tr>";
		echo "<tr><td colspan=7 class=label><hr noshade></td></tr>";

		echo '<tr><td colspan=7 class=label align=center>';
		if ($first>0) {
			$prev_last = $first-1;
			$prev_first = $prev_last - ($nb_users_list-1);
			if ($prev_first < 0) {
				$prev_first = 0;
				$prev_last = $nb_users_list-1;
			}
			$first_last = ($i>$nb_users_list) ? $nb_users_list-1 :  $i-1;
			echo '&nbsp;';
			displayUrl ("$action?site=$site&bn=$bn&userstate=$userstate&sort=$sort&first=0&last=$first_last&action=list&$dsp_par",	"", LABEL_BEGIN_USERS, "First page");
			echo '&nbsp;';
			displayUrl ("$action?site=$site&bn=$bn&userstate=$userstate&sort=$sort&first=$prev_first&last=$prev_last&action=list&$dsp_par", "", LABEL_PREV_USERS, "Previous users");
		}

		printf ("&nbsp;<B>%s %d - %d / %d</B>&nbsp;", LABEL_DISPLAY, $first+1, $i, $total_users);

		if ($total_users>$i) {
			$next_first = $last+1;
			$next_last = $last + $nb_users_list;
			$last_user = $total_users-1;
			$last_first = $last_user -  ($nb_users_list-1);
			if ($next_last>$last_user) {
				$next_last = $last_user;
			}
			echo '&nbsp;';
			displayUrl ("$action?site=$site&bn=$bn&formuser=$formuser&userstate=$userstate&sort=$sort&first=$next_first&last=$next_last&action=list&$dsp_par",	"", LABEL_NEXT_USERS, '');
			echo '&nbsp;';
			displayUrl ("$action?site=$site&bn=$bn&formuser=$formuser&userstate=$userstate&sort=$sort&first=$last_first&last=$last_user&action=list&$dsp_par",	"", LABEL_END_USERS, '');
		}
		print "</td></tr></table></form>\n";
	} else {
		echo ERROR_NO_MATCHING_USERS;
	}
}

function can_edit($userid) {
	global $site, $auth, $db;

	$user = $db->getUser($site, $userid);
	if (!is_array($user)) {
		return -3;
	}

	switch ($user["userpriv"]) {
		case "root":
			if ($auth->userid!="admin") {
				return -2;
			}
		case "admin":
			if ($auth->level < ROOT) {
				return -2;
			}
		break;
		case "moder":
			if ($auth->level < ADMIN) {
				return -2;
			}
		break;
	}
	
	return 1;
}

function can_delete($userid) {
	global $site, $auth, $db;

	$user = $db->getUser($site, $userid);
	if (!is_array($user)) {
		return -3;
	}

	if ($user["userid"] == "admin") {
		return -2;
	}

	switch ($user["userpriv"]) {
		case "root":
			if ($auth->userid!="admin") {
				return -2;
			}
		case "admin":
			if ($auth->level < ROOT) {
				return -2;
			}
		break;
		case "moder":
			if ($auth->level < ADMIN) {
				return -2;
			}
		break;
	}

	$forums = $db->listForums ($site);

	# Check if user to be deleted has access to forums not owned by the logged user
	# -----------------------------------------------------------------------------
	if (is_array ($forums) && ($auth->type == "moder")) {
		$my_forums = $db->listForums ($site, $auth->userid);

		// for each forum in this site
		reset ($forums);
		while (list($name) = each ($forums) ) {
			if (!is_array($my_forums[$name])) {
				// this forum is not owned by this user
				$forum = $forums[$name]["bn_name"];
				$privs = $db->getPrivs($site, $forum, $userid);
				if (is_array ($privs) ) {
					// Set the forum name as global for future usage (dirty but works...)
					$GLOBALS['not_owner_forum'] = $forum;
					return -1;
				}
			}
		}
	}
	return 1;
}

#	Display profile form for userid
#----------------------------------
function display_profile($user) {
	global $WA_SELF, $site, $bn, $ext, $db, $auth, $user_states, $user_privs;
	global $forum_types;
	global $action, $sort, $pattern, $search_field, $selection, $letter, $activity, $unit, $period, $userstate;

	extract($user);
	echo "<FORM METHOD='post' ACTION='$WA_SELF'>";
	hiddenField("userid",$userid);
	hiddenField("site",$site);
	hiddenField("bn",$bn);
	hiddenField("go",1);
	hiddenField("edit_user",$userid);
	hiddenField("action",$action);
	hiddenField("sort",$sort);
	hiddenField("pattern",$pattern);
	hiddenField("selection",$selection);
	if (is_array($search_field)) {
		foreach($search_field as $key=>$val) {
			hiddenField("search_field[$key]",$val);
		}
	}
	hiddenField("letter",$letter);
	hiddenField("activity",$activity);
	hiddenField("unit",$unit);
	hiddenField("period",$period);
	hiddenField("userstate",$userstate);
	table_header (TITLE_EDITING_USER . "<em>'$userid'</em> " . LABEL_IN_SITE .  ": <em>$site</em>");
	echo "<TABLE BORDER=0 WIDTH='100%'><tr>";

	echo "<td width=\"30%\" align=\"right\" class=\"s_label\">" . COLUMN_USER_NAME . ": </td><td>";
	textField ("username", $username, 50, 64);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . COLUMN_USER_EMAIL . ": </td><td>";
	textField ("useraddress", $useraddress, 50, 255);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . COLUMN_USER_WEBPAGE . ": </td><td>";
	textField ("homepage", $homepage, 50, 255);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . LABEL_ICQ . ": </td><td>";
	textField ("icq", $icq, 50, 64);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . LABEL_AIM . ": </td><td>";
	textField ("aim", $aim, 50, 64);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . LABEL_YAHOO . ": </td><td>";
	textField ("yahoo", $yahoo, 50, 64);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . LABEL_MSN . ": </td><td>";
	textField ("msn", $msn, 50, 64);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . LABEL_SIGNATURE . ": </td><td>";
	textArea ("signature", $signature, 3, 50);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . LABEL_CHANGE_AVATAR . ": </td><td>";
	$picture = trim($picture);
	echo (empty($picture))? "<font color=red>".LABEL_NO_PICTURE."</font>": "<img src='$picture' width=50 height=50>";
	textField ("picture", $picture, 50, 255);


	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . COLUMN_USER_DESCRIPTION . ": </td><td>";
	textArea ("details", $details, 3, 50);

	echo "</td></tr><tr><td width=\"40%\" align=\"right\" class=\"s_label\">" . COLUMN_USER_MAILOK . "</td><td class=\"s_label\">";
	radioButton ("mailok", "Y", $mailok, LABEL_YES); radioButton ("mailok", "N", $mailok, LABEL_NO);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . LABEL_USER_NEW_PASSWORD . " </td><td>";
	passwordField ("newpasswd1", "", 30, 32);

	echo "</td></tr><tr><td width=\"30%\" align=\"right\" class=\"s_label\">" . LABEL_USER_NEW_PASSWORD_AGAIN . " </td><td>";
	passwordField ("newpasswd2", "", 30, 32);

	echo "</td></tr></TABLE>";
	echo "<TABLE BORDER=1 WIDTH=100% CELLPADDING=5><tr>";
	echo "<td width=\"40%\" align=\"right\" VALIGN=TOP class=\"s_label\">" . COLUMN_USER_REGISTERED . ": </td><td class=\"s_label\">";
	printf ("<B>%s</B>", formated_date($unixdate));
	echo "</td></tr><tr><td align=\"right\" class=\"s_label\">" . COLUMN_USER_LOGIN_COUNT . ": </td><td class=label>";
	printf ("<B>%s</B> ", $totallogins);
	if ($totallogins >0) {
		printf (" (%s : <B>%s</B>)", COLUMN_USER_LAST_LOGIN, formated_date($lastlogin));
	}
	echo "</td></tr><tr><td align=\"right\" class=\"s_label\">" . COLUMN_USER_POST_COUNT . ": </td><td class=\"s_label\">";
	printf ("<B>%s</B> ", $totalposts);
	if ($totalposts >0) {
		printf ("(last post : <B>%s</B> in forum <B>%s</B>)", formated_date($lastpost), $lastforumpost);
	}
	echo "</td></tr></TABLE>";

	# Initialize user privileges choices
	# ----------------------------------
	$granted_privs["user"] = $user_privs["user"];

	if (($auth->type=="root") || ($auth->type=="admin") ) {
		$granted_privs["moder"] = $user_privs["moder"];
	}
	if ($auth->type=="root") {
		$granted_privs["admin"] = $user_privs["admin"];
	}
	if ($auth->userid=="admin") {
		$granted_privs["root"] = $user_privs["root"];
	}

	echo "<TABLE BORDER=0 WIDTH='100%'>";
	caption (CAPTION_USER_PRIVILEGE."<font color='blue'>$user_privs[$userpriv]</font>", "b");
		
	# if logged as admin or root : we allow to change user privileges and user state
	# ------------------------------------------------------------------------------
	if (count($granted_privs) > 1) {
		if ($userid != "admin") {
			echo "<tr><td WIDTH='40%' ALIGN='RIGHT' VALIGN='MIDDLE' class=label>" . LABEL_CHANGE_USER_PRIVILEGE	. "</td><td class=label>";
			listBox ("userpriv", $granted_privs, $userpriv);
		} else {
			echo "<tr><td colspan='2' align='center' VALIGN='MIDDLE' class=label>" . ERROR_NO_ADMIN_CHANGE_PRIVILEGE	. "";
			hiddenField ("userpriv", $userpriv);
		}
	} else {
		hiddenField ("userpriv", $userpriv);
		echo "<tr><td colspan='2' align='center' VALIGN='MIDDLE' class=label>";
	}
	echo "</td></tr><tr><td colspan='2' align='center'><b>".LABEL_USER_SITE_STATUS."<font color='blue'>$user_states[$state]</font><b></td></tr>";
	if (count($granted_privs) > 1) {
		if ($userid != "admin") {
			echo "<tr><td WIDTH='40%' ALIGN='RIGHT' VALIGN='MIDDLE' class=label>" . LABEL_CHANGE_STATUS	. "</td><td class=label>";
			listBox ("state", $user_states, $state);
			echo "</td></tr>";
		} else {
			echo "<tr><td colspan='2' align='center' VALIGN='MIDDLE' class=label>" . ERROR_NO_ADMIN_CHANGE_STATUS	. "</td></tr>";
			hiddenField ("userstate", $state);
		}
	}
	echo "</TABLE>";

	# Now, display all forums for which the logged user is responsible for
	#   We don't display forums for an administrator (have rights over all forums)
	# --------------------------------------------------------------------------

	if (($auth->type=="root") || ($auth->type=="admin") ) {
		$forums = $db->listForums ($site);
	} else {
		$forums = $db->listForums ($site, $auth->userid);
	}
	if (is_array($forums)) {
		reset($forums);
		while (list($name) = each($forums)) {
			if ( ($userpriv=="moder") || ($forums[$name]["type"] == "rest") || ($forums[$name]["type"] == "priv")	) {
			continue;
			} else {
				unset ($forums[$name]);
			}
		}
	}

	if ( (($userpriv=="moder") || ($userpriv=="user")) && (count($forums)>0) ) {
		echo '<hr><TABLE border=0 cellpadding=3 WIDTH="100%">';
		caption ('<b>'.CAPTION_CHANGE_USER_FORUM_PRIVILEGES.'</b><br>'.             LABEL_AS.'<u>'.$user_privs[$auth->type].'</u>,'	. LABEL_GRANT_PRIVILEGES.$userid, '');
		echo '<tr bgcolor="#cccccc">'.
				'<td class=label>' . COLUMN_FORUM . '</td>'.
				'<td class=label>' . COLUMN_FORUM_TITLE . '</td>'.
				'<td class=label>' . COLUMN_CAN_LIST . '</td>'.
				'<td class=label>' . COLUMN_CAN_READ . '</td>'.
				'<td class=label>' . COLUMN_CAN_WRITE . '</td>';
		if ($userpriv=="moder") {
			echo '<td class=label>' . LABEL_MODERATOR . '</td>';
		}
		echo '<td class=label>' . LABEL_STATUS . '</td></tr>';
		$sel_forums["none"] = LABEL_NONE;
		$addforum=0;

	# for each owned forum
	# ---------------------
		reset ($forums);
		while (list($name) = each ($forums) ) {
			$bn_title = $forums[$name]["bn_title"];
			$forum = $forums[$name]["bn_name"];
	# get privileges for this user on this forum
			$privs = $db->getPrivs($site, $forum, $userid);
			if (is_array ($privs) ) {
	# if the selected user have access to this forum, then display privileges
				$type = $forums[$name]['type'];
				printf ('<tr bgcolor="#e0eaf6"><td class="label"><b>%s</b></td><td class=label>%s</td>', $name.'	('.$forum_types[$type].')', $bn_title);
				if ( ($type == 'rest') || ($type == 'priv') ) {
					echo '<td class=label align="center">'. getCheckBox ($forum.'[listpriv]', '1', $privs['listpriv']).'</td>';
					echo '<td class=label align="center">'. getCheckBox ($forum.'[readpriv]', '1', $privs['readpriv']).'</td>';
					echo '<td class=label align="center">'. getCheckBox ($forum.'[writepriv]', '1', $privs['writepriv']).'</td>';
				} else {
					echo '<td class=label align="center"> x </td>';
					echo '<td class=label align="center"> x </td>';
					echo '<td class=label align="center"> x </td>';
				}
				if ($userpriv=="moder") {
					echo '<td class=label align="center">'. getCheckBox ($forum.'[modpriv]', '1', $privs['modpriv']).'</td>';
				}
				if ($privs["state"] != "P") {
					unset($user_states["P"]);
				}
				$user_states["D"] = LABEL_REMOVE_ACCESS;
				echo '<td class=label align="center">' . getListBox ($forum.'[state]', $user_states, $privs['state']). '</td></tr>';
			} else {
	# else add this forum to the combo box for later selection
				$sel_forums[$forum] = $bn_title;
				$addforum=1;
			}
		}

	# Now list forums for which the selected user doesn't have privilege
	# -------------------------------------------------------------
		if ($addforum==1) {
			print ("<tr bgcolor=#c0cad6><td align=center><b>" . LABEL_ADD_FORUM . "</b></td><td>");
			listBox ("new_forum", $sel_forums);
			print ("</td><td align=center>");
			checkBox ("new_privs[listpriv]", "1", "1");
			print ("</td><td align=center>");
			checkBox ("new_privs[readpriv]", "1", "1");
			print ("</td><td align=center>");
			checkBox ("new_privs[writepriv]", "1", "1");
			print ("</td><td align=center>");
			if ($userpriv=="moder") {
				checkBox ("new_privs[modpriv]", "1", "0");
				print ("</td><td align=center>");
			}
			unset($user_states["P"]);
			unset($user_states["D"]);
			listBox ("new_privs[state]", $user_states, "1");
			print ("</td></tr>");
		}
		echo " </TABLE>";
	}
	echo "<hr><table border=0 width=100%><tr><td bgcolor=#e0eaf6>";
	if (($auth->type=="root") || ($auth->type=="admin") || $state==1) {
		checkBox("mail_user_profile","1","1", LABEL_MAIL_USER_PROFILE);
	}
	echo "</td></tr></table><br><center>";
	submitButton("submit",LABEL_SAVE);
	echo "&nbsp;";
	resetButton("reset",LABEL_RESET);
	echo "&nbsp;&nbsp;&nbsp;";
	submitButton("return_to_list",LABEL_RETURN_LIST);
	table_footer();
	echo "</FORM>";
}

function display_confirm_mail($to, $subject = '', $body = '', $from = '', $replyto = '') {

	global $action, $auth;
	global $selection, $sort, $pattern, $activity, $unit, $period, $userstate;

	if (is_array($to)) {
		if (count($to)>1) {
			$dest_users = implode(", ", $to);
			$recipients = getListBox("recipients", $to);
			$dest_title = $to[0] . "...";
		} else {
			$dest_users = $to[0];
			$recipients = $to[0];
			$dest_title = $to[0];
		}
	} else {
		$dest_users = $to;
		$recipients = $to;
		$dest_title = $userid;
	}

	if (empty($from)) {
		$from = $auth->user['useraddress'];
	}

	if ($action == "confirm_mail") {
		$title_form = sprintf(LABEL_EDIT_MAIL_PROFILE, $dest_title);
		$return = "edit";
	} else {
		$title_form = sprintf(TITLE_MAIL_USERS, $dest_title);
		$return = "list";
	}
	table_header($title_form);
	beginForm($WA_SELF, "post");

	hiddenField("action", "send_mail");
	hiddenField("return", $return);
	hiddenField("userid", $dest_users);
	hiddenField("selection", $selection);
	hiddenField("pattern", $pattern);
	hiddenField("activity", $activity);
	hiddenField("period", $period);
	hiddenField("unit", $unit);
	hiddenField("userstate", $userstate);

?>
<table width="95%" border=0>
<tr>
  <td width=100 class=label><?php echo LABEL_TO ?></td>
  <td><?php echo "$recipients"?></td>
</tr>

<tr>
  <td width=100 class=label><?php echo COLUMN_FROM ?></td>
  <td><?php textField("m_from", $from, 60, 100);?></td>
</tr>
<tr>
  <td width=100 class=label><?php echo COLUMN_REPLY_TO ?></td>
  <td><?php textField("m_replyto", $replyto, 60, 100);?></td>
</tr>
<tr>
  <td width=100 class=label><?php echo COLUMN_SUBJECT ?></td>
  <td><?php textField("m_subject", $subject, 60, 255);?></td>
</tr>
<tr>
  <td width=100 valign="top" class=label><?php echo COLUMN_MESSAGE ?></td>
  <td><?php textArea("m_body", $body, 10, 60); ?></td>
</tr>
<tr><td	align=center colspan=2>
 <hr noshade width="90%">
<?php
	submitButton("send",LABEL_SEND_MAIL);
	echo "&nbsp;&nbsp;";
	resetButton("reset", BUTTON_RESET);
	echo "&nbsp;&nbsp;";
	submitButton("cancel", BUTTON_CANCEL);

	echo "</td></tr></table>";
	endForm();
	table_footer();
}

#-------------------------------------------------------------------------------------------------
#			ENTRY POINT
#-------------------------------------------------------------------------------------------------

if (!isset($action)) {
	$action = "list";
}

#----------------------------
#	Delete given users
#----------------------------
if ($action == "delete") {
	if (isset ($confirm_delete)) {
		$msg_delete = "";
		while (list(,$userid) = each($del_users)) {
			$userid = strip_magic_quotes($userid);
			$can_del = can_delete($userid);
			if ($can_del > 0) {
				$ret = $db->deleteUser($site, $userid);
				$msg_delete .= ($ret == 0)? sprintf(LABEL_USER_CONFIRM_DELETE."<br>", $userid) : sprintf(ERROR_SITE_USER_DELETE."<br>",$userid,$site);
			}elseif ($can_del == -3) {
				$msg_delete .= sprintf(ERROR_NO_USER_MATCHING."<br>", $userid);
			}elseif ($can_del == -2) {
				$msg_delete .= sprintf(ERROR_NO_REMOVE_PRIVILEGE."<br>", $userid);
			}elseif ($can_del == -1) {
				$msg_delete .= sprintf(ERROR_NO_REMOVE_PERMISSION."<br>", $userid, $GLOBALS['not_owner_forum']);
			}
		}
		$msg_delete = "<div align=left><span class=\"s_label\">$msg_delete</span></div>";
		msgForm($msg_delete, "$WA_SELF?site=$site&bn=$bn&sort=$sort&action=list&selection=$selection&pattern=$pattern&activity=$activity&period=$period&unit=$unit&userstate=$userstate");
		$action = "message";
	} else {
		$action = "list";
	}

}

if ($action == "subscribe") {
	if (isset ($confirm_subscribe)) {
		$msg_delete = "";
		while (list(,$userid) = each($del_users)) {
			$userid = strip_magic_quotes($userid);
			$ret=subscribe_user($userid, $gosubscribe, $keepthreads);
			$msg_delete .= ($gosubscribe==0)? sprintf(LABEL_USER_CONFIRM_UNSUBSCRIBE."<br>", $userid) : sprintf(LABEL_USER_CONFIRM_SUBSCRIBE."<br>", $userid);
		}
		$msg_delete = "<div align=left><span class=\"s_label\">$msg_delete</span></div>";
		if ($mail_user_subscribe) {
			$m_subject=sprintf(LABEL_MAIL_SUBSCRIBE_SUBJECT,$bn);
			$m_body = ($gosubscribe==1) ? sprintf (LABEL_MAIL_SUBSCRIBE_BODY_YES,$bn) : sprintf (LABEL_MAIL_SUBSCRIBE_BODY_NO, $bn);
			$action = "confirm_mail_subscribe";
		} else {
			msgForm($msg_delete, "$WA_SELF?site=$site&bn=$bn&sort=$sort&action=list&selection=$selection&pattern=$pattern&activity=$activity&period=$period&unit=$unit&userstate=$userstate");
			$action = "message";
		}
	} else {
		$action = "list";
	}

}

if ($action == "register") {
	if (isset ($confirm_register)) {
		$msg = "";

		if ($goregister==1) {
			$uf_fields["unixdate"] = $unixdate;
			$uf_fields["userid"] = $userid;
			$uf_fields["bn_name"] = $new_forum;
			$uf_fields["listpriv"] = $listpriv;
			$uf_fields["readpriv"] = $readpriv;
			$uf_fields["writepriv"] = $writepriv;
			$uf_fields["modpriv"] = 0;
			$uf_fields["state"] = 1;
			while (list(,$userid) = each($del_users)) {
				$userid = strip_magic_quotes($userid);
				$ret = $db->insertPrivs ($site, $bn, $userid, $uf_fields);
				$msg .= sprintf(WARNING_USER_ADDED."<br>", $userid, $bn);
			}
		} else {
			$userlist = implode("','", $del_users);
			$query = "DELETE FROM ${site}_userforum WHERE userid IN ('$userlist') AND bn_name='$bn'";
			$result = $db->query ($query);
			$msg .= "Les utilisateurs ont été supprimés du forum $bn";
		}

		msgForm("<div align=left><span class=\"s_label\">$msg</span></div>", "$WA_SELF?site=$site&bn=$bn&sort=$sort&action=list&selection=$selection&pattern=$pattern&activity=$activity&period=$period&unit=$unit&userstate=$userstate");
		$action = "message";

	} else {
		$action = "list";
	}

}

#----------------------------
#	Change status of given users
#----------------------------
if ($action == "status") {
	if (isset ($confirm_status)) {
		$msg_status = "";
		$left_users = array();
		$state_field = array();
		$state_field['state'] = $state;
		while (list(,$userid) = each($del_users)) {
			$userid = strip_magic_quotes($userid);
			$can_edit = can_delete($userid);
			if ($can_edit > 0) {
				$ret = $db->updateTable ($site."_users", $state_field, "userid='$userid'");
				if ($ret==0) {
					$msg_status .= sprintf(LABEL_USER_CONFIRM_STATUS."<br>", $userid, $user_states[$state]);
				} else {
					$msg_status .= sprintf(ERROR_NO_USER_STATUS."<br>",$userid,$site);
				}
			}elseif ($can_edit == -3) {
				$msg_status .= sprintf(ERROR_NO_USER_MATCHING."<br>", $userid);
				$left_users[] = $userid;
			}elseif ($can_edit == -2) {
				$msg_status .= sprintf(ERROR_NO_EDIT_PRIVILEGE."<br>", $userid);
				$left_users[] = $userid;
			}
		}
		unset($state_field);
		if (is_array($left_users)) {
			$left_users = array_diff($del_users, $left_users);
			unset($del_users);
			foreach($left_users as $left_user) $del_users[] = $left_user;
			unset($left_users);
		}
		$msg_status = "<div align=left><span class=\"s_label\">$msg_status</span></div>";
		if (count($del_users)==0) {
			$action = "list";
		} elseif ($mail_user_status) {
			$m_subject = sprintf(LABEL_MAIL_STATUS_SUBJECT,$site);
			$m_body = sprintf (LABEL_MAIL_STATUS_BODY,$site,$user_states[$state]);
			$action = "confirm_mail_status";
		} else { 
			msgForm($msg_status, "$WA_SELF?site=$site&bn=$bn&sort=$sort&action=list&selection=$selection&pattern=$pattern&activity=$activity&period=$period&unit=$unit&userstate=$userstate");
			$action = "message";
		}
	} else {
		$action = "list";
	}
}

#----------------------------
#	Delete or mail
#----------------------------
if ($action == "ask_delete_mail") {
	if (isset($delete)) {
		$action = "ask_delete";
	} elseif (isset($subscribe)) {
		$action="ask_subscribe";
	} elseif (isset($register)) {
		$action="ask_register";
	} elseif (isset($status)) {
		$action="ask_status";
	} else {
		$action = "ask_mail";
	}
}

#----------------------------
#	Set users to delete
#----------------------------
if ($action == "ask_delete" || $action=="ask_subscribe" || $action=="ask_status") {
	if (!is_array($del_users)) {
		if (isset($del_user)) {
			$del_users[] = $del_user;
		} else {
			$action = "list";
		}
	}
	if (isset($confirm_delete)) {
		$action = "message";
	}
	if (isset($confirm_subscribe)) {
		$action = "message";
	}
	if (isset($confirm_status)) {
		$action = "message";
	}
}

#----------------------------
#	Set mail to send
#----------------------------
if ($action == "ask_mail") {
	if (!is_array($del_users)) {
		$action = "list";
	}
}

#---------------------------
#	Send mail to user
#---------------------------
if ($action == "send_mail") {
	if ($send) {
		include ("$inc_dir/mail.$ext");
		$userids = explode(", ",$userid);
		while (list(,$u_id) = each($userids)) {
			$user = $db->getUser($site, $u_id);
			$useraddresses[] = $user['useraddress'];
			// $useraddresses .= ", ". $user['useraddress'];
		}
		// $useraddresses = ereg_replace ("^, ", "", $useraddresses);
		$sent = mail_users($useraddresses, $m_subject, $m_body, $m_from, $m_replyto);
		if ($sent) {
			$m = sprintf(LABEL_MAIL_USER_OK, $userid);
		}else {
			$m = sprintf(LABEL_MAIL_USER_NO_OK, $userid);
		}
		msgForm($m, "$WA_SELF?site=$site&bn=$bn&sort=$sort&action=$return&selection=$selection&pattern=$pattern&activity=$activity&period=$period&unit=$unit&userstate=$userstate&userid=$userid");
		$action = "message";
	}else {
		$action = $return;
	}
}


#------------------------------------
#	Edit user with given properties
#------------------------------------
if ($action == "edit") {

	if ($return_to_list) {
		$go = 0;
		$action = "list";
	}
	$userid = strip_magic_quotes($userid);
	$can_edit = can_edit($userid);
	if ($can_edit > 0) {
		if ($go) {
			$go = 0;
			#   Check for required fields
			if (file_exists("$bn_dir_default/user_fields.$ext") ) {
				include "$bn_dir_default/user_fields.$ext";
			} else {
				include "$tmpl_dir/admin/user_fields.$ext";
			}
			if (is_array ($user_bind_var)) {
				reset($user_bind_var);
				while (list($field, $required) = each($user_bind_var)) {
					if ($required && isset($_POST[$field]) && ($$field=="") ) {
						$mess = sprintf (ERROR_MISSING_FIELD, $field);
						MsgForm ($mess, "$WA_SELF?site=$site&userid=".urlencode($userid), 'back');
						exit;
					}
				}
			}

			$forums = $db->getForums($site, '', '', 0);
			# For each forum in this site
			if (is_array ($forums)) {
				reset ($forums);
				while (list($name) = each ($forums) ) {
					$forum = $name;
			# if moderator privilege has been revoked for this user
			#   then we check that he was not owner of this forum
					if (($userpriv!="moder") && ($forums[$name]["owner"] == $userid)) {
						$forums[$name]["owner"] = "admin";
						$ret = $db->updateForum ($site, $forum, $forums[$name]);
					}

			# if user privs have been set on this forum
					if (is_array($$forum)) {
						// initialize default values
						$uf_fields["listpriv"] = 0;
						$uf_fields["readpriv"] = 0;
						$uf_fields["writepriv"] = 0;
						$uf_fields["modpriv"] = 0;
						$uf_fields["state"] = 0;

			# gets all privileges set on this forum for this user
						while ( list($priv, $val) = each($$forum) ) {
							$uf_fields[$priv] = $val;
						}

			# if moderator privilege has been set over this forum
			# we check he has moderator privilege then force read/write access
						if ($uf_fields["modpriv"] == 1) {
							// check he is a moderator
							if ($userpriv=="moder") {
								// force all privileges
								$uf_fields["listpriv"]=1;
								$uf_fields["readpriv"]=1;
								$uf_fields["writepriv"]=1;
			# If moderator has been choosen, set forum's owner if not already set
								if (empty($forums[$name]["owner"]) ) {
									$forums[$name]["owner"] = $userid;
									$ret = $db->updateForum ($site, $forum, $forums[$name]);
									if ($ret < 0) {
										MsgForm (sprintf(ERROR_NO_OWNER_UPDATE,$forum, $site), "$WA_SELF?site=$site", 'back');
										exit;
									}
								}
							} else {
								$uf_fields["modpriv"] = 0;
							}
						}
		# Now we update privileges into userforum
		# ---------------------------------------
						$ret = 0;
						if ($uf_fields["state"]=="D") {;
							// remove access for this user
							$ret = $db->deletePrivs ("$site", $forum, $userid);
						} elseif ( ($userpriv!="admin") && ($userpriv!="root") ) {
							$ret = $db->updatePrivs ("$site", $forum, $userid, $uf_fields);
						}

						if ($ret < 0) {
							MsgForm ("Could not update privileges for user $userid over forum $forum", "$WA_SELF?site=$site&userid=$userid", "back");
							exit;
						}
					}
				}

			# Now we check if new privs have been selected for a new forum
			# We don't insert entry if user has admin privilege
				if (!empty($new_forum) && ($new_forum!="none") && ($userpriv!="admin")  && ($userpriv!="root")) {
					// initialize default values
					$uf_fields["unixdate"]=$unixdate;
					$uf_fields["userid"]=$userid;
					$uf_fields["bn_name"]=$new_forum;
					$uf_fields["listpriv"] = 0;
					$uf_fields["readpriv"] = 0;
					$uf_fields["writepriv"] = 0;
					$uf_fields["modpriv"] = 0;
					$uf_fields["totalpost"]=0;
					$uf_fields["lastpost"]=0;
					$uf_fields["state"] = 0;
					while ( list($priv, $val) = each($new_privs) ) {
						$uf_fields[$priv] = $val;
					}
			# moderator can also read, write, list => force all privileges
					if ($uf_fields["modpriv"] == 1) {
						// check he is a moderator
						if ($userpriv=="moder") {
							// force all privileges
							$uf_fields["listpriv"]=1;
							$uf_fields["readpriv"]=1;
							$uf_fields["writepriv"]=1;
			# If moderator has been choosen, set forum's owner if not already set
							$forum_fields = $db->getForum ($site, $new_forum);
							if (empty($forum_fields["owner"]) ) {
								$forum_fields["owner"] = $userid;
								$ret = $db->updateForum ($site, $new_forum, $forum_fields);
								if ($ret < 0) {
									MsgForm (sprintf(ERROR_NO_OWNER_UPDATE,$forum, $site), "$WA_SELF?site=$site", 'back');
									exit;
								}
							}
						} else {
							// user is not a moderator
							$uf_fields["modpriv"] = 0;
						}
					}

			# insert into userforum
					$ret = $db->insertPrivs ($site, $new_forum, $userid, $uf_fields);
					if ($ret < 0) {
						MsgForm (sprintf(ERROR_NO_ADD_PRIVILEGES, $userid,$new_forum), "$WA_SELF?site=$site&userid=$userid", 'back');
						exit;
					}
				}
			}

			#  Now update this user in the users table
			for (reset ($user_var); $form_field=current($user_var); next($user_var)) {
				if (isset($$form_field) && $form_field!="state") {
					$$field=strip_magic_quotes($$form_field);
					$user[$form_field]=$$field;
				}
			}

			// update user global state only if user is at least a site administrator
			if ($is_administrator) $user["state"]=$state;
			
			// Update password if needed
			if (!empty ($newpasswd1) && ($newpasswd1 == $newpasswd2)) {
				$user["password"] = md5(strip_magic_quotes($newpasswd1));
			}

			$ret = $db->updateUser ("$site", $userid, $user);

			if ($ret < 0) {
				MsgForm (str_replace("{USER}", $userid, str_replace("{SITE}", $site, ERROR_NO_SITE_USER_UPDATE)), "$WA_SELF?site=$site&userid=$userid", 'back');
				exit;
			} else {
				if ($mail_user_profile) {
					$action = "confirm_mail";
					if (is_array($forums)) {
						$registered_forums = "";
						$db->query ("select S.bn_name, S.type, S.bn_title from $site S, ${site}_userforum UF WHERE S.bn_name=UF.bn_name AND UF.userid='".$db->preserveQuotes($userid)."' AND S.type IN ('rest','priv')");
						while ($db->next_record()) {
							$registered_forums .= "* " . $db->f('bn_title') . " --- (".LABEL_REG_USER_FORUM . ")\n";
						}
					}

					if (empty($bn_mail_template) ) {
						include ("$bn_dir_default/mail_template.$ext");
					} else {
						include "$bn_dir/$bn_mail_template";
					}

					if (!empty($mail_confirm_reg_body)) {
						$forums_list = $registered_forums;  // backward compatibility
						$login_url = "$bn_base_url/login.$ext?site=$site";
						$tpl = str_replace('"', '\"', $mail_confirm_reg_subject);
						eval ("\$m_subject = \"$tpl\";");
						$tpl = str_replace('"', '\"', $mail_confirm_reg_body);
						eval ("\$m_body = \"$tpl\";");
						// set the "From" and "Reply-To" header
						$m_from = $bn_mail_from;
						if (!empty($bn_reply_to)) {
							$m_replyto = $bn_reply_to;
						}
					}
				}
			}

		# If new user has administrator privilege =>  insert into main database
			if ( ($userpriv == "admin" || $userpriv == "root") ) {

				$agora_dbparam = getDBaccess('agora');
				$agora_access = $agora_dbparam["bn_access"];
				$agora_dbname = $agora_dbparam["dbname"];
				$agora_dbhost = $agora_dbparam["dbhost"];
				$agora_dbport = $agora_dbparam["dbport"];
				$agora_dbuser = $agora_dbparam["dbuser"];
				$agora_dbpassword = $agora_dbparam["dbpassword"];

				if ($site_access != $agora_access) {
					include ("$inc_dir/$agora_access.$ext");
				}
				$agora_db_class = "${agora_access}_access";
				$agora_db = new $agora_db_class;
				$ret = $agora_db->openDB($agora_dbhost, $agora_dbport, $agora_dbuser, $agora_dbpassword, $agora_dbname, "agora");

				$agora_user = $agora_db->getUser("agora", $userid);
				if (is_array ($agora_user)) {
					$agora_db->updateUser ("agora", $userid, $user);
				} else {
					$agora_db->insertUser ("agora", $user);
				}
			}
		}// go

		$edit_user = $db->getUser($site,$userid);
	}else {
		if ($can_edit == -3) {
			$msg_delete = sprintf(ERROR_NO_USER_MATCHING."<br>", $userid);
		}else {
			$msg_delete = sprintf(ERROR_NO_EDIT_PRIVILEGE."<br>", $userid);
		}
		msgForm($msg_delete, "$WA_SELF?site=$site&bn=$bn&sort=$sort&action=list&pattern=$pattern&activity=$activity&period=$period&unit=$unit");
		$action = "message";
	}
}

#-------------------------------------------
#	List users with given properties
#-------------------------------------------
if ($action == "list") {
	$sort = (empty($sort) ) ? "userid" : $sort;

	if ((empty($selection)||$selection== "name") && empty($pattern) && (empty($letter)||$letter== "all")) {
		if ($first == "")   {
			$first = 0;
			$last = $first + $nb_users_list;
		}
	} else {
		$first = 0;
		$last = 0;
	}

	if ($selection == "activity") {
		$timeframe = $period * $unit * 24*60*60;
		$date = time() - $timeframe;
		unset($pattern);
	}elseif ($selection == "name") {
		unset($activity);
	}

	if ($activity == "didnt_post") {
		$query = "SELECT U.* FROM ${site}_users U WHERE U.unixdate>0 AND U.lastpost < $date";
	} elseif ($activity == "didnt_login") {
		$query = "SELECT U.* FROM ${site}_users U WHERE U.unixdate>0 AND U.lastlogin < $date";
	} elseif ($activity == "never_post"){
		$query = "SELECT U.* FROM ${site}_users U WHERE U.unixdate>0 AND U.totalposts = 0";
	} elseif ($activity == "never_login"){
		$query = "SELECT U.* FROM ${site}_users U WHERE U.unixdate>0 AND U.totallogins = 0";
	} elseif ($activity == "in_state"){
		if ($userstate=="none") {
			$result = $db->query ("SELECT userid FROM ${site}_userforum WHERE bn_name='$bn'");
			$reg_users = array();
			while ($db->next_record() ) {
				$reg_users[] = $db->f("userid");
			}
			if (count($reg_users>0) ) {
				$exclude = implode("','", $reg_users);
			}
			$query = "SELECT U.* FROM ${site}_users U WHERE U.unixdate>0 AND U.userpriv IN ('user','moder') AND	U.userid NOT IN ('$exclude')";
		} else {
			if (empty($bn)) {
				$query = "SELECT * FROM ${site}_users U WHERE state = '$userstate'";
			} else {
				$query = "SELECT U.* FROM ${site}_users U, ${site}_userforum UF WHERE UF.bn_name='$bn' AND U.userid=UF.userid AND UF.state = '$userstate'";
			}
		}
	} elseif ($activity == "subscribed"){
		$query = "SELECT U.* FROM ${site}_users U, ${site}_userthread UT WHERE U.useraddress=UT.useraddress AND	UT.bn_name='$bn' AND UT.thread=0";
	} elseif ($activity == "unsubscribed"){
		$result = $db->query ("SELECT useraddress FROM ${site}_userthread WHERE bn_name='$bn'");
		$sub_users = array();
		while ($db->next_record() ) {
			$sub_users[] = $db->f("useraddress");
		}
		if (count($sub_users>0) ) {
			$exclude = implode("','", $sub_users);
		}
		$query = "SELECT U.* FROM ${site}_users U WHERE U.unixdate>0 AND U.useraddress NOT IN ('$exclude')";
	} else {
		$query = "SELECT U.* FROM ${site}_users U WHERE U.unixdate>0";
	}

	if (!empty($pattern)) {
		if ($search_field['userid']) {
			$s = "U.userid LIKE '%$pattern%'";
		}
		if ($search_field['useraddress']) {
			$s .= (empty($s)) ? "U.useraddress LIKE '%$pattern%'" : " OR U.useraddress LIKE '%$pattern%'";
		}
		if ($search_field['username']) {
			$s .= (empty($s)) ? "U.username LIKE '%$pattern%'" : " OR U.username LIKE '%$pattern%'";
		}

		if (!empty($s)) {
			$query .= " AND ($s)";
		}
	} elseif (!empty($letter)) {
		$query .= " AND (U.userid LIKE '$letter%' OR U.username LIKE '$letter%')";
	}

	$query .= " ORDER BY U.$sort";
	$result = $db->query ($query);

	$i=0;
	$users = array();

	while ($db->next_record() ) {
		$u = $db->f("userid");
		$users[$u] = $db->Record;
		$i++;
	}


	//$users = $db->getUsers($site, "$bn", "", $pattern, $where, $sort);
}
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------

#----------------------------------
#	Display users management page
#----------------------------------

$title_form	= TITLE_SELECT_USERS;

if (!is_array($users) && isset($list)) {
	$title_form = ERROR_NO_MATCHING_USERS;
}
?>
<HEAD>
 <TITLE>w-agora administration - <?php echo (empty($bn))? TITLE_SITE_USER_ADMIN : TITLE_FORUM_USER_ADMIN?></TITLE>
</HEAD>
<BODY>

<?php

switch ($action) {
  case 'list':
	echo "<br><a name=\"top\"></a>";
	$title_list = title_list();
	echo "<p align=center><a href=\"#search_form\">".LABEL_SEARCH."</a></p>";
	table_header ($title_list);
	list_users($users, '', $first, $last);
	table_footer();
	echo "<a name=\"search_form\"></a>";
	echo "<p align=center><a href=\"#top\">".LABEL_TOP."</a></p>";
	form_user ($title_form);
  break;

  case 'ask_delete':
	confirm_delete_form ($del_users);
  break;

  case 'ask_subscribe':
	confirm_subscribe_form ($del_users);
  break;

  case 'ask_register':
	confirm_register_form ($del_users);
  break;

  case 'ask_status':
	confirm_status_form ($del_users,$state);
  break;

  case 'edit':
	display_profile ($edit_user);
  break;

  case 'confirm_mail':
	display_confirm_mail ($userid, $m_subject, $m_body, $m_from, $m_replyto);
  break;

  case 'confirm_mail_subscribe':
  case 'confirm_mail_status':
	display_confirm_mail ($del_users, $m_subject, $m_body, $m_from, $m_replyto);
  break;

  case 'ask_mail':
	display_confirm_mail ($del_users);
  break;
}
?>
</BODY>
</HTML>