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

$menu_section = "me";

if (!isset($_SESSION['md5'])) {
	header("Location: index.php?http_referer=" . urlencode($_SERVER['REQUEST_URI']) . "&" . strip_tags(SID));
	exit;
}


require_once ("class/File.class.php");
$file = new File($db, $core_config['file']);

if (isset($core_config['module'])) {
	$file->core_config_module = $core_config['module'];
}

$file->module_id = 0; // core
$file->no_image = $core_config['file']['image']['thumb'][1]['no_image'];
$user->file = $file;


require_once ('class/Tag.class.php');
$tag = new Tag($db, null, $core_config['tag']['core']['network']);
$tag->user_id = $_SESSION['user_id'];
$output_tags = $tag->selTags();


if (isset($_POST['send_message'])) {
	if (empty($_POST['to_identity_ids']) && empty($_POST['to_identity_id'])) {
		
		$GLOBALS['am_error_log'][] = array('no_receiver_error');
		
		$allow_compose = 1;
		
		$output_message = $_POST;
		$output_message['message_body'] = stripslashes($output_message['message_body']);
		
	}
	else { // we send
		$me_identity = $user->selUserIdentity($_SESSION['user_id']);
		$_POST['from_identity_id'] = $me_identity['identity_id'];

		$_POST['message_subject'] = stripslashes(htmlspecialchars($_POST['message_subject']));
		// setup mail
		require_once('class/Mail/class.phpmailer.php');
		$mail = new PHPMailer($core_config['mail']);
		$mail->AddReplyTo ($core_config['mail']['no_reply_address'], $lang['subject_noreply']);
		$mail->Subject = $lang['subject_email_message'];
		
		// create URL
		$url = "http://" . $_SERVER['HTTP_HOST'];
		$url .= dirname ($_SERVER['PHP_SELF']);
		// sometimes the server adds \ as the last character - we need to check.
		if (substr($url, -1, 1) != "/") {
			$url .= "/";
		}
		$url .= "index.php?amn=core_msg_view";
			
		if (!empty($_POST['to_identity_id'])) { // we send to a single user
		
			$query = "
				SELECT i.user_id
				FROM " . $db->prefix . "_user_identity i
				WHERE i.identity_id=" . $_POST['to_identity_id']
			;
			
			$result = $db->Execute($query);
			
			if (isset($result->fields)) {
				$user_id = $result->fields['user_id'];
				$result->Close();
			
				// do they want an email notification?
	 			if ($user->selUserPreference($user_id, $core_config['user']['preference']['email_message'])) {
					$output_to_user = $user->selUser($user_id);
					$output_from_user = $user->selUserIdentity($_SESSION['user_id']);
					
					// create mail content
					$body_mail_txt = readTxtFile($language_path . "texts/email_message_notify.txt.php");
					$body_mail_txt = str_replace("SYS_KEYWORD_NAME", $output_to_user['user_firstname'], $body_mail_txt);
					$body_mail_txt = str_replace("SYS_KEYWORD_MESSAGE", $_POST['message_subject'] . "\n\n" . $_POST['message_body'], $body_mail_txt);
					$body_mail_txt = str_replace("SYS_KEYWORD_URL", $url, $body_mail_txt);
					$body_mail_txt = str_replace("SYS_KEYWORD_FROM", $output_from_user['identity_nic'], $body_mail_txt);
					$body_mail_txt = stripslashes($body_mail_txt);
					
					require_once('components/core/class/Kses/kses.php');
		
					$body_mail_txt = kses_parse($body_mail_txt, 'max');
					$body_mail_txt = nl2br($body_mail_txt);
					
					// HTML-version of the mail
					$html  = "<HTML><HEAD><TITLE></TITLE></HEAD>";
					$html .= "<BODY>";
					$html .= utf8_decode($body_mail_txt);
					$html .= "</BODY></HTML>";
					
					$mail->Body = $html;
					// non - HTML-version of the email
					$mail->AltBody   = utf8_decode($body_mail_txt);
					
					$mail->ClearAddresses();
					$mail->AddAddress($output_to_user['user_email'], '');
					
					if($mail->Send()) {
						// sent
					}
					
				}
				$im->sendMessage($_POST);
			}
			
			header("Location: index.php?amn=core_msg_list&box=2&" . strip_tags(SID));
			exit;
			
		}
		elseif (!empty($_POST['to_identity_ids'])) {
			// we send to multiple users
			foreach ($_POST['to_identity_ids'] as $key => $i):
			
			$query = "
				SELECT i.user_id
				FROM " . $db->prefix . "_user_identity i
				WHERE i.identity_id=" . $i
			;
			
			$result = $db->Execute($query);
			$user_id = $result->fields['user_id'];
			$result->Close();
			
				if ($user->selUserPreference($user_id, $core_config['user']['preference']['email_message'])) {
					// get users information
 					$output_to_user = $user->selUser($user_id);
					$output_from_user = $user->selUserIdentity($_SESSION['user_id']);
					
					// create mail content
					$body_mail_txt = readTxtFile($language_path . "texts/email_message_notify.txt.php");
					$body_mail_txt = str_replace("SYS_KEYWORD_NAME", $output_to_user['user_firstname'], $body_mail_txt);
					$body_mail_txt = str_replace("SYS_KEYWORD_MESSAGE", $_POST['message_subject'] . "\n\n" . $_POST['message_body'], $body_mail_txt);
					$body_mail_txt = str_replace("SYS_KEYWORD_FROM", $output_from_user['identity_nic'], $body_mail_txt);
					$body_mail_txt = str_replace("SYS_KEYWORD_URL", $url, $body_mail_txt);
					$body_mail_txt = stripslashes($body_mail_txt);
					
					require_once('components/core/class/Kses/kses.php');
		
					$body_mail_txt = kses_parse($body_mail_txt, 'max');
					$body_mail_txt = nl2br($body_mail_txt);
					
					// HTML-version of the mail
					$html  = "<HTML><HEAD><TITLE></TITLE></HEAD>";
					$html .= "<BODY>";
					$html .= utf8_decode($body_mail_txt);
					$html .= "</BODY></HTML>";
					
					$mail->Body = $html;
					// non - HTML-version of the email
					$mail->AltBody = utf8_decode($body_mail_txt);
					
					$mail->ClearAddresses();
					$mail->AddAddress($output_to_user['user_email'], '');
					
					if($mail->Send()) {
						// sent
					}
				}
				
 				$_POST['to_identity_id'] = $i; 
				$im->sendMessage($_POST);
			endforeach;
			
			header("Location: index.php?amn=core_msg_list&box=2&" . strip_tags(SID));
			exit;
		}
	}
	
}
elseif (isset($_REQUEST['reply'])) {
	$output_message = $im->selMessage($_REQUEST['message_id']);
	
	$query = "
		SELECT i.user_id
		FROM " . $db->prefix . "_user_identity i
		WHERE i.identity_id=" . $output_message['from_identity_id']
	;
	
	$result = $db->Execute($query);
	$user_id = $result->fields['user_id'];
	$result->Close();
	
	$query = "
		SELECT 1
		FROM " . $db->prefix . "_user_blocked b
		WHERE b.user_id=" . $user_id . " AND b.user_id_blocked=" . $_SESSION['user_id'];
	;

	$result = $db->Execute($query);
	
	$blocked = isset($result->fields['1']);
	$result->Close();
	
	if (!isset($output_message['from_identity_id']) || $output_message['from_identity_id'] < 1) {
		// a system message - no reply
		header("Location: index.php?amn=core_msg_list&" . strip_tags(SID));
		exit;
	}
	elseif (!$blocked) {// Checks if that user has blocked me
		$allow_compose = 1;
		
		// get their identity
		unset($user->identity_type);
		$output_identity = $user->selUserIdentity(null, $output_message['from_identity_id']);
		
		$body->set("identity", $output_identity);
		
		// insert previous message into replay
		$output_message["message_subject"] = $lang['message']['reply']['re'] . ": ".$output_message["message_subject"];
		
		$output_message["message_body"] = $lang['message']['reply']['insert'] . $output_message["message_body"];
		$output_message["message_body"] = str_replace("\n", "\n" . $lang['message']['reply']['insert'] , $output_message["message_body"]);
		$output_message["message_body"] = $lang['message']['reply']['greeting'] . " " . $output_identity['identity_nic'] . $lang['message']['reply']['greeting_end'] . "\n\n\n\n" . $output_message["message_body"];
	
		$output_message["message_body"] = stripslashes($output_message['message_body']);
	}
	else {
		header("Location: index.php?amn=core_msg_list&" . strip_tags(SID));
		exit;
	}

}
elseif (isset($_POST['preview_message'])) {
	$output_message['message_subject'] = stripslashes(htmlspecialchars($_POST["message_subject"]));
	$output_message['message_body'] = stripslashes($_POST['message_body']);
	
	require_once('components/core/class/Kses/kses.php');
		
	$output_message['display_message_body'] = kses_parse($_POST['message_body'], 'max');
	$output_message['display_message_body'] = nl2br($output_message['display_message_body']);
	$allow_compose = 1;

}


