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


class Message {

	var $message_allocation = 0;
	
	// IM --------------------------------------------------------------------
	// the constuctor
	// Tom Calthrop 21st September 2006
	//
	function Message($user_id, $db, $config) {
		$this->user_id = $user_id;
		$this->db = $db;
		$this->config = $config;
		$this->selUserMessageAllocation();
	}//EO Message
	
	
	
	// sendMessage --------------------------------------------------------------------
	// create new message entry in database
	// erik sundelof - 29th Nov 2004
	//
	function sendMessage($msg, $copy_to_out = null) {
		// Creating message for the receiver - box=in_box
		$this->insertMessage($msg['from_identity_id'], $msg['to_identity_id'], $msg, $this->config['box']['in']);
		
		//if the system sends a message the $this->user_id = 0 and we do not place a message in senders box
		
		
		if (isset($copy_to_out)) {
			// Creating message for the sender - box=out_box
			$this->insertMessage($msg['from_identity_id'], $msg['to_identity_id'], $msg, $this->config['box']['out']);
		}
	}//EO sendMessage
	
	
	
	// insertMessage --------------------------------------------------------------------
	// create new message entry in database
	// erik sundelof - 29th Nov 2004
	//
	function insertMessage($from_identity_id, $to_identity_id, $msg, $message_box) {

		$msg['message_subject'] = str_replace("'", "&#39;", $msg['message_subject']);
		
		if (!isset($msg['message_response'])) {
		    $msg['message_response'] = $this->config['response']['no_reply_needed'];
		}
		
		if (!isset($msg['message_priority'])) {
		    $msg['message_priority'] = $this->config['priority']['normal'];
		}
		
		$rec = array();
		$rec['to_identity_id'] = $to_identity_id;
		$rec['from_identity_id'] = $from_identity_id;
		$rec['to_user_id'] = $msg['to_user_id'];
		$rec['message_subject'] = $msg['message_subject'];
		$rec['message_body'] = $msg['message_body'];
		$rec['message_box'] = $message_box;
		$rec['message_create_datetime'] = time();
		$rec['message_status'] = $this->config['status']['unread'];
		$rec['message_response'] = $msg['message_response'];
		$rec['message_priority'] = $msg['message_priority'];

		if (isset($_SESSION['user_id'])) {
			$rec['owner_user_id'] = $_SESSION['user_id'];
		}
		
		$table = $this->db->prefix . "_user_message";
		
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		if (empty($result)) {
			$error_info = "function=insertMessage class=Message.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO insertMessage

	
	
	// messageCount --------------------------------------------------------------------
	//tom calthrop - 21st Feb 2004
	function messageCount($message_box = null, $user_type = null, $status = null) {
		if (!isset($user_type)) {
			$user_type = "owner_user_id";
		}
		
		if (!isset($message_box)) {
			$message_box = $this->config['box']['in'];
		}
		
		$ids = '';
		$identitites = User::selUserIdentities($this->user_id);

		for($i = 0; $i < count($identitites); $i++) {
			$ids .= $identitites[$i]['identity_id'];
			if ($i != count($identitites) - 1) {
				$ids .= ', ';
			}
		}
		
		$query = "
			SELECT message_id as total, message_body
			FROM " . $this->db->prefix . "_user_message
			WHERE
			message_box= " . $message_box . " AND 
			" . $user_type. " IN (" . $ids . ") AND "
		;
		
		if (isset($status)) {
			$query .= "message_status=" . $status . " AND ";
		}
		
		$query .= "1=1";
	
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
			$msg_count = 0;
			$msg_size = 0;

			while (!$result->EOF) {
				$msg_count++;
				$msg_size = $msg_size + strlen($result->fields['message_body']);
				
				$result->MoveNext();
			}
			
			$temp = array();
			$temp['total'] = $msg_count;
			$temp['usage'] = $msg_size;
			
			return $temp;
		}
		else {
			$error_info = "function=messageCount class=Message.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO messageCount
	
	
	
	// selMessages --------------------------------------------------------------------
	// Get the message list from the message box of interest
	// erik sundelof - 29th Nov 2004
	//
	function selMessages() {
		$query = "
			SELECT 
			m.message_id, m.message_priority, m.message_response, m.to_identity_id, 
			m.from_identity_id, m.message_status, m.message_subject, m.message_body, 
			m.message_create_datetime, m.owner_user_id 
			FROM 
			" . $this->db->prefix . "_user_message m 
			WHERE 
			m.message_box = " . $this->box . " AND "
		;
		
		$identitites = User::selUserIdentities($this->user_id);
		$ids = '';

		for($i = 0; $i < count($identitites); $i++) {
			$ids .= $identitites[$i]['identity_id'];
			if ($i != count($identitites) - 1) {
				$ids .= ', ';
			}
		}

		// Selection of messages is differs for different boxes...
		if ($this->box == $this->config['box']['out']) {
			$query .= "m.from_identity_id IN (" . $ids . ") AND ";
		}
		else { // in box
			$query .= "m.to_identity_id IN (" . $ids . ") AND ";
		}
		
		$query .= "
			1=1 
			ORDER BY 
			m.message_create_datetime DESC"
		;
		
		$result = $this->db->Execute($query);

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

			$temp = array();

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

				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=selMessages class=Message.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selMessages
	
	
	
	// selMessage --------------------------------------------------------------------
	// Return a single message
	// tom calthrop - 22nd September 2006
	//
	function selMessage($message_id) {
		$query = "
			SELECT 
			m.message_id, m.message_priority, m.message_response, m.to_identity_id, 
			m.from_identity_id, m.message_status, m.message_subject, m.message_body, 
			m.message_create_datetime, m.owner_user_id, m.to_user_id
			FROM 
			" . $this->db->prefix . "_user_message m 
			WHERE 
			m.message_id = " . $message_id
		;
		
		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = $result->fields;
			$result->MoveNext();

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=selMessage class=Message.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selMessage
	
	
	// deleteMessages --------------------------------------------------------------------
	// Deletes messages
	// 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('db_error', $error_info);
			}
		}
	}//EO deleteMessages
	
	
	
	// setMessagesStatus --------------------------------------------------------------------
	// set the status of the messages to unread
	// erik sundelof - 29th Nov 2004
	function setMessagesStatus($message_arr, $status) {
		$rownums = count ($message_arr);
		for ($i=0; $i < $rownums; $i++) {
			$query = "
				SELECT * FROM " . $this->db->prefix . "_user_message 
				WHERE 
				message_id=". $message_arr[$i]
			;
		
			$result = $this->db->Execute($query);
		
			$rec = array();
			$rec['message_status'] = $status;
		
			$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
		}
	}//EO setMessagesStatus
	
	
	
	// 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 = "
				SELECT * FROM " . $this->db->prefix . "_user_message 
				WHERE 
				message_id=" . $move_arr[$i]
			;
			
			$result = $this->db->Execute($query);

			$rec = array();
			$rec['message_box'] = $this->config['box']['save'];
			
			$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
		}
	}//EO moveToSavebox
	
	
	
	// selUserMessageAllocation --------------------------------------------------------------------
	// select the messaging allocation from the allocation table
	// tom calthrop - 30th Nov 2006
	function selUserMessageAllocation() {
		$query = "
			SELECT file_allocation 
			FROM " . $this->db->prefix . "_file_allocation 
			WHERE 
			item_id=". $this->user_id . " AND 
			item_type=". $this->config['file']['allocation']['type']['message'] . " AND 
			module_id=0"
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
			$this->message_allocation = $result->fields['file_allocation'];
		}
		else {
			$this->message_allocation = 0;
		}
	}//EO selUserMessageAllocation
	
	
	

}
?>