<?php

/*
 * W-AGORA 4.0
 * -----------
 * $Id: admin_subscribed_user.php,v 1.9 2006/01/19 21:21:19 mdruilhe Exp $
 * Usage:   manage subscriptions
 * Authors:	Laurent Aufrere
 *			Marc Druilhe
 */

require	("init_admin.inc");

require ("$site_cfg_file"); 
require_once("$cfg_file"); 

function getSubscribedUserid ($useraddress) {
	global $site, $db;

	$query = "SELECT userid,username FROM ${site}_users WHERE useraddress='$useraddress'";
	$result = $db->query ($query);
	if (!$result) {
		return -3;
	}
	while ($db->next_record() ) {
		$uid = $db->f("userid");
		$userids[$uid]=$db->f("username");
	}
	return $userids;
}

function getUnsubscribedUsers ($useraddress) {
	global $site, $db;

	$query = "SELECT U.userid,U.username,U.useraddress FROM ${site}_users U, ${site}_userthread S WHERE U.useraddress=S.useraddress AND S.bn_name='$forum'";
	$result = $this->query ($query);
	if (!$result) {
		return -3;
	}

	$i=0;
	while ($this->next_record() ) {
		$useraddresses[$i++] = $this->f("useraddress");
	}
	return $useraddresses;
}


# Displays form to confirm users deleting
# ---------------------------------------
function confirm_unsubscribe_form () {
	global $site, $bn, $WA_SELF;

	$useraddresses =array();

	if (!empty($_POST['del_users'])) {
		$useraddresses = $_POST['del_users'];
	} elseif (isset($_POST['del_user'])) {
		$useraddresses[] = $_POST['del_user'];
	} elseif (isset($_GET['del_user'])) {
		$useraddresses[] = $_GET['del_user'];
	}

	if (count($useraddresses)==0) {
		msgForm ("Error: No user to unsubscribe", "$WA_SELF?site=$site&bn=$bn&action=list");
		Return false;
	}

	beginForm();
	hiddenField("action", "do_unsubscribe");

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

	echo "<table border=0 width=100%><tr><td bgcolor=#e0eaf6>";
	checkBox("keepthreads", $keepthreads, "0", "&nbsp;".LABEL_KEEP_THREADS);
	br();
	checkBox("mail_user_subscribe", "1", "1", "&nbsp;".LABEL_MAIL_USER_SUBSCRIBE);

	echo "</td></tr></table><hr>";

	submitButton ("confirm_delete", LABEL_UNSUBSCRIBE);
	echo "&nbsp;";
	backButton ("cancel_delete", BUTTON_CANCEL);
	echo "</form>";
}


function confirm_subscribe_form () {
	global $site, $bn, $WA_SELF;

	$useraddresses = '';

	if (!empty($_POST['user_list'])) {
		$useraddresses = join("\n", $_POST['user_list']);
	} 

	if (!empty($_POST['address_list'])) {
		$useraddresses .= "\n";
		$useraddresses .= $_POST['address_list'];
	} 

	if (is_uploaded_file($_FILES['csvfile']['tmp_name'])) {
		$useraddresses .= "\n";
		$useraddresses .= join ("\n", file($_FILES['csvfile']['tmp_name']));
	}

	if (empty($useraddresses)) {
		msgForm ("Error: No user to subscribe", "$WA_SELF?site=$site&bn=$bn&action=list");
		Return false;
	}

	beginForm();
	hiddenField("action", "do_subscribe");

	echo "<ul>";
	$words = preg_split ("/[\s,;]+/", $useraddresses);
	reset ($words);
	$list = array();
	while ( list(,$word) = each($words) ) {
		$word = trim($word);
		if(!empty($word) && !isset($list[$word]) ) {
			echo "<li>$word";
			$list[$word]=1;
			$address_list .= "$word ";
		}
	}
	hiddenField("address_list", $address_list);

	echo "</ul><hr>";

	echo "<table border=0 width=100%><tr><td bgcolor=#e0eaf6>";
	checkBox("mail_user_subscribe", "1", "1", "&nbsp;".LABEL_MAIL_USER_SUBSCRIBE);
	echo "</td></tr></table><hr>";

	submitButton("confirm_subscribe", LABEL_SUBSCRIBE);
	echo "&nbsp;";
	backButton ("cancel_subscribe", BUTTON_CANCEL);
	echo "</form>";
}


