<?php

// -----------------------------------------------------------------------
// This file is part of AROUNDMe
// 
// 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 either get a user_id or reply passed to the page or we list our relations.
// if we get a reply we check that the original message exists and if so we 
// allow send. 
// If we get a user_id and the user allows us to send to them we allow send
// else we list relations
// if no relatons we error and display error
// -----------------------------------------------------------------------
// 
// we either get a user_id (if we are sending to a user or if we are 
// replying. If we do not get this we display our relations list. If we 
// have no relations we cannot send a message.
// -----------------------------------------------------------------------

$menu_section = "my";
include "inc/header.inc.php";

if (!isset($me['user_id']) || $me['user_id'] < 1) {
	header("Location: index.php?" . strip_tags(SID));
	exit;
}

// SETUP LANGUAGE --------------------------------------------------------
require_once($languagePath . 'common.lang.php');
require_once($languagePath . 'msg_view.lang.php');
require_once($languageArrayPath . 'arr_user.lang.php');
require_once($languageArrayPath . 'arr_message.lang.php');


// setup Wiki
require_once('class/Wiki/Wiki.php');
$wiki = new Text_Wiki();
$wiki->disableRule('freelink');
$wiki->disableRule('wikilink');
$wiki->setRenderConf('xhtml', 'image', 'base', $c_node['dir']['asset_path']);


// SETUP RELATIONS
require_once('class/SocialNetwork.class.php');
$sn = new Socialnetwork($me['user_id'], $db, $c_node['sn']['max_degree']);
$sn->relation_type_ids = $c_node['user']['relation_type'];
$sn->status_ids = $c_node['user']['status'];


// SETUP TAGS
require_once('class/Tag.class.php');
$tag = new Tag($db, $c_node['rsp']['item_type']['network']);
$tag->user_id = $me['user_id'];
$output_my_tags = $tag->selTags();


