<?php

// -----------------------------------------------------------------------
// This file is part of igloo
//
// 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., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------



class Newsletter {
	// CLASS FUNCTIONS
	// Newsletter
	// sendNewsletter
	// insertNewsletter
	// selNewsletter
	// selNewsletters
	
	
	
	// 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";
		}
		
		if (empty($data['group_id'])) {
			$data['group_id'] = "null";
		}
		
		if (isset($_SESSION['s_user_id'])) {
			$user_id = $_SESSION['s_user_id'];
		}
		else {
			$user_id = "null";
		}
		
		if (isset($data['to_role_id']) && $data['to_role_id'] > 0) {
			$role_id = $data['to_role_id'];
		}
		else {
			$role_id = "null";
		}
		
		$rec = array();
		$rec['from_user_id'] = $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['group_id'] = $data['group_id'];
		$rec['role_id'] = $role_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['igloo_error_log'][] = array(1, $error_info);
		}
	} // EO insertNewsletter
	
	
	
	// sendNewsletter ----------------------------------------------------
	// Sends X (nr_per_batch var) then send again until complete or [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 ";
		}
		else if(!empty($this->type_ids)) {
			$type_ids = "";
			foreach($this->type_ids as $key => $i):
				$type_ids .= $i;
				if (count($this->type_ids) > $key+1) {
				    $type_ids .=",";
				}
			endforeach;
			$query .="to_type_id in (" . $type_ids . ") 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 = "";
			
			$message_body_html = $nl_result->fields['message_body'];
			// non - HTML-version of the email
			$this->mail->AltBody   = $message_body_text;
			
			// HTML version based upon wiki markup
			$c_node['dir']['class_path'] = "class/";
			require_once($c_node['dir']['class_path'] . 'Wiki/Wiki.php');
			$wiki =& new Text_Wiki();
			$wiki->disableRule('wikilink');
			$message_body_html = $wiki->transform($message_body_html, 'Xhtml');
			
			// Setup of the email
			$this->mail->Subject = $nl_result->fields["message_subject"];
			
			
			// 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 group members
			if (!empty($nl_result->fields['group_id'])) {
				$query = "
					SELECT u.user_firstname, u.user_email 
					FROM " . $this->db->prefix . "_group_membership 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'];
				}
				
			}
			//select all members
			elseif ($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();
				
				
				// 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();
					unset($log);
					
					$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 != true) { // not bulk email
					if($end_id < $max){
						header("Location: nlt_send.php");
					}
					elseif (isset($nl_result->fields['group_id'])) {
						header("Location: nlt_edit.php?complete=" . $max . "&group_id=" . $nl_result->fields['group_id']);
					}
					else {
						header("Location: nlt_edit.php?complete=" . $max);
					}
					exit;
				}
			}
		}
	}
	
	
	
	// selNewsletter ----------------------------------------------------
	// selects a newsletter
	// tom calthrop - 22nd Oct 2005
	//
	function selNewsletter($newsletter_id) {
		
		$query = "
			SELECT * 
			FROM " . $this->db->prefix . "_newsletter 
			WHERE
			message_id=" . $newsletter_id
		;
		
		$result = $this->db->SelectLimit($query, 1); //returns last 1 rows
		
		if (isset($result->fields)) {
			$temp = $result->fields;
			
			$result->Close();

			return $temp;
		}
		else {
			$error_info = "function=selNewsletter class=Newsletter.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['igloo_error_log'][] = array(1, 1, $error_info);
		}
	} //EO selNewsletter()
	
	
	
	// selNewsletters ----------------------------------------------------
	// selects all newsletters
	// tom calthrop - 22nd Oct 2005
	//
	function selNewsletters() {
		
		$query = "
			SELECT * 
			FROM " . $this->db->prefix . "_newsletter"
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
			$temp = array();
			
			while (!$result->EOF) {
				
				$temp1 = $result->fields;

				array_push($temp, $temp1);

				$result->MoveNext();
			}
	
			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=selNewsletters class=Newsletter.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['igloo_error_log'][] = array(1, 1, $error_info);
		}
	} //EO selNewsletters()
	
}
?>