include_once ('class/Participation.class.php');
$participation = new Participation($db, $core_config);
$participation->relation_portable = 1;


$query = "
	SELECT DISTINCT r.identity_id_relation AS identity_id, r.identity_id_relation, i.identity_nic,
	i.identity_create_datetime, l.location_name
	FROM " . $db->prefix . "_relation r
	INNER JOIN " . $db->prefix . "_user_identity i
	ON r.identity_id_relation=i.identity_id
	INNER JOIN " . $db->prefix . "_user u
	ON r.user_id=u.user_id
	INNER JOIN " . $db->prefix . "_user_location l
	ON u.location_id=l.location_id
	WHERE r.user_id=" . $_SESSION['user_id'] . " AND 
	i.identity_allow_msg=1"
;

$result = $db->Execute($query);
$output_identities = array();
while(!$result->EOF) {
	array_push($output_identities, $result->fields);
	$result->moveNext();
}
$result->Close();

foreach($output_identities as $key => $i) {
	$tag->item_id = $i['identity_id_relation'];
	$output_identities[$key]['tags'] = $tag->selTags();
}

$allow_compose = 1;
$body->set('identities', $output_identities);


if (isset($allow_compose)) {
	$body->set('allow_compose', 1);
	
	$images = $file->selFiles("images", "t2");
	$body->set("images", $images);
	
	if (!isset($output_message)) {
		$output_message['message_subject'] = "";
		$output_message['message_body'] = "";
		$output_message["message_body_display"] = "";
		$output_message['message_priority'] = $core_config['messaging']['priority']['normal'];
		$output_message['message_response_type'] = $core_config['messaging']['response']['reply_request'];
	}
	
	if (isset($_REQUEST['message_priority'])) {
		$output_message['message_priority'] = $_REQUEST['message_priority'];
	}
	
	if (isset($_REQUEST['message_response'])) {
		$output_message['message_response'] = $_REQUEST['message_response'];
	}
	
	$body->set('message', $output_message);
}


if (isset($_REQUEST['to_identity_id']) && !empty($_REQUEST['to_identity_id'])) {
	$identity = $user->selUserIdentity(null, $_REQUEST['to_identity_id']);
	if (!empty($identity)) {
		$body->set('identity', $identity);
	}
}

if (!empty($output_tags)) {
	$body->set('tags', $output_tags);
}

if (isset($_REQUEST['tag'])) {
	$body->set('tag', $_REQUEST['tag']);
}

?>