<?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.
// -----------------------------------------------------------------------

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


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


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


// SETUP DATABASE --------------------------------------------------------
require_once('../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 COMMENTS --------------------------------------------------------
	require_once('../components/core/class/Comment.class.php');
	$comment = new Comment($db, null);
	$comment->order_by = "c.comment_create_datetime desc";
	$comment->limit = 1;

	
	//SETUP DATE -----------------------------------------------------------------------
	require_once('../components/core/class/Date.class.php');
	$date = new Date();


	// SETUP MAIL -------------------------------------------------------------
	require_once('../components/core/class/Mail/class.phpmailer.php');
	$mail = new PHPMailer($core_config['mail']);
		
	$mail->AddReplyTo($core_config['mail']['no_reply_address'], 'no reply');
	
	
	// SETUP THE BODY TEXT ---------------------------------------------
	$language_id = $core_config['language']['default_id'];
	$language_path = $path . "../components/core/language/" . $language_id . "/" . $core_config['template']['default_name'] . "/";
	//$language_text_path = $languagePath . "texts/";
	$source_mail_txt = readTxtFile($language_path . "texts/bookmark_notification.txt.php");
	include $language_path . 'bookmark_notification.lang.php';
	
	// Setup of the email
	$mail->Subject = $lang['txt_subject'];
	
	
	// SELECT BOOKMARKS ------------------------------------------------------
	$bm_query = "
		SELECT DISTINCT module_id, item_id 
		FROM " . $db->prefix . "_bookmark 
		WHERE 
		bookmark_notify=1 AND 
		bookmark_batch_request=1 
		order by module_id, item_id"
	;
	
	$bm_result = $db->Execute($bm_query);
	
	// for each item we get the item details
	if (isset($bm_result->fields)) {
		// get the functions for modules
		if (!empty($core_config['module'])) {
			foreach($core_config['module'] as $key => $i):
				$suffix = $core_config['module'][$key]['prefix'];
				
				if(is_file("components/" . $suffix . "/inc/" . $suffix . "_item_select.function.php")) {
					include_once("components/" . $suffix . "/inc/" . $suffix . "_item_select.function.php");
				}
			endforeach;
		}
		
		while (!$bm_result->EOF) {
			$item = array();

			$suffix = $core_config['module'][$bm_result->fields['module_id']]['prefix'];
			$function_name = "selItemModule_" . $suffix;
			
			if (function_exists($function_name)) {
				array_push($item, $function_name($bm_result->fields['item_id']));
			}

			// we got -> $item['item_title'], $item['item_url']
			
			$item['item_url'] = $core_config['node']['url']['www_path'] . $item['item_url']
			
			// get latest comment
			$comment->module_id = $bm_result->fields['module_id'];
			$comment->item_id = $bm_result->fields['item_id'];
			
			$latest_comment = $comment->selComments();
			$item['comment'] = $latest_comment[0];
			
			$item['comment']['comment_create_datetime'] = $date->formatDate($item['comment']['comment_create_datetime'], 1);
			
			
			// FORMAT EMAIL
			$message_body = $source_mail_txt;
			$message_body = str_replace("SYS_KEYWORD_TITLE", $item['title'], $message_body);
			$message_body = str_replace("SYS_KEYWORD_URL", $item['item_url'] , $message_body);
			$message_body = str_replace("SYS_KEYWORD_NIC", $item['comment']['identity_nic'], $message_body);
			$message_body = str_replace("SYS_KEYWORD_HOMETOWN", $item['comment']['location_name'], $message_body);
			$message_body = str_replace("SYS_KEYWORD_DATETIME", $item['comment']['comment_create_datetime'], $message_body);


			$message_body_html = str_replace("SYS_KEYWORD_BODY", $item['comment']['comment_body'], $message_body);
			$message_body_txt = str_replace("SYS_KEYWORD_BODY", strip_tags($item['comment']['comment_body']), $message_body);
			
			
			// for each item we get the users who are tracking this
			$bm_users_query = "
				SELECT user_id 
				FROM " . $db->prefix . "_bookmark 
				WHERE 
				item_id=" . $bm_result->fields['item_id'] . " AND 
				module_id=" . $bm_result->fields['module_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) {
					// we do not send notification to the author
					if ($item['comment']['user_id'] != $bm_users_result->fields['user_id']) {
					
						$to_user = $user->selUser($bm_users_result->fields['user_id']);
						
						$message_body_html = str_replace("SYS_KEYWORD_NAME", $to_user['user_firstname'], $message_body_user);
						$message_body_txt = str_replace("SYS_KEYWORD_NAME", $to_user['user_firstname'], $message_body_user);
						
						
						// 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_txt);
						
						// 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['am_log']) && $GLOBALS['am_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->module_id = $bm_result->fields['module_id'];
			$bookmark->item_id = $bm_result->fields['item_id'];
			$bookmark->updateBookmarkNotification($bm_result->fields['item_id']); // remove notification request
			
			$bm_result->MoveNext();
		}
	}
	
	$mail->SmtpClose(); // Manually close the SMTP connection
	
	$db->Close();
}
?>