<?
/* 
   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.
*/
?>
<?
include "../common.inc.php";
include "communication.inc.php";

$sleepmin=500000;  // 0.5 seconds
$sleepmax=2000000; // 2.0 second

if(file_exists("../data/communication.lock"))
{
	$lines=file("../data/communication.lock");
	$id=trim($lines[0]);
	$to=trim($lines[4]);

	$q=mysql_query("SELECT * FROM emails WHERE id='$id'");
	$communication=mysql_fetch_object($q);

	$from=$communication->from;
	$subject=$communication->subject;
	$body=$communication->body;
	$headers="From: $from\r\nReply-To: $from\r\nReturn-Path: $from\r\n";
	$x=1;

	if(array_key_exists($to,$mailqueries))
	{
		$q=mysql_query($mailqueries[$to]['query']);
		while($r=mysql_fetch_object($q))
		{
			if($r->firstname && $r->lastname)
				$to="$r->firstname $r->lastname <".$r->email.">";
			else if($r->firstname)
				$to="$r->firstname <".$r->email.">";
			else
				$to=$r->email;

			mail($to,$subject,$body,$headers);
			$fp=fopen("../data/communication.lock.$id","w");
			fputs($fp,$x."\n");
			fclose($fp);
			usleep(rand($sleepmin,$sleepmax));
			$x++;

		}
		unlink("../data/communication.lock.$id");
		unlink("../data/communication.lock");
	}
	else
		echo i18n("Unknown 'to' to send email communication to (%1)",array($to));

}
else
{
	//no communication to send... why were we called?!?!?!
}

?>