function subscribe_users() {
	global $site, $bn, $db, $WA_SELF;


	$useraddresses = '';

	if (empty($_POST['address_list'])) {
		msgForm ("Error: No user to subscribe", "$WA_SELF?site=$site&bn=$bn&action=list");
		Return false;
	}

	$useraddresses = $_POST['address_list'];


	$subscribe_msg = "";
	$words = preg_split ("/[\s,;]+/", trim($useraddresses) );
	reset($words);
	while ( list(,$word)=each($words) ) {
		if (preg_match('/.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,5}|[0-9]{1,3})(\]?)\b/', $word, $result) ) {
			$email = trim($result[0]);
			if (!validate_email ($email)) {
				$subscribe_msg .= ERROR_INVALID_EMAIL . " : $email<br>\n";
				continue;
			}
			if ($db->subscribeUser ($site, $bn, $email, 0) != 0) {
				$subscribe_msg .= ERROR_INVALID_EMAIL . " : $email<br>\n";
				continue;
			}
			$subscribed_addresses[] = $email;
			$subscribe_msg .= sprintf(LABEL_USER_CONFIRM_SUBSCRIBE, $email)."<br>\n";
		} else {
			$subscribe_msg .= ERROR_INVALID_EMAIL . " : $word <br>\n";
		}
	}

	if(!empty($subscribe_msg) ) {
		msgWarning ($subscribe_msg); br(); br();
	}
	Return ($subscribed_addresses);
}

function unsubscribe_users() {
	global $site, $bn, $db, $WA_SELF;

	$useraddresses = '';

	if (!isset ($_POST['confirm_delete'])) {
		Return false;
	}

	if (empty($_POST['del_users'])) {
		msgForm ("Error: No user to unsubscribe", "$WA_SELF?site=$site&bn=$bn&action=list");
		Return false;
	}

	$useraddresses = $_POST['del_users'];

	$unsubscribe_msg = "";
	$keepthreads = (isset($_POST['keepthreads'])) ? 1 : 0;

	reset ($useraddresses);
	while (list(,$useraddress) = each($useraddresses)) {
		$ret = $db->unSubscribeUser($site, $bn, $useraddress, 0, $keepthreads);
		if ($ret == 0) {
			$unsubscribe_msg .= sprintf(LABEL_USER_CONFIRM_UNSUBSCRIBE . "<br>", $useraddress);
			$unsubscribed_addresses[] = $useraddress;
		} else {
			$unsubscribe_msg .= sprintf(ERROR_FORUM_USER_UNSUBSCRIBE . "<br>", $useraddress, $bn);
		}
	}

	if(!empty($unsubscribe_msg) ) {
		msgWarning ($unsubscribe_msg); br(); br();
	}
	Return ($unsubscribed_addresses);

}


