<?php
// -----------------------------------------------------------------------
// This file is part of AROUNDMe
// 
// Copyright (C) 2003 - 2007 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.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; either version 2, or (at your option) any
// later version.
// 
// 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 program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------

// newsletter status_ids
// 0 = not send yet
// 1 = processsing
// 2 = completed

$path = dirname(__FILE__) . "/";

include $path . "../components/core/config/aroundme_core.config.php";
include $path . "../batch/batch.config.php";


session_name($core_config['node']['php_session_name']);
session_start();


// SETUP LOGGING ---------------------------------------------------
$GLOBALS['am_log'] = $c_node['log'];


// SETUP DATABASE --------------------------------------------------------
require_once('../components/core/class/Adodb/adodb.inc.php');
$ADODB_CACHE_DIR = 'cache/Adodb';
$ADODB_FETCH_MODE = ADODB_FETCH_BOTH;
$ADODB_COUNTRECS = false;
$db = NewADOConnection($core_config['db']['driver']);
if ($db->Connect($core_config['db']['host'], $core_config['db']['user'] , $core_config['db']['pass'] , $core_config['db']['db'])) {
	$db->prefix = $core_config['db']['prefix'];
	
	
	// SETUP MAIL -------------------------------------------------------------
	require_once('../components/core/class/Mail/class.phpmailer.php');
	$mail = new PHPMailer($core_config['mail']);
		
	$mail->AddReplyTo($core_config['mail']['no_reply_address'], 'no reply');
	
	
	// select the first announcement with batch request set -----------------------------------
	$query = "
		SELECT * 
		FROM " . $db->prefix . "_announce  
		WHERE
		batch_request=1"
	;

	$ann_result = $db->SelectLimit($query, 1, 0);

	if(!empty($ann_result->fields)){
		// we get the membership types
		$query = "
			SELECT * 
			FROM " . $db->prefix . "_announce_membership_type  
			WHERE
			announce_id=" . $ann_result->fields['announce_id']
		;
		
		$amt_result = $this->db->Execute($query);
		
		$membership_type_ids = array();

		if (isset($amt_result->fields)) {
			while(!$amt_result->EOF) {
				array_push($membership_type_ids, $amt_result->fields['membership_type_id']);
				$result->moveNext();
			}
		}
		
		// we prepare the message
		if (!empty($membership_type_ids)) {
			// Text-version of the mail
			$message_body_text = "";
		
			$message_body_html = $ann_result->fields['announce_body'];
			// non - HTML-version of the email
			$mail->AltBody   = strip_tags($message_body_text);
			
			// Setup of the email
			$mail->Subject = $ann_result->fields['announce_title'];
			
			
			//and select the next X people to send to
			$query = "
				SELECT user_id, user_firstname, user_email 
				FROM  " . $db->prefix . "_user 
				WHERE 
				language_id=". $ann_result->fields['language_id'] . " AND 
				membership_type_id in (" . implode(",", $membership_type_ids) . ") AND
				status_id=" . $c_node['user']['status']['active'] . " AND
				user_id>" . $ann_result->fields['start_user_id']
			;

			// get the total number of emails that should be sent
			$result = $db->SelectLimit($query, $batch_config['nr_per_batch']);


			if (!empty($result)) {
				
				$sendcount=0;
				
				while(!$result->EOF){
					// HTML-version of the mail
					$html  = "<HTML><HEAD><TITLE></TITLE></HEAD>";
					$html .= "<BODY>";
					$html .= utf8_decode($message_body_html);
					$html .= "</BODY></HTML>";
					
					//format message
					if (empty($result->fields['user_firstname'])) {
						$result->fields['user_firstname'] = "";
					}
					
					$html = str_replace("SYS_KEYWORD_NAME", $result->fields['user_firstname'], $html);
					$mail->Body = $html;
					
					// add new email-address to mailer-object
					$mail->AddAddress($result->fields['user_email'], $result->fields['user_firstname']);
					
					
					// Send email
					if(!$mail->Send()) {
						$log = "There has been a mail error sending an announcement (subject:" . $mail->Subject . ")to " . $result->fields['user_email'] . "," . $result->fields['user_firstname'] . ".";
					}
				
					//write to log file
					if (isset($GLOBALS['am_log']) && $GLOBALS['am_log'] == true) {
						if (!isset($log)) {
							$log = "announcement (subject:" . $mail->Subject . ") to " . $result->fields['user_email'] . "," . $result->fields['user_firstname'] . " sent.";
						}
						writeLogFile($log);
					}
					
					
					
					// Clear all addresses for next loop
					$mail->ClearAddresses();
					unset($log);
					
					$end_user_id = $result->fields['user_id'];
					
					$sendcount++;
					
					$result->MoveNext();
				}
				
				// we update the newsletter table
				$rec = array();
				
				$batch_request = 1; //processing
				
				if ($sendcount < $batch_config['nr_per_batch']) {
					$batch_request = 2; //completed
				}

				$rec = array();
				$rec['batch_request'] = $batch_request;
				
				if (isset($end_user_id)) {
					$rec['start_user_id'] = $end_user_id;
				}
				
				$query = $db->GetUpdateSQL($ann_result, $rec, false, get_magic_quotes_gpc());
					
				$result = $db->Execute($query);
				
				$mail->SmtpClose(); // Manually close the SMTP connection
			}
			
			$db->Close();
		}
	}
}
?>