<?php
// -----------------------------------------------------------------------
// This file is part of AROUNDMe
// 
// Copyright (C) 2003 - 2006 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__) . "/";

session_start();
include $path . "../config/config_aroundme.inc.php";
include $path . "../inc/functions.inc.php";


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


// SETUP DATABASE ----------------------------------------------------------
require_once($path . '../class/Adodb/adodb.inc.php');
$ADODB_CACHE_DIR = 'cache/Adodb';
$ADODB_FETCH_MODE = ADODB_FETCH_BOTH;
$db = NewADOConnection($c_node['db']['driver']);
if ($db->Connect($c_node['db']['host'], $c_node['db']['user'] , $c_node['db']['pass'] , $c_node['db']['db'])) {
	$db->prefix = $c_node['db']['prefix'];
	
	
	// SETUP MAIL -------------------------------------------------------------
	require_once($path . '../class/Mail/class.phpmailer.php');
	$mail = new PHPMailer();
	$mail->Host = 		$c_node['mail']['host'];
	$mail->Port = 		$c_node['mail']['port'];
	$mail->Mailer = 	$c_node['mail']['mailer'];
	
	if (isset($c_node['mail']['smtp']['username'])) {
		$mail->SMTPAuth = true;
		$mail->Username = $c_node['mail']['smtp']['username'];
		$mail->Password = $c_node['mail']['smtp']['password'];
	}
	
	$mail->From = 		$c_node['mail']['no_reply_address'];
	$mail->FromName = 	$c_node['mail']['from_name'];
	$mail->WordWrap = 	$c_node['mail']['wordwrap'];
	$mail->Priority = 			3;
	$mail->Encoding = 			"8bit";
	$mail->CharSet = 			"iso-8859-1";
	$mail->SMTPKeepAlive =      true;
	$mail->IsHTML(true);
	
	
	// SETUP WIKI -------------------------------------------------------------
	$c_node['class_path'] = $path . "../";
	require_once($path . '../class/Wiki/Wiki.php');
	$wiki = new Text_Wiki();
	$wiki->disableRule('wikilink');
	$wiki->disableRule('freelink');
	
	
	// select the newsletter(s) -----------------------------------
	$query = "
		SELECT * 
		FROM " . $db->prefix . "_newsletter 
		WHERE
		status_id<2 AND 
		to_type_id!=" . $c_node['newsletter']['type']['digest']
	;
	
	if (isset($_SESSION['newsletter_id'])) {
		$query .= " AND message_id=" . $_SESSION['newsletter_id'];
	}
	else {
		$query .= " order by status_id desc, message_id";
	}
	
	$nl_result = $db->SelectLimit($query, 1, 0);
	
	if(!empty($nl_result->fields)){ 
		// Text-version of the mail
		$message_body_text = "";
		
		$message_body_html = $nl_result->fields['message_body'];
		// non - HTML-version of the email
		$mail->AltBody   = $message_body_text;
		
		// HTML version based upon wiki markup
		$message_body_html = $wiki->transform($message_body_html, 'Xhtml');
		
		// Setup of the email
		$mail->Subject = $nl_result->fields["message_subject"];
		
		if ($nl_result->fields['to_type_id'] == $c_node['newsletter']['type']['node_invited']) {
			$query = "
				SELECT invited_email as user_email 
				FROM  " . $db->prefix . "_user_invited"
			;
		}
		else {
			$query = "
				SELECT user_id, user_firstname, user_email 
				FROM  " . $db->prefix . "_user 
				WHERE 
				language_id=". $nl_result->fields['language_id'] . " AND "
			;
			
			//select group members
			if (!empty($nl_result->fields['group_id'])) {
				$query = "
					SELECT user_id, user_firstname, user_email 
					FROM " . $this->db->prefix . "_group_member gm
					JOIN " . $this->db->prefix . "_user u ON gm.user_id=u.user_id 
					WHERE 
					gm.group_id=" . $nl_result->fields['group_id'] . " AND 
					gm.status_id=" . $this->group_status_ids['active']
				;
				
				if (!empty($nl_result->fields['role_id'])) {
					$query .= " AND gm.role_id=" . $nl_result->fields['role_id'];
				}
				
			}
			elseif ($nl_result->fields['to_type_id'] == $c_node['newsletter']['type']['node']) {
				$query .= "
					status_id=" . $c_node['user']['status']['active'] . " AND "
				;
			}
			//select pending members
			elseif ($nl_result->fields['to_type_id'] == $c_node['newsletter']['type']['node_pending']) {
				$query .= "
					status_id=" . $c_node['user']['status']['pending'] . " AND "
				;
			}
			elseif ($nl_result->fields['to_type_id'] == $c_node['newsletter']['type']['role']) {
				$query .= "
					role_id=" . $nl_result->fields['role_id'] . " AND "
				;
			}
			
			$query .= "
				user_id>" . $nl_result->fields['start_user_id'] . " AND 1=1"
			;
		}
		
		// get the total number of emails that should be sent
		$result = $db->SelectLimit($query, $c_node['newsletter']['nr_per_batch']);
		
		if (!empty($result)) {
			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("FIRSTNAME", $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 newsletter (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 = "newsletter (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'];
				
				$result->MoveNext();
			}
			
			// we update the newsletter table
			$rec = array();
			
			$status_id = 1; //processing
			
			if (count($result->fields) < $c_node['newsletter']['nr_per_batch']) {
				$status_id = 2; //completed
			}
			
			$rec['status_id'] = $status_id;
			
			if (isset($end_user_id)) {
				$rec['start_user_id'] = $end_user_id;
			}
			
			$query = $db->GetUpdateSQL($nl_result, $rec, false, get_magic_quotes_gpc());
				
			$result = $db->Execute($query);
			
			$mail->SmtpClose(); // Manually close the SMTP connection
		}
		
		$db->Close();
	}
}
?>