<?
/* 
   This file is part of the 'Science Fair In A Box' project
   SFIAB Website: http://www.sfiab.ca

   Copyright (C) 2005 Sci-Tech Ontario Inc <info@scitechontario.org>
   Copyright (C) 2005 James Grant <james@lightbox.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation, version 2.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/
?>
<?
 require("../common.inc.php");
 require_once("../user.inc.php");
 user_auth_required('committee', 'admin');
 include "communication.inc.php";
 send_header("Communication",
 		array('Committee Main' => 'committee_main.php',
			'Administration' => 'admin/index.php'),
            "communication"
			);
 echo "<br />";

 if($_POST['action']=="add")
 {
 	if(!$_POST['val'])
	{
		echo error(i18n("Email Key is required"));
		$_GET['action']="add";
	}
	else if(!$_POST['name'])
	{
		echo error(i18n("Email Name is required"));
		$_GET['action']="add";
	}
	else if(!$_POST['from'])
	{
		echo error(i18n("Email From is required"));
		$_GET['action']="add";
	}
	else
	{
		mysql_query("INSERT INTO emails (val,name,description,`from`,subject,body,type) VALUES (".
				"'".mysql_escape_string(stripslashes($_POST['val']))."', ".
				"'".mysql_escape_string(stripslashes($_POST['name']))."', ".
				"'".mysql_escape_string(stripslashes($_POST['description']))."', ".
				"'".mysql_escape_string(stripslashes($_POST['from']))."', ".
				"'".mysql_escape_string(stripslashes($_POST['subject']))."', ".
				"'".mysql_escape_string(stripslashes($_POST['body']))."', ".
				"'user')");
		echo mysql_error();
		echo happy(i18n("Email successfully added"));
	}
 }

 if($_POST['action']=="edit")
 {
	if(!$_POST['name'])
	{
		echo error(i18n("Email Name is required"));
		$_GET['action']="edit";
		$_GET['edit']=$_POST['edit'];
	}
	else if(!$_POST['from'])
	{
		echo error(i18n("Email From is required"));
		$_GET['action']="edit";
		$_GET['edit']=$_POST['edit'];
	}
	else
	{
		mysql_query("UPDATE emails SET ".
				"name='".mysql_escape_string(stripslashes($_POST['name']))."', ".
				"description='".mysql_escape_string(stripslashes($_POST['description']))."', ".
				"`from`='".mysql_escape_string(stripslashes($_POST['from']))."', ".
				"subject='".mysql_escape_string(stripslashes($_POST['subject']))."', ".
				"body='".mysql_escape_string(stripslashes($_POST['body']))."' ".
				" WHERE id='".$_POST['edit']."'");
				echo mysql_error();
		echo happy(i18n("Email successfully saved"));
	}

 }

 if($_GET['action']=="delete" && $_GET['delete'])
 {
 	mysql_query("DELETE FROM emails WHERE id='".$_GET['delete']."'");
	echo happy("Email successfully deleted");

 }

	if($_GET['action']=="send" && $_GET['send'])
	{
		$q=mysql_query("SELECT * FROM emails WHERE id='".$_GET['send']."'");
		$r=mysql_fetch_object($q);

		echo i18n("Please confirm you would like to send the following email, and choose who to send it to");
		echo "<br>";
		echo "<br>";
		echo "<form method=\"get\" action=\"communication.php\">";
		echo "<table cellspacing=0 cellpadding=3 border=1>";
		echo "<tr><td><b>From:</b></td><td>".htmlspecialchars($r->from)."</td></tr>";
		echo "<tr><td><b>To:</b></td><td>";
		echo "<select name=\"to\">";
		echo " <option value=\"\">Choose Email Recipients</option>";
		$str="";
		foreach($mailqueries AS $k=>$mq)
		{
			$tq=mysql_query($mq['query']);
            if(mysql_error()) {
                echo mysql_error();
                exit;
                
            }
			$num=mysql_num_rows($tq);
			$str.="<h2>".$mq['name']." $num </h2>";
			while($tr=mysql_fetch_object($tq)) {
				$str.="[".$tr->uid."][".$tr->year."] ".$tr->firstname." ".$tr->lastname." &lt;{$tr->email}&gt;<br />";
			}
			echo " <option value=\"$k\">".i18n($mq['name'])." (".i18n("%1 recipients",array($num),array("number")).")</option>";
		}
		echo "</select>";
		echo "</td></tr>";
		echo "<tr><td><b>Date:</b></td><td>".date("r")."</td></tr>";
		echo "<tr><td><b>Subject:</b></td><td>".htmlspecialchars($r->subject)."</td></tr>";
		$body=htmlspecialchars($r->body);

		echo "<tr><td colspan=2>".nl2br($body)."</td></tr>";

		echo "</table>";

		if(!function_exists("exec")) {
			echo "<div class=\"error\">Sending requires php's exec() function to be available</div>\n";
		}
		else
		{
		echo "<table border=0 cellspacing=0 cellpadding=30 width=\"100%\">";
		echo "<tr><td align=center>";
		echo "<input type=hidden name=action value=\"reallysend\">";
		echo "<input type=hidden name=reallysend value=\"".$_GET['send']."\">";
		echo "<input type=submit value=\"Yes, Send Email\">";
		echo "</form>";
		echo "</td><td>";
		echo "<form method=get action=\"communication.php\">";
		echo "<input type=submit value=\"No, Do Not Send\">";
		echo "</form>";
		echo "</td></tr>";
		echo "</table>";
		}
		echo $str;
	}
	else if($_GET['action']=="reallysend" && $_GET['reallysend'] && $_GET['to'])
	{
		if(file_exists("../data/communication.lock"))
		{
			echo error("Another email communication is already in progress");
			$lines=file("../data/communication.lock");
			echo "<br>";
			echo "<a href=\"communication_send_status.php\">Click here to see the status of the communication sending that is in progress</a>";
		}
		else
		{
			$to = $_GET['to'];
			if(array_key_exists($to,$mailqueries))
			{

				$q=mysql_query($mailqueries[$to]['query']);
				echo mysql_error();

				$num_subscribed=mysql_num_rows($q);
				if($num_subscribed)
				{

					$q=mysql_query("SELECT * FROM emails WHERE id='".$_GET['reallysend']."'");
					$r=mysql_fetch_object($q);

					//communcation lock file lines:
					//	1: Email ID
					//	2: Date it was started
					//	3: Subject
					//	4: Total Recipients
					//	5: _GET['to']
					$fp=fopen("../data/communication.lock","w");
					fputs($fp,$r->id."\n");
					fputs($fp,date("r")."\n");
					fputs($fp,$r->subject."\n");
					fputs($fp,$num_subscribed."\n");
					fputs($fp,$_GET['to']."\n");
					fclose($fp);

					exec("/usr/local/bin/php -q send_communication.php ".$_GET['reallysend']." >/dev/null 2>&1 &");

					echo "<br />";
					echo happy("Email Communication sending has started!");
					echo "<br>";
					echo "<a href=\"communication_send_status.php\">Click here to see the sending progress</a>";
				}
				else
				{
					echo error(i18n("No recipients"));
				}



			}
			else
				echo error(i18n("Unknown 'to' to send email communication to (%1)",array($_GET['to'])));

		}
	}
 else if($_GET['action']=="add" || $_GET['action']=="edit")
 {
	echo "<form method=\"post\" action=\"communication.php\">";
	if($_GET['action']=="edit")
	{
		$q=mysql_query("SELECT * FROM emails WHERE id='".$_GET['edit']."'");
		$r=mysql_fetch_object($q);
		$buttontext=i18n("Save Email");
		echo "<input type=\"hidden\" name=\"action\" value=\"edit\">\n";
		echo "<input type=\"hidden\" name=\"edit\" value=\"".$_GET['edit']."\">\n";
		echo "<h3>".i18n("Edit Email")."</h3>";

		$val=$r->val;
		$name=$r->name;
		$description=$r->description; 
		$subject=$r->subject;
		$from=$r->from;
		$body=$r->body;
	}
	else
	{
		$buttontext=i18n("Add Email");
		echo "<input type=\"hidden\" name=\"action\" value=\"add\">\n";
		echo "<h3>".i18n("Add Email")."</h3>";
	}
	if($_POST['val']) $val=stripslashes($_POST['val']);
	if($_POST['name']) $name=stripslashes($_POST['name']);
	if($_POST['description']) $description=stripslashes($_POST['description']);
	if($_POST['subject']) $subject=stripslashes($_POST['subject']);
	if($_POST['from']) $from=stripslashes($_POST['from']);
	if($_POST['body']) $body=stripslashes($_POST['body']);

	if(!$from && $config['fairmanageremail']) $from="Fair Manager <".$config['fairmanageremail'].">";

	echo "<table>";
	echo "<tr><td>".i18n("Email Name")."</td><td><input type=\"text\" name=\"name\" size=\"60\" value=\"$name\" /></td></tr>\n";
	echo "<tr><td>".i18n("Email Key")."</td><td>";
	if($r->type=="system")
		echo $val;
	else
		echo "<input type=\"text\" name=\"val\" size=\"40\" value=\"$val\" /> (must be unique)";
	echo "</td></tr>\n";
	echo "<tr><td>".i18n("Email Description")."</td><td><input type=\"text\" name=\"description\" size=\"60\" value=\"$description\" /></td></tr>\n";
	echo "<tr><td colspan=\"2\"><hr /></td></tr>";
	echo "<tr><td>".i18n("Email Subject")."</td><td><input type=\"text\" name=\"subject\" size=\"60\" value=\"$subject\" /></td></tr>\n";
	echo "<tr><td>".i18n("Email From")."</td><td><input type=\"text\" name=\"from\" size=\"60\" value=\"$from\" /></td></tr>\n";
	echo "<tr><td>".i18n("Email Body")."</td><td><textarea name=\"body\" cols=\"80\" rows=\"10\" style=\"font-size: 0.75em\">".htmlspecialchars($body)."</textarea></td></tr>";
	echo "<tr><td colspan=\"2\" align=\"center\"><input type=\"submit\" value=\"".$buttontext."\"></td></tr>";
	echo "</table>";
	echo "</form>";

 }
 else
 {
 	if(!$config['fairmanageremail'])
		echo notice(i18n("Warning: The 'Fair Manager Email' has not been set in SFIAB Configuration / Configuration Variables / Global.  Please set it.  The 'Fair Manager Email' is the default 'From' address for all emails and without a 'From' address, no emails can be sent!"));

	 $q=mysql_query("SELECT * FROM emails ORDER BY type,name");
	 echo "<A href=\"communication.php?action=add\">Add New Email</a>";
	 echo "<table class=\"summarytable\">";
	 echo "<tr>";
	 echo " <th>".i18n("Name")."</th>";
	 echo " <th>".i18n("Type")."</th>";
	 echo " <th>".i18n("Actions")."</th>";
	 echo "</tr>";
	 while($r=mysql_fetch_object($q))
	 {

		echo "<tr><td>$r->name</td>";
		echo "<td>$r->type</td>";

		echo " <td align=\"center\">";
		echo "<a href=\"communication.php?action=edit&edit=$r->id\"><img border=\"0\" src=\"".$config['SFIABDIRECTORY']."/images/16/edit.".$config['icon_extension']."\"></a>";

		//only user emails can be deleted, system ones are required and cannot be removed
		if($r->type=="user")
		{
			echo "&nbsp;";
			echo "<a onclick=\"return confirmClick('Are you sure you want to remove email?')\" href=\"communication.php?action=delete&delete=$r->id\"><img border=0 src=\"".$config['SFIABDIRECTORY']."/images/16/button_cancel.".$config['icon_extension']."\"></a>";
			echo "&nbsp;";
			echo "<a href=\"communication.php?action=send&send=$r->id\">Send</a>";
		}

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


 }

 send_footer();
?>