# Displays all selected users
# ---------------------------
function list_users () {
	global $site, $bn, $db, $WA_SELF, $ext;
	global $icon_dir, $img_dir;
	global $first, $last;
	global $nb_users_list;

	print "<h2>". LABEL_SUBSCRIBE_USER .'</h2>';

	// First form => add users to the list
	// ACTION => subscribe

	echo "<form name='listForm' METHOD=\"post\" ENCTYPE=\"multipart/form-data\" action='$WA_SELF'>";
	hiddenField ("bn", $bn);
	hiddenField ("site", $site);
	hiddenField("action","subscribe");

	// get the list of already subscribed emails
	br(); print (LABEL_RETRIEVING_USERS); flush();
	$useraddresses = $db->getSubscribedUsers ($site, $bn, 0);

	// Then get the list of registered but not subscribed users
	if(count($useraddresses)>0) {
		$email_list = implode("','", $useraddresses);
		$exclude = "AND U.useraddress NOT IN ('$email_list')";
	} else {
		$exclude = '';
	}
	$f = $db->getForum ($site, $bn);

	if ($f['type']=='priv') {
		// Get only users with read access
		$query = "SELECT U.userid, U.username,U.useraddress FROM ${site}_users U, ${site}_userforum UF WHERE U.userid=UF.userid AND UF.bn_name='$bn' AND UF.readpriv=1 $exclude ORDER BY U.username";
	} else {
		$query = "SELECT U.userid, U.username,U.useraddress FROM ${site}_users U WHERE lastlogin>0 $exclude ORDER BY U.username";
	}

	$user_list = array();
	$db->query ($query);
	while ($db->next_record() ) {
		$username = $db->f('username');
		$email = $db->f('useraddress');
		$user_list[$email] = "$username ($email)";
	}

	if(count($user_list) > 0 ) {
		echo "<br><br>". LABEL_CHOOSE_USER_ADD. " :<br>" . getListBox ("user_list", $user_list, "", 1);	
	}
	echo "<br><br>". LABEL_ENTER_EMAILS_TO_ADD. " :<br>" . getTextArea ("address_list", "", 5, 40);
	echo "<br><br>". LABEL_CHOOSE_EMAILS_FILE." :<br>";
	echo "<INPUT TYPE=\"file\" NAME=\"csvfile\" width=\"260\" SIZE=\"30\" /><br><br>";
	submitButton ("btn_subscribe", LABEL_SUBSCRIBE);
	print "</form>\n";
	echo "<hr>";

	// ------------------------------------------
	// 2nd form => List users to edit/unsubscribe
	// ACTION => unsubscribe
	// ------------------------------------------

	if (!is_array($useraddresses)) {
		printf (ERROR_NO_MATCHING_ADDRESS, $useraddress, $bn);
		Return;
	}

	$total_users = count($useraddresses);

	if (empty($first) ) {
		$first = 0;
		$last = $first + $nb_users_list;
	}

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

	beginForm();
	hiddenField("action", "unsubscribe");

	echo "<table width='100%' CELLPADDING='2' CELLSPACING='0'><tr><td class=s_label $bgcolor></td><td class=s_label $bgcolor>" . COLUMN_USER_EMAIL. "</td><td class=s_label $bgcolor></td><td class=s_label $bgcolor>". LABEL_USERS. "</td></tr>\n";

	reset ($useraddresses);

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

	while (($i <= $last) && (list(,$useraddress) = each ($useraddresses) )) {

		$ch_box = getCheckBox("del_users[]",$useraddress,"");
		$userid_color = $useraddress;
		$action_url = "<a href='$WA_SELF?site=$site&bn=$bn&action=edit&useraddress=" . $useraddress .
	"'>$userid_color</a>";
		$del_icon = "<a href='$WA_SELF?site=$site&bn=$bn&action=unsubscribe&del_user=" . $useraddress . "'><img
	src='$icon_dir/unsubscribe.gif' align=absmiddle border=0></a>";
		$list_userids = getSubscribedUserid ($useraddress);
		$userid_url="";
		if (is_array($list_userids)) {
			reset($list_userids);
			while (list($userid,$username) = each ($list_userids) ) {
				$userid_url .= "<a href='admin_user.$ext?site=$site&bn=$bn&action=edit&userid=" . $userid."'><acronym
title='$username'>$userid</acronym></a> ";
			}
		}

		printf ("<tr class=\"mouseout\" onmouseout=\"changeclass(this,'mouseout')\" onmouseover=\"changeclass(this,'mouseover')\"><td>%s</td><td class=s_label>%s</td><td class=s_label>%s</td><td class=s_label> %s</td></tr>\n", $ch_box, $action_url, $del_icon, $userid_url);
		$i++;
	}

	$del_button = getSubmitButton ("btn_delete", LABEL_UNSUBSCRIBE);
	// $mail_button = getSubmitButton ("btn_mail", LABEL_MAIL_USER);
	$set_button = "";
	$unset_button = "<input value=" . LABEL_UNSELECT . " type=reset>";
	printf ("<tr><td colspan=9 class=label><hr noshade></td></tr><tr><td colspan=6><img src='$img_dir/arrow.gif'
border=0>%s %s &nbsp; %s &nbsp; %s</td><td colspan=3 align=right><B>%s %d - %d /    %d</B><br>", $set_button,
$unset_button, $del_button, $mail_button,LABEL_DISPLAY,   $first+1, $i,	$total_users);
	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 ("$WA_SELF?site=$site&bn=$bn&first=0&last=$first_last", "", LABEL_BEGIN_USERS, LABEL_BEGIN_USERS);
		echo '&nbsp;';
		displayUrl ("$WA_SELF?site=$site&bn=$bn&state=$state&first=$prev_first&last=$prev_last", "",
LABEL_PREV_USERS, LABEL_PREV_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 ("$WA_SELF?site=$site&bn=$bn&first=$next_first&last=$next_last&action=list", "",
LABEL_NEXT_USERS, '');
		echo '&nbsp;';
		displayUrl ("$WA_SELF?site=$site&bn=$bn&first=$last_first&last=$last_user&action=list", "",
LABEL_END_USERS, '');
	}
	print "</td></tr></table>";
	print "</form>\n";

	Return;
}


