<?php

// -----------------------------------------------------------------------
// This file is part of beacon
//
// Copyright (C) 2003, 2005 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., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
// -----------------------------------------------------------------------



class Newsletter {
	// CLASS FUNCTIONS
	// Newsletter
	// sendNewsletter
	// insertNewsletter
	
	
	
	// Newsletter ----------------------------------------------------------
	// the constuctor
	// tom calthrop - 8th June 2005
	//
	function Newsletter($db, $config_nlt=null) {
		$this->db = $db;
		$this->config_nlt = $config_nlt;
	}//EO Comment
	
	
	
	// insertNewsletter ----------------------------------------------------
	// inserts record into newsletter table
	// tom calthrop - 22nd May 2004
	//
	function insertNewsletter($data) {
		
		if (empty($data['item_id'])) {
			$data['item_id'] = "null";
		}
		
		$rec = array();
		$rec['from_user_id'] = $_SESSION['s_user_id'];
		$rec['to_type_id'] = $data['to_type_id'];
		$rec['message_subject'] = $data['subject'];
		$rec['message_body'] = $data['message'];
		$rec['message_create_datetime'] = time();
		$rec['item_id'] = $data['item_id'];
		$rec['language_id'] = $data['language_id'];
		$rec['start_id'] = 0;
		
		$table = $this->db->prefix . "_newsletter";
		
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
			$this->message_id = $this->db->Insert_ID();
		}
		else {
			$error_info = "function=insertNewsletter class=Newsletter.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, $error_info);
		}
	} // EO insertNewsletter
	
	
	
	// sendNewsletter ----------------------------------------------------
	// Sends X (nr_per_batch var) then send again until complete ot [in batch
	// (cron) mode] sends once
	// tom calthrop - 8th June 2005
	//
	function sendNewsletter($message_id = null) {
		
		$query = "
			SELECT * 
			FROM " . $this->db->prefix . "_newsletter 
			WHERE
			message_status=0 AND "
		;
		
		if (isset($message_id)) {
			$query .= "message_id=" . $message_id . " AND ";
		}
		
		$query .= "1=1";
		
		$nl_result = $this->db->SelectLimit($query, 1, 0);
		
		if(!empty($nl_result->fields)){ 
			
			// Text-version of the mail
			$message_body_text = "";
			// HTML-version of the email
			$message_body_html = $nl_result->fields['message_body'];
			
			// Setup of the email
			$this->mail->Subject   = $nl_result->fields["message_subject"];
			$this->mail->AltBody   = $message_body_text;
			
			// checks if a start index has been specified 
			$start_id = isset($nl_result->fields['start_id']) & !empty($nl_result->fields['start_id']) ? $nl_result->fields['start_id'] : 0;
			$end_id   = $start_id + $this->config_nlt['nr_per_batch'];
			
			
			//select all members
			if ($nl_result->fields['to_type_id'] == $this->config_nlt['type']['node']) {
				$query = "
					SELECT user_firstname, user_email 
					FROM  " . $this->db->prefix . "_user 
					WHERE 
					language_id=". $nl_result->fields['language_id'] . " AND 
					status_id=" . $this->user_status_ids['active']
				;
			}
			//select pending members
			elseif ($nl_result->fields['to_type_id'] == $this->config_nlt['type']['node_pending']) {
				$query = "
					SELECT user_firstname, user_email 
					FROM  " . $this->db->prefix . "_user 
					WHERE 
					language_id=". $nl_result->fields['language_id'] . " AND 
					status_id=" . $this->user_status_ids['pending']
				;
			}
			//select invited members
			elseif ($nl_result->fields['to_type_id'] == $this->config_nlt['type']['node_invited']) {
				$query = "
					SELECT invited_email as user_email 
					FROM  " . $this->db->prefix . "_user_invited"
				;
			}
			
			// get the total number of emails that should be sent
			$result = $this->db->Execute($query);
			
			if (!empty($result)) {
				$max = $result->RecordCount();
				$result->Close();
				
				// Getting "nr_addresses" persons to send to...
				$result = $this->db->SelectLimit($query, $this->config_nlt['nr_per_batch'], $start_id);
				
				while(!$result->EOF){
					// HTML-version of the mail
					$html  = "<HTML><HEAD><TITLE></TITLE></HEAD>";
					$html .= "<BODY>";
					$html .= $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);
					$this->mail->Body = $html;
					
					// add new email-address to mailer-object
					$this->mail->AddAddress($result->fields['user_email'], $result->fields['user_firstname']);
					
					// Send email
					if(!$this->mail->Send()) {
						$log = "There has been a mail error sending newsletter (subject:" . $this->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:" . $this->mail->Subject . ") to " . $result->fields['user_email'] . "," . $result->fields['user_firstname'] . " sent.";
						}
						writeLogFile($log);
					}
					
					// Clear all addresses for next loop
					$this->mail->ClearAddresses();
					
					$result->MoveNext();
				}
				
				$result->Close();
				
				$rec = array();
				
				if ($end_id >= $max) { 
					$rec['message_status'] = 1;
				} else {
					$rec['start_id'] = ($end_id+1);
				}
				
				$query = $this->db->GetUpdateSQL($nl_result, $rec, false, get_magic_quotes_gpc());
					
				$result = $this->db->Execute($query);
				
				$this->mail->SmtpClose(); // Manually close the SMTP connection
				
				$this->db->Close();
				
				if ($this->bulk != 1) { // not bulk email
					if($end_id < $max){
						header("Location: nlt_send.php");
					}
					else {
						header("Location: nlt_edit.php?complete=" . $max);
					}
					exit;
				}
			}
		}
	}
}
?>
