<?php

// -----------------------------------------------------------------------
// This file is part of aroundme
// 
// 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., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
// -----------------------------------------------------------------------


// Include the Message class so that the message functionality is obtained
include "Message.class.php";

class IM {
	// CLASS FUNCTIONS
	// IM
	// setStatus
	// getStatus
	// setBoxes
	// setStatistics
	// getStatistics
	// getMessageBox
	// deleteMessages
	// moveToSavebox
	// setMessagesStatus
	// newMessage
	// sendMessage
	// messageCount
	
	
	
	// Instance variables
	var $user_id;                        // User id
	var $db;                              // get db connect
	var $max_size;                        // max size
	var $output_message_statistics;       // allocate statitical variable
	var $status;                          // holding the message status coding
	var $boxes;                           // holding the coding of the boxes
	
	
	
	// IM --------------------------------------------------------------------
	// the constuctor
	// erik sundelof - 29th Nov 2004
	//
	function IM($user_id, $db, $max_size) {
		$this->user_id = $user_id;
		$this->db = $db;
		$this->max_size = $max_size;
	}//EO IM
	
	
	
	// setStatus --------------------------------------------------------------------
	// Set message status coding
	// erik sundelof - 29th Nov 2004
	//
	function setStatus($unread, $read)  {
		$this->status["unread"] = $unread;
		$this->status["read"]   = $read;
	}//EO setStatus
	
	
	
	// getStatus --------------------------------------------------------------------
	// Getting the status for read/unread
	// erik sundelof - 29th Nov 2004
	//
	function getStatus($type) {
		return $this->status[$type];
	}//EO getStatus
	
	
	
	// setBoxes --------------------------------------------------------------------
	// Set message box coding
	// erik sundelof - 29th Nov 2004
	//
	function setBoxes($inbox, $savebox, $outbox) {
		$this->boxes["in_box"]     = $inbox;
		$this->boxes["save_box"]   = $savebox;
		$this->boxes["out_box"]    = $outbox;
	}//EO setBoxes
	
	
	