function confirm_mail_form ($to, $subject='', $body='', $title="") {

	if (is_array($to)) {
		$to = implode (", ", $to);
	}

	table_header ($title);
	beginForm ();
	hiddenField ("action", "send_mail");
	hiddenField ("m_to", $to);

	echo "<table border=0 width=100% cellpadding=5>";
	echo "<tr><td width=\"40%\" align=right>" . LABEL_TO . "</td><td width=60%>$to</td></tr>";
	echo "<tr><td align=right>" . LABEL_SUBJECT . "</td><td>" . getTextField ("m_subject", $subject, 50). "</td></tr>";
	echo "<tr><td valign=top align=right>" . LABEL_CONTENT . "</td><td>";
	textArea ("m_body", $body, 20, 50);
	echo "</td></tr><tr><td colspan=2 align=center>";
	submitButton ("send", LABEL_SEND);
	echo "&nbsp;&nbsp;";
	submitButton ("cancel", BUTTON_CANCEL);
	echo "</td></tr></table></form>";
	table_footer();
}

function change_email_form ($useraddress, $keepthreads=0){
	global $WA_SELF, $site, $bn, $ext, $db;
	global $action;

	beginForm();
	hiddenField("action", 'do_change_email');
	hiddenField("useraddress", $useraddress);

	table_header (TITLE_EDITING_USER . "<em>'$useraddress'</em> " . LABEL_IN_FORUM .  ": <em>$bn</em>");
	echo "<table width=\"100%\" border=0 cellspacing=1 cellpadding=5>";
	echo "<TR><TH align=\"center\" colspan=2><?php echo $form_title ;?></TH></TR>";
	echo "<tr><td WIDTH=\"30%\" ALIGN=RIGHT class=s_label>". COLUMN_USER_EMAIL . " </td><td>$useraddress</td></tr>";
	echo "<tr><TD WIDTH=\"30%\" ALIGN=RIGHT class=s_label>" . COLUMN_USER_NEW_EMAIL."</td><td>". getTextField ("newaddress", $useraddress, 30, 64) . "</td></tr>";
	echo "</table>";

	echo "<hr><table border=0 width=100%><tr><td bgcolor=#e0eaf6>";
	checkBox ("keepthreads", $keepthreads, "1", LABEL_KEEP_THREADS);
	br();
	checkBox("mail_user_subscribe", "1", "1", "&nbsp;".LABEL_MAIL_USER_SUBSCRIBE);
	echo "</td></tr></table><hr>";

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


#---------------------------------------------
#		 M A I N   E N T R Y   P O I N T
#---------------------------------------------

# Display header
# ---------------
$name = ereg_replace ("^${site}_", "", $bn);
display_header (str_replace("{FORUM}", $name, TITLE_FORUM_SUBSCRIBED_USER_ADMIN));

if (empty($action)) {
	$action = "list";
}

switch ($action) {

  case 'list':
	table_header (LABEL_USERS . sprintf(LABEL_REG_USERS_FORUM, $bn) );
	list_users();
	table_footer();
  break;

  case 'subscribe':
	table_header(LABEL_CONFIRM_USER_SUBSCRIBE);
	confirm_subscribe_form();
	table_footer();
  break;

  case 'unsubscribe':
	table_header(LABEL_CONFIRM_USER_UNSUBSCRIBE);
	confirm_unsubscribe_form();
	table_footer();

  break;

  case 'do_subscribe':
	$useraddress = subscribe_users();
	if (is_array($useraddress) && isset($_POST['mail_user_subscribe']) ) {
		$m_subject = sprintf(LABEL_MAIL_SUBSCRIBE_SUBJECT,$bn);
		$m_body = sprintf(LABEL_MAIL_SUBSCRIBE_BODY_YES,$bn);
		$title_form = sprintf(TITLE_MAIL_USERS, implode(', ', $useraddress) );
		confirm_mail_form($useraddress, $m_subject, $m_body, $title_form);
	} else {
		table_header (LABEL_USERS . sprintf(LABEL_REG_USERS_FORUM, $bn) );
		list_users();
		table_footer();
	}
  break;

  case 'do_unsubscribe':
	$useraddress = unsubscribe_users();
	if (is_array($useraddress) && isset($_POST['mail_user_subscribe']) ) {
		$m_subject = sprintf(LABEL_MAIL_SUBSCRIBE_SUBJECT, $bn);
		$m_body = sprintf(LABEL_MAIL_SUBSCRIBE_BODY_NO, $bn);
		$title_form = sprintf(TITLE_MAIL_USERS, implode(', ', $useraddress) );
		confirm_mail_form($useraddress, $m_subject, $m_body, $title_form);
	} else {
		table_header (LABEL_USERS . sprintf(LABEL_REG_USERS_FORUM, $bn) );
		list_users();
		table_footer();
	}
  break;


  case 'send_mail':
	if (isset($_POST['send'])) {
		include ("$inc_dir/mail.$ext");
		if (strstr($m_to, ',')) {
			$to_arr = explode(",", $m_to);
		} else {
			$to_arr = $m_to;
		}
		$sent = mail_users ($to_arr, $m_subject, $m_body);
		if ($sent) {
			$msg = sprintf(LABEL_MAIL_USER_OK, $m_to);
		} else {
			$msg = sprintf(LABEL_MAIL_USER_NO_OK, $m_to);
		}
		msgWarning($msg); br(); br();
	}
	table_header (LABEL_USERS . sprintf(LABEL_REG_USERS_FORUM, $bn) );
	list_users();
	table_footer();
  break;

  case 'edit':
	change_email_form ($useraddress, $keepthreads);
  break;

  case 'do_change_email':

	if (isset($return_to_list)) {
		table_header (LABEL_USERS . sprintf(LABEL_REG_USERS_FORUM, $bn) );
		list_users();
		table_footer();
		exit();
	}

	if ($useraddress != $newaddress) {
		$query  = "UPDATE ${site}_userthread SET useraddress='$newaddress' WHERE useraddress='$useraddress'";
		if (isset($keepthreads)) {
			$query .= " AND thread=0";
		}

		$result = $db->query ($query);
		if ($result) {
			if (isset($_POST['mail_user_subscribe']) ) {
				$m_subject = sprintf(LABEL_MAIL_SUBSCRIBE_SUBJECT, $bn);
				$m_body = sprintf(LABEL_MAIL_SUBSCRIBE_BODY_YES, $bn);
				$title_form = sprintf(LABEL_EDIT_MAIL_SUBSCRIBE, $to);
				confirm_mail_form($newaddress, $m_subject, $m_body, $title_form);
			}
		}
	}

  break;

}

?>
</BODY>
</HTML>
