<?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/config/batch.config.php";
include $path . "../components/core/inc/aroundme_core.functions.php";


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


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


// SETUP DATABASE --------------------------------------------------------
require_once($path . '../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($path . '../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 = $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']);
				$amt_result->moveNext();
			}
		}
		
		// we prepare the message
		if (!empty($membership_type_ids)) {
			// we get the html template
			$template_path_core = $path . "../components/core/template/" . $core_config['template']['default_name'] . "/";
			
			require_once($path . '../components/core/class/Template.class.php');
			$html_tpl = & new Template($template_path_core); // inner template

			// get html language
			$language_path_core = $path . "../components/core/language/" . $ann_result->fields['language_id'] . "/" . $core_config['template']['default_name'] . "/";
			
			require_once($language_path_core . 'html_email.lang.php');
			$html_tpl->set('lang', $lang); // language


			$url = $batch_config['node']['url']['www_path'];
			$url .= "index.php?amn=core_ann_view&announce_id=" . $ann_result->fields['announce_id'];
			$url_html = "<a href=\"" . $url . "\">" .$ann_result->fields['announce_title'] . "</a>";
			
			
			$message_body_text = $ann_result->fields['announce_body'];
			$message_body_text = strip_tags($message_body_text) . "\n\n" .$url;
			
			$message_body_html = $ann_result->fields['announce_body'] . "<br /><br />" .$url_html;

			// HTML-version of the mail
			$html_tpl->set('content', utf8_decode($message_body_html));
			$message_body_html = $html_tpl->fetch('html_email.tpl.php');
			
			$message_body_text = utf8_decode($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 u.user_id, u.user_firstname, u.user_email 
				FROM  " . $db->prefix . "_user u, " . $db->prefix . "_user_preference up 
				WHERE 
				u.language_id=". $ann_result->fields['language_id'] . " AND 
				u.membership_type_id in (" . implode(",", $membership_type_ids) . ") AND
				u.status_id=" . $core_config['user']['status']['active'] . " AND
				u.user_id>" . $ann_result->fields['start_user_id'] . " AND
				u.user_id=up.user_id AND 
				up.user_preference_id=" . $core_config['user']['preference']['email_announcements']
			;
			
			// 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){
					//format message
					if (empty($result->fields['user_firstname'])) {
						$result->fields['user_firstname'] = "";
					}
					
					$html_email = str_replace("SYS_KEYWORD_NAME", $result->fields['user_firstname'], $message_body_html);
					$alt_body = str_replace("SYS_KEYWORD_NAME", $result->fields['user_firstname'], $message_body_text);

					//send email
					$mail->Body = $html_email;
					$mail->AltBody = utf8_decode($alt_body);
					
					// 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, $path . "../");
					}
					
					
					
					// 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
				$query = "
					SELECT * 
					FROM " . $db->prefix . "_announce  
					WHERE
					announce_id=" . $ann_result->fields['announce_id']
				;

				$ann_item_result = $db->Execute($query);

				if(!empty($ann_item_result->fields)){
				
					$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_item_result, $rec, false, get_magic_quotes_gpc());
					
					$result = $db->Execute($query);
				}
				
				$mail->SmtpClose(); // Manually close the SMTP connection
			}
			
			$db->Close();
		}
	}
}
?>