	// setStatistics --------------------------------------------------------------------
	// Setting message statistics
	// erik sundelof - 29th Nov 2004
	//
	function setStatistics() {
		// Setting the statistics
		$query = "
			SELECT m.message_body, m.message_box, m.message_status
			FROM " . $this->db->prefix . "_user_message m
			LEFT JOIN " . $this->db->prefix . "_user u on m.owner_user_id=u.user_id
			WHERE
			(m.message_box = " . $this->boxes["in_box"] . " and m.to_user_id =" . $this->user_id . ") or
			(m.message_box = " . $this->boxes["save_box"] . " and m.to_user_id =" . $this->user_id . ") or
			(m.message_box = " . $this->boxes["out_box"] . " and m.from_user_id =" . $this->user_id . ")"
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$total_size = 0;
			$total_in_box_size = 0;
			$in_box_messages = 0;
			$total_save_box_size = 0;
			$save_box_messages = 0;
			$total_out_box_size = 0;
			$out_box_messages = 0;
			$total_messages = 0;
			$unread_messages = 0;

			while (!$result->EOF) {

				if ($result->fields['message_box'] == $this->boxes["in_box"]) {
					$total_in_box_size = $total_in_box_size + strlen($result->fields['message_body']);
					$in_box_messages++;
					if ($result->fields['message_status'] == $this->getStatus("unread")) {
						$unread_messages++;
					}
				}
				else if ($result->fields['message_box'] == $this->boxes["save_box"]) {
					$total_save_box_size = $total_save_box_size + strlen($result->fields['message_body']);
					$save_box_messages++;
				}
				else if ($result->fields['message_box'] == $this->boxes["out_box"]) {
					$total_out_box_size = $total_out_box_size + strlen($result->fields['message_body']);
					$out_box_messages++;
				}
				$total_messages++;
				$result->MoveNext();
			}

			$total_size = $total_in_box_size + $total_save_box_size + $total_out_box_size;

			$result->Close();

			$this->output_message_statistics =
				array(
					'total_size'=> 				$total_size,
					'total_messages'=> 			$total_messages,
					'total_size_allowed'=> 		$this->max_size,
					'in_box_size'=> 			$total_in_box_size,
					'in_box_messages'=> 		$in_box_messages,
					'out_box_size'=> 			$total_out_box_size,
					'out_box_messages'=> 		$out_box_messages,
					'save_box_size'=> 			$total_save_box_size,
					'save_box_messages'=> 		$save_box_messages,
					'unread'=> 					$unread_messages
				);
		}
		else {
			$error_info = "function=setStatistics class=IM.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO setStatistics
	
	
	
	// getStatistics --------------------------------------------------------------------
	// obtaining the output statistics
	// erik sundelof - 29th Nov 2004
	//
	function getStatistics() {
		return $this->output_message_statistics;
	}//EO getStatistics
	
	
	
	// getMessageBox --------------------------------------------------------------------
	// Get the message list from the message box of interest
	// erik sundelof - 29th Nov 2004
	//
	function getMessageBox($message_box)
	{
		// Selection of messages is differs for different boxes...
		if ($message_box == "out_box") {
			$selection = " and m.from_user_id =" . $this->user_id;
			$join = "m.to_user_id=p.user_id";
		}
		else if ($message_box == "save_box") {
			$selection = " and (m.to_user_id =" . $this->user_id ." or m.from_user_id =" . $this->user_id . ")";
			$join = "m.owner_user_id=p.user_id";

		}
		else if ($message_box == "in_box") {
			$selection = " and m.to_user_id =" . $this->user_id;
			$join = "m.from_user_id=p.user_id";
		}

		// Forming query and selecting the messages with the correct owner id:s...
		// The \" m.to_user_id, m.owner_user_id, m.from_user_id \" are there so that one can track
		// everything about the users linked to that particular message outside the class.

		$query = "
			SELECT p.profile_nic, m.message_id,
			m.owner_user_id, m.to_user_id, m.from_user_id,
			m.message_status, m.message_subject, m.message_body, m.message_create_datetime
			FROM " . $this->db->prefix . "_user_message m
			LEFT JOIN " . $this->db->prefix . "_user_profile p on ". $join ." and p.profile_default=1  
			WHERE 
			m.message_box = " . $this->boxes[$message_box] . $selection . " ORDER BY  m.message_create_datetime DESC";
		;
		
		// Getting the message_box list
		$result = $this->db->Execute($query);

		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				array_push($temp, $result->fields);

				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=getMessageBox class=IM.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getMessageBox
	
	
	
	// deleteMessages --------------------------------------------------------------------
	// Delete message
	// erik sundelof - 29th Nov 2004
	//
	function deleteMessages($del_arr) {
		$rownums = count ($del_arr);

		for ($i=0; $i < $rownums; $i++) {
			$query = "
				DELETE from " . $this->db->prefix . "_user_message
				WHERE
				message_id = " . $del_arr[$i]
				;

			$result = $this->db->Execute($query);

			if (empty($result)) {
				$error_info = "function=deleteMessages class=IM.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
				$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
			}
		}
	}//EO deleteMessages
	
	
	
	// moveToSavebox --------------------------------------------------------------------
	// move message to save_box, send in the save_box to
	// ensure that the index is correct
	// erik sundelof - 29th Nov 2004
	function moveToSavebox($move_arr) {
		$rownums = count ($move_arr);

		for ($i=0; $i < $rownums; $i++) {
			$query = "
				UPDATE " . $this->db->prefix . "_user_message SET message_box=" . $this->boxes["save_box"] . "
				WHERE
				message_id=" . $move_arr[$i]
				;

			$result = $this->db->Execute($query);

			if (empty($result)) {
				$error_info = "function=moveToSavebox class=IM.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
				$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
			}
		}
	}//EO moveToSavebox
	
	
	
	// setMessagesStatus --------------------------------------------------------------------
	// set the status of the messages to unread
	// erik sundelof - 29th Nov 2004
	function setMessagesStatus($message_arr, $status) {
		$rownums = count ($message_arr);             // Counting messages
		$message = new Message($this->db);           // create tmp message object

		for ($i=0; $i < $rownums; $i++) {
			$message->setMessageId($message_arr[$i]); // Assign id
			$message->setStatus($status);             // Assign status
		}
	}//EO setMessagesStatus
	
	
	
	// newMessage --------------------------------------------------------------------
	// create new message entry in database
	// erik sundelof - 29th Nov 2004
	function newMessage($owner_user_id, $to_user_id, $message_subject, $message_body, $message_box, $message_type = null) {
		
		$message_body = str_replace("'", "&#39;", $message_body);
		$message_subject = str_replace("'", "&#39;", $message_subject);
		/*
		* message types:
		* added by Tom Calthrop
		* Message type 1 = will display the "add new friend" button in the msg_item.php template
		* Message type 2 = you've been joined message - will rebuild your social network session
		*/
		if (!isset($message_type)) {
		    $message_type = "null";
		}

		$message_status = $this->getStatus("unread");

		// save user into br_user
		$query = "INSERT INTO " . $this->db->prefix . "_user_message SET
			owner_user_id='$owner_user_id', to_user_id='$to_user_id', from_user_id='$this->user_id',
			message_subject='$message_subject', message_body='$message_body', message_box='$message_box',
			message_create_datetime=NOW(), message_status='$message_status', message_type=$message_type";

		$result = $this->db->Execute($query);

		if (empty($result)) {
			$error_info = "function=newMessage class=IM.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO newMessage
	
	
	
	// sendMessage --------------------------------------------------------------------
	// create new message entry in database
	// erik sundelof - 29th Nov 2004
	function sendMessage($to_user_id, $message_subject, $message_body, $message_type = null) {
		
		//if the system sends a message the $this->user_id = 0 and we do not place a message in senders box
		if (isset($this->user_id) && $this->user_id >0) {
			// Creating message for the sender - box=out_box
			$this->newMessage($this->user_id, $to_user_id, $message_subject, $message_body, $this->boxes["out_box"]);
		}
		
		// Creating message for the receiver - box=in_box
		if (isset($message_type)) {
		    $this->newMessage($to_user_id, $to_user_id, $message_subject, $message_body, $this->boxes["in_box"], $message_type);
		}
		else {
			$this->newMessage($to_user_id, $to_user_id, $message_subject, $message_body, $this->boxes["in_box"]);
		}
	}//EO sendMessage

	
	
	// messageCount --------------------------------------------------------------------
	//tom calthrop - 21st Feb 2004
	function messageCount() {
		$query = "
			SELECT count(message_id) as total_unread
			FROM " . $this->db->prefix . "_user_message
			WHERE
			message_box = " . $this->boxes['in_box'] . " and
			message_status = " . $this->status['unread'] . " and
			to_user_id =" . $this->user_id
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
			return $result->fields['total_unread'];
		}
		else {
			$error_info = "function=messageCount class=IM.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO messageCount
}

?>