// Handling the message choices
if (isset($_POST['send_message'])) {
	$message_subject = stripslashes(htmlspecialchars($frmdata['message_subject']));
	
	if (!empty($frmdata['to_user_ids']) || !empty($frmdata['to_user_id'])) {
		
		// setup mail
		require_once('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->AddReplyTo	($c_node['mail']['no_reply_address'], $lang['subject_noreply']);
		$mail->FromName = 	$c_node['mail']['from_name'];
		$mail->WordWrap = 	$c_node['mail']['wordwrap'];
		$mail->Subject = 	$lang['subject_email_message'];
		
		$mail->Priority = 			3;
		$mail->Encoding = 			"8bit";
		$mail->CharSet = 			"iso-8859-1";
		$mail->SMTPKeepAlive =      true;
		$mail->IsHTML(true);
	
		// create URL
		$url = "http://" . $_SERVER['HTTP_HOST'];
		$url .= dirname ($_SERVER['PHP_SELF']);
		// sometimes the server adds \ as the last characture - we need to check.
		if (substr($url, -1, 1) != "/") {
			$url .= "/";
		}
		$url .= "msg_view.php";
		
		if (!empty($frmdata['to_user_id'])) {
			// we send to a single user
			if ($user->selUserPreference($frmdata['to_user_id'], $c_node['user']['preference']['email_message'])) {
				
				// get users information
				$output_to_user = $user->getUser($frmdata['to_user_id']);
				$output_from_profile = $user->selProfile(null, $me['user_id']);
				
				// create mail content
				$body_mail_txt = readTxtFile($languageTextPath . "mail_email_message.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", $message_subject . "\n\n" . $frmdata['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_profile['profile_nic'], $body_mail_txt);
				$body_mail_txt = stripslashes($body_mail_txt);
				
				$body_mail_txt = $wiki->transform($body_mail_txt, 'Xhtml');
				
				// 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($frmdata['to_user_id'], $message_subject, $frmdata['message_body']);
			
			header("Location: msg_view.php?" . strip_tags(SID));
			exit;
		}
		elseif (!empty($frmdata['to_user_ids'])) {
			// we send to multiple users
			foreach ($frmdata['to_user_ids'] as $key => $i):
			
				if ($user->selUserPreference($i, $c_node['user']['preference']['email_message'])) {
					// get users information
					$output_to_user = $user->getUser($i);
					$output_from_profile = $user->selProfile(null, $me['user_id']);
					
					// create mail content
					$body_mail_txt = readTxtFile($languageTextPath . "mail_email_message.txt.php");
					
					$body_mail_txt = str_replace("NAME", $output_to_user['user_firstname'], $body_mail_txt);
					$body_mail_txt = str_replace("MESSAGE", $message_subject . "\n\n" . $frmdata['message_body'], $body_mail_txt);
					$body_mail_txt = str_replace("FROM", $output_from_profile['profile_nic'], $body_mail_txt);
					$body_mail_txt = str_replace("URL", $url, $body_mail_txt);
					$body_mail_txt = stripslashes($body_mail_txt);
					
					$body_mail_txt = $wiki->transform($body_mail_txt, 'Xhtml');
					
					// 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($i, $message_subject, $frmdata['message_body']);
			endforeach;
			
			header("Location: msg_view.php?" . strip_tags(SID));
			exit;
		}
	}
	else { // error - no to user id checkboxes checked
		$GLOBALS['am_error_log'][] = array(47, null, null);
		$output_message["message_subject"] = stripslashes(htmlspecialchars($frmdata["message_subject"]));
		$output_message["message_body"] = stripslashes($frmdata["message_body"]);
		$output_message["message_body_display"] = $output_message["message_body"];
		$display = "compose_allowed";
	}
	
}
elseif (isset($_REQUEST['reply'])) {

	$message = new Message($db, $_REQUEST['message_id']); // create message
	$message->user_id = $me['user_id'];
	$message->setBoxes($c_node['messaging']['message_in_box'], $c_node['messaging']['message_save_box'], $c_node['messaging']['message_out_box']);
	$output_message = $message->getMessage();             // get message
	
	if ($output_message['to_user_id'] == $me['user_id']) {
		// Getting username
		$user->user_id = $output_message['from_user_id'];
		$to_user = $user->selProfile();
		$to_user_id = $output_message['from_user_id'];
		
		// Adding RE (langauge node?)
		$output_message["message_subject"] = $lang['message']['reply']['re'] . ": ".$output_message["message_subject"];
	
		// Changing message_body - add a reply indicator
		if ($lang['message']['reply']['position'] == "right") { // right to left texts
			$output_message["message_body"] = str_replace("\n", $lang['message']['reply']['insert'] . "\n" , $output_message["message_body"]);
			// add name and greeting
			$output_message["message_body"] = $lang['message']['reply']['greeting_end'] . $to_user['profile_nic']  . " " . $lang['message']['reply']['greeting'] . "\n\n\n\n" . $output_message["message_body"];
		}
		else { // left to right texts
			$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'] . " " . $to_user['profile_nic'] . $lang['message']['reply']['greeting_end'] . "\n\n\n\n" . $output_message["message_body"];
		}
		
		$output_message["message_body_display"] = stripslashes($output_message['message_body']);
		
		// Checks if that user have blocked me....
		if ($sn->checkUserBlocked($to_user_id)) {
			$display = "compose_allowed";
		}
	}
}
elseif (isset($_POST['preview_message'])) {
	$output_message['message_subject'] = stripslashes(htmlspecialchars($frmdata["message_subject"]));
	$output_message['message_body'] = stripslashes($frmdata['message_body']);
	$output_message['message_body_display'] = $wiki->transform($frmdata['message_body'], 'Xhtml');
	
	$display = "preview_msg";

}
elseif (isset($_POST['edit_message_again'])) {
	$output_message["message_subject"] = stripslashes($frmdata['message_subject']);
	$output_message["message_body"] = $frmdata["message_body"];
	$output_message["message_body_display"] = $output_message['message_body'];

	$display = "compose_allowed";

}
else {
	$output_message['message_subject'] = "";
	$output_message['message_body'] = "";
	$output_message["message_body_display"] = "";
	
	$display = "compose_allowed";
}


if (!empty($_REQUEST['to_user_id'])) {
	// check to see whether we are allowed to IM this person
	if ($sn->checkUserBlocked($_REQUEST['to_user_id'])) {
		$user->user_id = $_REQUEST['to_user_id'];
	    $to_user = $user->selProfile();
		$to_user_id = $_REQUEST['to_user_id'];
		
		// does this person allow messaging to this profile?
		if ($display == "compose_allowed") {
			unset($display);
			
			if (!empty($to_user['profile_allow_msg'])) {
				$display = "compose_allowed";
			}
		}
	}

}


$user->user_id = $me['user_id'];
$output_friend_ids = $sn->selRelations($me['user_id']);

if (!empty($output_friend_ids)) {
	foreach($output_friend_ids as $key => $i):
		$user->user_ids[] = $i['user_id_relation'];
	endforeach;
	
	unset ($user->file);
	$user->orderby = "p.profile_nic";
	$output_users = $user->selProfiles();
}

// find out if allw me to see their true self
$output_relation_of_users = $sn->selRelations($me['user_id'], 1);

if (!empty($output_users)) {
	foreach($output_users as $key => $i):
		if (!empty($output_relation_of_users)) {
			foreach($output_relation_of_users as $keyr => $r):
				if ($i['user_id'] == $r['user_id']) {
					$output_users[$key]['am_relation_to_them'] = $r;
					unset ($output_relation_of_users[$keyr]);
				}
			endforeach;
		}
		
		if (!empty($_REQUEST['tag'])) {
			$tag->item_id = $i['user_id'];
			$output_users[$key]['tags'] = $tag->selTags();
		}
	endforeach;
}

if (isset($to_user)) {
	// setup file
	$file->noimage = $c_node['file']['image']['thumb'][1]['noimage'];
	$file->thumb = $c_node['file']['image']['thumb'][1]['name'];
	
	
	// setup file
	if (isset($to_user['file_id'])) {
		$file->file_id = $to_user['file_id'];
		$to_user['image'] = $file->getFileRecord();
	}
	if (isset($to_user) && empty($to_user['image'])) {
		$to_user['image']['file_title'] = "";
		$to_user['image']['file'] = $file->noimage;
	}
}

// ----------------------------------------------------------------------------
// Setting statistics
$im->setStatistics();

// Getting statistics
$output_message_statistics = $im->getStatistics();
// ----------------------------------------------------------------------------

// display "no compose" screen if MB is over 100% full
$percentage_used = floor((100/$output_message_statistics['total_size_allowed']) * $output_message_statistics['total_size']);
if (isset($percentage_used) && $percentage_used >= 100) {
    $display = "size_allocation_exceeded";
}


// move to template
if (!empty($output_users)) {
	$body->set('users', $output_users);
}
if (!empty($output_message)) {
	$body->set('message', $output_message);
}

if (!empty($old_subject)) {
	$body->set('old_subject', $old_subject);
}
else {
	$body->set('old_subject', "");
}

if (!empty($old_message)) {
	$body->set('old_message', $old_message);
}
else {
	$body->set('old_message', "");
}

if (!empty($friends)) {
    $body->set('friends', $friends);// List of friends
}

if (!empty($to_user_id)) {
    $body->set('to_user_id', $to_user_id);// to_user_id
}

if (!empty($to_user)) {
    $body->set('to_user', $to_user);// Name of user to_user_id
}

if (isset($display)) {
    $body->set('display', $display);// Name of user to_user_id
}

if (!empty($output_my_tags)) {
	$body->set('my_tags', $output_my_tags);
}

if (!empty($_REQUEST['tag'])) {
	$body->set('tag', $_REQUEST['tag']);
}
$body->set('message_statistics', $output_message_statistics);			// Stats...
$body->set('message_status_read', $c_node['messaging']['message_status_read']);		// Status code: READ
$body->set('message_status_unread', $c_node['messaging']['message_status_unread']);	// Status code: UNREAD

include "inc/footer.inc.php";

?>
