<?php
// -----------------------------------------------------------------------
// This file is part of Igloo
// 
// 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.
// -----------------------------------------------------------------------

// we get (distinct) the bookmarked items marked with "batch_request"
// for each item we get the users
// we send notification to each user
// we return batch_request to null


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

include $path . "../config/config_igloo.inc.php";
include $path . "../inc/functions.inc.php";

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

// SETUP LOGGING ---------------------------------------------------
$GLOBALS['igloo_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');
	
	
	//SETUP DATE ---------------------------------------------------------------
	require_once($path . '../class/Date.class.php');
	$date = new Date();
	
	
	// SETUP USER --------------------------------------------------------------
	require_once($path . '../class/User.class.php');
	$user = new User($db, $date);
	
	
	// SETUP BLOGS -------------------------------------------------------------
	require_once($path . '../class/Blog.class.php');
	$blog = new Blog($db, null, null);
	
	
	// SETUP LIBRARY -----------------------------------------------------------
	require_once($path . '../class/Library.class.php');
	$library = new Library($db, null, null);
	
	
	// SETUP SCHEDULE -------------------------------------------------------
	require_once($path . '../class/Schedule.class.php');
	$schedule = new Schedule($db, null, $date, null);
	$schedule->schedule_config = $c_node['schedule'];
	
	
	// SETUP POLLS  ---------------------------------------------------------
	require_once($path . '../class/Poll.class.php');
	$poll = new Poll($db, null);
	
	
	// SETUP FORUM  ---------------------------------------------------------
	require_once($path . '../class/Forum.class.php');
	$forum = new Forum($db, null, null);
	
	
	// SETUP BOOKMARKS  -----------------------------------------------------
	require_once($path . '../class/Bookmark.class.php');
	$bookmark = new Bookmark($db, null, null);
	$bookmark->bookmark_type  = $c_node['bookmark']['type']['watch'];
	
	// SETUP COMMENTS  ------------------------------------------------------
	require_once($path . '../class/Comment.class.php');
	$comment = new Comment($db, null);
	$comment->limit = 1;
	$comment->orderby = "c.comment_create_datetime desc";
	
	
	// SETUP THE MAIL BOBY TEXT ---------------------------------------------
	$language_id = $c_node['node']['language']['default'];
	$languagePath = $path . "../language/" . $language_id . "/" . $c_node['node']['template_default_name'] . "/";
	$languageTextPath = $languagePath . "texts/";
	$source_mail_txt = readTxtFile($languageTextPath . "mail_email_notify.txt.php");
	include $languagePath . 'mail_notification.lang.php';
	
	// Setup of the email
	$mail->Subject = $lang['txt_subject'];
	
	
	// SELECT ITEM_IDs ------------------------------------------------------
	$bm_query = "
		SELECT DISTINCT item_id, rsp_item_type_id 
		FROM " . $db->prefix . "_bookmark 
		WHERE 
		bookmark_notify=1 AND 
		bookmark_batch_request=1 
		order by rsp_item_type_id, item_id"
	;
	
	$bm_result = $db->Execute($bm_query);
	
	// for each item we get the item details
	if (isset($bm_result->fields)) {
		while (!$bm_result->EOF) {
			unset($rsp_item_lnk, $rsp_item);
			
			$bm_temp1 = $bm_result->fields;
			
			if ($bm_result->fields['rsp_item_type_id'] == $c_node['rsp']['item_type']['blog']) {
				$blog->blog_id = $bm_result->fields['item_id'];
				$rsp_item = $blog->selBlog();
				$rsp_item['title'] = $rsp_item['blog_title'];
				$rsp_item['synopsis'] = $rsp_item['blog_synopsis'];
				$rsp_item_lnk = "blg_view.php?blog_id=" . $bm_result->fields['item_id'];
				
				$comment->rsp_item_type_id = $c_node['rsp']['item_type']['blog'];
				if (!empty($rsp_item['group_id'])) {
					$comment->group_id = $rsp_item['group_id'];
				}
				$rsp_item_last_comment = $comment->selComments($bm_result->fields['item_id']);
				unset($comment->group_id);
			}
			elseif ($bm_result->fields['rsp_item_type_id'] == $c_node['rsp']['item_type']['library']) {
				$library->library_id = $bm_result->fields['item_id'];
				$rsp_item = $library->selLibraryItem();
				$rsp_item['title'] = $rsp_item['library_title'];
				$rsp_item['synopsis'] = $rsp_item['library_synopsis'];
				$rsp_item_lnk = "lib_view.php?library_id=" . $bm_result->fields['item_id'];
				
				$comment->rsp_item_type_id = $c_node['rsp']['item_type']['library'];
				if (!empty($rsp_item['group_id'])) {
					$comment->group_id = $rsp_item['group_id'];
				}
				$rsp_item_last_comment = $comment->selComments($bm_result->fields['item_id']);
				unset($comment->group_id);
			}
			elseif ($bm_result->fields['rsp_item_type_id'] == $c_node['rsp']['item_type']['schedule']) {
				$schedule->schedule_id = $bm_result->fields['item_id'];
				$rsp_item = $schedule->selScheduleItem();
				$rsp_item['title'] = $rsp_item['schedule_title'];
				$rsp_item['synopsis'] = $rsp_item['schedule_synopsis'];
				$rsp_item_lnk = "sch_view.php?schedule_id=" . $bm_result->fields['item_id'];
				$rsp_item_last_comment = $comment->selComments($bm_result->fields['item_id']);
				unset($comment->group_id);
			}
			elseif ($bm_result->fields['rsp_item_type_id'] == $c_node['rsp']['item_type']['forum']) {
				$forum->subject_id = $bm_result->fields['item_id'];
				$rsp_item = $forum->selSubject();
				$rsp_item['title'] = $rsp_item['subject_title'];
				$rsp_item['synopsis'] = $rsp_item['subject_synopsis'];
				$rsp_item_lnk = "frm_view.php?subject_id=" . $bm_result->fields['item_id'];
				
				$comment->rsp_item_type_id = $c_node['rsp']['item_type']['forum'];
				if (!empty($rsp_item['group_id'])) {
					$comment->group_id = $rsp_item['group_id'];
				}
				$rsp_item_last_comment = $comment->selComments($bm_result->fields['item_id']);
				unset($comment->group_id);
			}
			elseif ($bm_result->fields['rsp_item_type_id'] == $c_node['rsp']['item_type']['poll']) {
				$poll->poll_id = $bm_result->fields['item_id'];
				$rsp_item = $poll->selPoll();
				$rsp_item['title'] = $rsp_item['poll_question'];
				$rsp_item['synopsis'] = "";
				$rsp_item_lnk = "pol_view.php?poll_id=" . $bm_result->fields['item_id'];
				
				$comment->rsp_item_type_id = $c_node['rsp']['item_type']['poll'];
				if (!empty($rsp_item['group_id'])) {
					$comment->group_id = $rsp_item['group_id'];
				}
				$rsp_item_last_comment = $comment->selComments($bm_result->fields['item_id']);
				unset($comment->group_id);
			}
			
			$rsp_item_lnk = $c_node['dir']['www_path'] . $rsp_item_lnk;
			$rsp_item_last_comment[0]['comment_create_datetime'] = $date->formatDate($rsp_item_last_comment[0]['comment_create_datetime'], 1);
			
			// FORMAT EMAIL
			$message_body = $source_mail_txt;
			$message_body = str_replace("SYS_KEYWORD_TITLE", $rsp_item['title'], $message_body);
			$message_body = str_replace("SYS_KEYWORD_SYNOPSIS", $rsp_item['synopsis'], $message_body);
			$message_body = str_replace("SYS_KEYWORD_URL", $rsp_item_lnk, $message_body);
			$message_body = str_replace("SYS_KEYWORD_NIC", $rsp_item_last_comment[0]['profile_nic'], $message_body);
			$message_body = str_replace("SYS_KEYWORD_HOMETOWN", $rsp_item_last_comment[0]['profile_hometown'], $message_body);
			$message_body = str_replace("SYS_KEYWORD_DATETIME", $rsp_item_last_comment[0]['comment_create_datetime'], $message_body);
			$message_body = str_replace("SYS_KEYWORD_BODY", $rsp_item_last_comment[0]['comment_body_raw'], $message_body);
			
					
			// for each item we get the users
			$bm_users_query = "
				SELECT user_id 
				FROM " . $db->prefix . "_bookmark 
				WHERE 
				item_id=" . $bm_result->fields['item_id'] . " AND 
				rsp_item_type_id=" . $bm_result->fields['rsp_item_type_id'] . " AND 
				bookmark_notify=1 AND 
				bookmark_batch_request=1"
			;
			
			$bm_users_result = $db->Execute($bm_users_query);
			
			//for each user send email
			if (isset($bm_users_result->fields)) {
				while (!$bm_users_result->EOF) {
					$to_user = $user->getUser($bm_users_result->fields['user_id']);
					
					$message_body_user = $message_body;
					
					// for most instances we predict not much varience in language
					if ($language_id != $to_user['language_id']) {
						$language_id = $to_user['language_id'];
						$languagePath = $path . "../language/" . $language_id . "/" . $c_node['node']['template_default_name'] . "/";
						$languageTextPath = $languagePath . "texts/";
						$source_mail_txt = readTxtFile($languageTextPath . "mail_email_notify.txt.php");
						include $languagePath . 'mail_notification.lang.php';
						// Setup of the email
						$mail->Subject = $lang['txt_subject'];
						
						// FORMAT EMAIL
						$message_body_user = str_replace("SYS_KEYWORD_TITLE", $rsp_item['title'], $message_body_user);
						$message_body_user = str_replace("SYS_KEYWORD_SYNOPSIS", $rsp_item['synopsis'], $message_body_user);
						$message_body_user = str_replace("SYS_KEYWORD_URL", $rsp_item_lnk, $message_body_user);
						$message_body_user = str_replace("SYS_KEYWORD_NIC", $rsp_item_last_comment[0]['profile_nic'], $message_body_user);
						$message_body_user = str_replace("SYS_KEYWORD_HOMETOWN", $rsp_item_last_comment[0]['profile_hometown'], $message_body_user);
						$message_body_user = str_replace("SYS_KEYWORD_DATETIME", $rsp_item_last_comment[0]['comment_create_datetime'], $message_body_user);
						$message_body_user = str_replace("SYS_KEYWORD_BODY", $rsp_item_last_comment[0]['comment_body_raw'], $message_body_user);
					}
					
					
					$message_body_user = str_replace("SYS_KEYWORD_NAME", $to_user['user_firstname'], $message_body_user);
					
					$message_body_user = stripslashes($message_body_user);
					$message_body_text = $message_body_user;
					$message_body_html = $message_body_user;
					
					
					$message_body_html = $wiki->transform($message_body_html, 'Xhtml');
					
					// HTML-version of the mail
					$html  = "<HTML><HEAD><TITLE></TITLE></HEAD>";
					$html .= "<BODY>";
					$html .= utf8_decode($message_body_html);
					$html .= "</BODY></HTML>";
					$mail->Body = $html;
					// non - HTML-version of the email
					$mail->AltBody   = utf8_decode($message_body_text);
					
					// add new email-address to mailer-object
					$mail->AddAddress($to_user['user_email'], $to_user['user_firstname']);
					
					// Send email
					if(!$mail->Send()) {
						$log = "There has been a mail error sending a notification (subject:" . $mail->Subject . ")to " . $to_user['user_email'] . "," . $to_user['user_firstname'] . ".";
					}
					
					//write to log file
					if (isset($GLOBALS['igloo_log']) && $GLOBALS['igloo_log'] == true) {
						if (!isset($log)) {
							$log = "notification (subject:" . $mail->Subject . ") to " . $to_user['user_email'] . "," . $to_user['user_firstname'] . " sent.";
						}
						writeLogFile($log, "../");
					}
					
					// Clear all addresses for next loop
					$mail->ClearAddresses();
					unset($log);
					
					$bm_users_result->MoveNext();
				}
			}
			// reset bookmarks
			$bookmark->rsp_item_type_id = $bm_result->fields['rsp_item_type_id'];
			$bookmark->updateBookmarkNotification($bm_result->fields['item_id']); // remove notification request
			
			$bm_result->MoveNext();
		}
	}
	
	$mail->SmtpClose(); // Manually close the SMTP connection
	
	$db->Close();
}
?>