<?php
// +---------------------------------------------------------------------------------------+
// | TenderSystem                                                                          |
// +---------------------------------------------------------------------------------------+
// | The contents of this file are subject to the TenderSystem Public License Version 1.1  |
// | ("License"); you may not use this file except in compliance with the License. You may |
// | obtain a copy of the License at http://www.tendersystem.com/tpl/                      |
// |                                                                                       |
// | Software distributed under the License is distributed on an "AS IS" basis, WITHOUT    |
// | WARRANTY OF ANY KIND, either express or implied. See the License for the specific     |
// | language governing rights and limitations under the License.                          |
// |                                                                                       |
// | All copies of the Covered Code must include the "Powered by TenderSystem" logo and    |
// | ValueCard copyright notice on every user interface screen and in every outgoing       |
// | email in the same form as they appear in the distribution.                            |
// |                                                                                       |
// | The Original Code is: TenderSystem                                                    |
// | The Initial Developer of the Original Code is ValueCard (Pty) Limited.                |
// | Portions created by ValueCard are Copyright (C) 2002 ValueCard (Pty) Limited.         |
// | All Rights Reserved.                                                                  |
// | Contributor(s): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* Message class
* @package TenderSystem
* @subpackage generic
* @copyright Copyright &copy; 2002, ValueCard (Pty) Ltd
* @license http://www.tendersystem.com/tpl/ TenderSystem Public License
* @version 
*/

// Security - ensure that file never called directly
// not required if global variables are off or API is hosted on a non-public server
if (eregi(basename(__FILE__),$_SERVER['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

Class message {
	// class paramaters
	var $message;
	var $response;
	var $users;
	var $creatorid;
	var $error;
	var $error_text;
	var $sessionid;
	
	/**
	 * send a email message
	 * 
	 * @param array message Email message information
	 * @param integer usersid The Users ID
	 * @param integer usersid The Creators ID
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param array Control Panel information  
	 */
	function send_email_message($message,$usersid,$creatorid,$cfg,$conn) {
		// remove old message info
		unset($this->message);
		$this->message = $message;
		$this->creatorid = $creatorid;
		if($this->creatorid === "0") {
			$this->creatorid = "NULL";
		}
		$this->usersid = $usersid;
		if($this->usersid === "0") {
			$this->usersid = "1";
		}
		// Check if main parameters exist 
		if (!$this->message['subject']){
			// 1068 - missing Email subject
			$this->error[] = "1068";
		}
		if (!$this->message['body']){
			// 1069 - missing Email body
			$this->error[] = "1069";
		}
		if (!$this->message['name']) {
			// 1070 - Missing email recipient name
			$this->error[] = "1070";
		}
		if (!$this->message['email']) {
			// 1071 - Missing recipient email address
			$this->error[] = "1071";
		}
		if (!$this->message['classification']) {
			// 1072 - Missing email classification
			$this->error[] = "1072";
		}
		// errors 
		if (!empty($this->error)) {
			// Error in Message Class
			require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
			foreach($this->error as $value) {
				$error_text[] = $lang[$value]." ";
			}
			// instantiate the error class and log
			$new_error = new error;
			// set the error text
			$new_error->log("Message","serious",$error_text,$cfg);
			// response
			return FALSE;
		}
		$new_users = new user;
		$userinfo = $new_users->get_info($this->usersid,$cfg,$conn);
		if($userinfo['emailimages'] == 'B') {
			$this->message['body'] = $this->add_alt($this->message['body'],0,$cfg);
		} elseif($userinfo['emailimages'] == 'W') {
			$this->message['body'] = $this->strip_images($this->message['body'],$cfg);
		}		
		$this->message['body'] = $this->parse_email_body($userinfo['theme'],$cfg);
		$this->message['send_method'] = "email";
		return $this->schedule_message($cfg,$conn);
	}
	
	function strip_images($body,&$cfg) {
		$start_img = strpos($body,"<img");
		$end_img = strpos($body,"/img>",$start_img+1);
		$end_len = 5;
		if(!$end_img) {
			$end_img = strpos($body,"/>",$start_img+1);
			$end_len = 2;
		}
		$start_alt = strpos($body,'alt="',$start_img+1);
		$end_alt = strpos($body,'"',$start_alt+5);
		if(!$start_img || !$end_img) { // no images
			return $body;
		} elseif(!$start_alt || $start_alt >= $end_img) { // no alt
			$new_body = substr($body,0,$start_img).substr($body,$end_img+$end_len);
			return $this->strip_images($new_body,$cfg);
		} elseif(!$end_alt || !$end_alt >= $end_img) { // no proper alt
			$new_body = substr($body,0,$start_img).substr($body,$end_img+$end_len);
			return $this->strip_images($new_body,$cfg);
		} else { // replace img with alt
			$text_alt = substr($body,$start_alt+5,$end_alt - ($start_alt+5));
			$new_body = substr($body,0,$start_img).$text_alt.substr($body,$end_img+$end_len);
			return $this->strip_images($new_body,$cfg);
		}
	}
	
	function add_alt($body,$start,&$cfg) {
		$start_img = strpos($body,"<img",$start+1);
		$end_img = strpos($body,"/img>",$start_img+1);
		$end_len = 5;
		if(!$end_img) {
			$end_img = strpos($body,"/>",$start_img+1);
			$end_len = 2;
		}
		$start_alt = strpos($body,'alt="',$start_img+1);
		$end_alt = strpos($body,'"',$start_alt+5);
		if(!$start_img || !$end_img) { // no images
			return $body;
		} elseif(!$start_alt || $start_alt >= $end_img) { // no alt
			return $body;
		} elseif(!$end_alt || !$end_alt >= $end_img) { // no proper alt
			return $body;
		} else { // replace img with alt
			$text_alt = substr($body,$start_alt+5,$end_alt - ($start_alt+5));
			$img = substr($body,$start_img,$end_img +  $end_len - $start_img);
			$new_body = substr($body,0,$start_img).$text_alt." ".$img.substr($body,$end_img+$end_len);
			return $this->add_alt($new_body,$end_img+$end_len,$cfg);
		}
	}
	
	
	function send_schedule_messages($cfg,$conn) {
		$time_stamp = ts_time($cfg) - $cfg['message']['schedule']['time'];
		// determine if present
		$sqlstr = "SELECT * ";
		$sqlstr.= "FROM ~message_schedule ";
		$sqlstr.= "WHERE status = '1' ";
		$sqlstr.= "AND attempts < ".$cfg['message']['schedule']['attempts']." ";
		$sqlstr.= "AND (attempt_date IS NULL ";
		$sqlstr.= "OR attempt_date < '".date("Y-m-d",$time_stamp)."' ";
		$sqlstr.= "OR ( attempt_date = '".date("Y-m-d",$time_stamp)."' ";
		$sqlstr.= "AND attempt_time < '".date("H:i:s",$time_stamp)."')) ";
		$sqlstr.= "ORDER BY id ASC ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		// execute the query
 		$all = $conn->GetAll($sqlstr);
       	if ($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// 1065 - Error occurred while querying the Database
			$this->error[] = "1065";
			// response
			return FALSE;
       	}
       	// go through each message
       	foreach($all as $key => $value) {
   			// attempts
			$update['attempts'] = $value['attempts'] + 1;
			$update['status'] = "1";
			// insert attempted time
			$new_database->setTime("attempt",$update,"",$cfg);
			if($value['send_method'] == "email") {
				if($this->send_email($value,$cfg,$conn)) {
					// sent successfully
					$update['status'] = "2";
				}
			} elseif($value['send_method'] == "sms") {
				if($this->send_sms($value,$cfg,$conn)) {
					// get cost
					$new_user = new user;
					$update['cost'] = $new_user->get_sms_cost($value['user_id'],$cfg,$conn) + $value['cost'];
					// sent successfully
					$update['status'] = "2";
				}
			} else {
				// instantiate the error class and log
				$new_error = new error;
				// convert error message
				require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
				// 1073 - Unknown send_method stored
				$error_text[]= $lang['1073']." : ".$value['send_method'];
				// log the error
				$new_error->log("Message","serious",$error_text,$cfg);
				// response
				return 0;
			}
			// check if final attempt
			if($update['attempts'] >= $cfg['message']['schedule']['attempts'] && $update['status'] == "1") {
				$update['status'] = "0";
			}
			$where = "id = ".$value['id'];
			$new_database = new database;
			if(!$new_database->update_table("~message_schedule",$update,$where,$cfg,$conn)) {
				$this->error = array_merge($this->error,$new_database->error);
				require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
				foreach($this->error as $value) {
					$error_text[] = $lang[$value]." ";
				}
				// instantiate the error class and log
				$new_error = new error;
				// 	set the error text
				$new_error->log("Message","serious",$error_text,$cfg);
			} 
			unset($update);
       	}
       	return TRUE;
	}
	
	function create_reply($message,$cfg,$conn) {
		// insert the items in the database
		$new_database = new database;
		$table_name = "~message_schedule";
		$message['id'] = $new_database->get_next_id($table_name,$cfg,$conn);
		$message['cost'] = "0.00";
		$message['user_id'] = "1";
		$message['attempts'] = "0";
		$message['status'] = "2";
		$message['created_by'] = "NULL";
		// insert created time
		$new_database->setTime("created",$message,"",$cfg);
		// do body alone
		$body = $message['body'];
		unset($message['body']);
		$new_database->parse_sql($table_name,$cfg);
		// execute the insert
 		$conn->AutoExecute($table_name,$message,"INSERT");
       	if ($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$this->error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$this->error_text,$cfg);
			// 1064 - Error occurred while inserting into Database
			$this->error[] = "1064";
			// response
			return FALSE;
       	}
       	// add the content (some database the blob must be done separately)
		if($cfg['smtp']['blob']) {
			$where = " id = '".$message['id']."'";
			// execute the update
			$conn->UpdateBlob($table_name,"body",$body,$where);
			if ($conn->ErrorMsg()) {
				// instantiate the error class and log
				$new_error = new error;
				$this->error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
				$new_error->log("SQL","critical",$this->error_text,$cfg);
				// Error occurred while updating into Database
				$this->error[] = "1066";
	       	}
		}
		$this->response = $message;
		// return item id
		return $message['id'];
	}
	
	function schedule_message($cfg,$conn) {
		// insert the items in the database
		$new_database = new database;
		$table_name = "~message_schedule";
		$insert['id'] = $new_database->get_next_id($table_name,$cfg,$conn);
		if($this->message['send_method'] == "email") {
			$insert['subject'] = $this->message['subject'];
			$insert['name'] = $this->message['name'];
			$insert['email'] = $this->message['email'];
			if($this->message['cc']) {
				$insert['emailcc'] = $this->message['cc'];
			}
		} elseif($this->message['send_method'] == "sms") {
			$insert['phone_mobile'] = $this->message['phone_mobile'];
		}
		$insert['classification'] = $this->message['classification'];
		$insert['send_method'] = $this->message['send_method'];
		if($this->message['reference']) {
			$insert['reference'] = $this->message['reference']; 	
		}
		if($this->message['receipt_code']) {
			$insert['receipt_code'] = $this->message['receipt_code']; 	
		}
		if($this->message['receipt_status']) {
			$insert['receipt_status'] = $this->message['receipt_status']; 	
		}
		$insert['cost'] = "0.00";
		$insert['user_id'] = $this->usersid;
		$insert['attempts'] = "0";
		$insert['status'] = "1";
		$insert['created_by'] = $this->creatorid;
		// insert created time
		$new_database->setTime("created",$insert,"",$cfg);
		// do body alone
		if ($cfg['smtp']['blob'] === "security") {
			// attempt to send email
			$insert['attempts']++;
			// insert attempted time
			$new_database->setTime("attempt",$insert,"",$cfg);
			if($this->message['send_method'] == "email" && $this->send_email($this->message,$cfg,$conn)) {
				// sent successfully
				$insert['status'] = "2";
			} elseif($this->message['send_method'] == "sms" && $this->send_sms($this->message,$cfg,$conn)) {
				// get cost
				$new_user = new user;
				$insert['cost'] += $new_user->get_sms_cost($insert['user_id'],$cfg,$conn);
				// sent successfully
				$insert['status'] = "2";
			} else {
				// failed
				$insert['status'] = "0";
			}
			// don't insert body
			$insert['body'] = "1";
		} elseif($cfg['smtp']['blob'] === FALSE) {
			// attempt to send email
			$insert['attempts']++;
			// insert attempted time
			$new_database->setTime("attempt",$insert,"",$cfg);
			if($this->message['send_method'] == "email" && $this->send_email($this->message,$cfg,$conn)) {
				// sent successfully
				$insert['body'] = "2";
				$insert['status'] = "2";
			} elseif($this->message['send_method'] == "sms" && $this->send_sms($this->message,$cfg,$conn)) {
				// get cost
				$new_user = new user;
				$insert['cost'] += $new_user->get_sms_cost($insert['user_id'],$cfg,$conn);
				// sent successfully
				$insert['body'] = "2";
				$insert['status'] = "2";
			} else {
				// schedule message
				$insert['body'] = $this->message['body'];
			}
		} elseif($cfg['message']['schedule']['go']) {
			// attempt to send email
			$insert['attempts']++;
			// insert attempted time
			$new_database->setTime("attempt",$insert,"",$cfg);
			$insert['body'] = $this->message['body'];
			if($this->message['send_method'] == "email" && $this->send_email($this->message,$cfg,$conn)) {
				// sent successfully
				$insert['status'] = "2";
			} elseif($this->message['send_method'] == "sms" && $this->send_sms($this->message,$cfg,$conn)) {
				// get cost
				$new_user = new user;
				$insert['cost'] += $new_user->get_sms_cost($insert['user_id'],$cfg,$conn);
				// sent successfully
				$insert['status'] = "2";
			}
		} elseif($cfg['message']['schedule']['status'] === FALSE) {
			// attempt to send email
			$insert['attempts']++;
			// insert attempted time
			$new_database->setTime("attempt",$insert,"",$cfg);
			$insert['body'] = $this->message['body'];
			if($this->message['send_method'] == "email" && $this->send_email($this->message,$cfg,$conn)) {
				// sent successfully
				$insert['status'] = "2";
			} elseif($this->message['send_method'] == "sms" && $this->send_sms($this->message,$cfg,$conn)) {
				// get cost
				$new_user = new user;
				$insert['cost'] += $new_user->get_sms_cost($insert['user_id'],$cfg,$conn);
				// sent successfully
				$insert['status'] = "2";
			} else {
				// failed
				$insert['status'] = "0";
			}
		} else {
			$insert['body'] = $this->message['body'];
		}
		
		$new_database->parse_sql($table_name,$cfg);
		// execute the insert
 		$conn->AutoExecute($table_name,$insert,"INSERT");
       	if ($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$this->error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$this->error_text,$cfg);
			// Error occurred while inserting into Database
			$this->error[] = "1064";
			// response
			return FALSE;
       	}
       	// add the content (some database the blob must be done separately)
		if($insert['body'] !== "1" && $insert['body'] !== "2") {
			$where = " id = '".$insert['id']."'";
			// execute the update
			$conn->UpdateBlob($table_name,"body",$this->message['body'],$where);
			if ($conn->ErrorMsg()) {
				// instantiate the error class and log
				$new_error = new error;
				$this->error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
				$new_error->log("SQL","critical",$this->error_text,$cfg);
				// Error occurred while updating into Database
				$this->error[] = "1066";
				// response
				return FALSE;
	       	}
		}
		$this->response = $insert;
		// return item id
		return $insert['id'];
	}
	
	function parse_email_body($theme,$cfg) {
		$html = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">";
		$html.= "<html>";
		$html.= "<head>";
		$html.= "<title>".$this->message['subject']."</title>";
		// check theme
		if(file_exists($cfg['file'].'theme/'.$theme.'/style.css')) {
			$style = file_get_contents($cfg['file'].'theme/'.$theme.'/style.css');
		} else {
			$style = file_get_contents($cfg['file'].'theme/'.$cfg['theme'].'/style.css');
		}
		if($style) {
			$html.= "<style>".$style."</style>";
		}
		$html.= "</head>";
		$html.= "<body>";
		// table must be present otherwise email runs of the page
		$html.= "<table width=\"660\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\">";
		$html.= "<tr><td id=\"<!--end-->\"></td></tr>";
		// populate content
		$html.= $this->message['body'];
		$html.= "<br/><br/>";
		// include footer message
		$html.= str_replace("[br]","<br>",$cfg['smtp']['message']);
		$html.= "<br/><br/>";
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//	NOTICE: THIS IMAGE, LINK AND NOTICE MAY NOT BE REMOVED OR ALTERED ACCORDING TO TENDERSYSTEM PUBLIC LICENSE VERSION 1.1
		//	BY NOT DISPLAYING THIS IMAGE OR LINK IN EVERY EMAIL YOU FORFEIT THE RIGHT TO USE THIS PROGRAM 
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$html.= "<a href=\"http://www.tendersystem.com\">";
		if ($cfg['smtp']['receipt']['img']['enable']) {
			$this->message['receipt_code'] = time()."_".mt_rand();
			$this->message['receipt_status'] = "3";
			$image_src = $cfg['url']."main.php?module=generic&function=message_receipt&show_image=yes&receipt_code=".$this->message['receipt_code'];
		} else {
			$image_src = $cfg['url']."img/tendersystem.gif";
		}
		$html.= "<img align=\"top\" src=\"".$image_src."\" border=\"0\" alt=\"Powered&nbsp;by&nbsp;TenderSystem&nbsp;version&nbsp;".$cfg['version']."\"/>";
		$html.= "</a>";
		// insert the SourgeFORGE logo if activated
		if ($cfg['smtp']['sourceforge']) {
			$html.= "&nbsp;&nbsp;";
			$html.= "<a href=\"http://sourceforge.net/projects/tendersystem/\">";
			$html.= "<img align=\"top\" src=\"http://sourceforge.net/sflogo.php?group_id=134537&type=1\" border=\"0\" alt=\"SourceFORGE.net\"/>";
			$html.= "</a>";
		}
		$html.= "<br/><br/>";
		$html.= "<font class=\"footer\">This message was generated by TenderSystem version ".$cfg['version'].". ";
		$html.= "This software is distributed under the <a href=\"http://www.tendersystem.com/tpl/\">TenderSystem Public License</a> on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.</font>";
		//******************************************************************************************
		//* NOTICE
		//******************************************************************************************
		$html.= "</td>";
		$html.= "</tr>";
		$html.= "<tr>";
		$html.= "<td id=\"<!--/end-->\">";
		// Disclaimer
		$html.= "<font class=\"footer\">";
		$html.= str_replace("[br]","<br>",$cfg['smtp']['disclaimer']);
		$html.= "</font>";
		$html.= "</td>";
		$html.= "</tr>";
		$html.= "</table>";
		$html.= "</body>";
		$html.= "</html>";
		// if tidy lib is avialable
		/*if(function_exists("tidy_parse_string") && $cfg['smtp']['tidy']) {
			$config = array('indent' => TRUE,
               				'output-xhtml' => TRUE,
               				'wrap' => 200);
			$tidy = tidy_parse_string($html,$config, 'UTF8');
			$tidy->cleanRepair();
			$html = $tidy->value;
		}*/
		// dont use tabs
		$cfg['smtp']['keyword'][] = "\t";
		// dont use keywords
		return str_replace($cfg['smtp']['keyword']," ",$html);
	}
	
	function send_email($message,$cfg,$conn) {
		// include language
		require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");		
		if(!$cfg['smtp']['status'] || !$cfg['smtp']['server'] || !$cfg['smtp']['port']) {
			// 1074 - Could not send email because SMTP is not activated or configured correctly in settings
			$this->error[] = "1074";
			// convert error message
			foreach($this->error as $value) {
				$error_text[] = $lang[$value]." ";
			}
			// instantiate the error class and log
			$new_error = new error;
			// set the error text
			$new_error->log("Message","critical",$error_text,$cfg);
			// response
			return FALSE;
		}
		// set the recipient info
		$message['recipient'] = "\"".$message['name']."\" <".$message['email'].">";
		$high_priority = FALSE;
		// determine from which email to send the email
		if (strpos($message['classification'],"_return")) {
			$message['sender'] = "\"".$cfg['smtp']['from']."\" <".$cfg['smtp']['tender']['email'].">";
			$message['return_path'] = $cfg['smtp']['tender']['email'];
			// set the priority
			if ($cfg['smtp']['tender']['emailpriority']) {
				$high_priority = TRUE;
			}
		} else {
			$message['sender'] = "\"".$cfg['smtp']['from']."\" <".$cfg['smtp']['support']['email'].">";
			$message['return_path'] = $cfg['smtp']['support']['email'];
			// set the priority
			if ($cfg['smtp']['support']['emailpriority']) {
				$high_priority = TRUE;
			}
		}
		// instantiate mail object
        $new_mail = new htmlMimeMail();
        // set SMTP Params
        $new_mail->setSMTPParams(	$cfg['smtp']['server'],
        							$cfg['smtp']['port'],
        							$cfg['smtp']['helo'],
        							$cfg['smtp']['auth'],
        							$cfg['smtp']['user'],
        							$cfg['smtp']['password']);
        // checf if cfg exists for backward compatibality
        if($cfg['smtp']['encoding']) {
	        // set text encoding
	        $new_mail->setTextEncoding($cfg['smtp']['encoding']);
	        // set html encoding
	        $new_mail->setHTMLEncoding($cfg['smtp']['encoding']);
		} else {
			 // set text encoding
	        $new_mail->setTextEncoding("quoted-printable");
	        // set html encoding
	        $new_mail->setHTMLEncoding("quoted-printable");
		}
        // set text charset
        $new_mail->setTextCharset("UTF-8");
        // set text charset
        $new_mail->setHTMLCharset("UTF-8");
         // set text charset
        $new_mail->setHeadCharset("UTF-8");
		// get the error message
		// Unfortunately the email contains HTML which cannot be displayed by your email client.
		$text = "Unfortunately the email contains HTML which cannot be displayed by your email client.";
		// Add the text and html
		$new_mail->setHtml($message['body'], $text);
		// set the return path
		$new_mail->setReturnPath($message['return_path']);
		// set the headers
		$new_mail->setFrom($message['sender']);
		// if email must be sent to a backup address
		if ($cfg['smtp']['backup']['status']) {
			// set BCC header
			$new_mail->setBcc($cfg['smtp']['backup']['email']);
		}
		if ($message['cc']) {
			// set CC header
			$new_mail->setCc($message['cc']);
		}
		if ($message['emailcc']) {
			// set CC header
			$new_mail->setCc($message['emailcc']);
		}
		if ($this->message['attachment']['body'] && $this->message['attachment']['name'] && $this->message['attachment']['classification']) {
			// set attachment
			$new_mail->addAttachment($this->message['attachment']['body'],$this->message['attachment']['name'],$this->message['attachment']['classification']);
		}
		// set the Subject
		$new_mail->setSubject($message['subject']);
		// set the mail format
		$new_mail->setHeader('X-Mailer', 'HTML Mime mail class');
		// set the importance
		if ($high_priority) {
			$new_mail->setImportance();
		}
		// send it using SMTP
		$result = $new_mail->send(array($message['recipient']), 'smtp');
		// These errors are only set if you're using SMTP to send the message
		if (!$result) {
			// instantiate the error class and log
			$new_error = new error;
			// set the error text
			foreach ($new_mail->errors as $value) {
				$this->error_text.= $value." ";
			}
			$new_error->log("Message","critical",$this->error_text,$cfg);
			// response
			return FALSE;
		} else {
			// response
			return TRUE;
		}
	}
	
	/**
	 * send a sms message
	 * 
	 * @param array message sms message information
	 * @param integer usersid The Users ID
	 * @param integer usersid The Creators ID
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param array Control Panel information  
	 */
	function send_sms_message($message,$usersid,$creatorid,$cfg,$conn) {
		// remove old message info
		unset($this->message);
		$this->message = $message;
		$this->creatorid = $creatorid;
		$this->usersid = $usersid;
		if($this->creatorid === "0") {
			$this->creatorid = "NULL";
		}
		$this->usersid = $usersid;
		if($this->usersid === "0") {
			$this->usersid = "1";
		}
		// Check if main parameters exist 
		if (!$this->message['phone_mobile']){
			// 1075 - Missing phone_mobile
			$this->error[] = "1075";
		} else {
			$this->message['phone_mobile'] = trim($this->message['phone_mobile']);	
		}
		if (!$this->message['body']){
			// 1076 - Missing sms body
			$this->error[] = "1076";
		}
		// errors 
		if (!empty($this->error)) {
			require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
			foreach($this->error as $value) {
				$error_text[] = $lang[$value]." ";
			}
			// instantiate the error class and log
			$new_error = new error;
			// set the error text
			$new_error->log("Message","serious",$error_text,$cfg);
			// response
			return FALSE;
		}
		// determine if prefix present
		if ($this->message['phone_prefix'] && $this->message['phone_mobile'][0] !== "+") {
			// set prefix
			$this->message['phone_mobile'] = $this->message['phone_prefix'].substr($this->message['phone_mobile'],1);
		} elseif($this->message['phone_mobile'][0] !== "+") {
			// set default prefix
			$this->message['phone_mobile'] = $cfg['sms']['code'].substr($this->message['phone_mobile'],1);
		}
		if ($cfg['sms']['receipt']) {
			$this->message['receipt_code'] = time()."_".mt_rand();
			$this->message['receipt_status'] = "1";
		}
		$this->message['send_method'] = "sms";
		return $this->schedule_message($cfg,$conn);
	}
	
	function send_sms($message,$cfg,$conn) {
		if(!$cfg['sms']['status'] || !$cfg['sms']['api_id'] || !$cfg['sms']['user'] || !$cfg['sms']['password'] || !$cfg['sms']['urlsend']) {
			// Could not send SMS because SMS is not activated or configured correctly in settings.
			$this->error[] = "1075";
			// convert error message
			require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
			foreach($this->error as $value) {
				$error_text[] = $lang[$value]." ";
			}
			// instantiate the error class and log
			$new_error = new error;
			// set the error text
			$new_error->log("Message","critical",$error_text,$cfg);
			// response
			return FALSE;
		}
		// set the content size
		$message_size = strlen($message['body']);
		// ensure that & not present in message
		$message['body'] = str_replace("&"," and ",$message['body']);
		// ensure that sms is not longer than 480 characters
		if ($message_size > 480) {
			// truncate message
			$content = substr($message['body'], 0, 476);
			$content.= "...";
			// SMS is more than 3 messages so was truncated to 480 characters. 
			$this->error[] = "1076";
			// convert error message
			require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
			foreach($this->error as $value) {
				$error_text[] = $lang[$value];
			}
			// instantiate the error class and log
			$new_error = new error;
			// set the error text
			$new_error->log("Message","serious",$error_text,$cfg);
			// response
			return FALSE;
		} else {
			// set the message body to content
			$content = $message['body'];
			// determine if Powered by TenderSystem can be included
			if ($message_size < 136) {
				// include Powered by TenderSystem
				$content.= " Powered by TenderSystem.";
			} elseif ($message_size > 160 && 296 > $message_size) {
				// include Powered by TenderSystem
				$content.= " Powered by TenderSystem.";
			} elseif ($message_size > 320 && 456 > $message_size) {
				// include Powered by TenderSystem
				$content.= " Powered by TenderSystem.";
			}
		}
		if(!$this->sessionid) {
			if($this->create_sms_session($cfg,$conn) <= 0) {
				// instantiate the error class and log
				$new_error = new error;
				// convert error message
				require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
				// No more sms credits
				$error_text[]= $lang['1077'];
				// log the error
				$new_error->log("Message","serious",$error_text,$cfg);
				// response
				return FALSE;	
			}
		}
		$send_url = $cfg['sms']['urlsend']."?session_id=".$this->sessionid;
		$send_url.= "&to=".$message['phone_mobile']."&text=".urlencode($content)."&concat=3";
		if($message['receipt_code']) {
			$send_url.="&req_feat=8192&deliv_ack=1&climsgid=".$message['receipt_code'];
		}
		if($cfg['sms']['receipt'] == "callback") {
			$send_url.="&req_feat=8192&callback=2&deliv_ack=1";
		}
		$send_message = file_get_contents($send_url);
		$send_status = explode(":",$send_message);
		if ($send_status[0] == "ID") {
			// set the reference
			$this->message['reference'] = $send_status[1];
			// response
			return TRUE;
		} elseif ($send_status[0] == "ERR") {
			// set the error
			$send_error = trim($send_status[1]);
			// instantiate the error class and log
			$new_error = new error;
			// convert error message
			require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
			// 1078 - SMS application error
			$this->error_text[] = $lang['1078'].": ".$send_error;
			// log the error
			$new_error->log("Message","serious",$this->error_text,$cfg);
			// response
			return FALSE;
		} else {
			// instantiate the error class and log
			$new_error = new error;
			// convert error message
			require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
			// 1079 - Connection to SMS application server could not be established
			$error_text[]= $lang['1079'];
			// log the error
			$new_error->log("Message","serious",$error_text,$cfg);
			// response
			return FALSE;
		}
	}
	
	function create_sms_session($cfg,$conn) {
		// create a session
		$send_url = str_replace("http/sendmsg","http/auth",$cfg['sms']['urlsend'])."?api_id=".$cfg['sms']['api_id']."&user=".$cfg['sms']['user']."&password=".$cfg['sms']['password'];
		$ret = file_get_contents($send_url);
		$info = explode(":",$ret);
		if($info[0] == "OK") {
			$this->sessionid = trim($info[1]);
			// get balance
			$send_url = str_replace("http/sendmsg","http/getbalance",$cfg['sms']['urlsend'])."?session_id=".$this->sessionid;
			$ret = file_get_contents($send_url);
			$info = explode(":",$ret);
			if($info[0] == "Credit") {
				return trim($info[1]);
			} else {
				// set the error
				$send_error = trim($info[1]);
			}
		} else {
			// set the error
			$send_error = trim($info[1]);
		}
		if($send_error) {
			// instantiate the error class and log
			$new_error = new error;
			// convert error message
			require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
			// 1078 - SMS application error:
			$this->error_text[] = $lang['1078'].": ".$send_error;
			// log the error
			$new_error->log("Message","serious",$this->error_text,$cfg);
		}
		// response
		return 0;
	}

	function check_receipt($receipt_code,$cfg,$conn) {
		// only do a query if receipt code present to prevent SQL error
		if ($receipt_code) {
			// determine if present
			$sqlstr = "SELECT id ";
			$sqlstr.= "FROM ~message_schedule ";
			$sqlstr.= "WHERE receipt_code = '".$receipt_code."' ";
			$sqlstr.= "ORDER BY id DESC";
			$new_database = new database;
			$new_database->parse_sql($sqlstr,$cfg);
			// execute the query
	 		$response = $conn->GetOne($sqlstr);
	       	if ($conn->ErrorMsg()) {
				// instantiate the error class and log
				$new_error = new error;
				$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
				$new_error->log("SQL","critical",$error_text,$cfg);
				// set the response error
				$this->error[] = "1065";
				// response
				return FALSE;
	       	}
			// return message
			return $response;
		} else {
			return FALSE;
		}
	}
	
	function update_receipt_status($message_id,$receipt_ip,$status,$cfg,$conn) {
		$new_database = new database;
		$update['receipt_ip'] = $receipt_ip;
		$update['receipt_status'] = intval($status);
		$new_database->setTime("receipt",$update,"",$cfg);
		$where = " id = ".$message_id;
		if(!$new_database->update_table("~message_schedule",$update,$where,$cfg,$conn)) {
			if(!empty($new_database->error)) {
				$this->error = array_merge($this->error,$new_database->error);
			}
			return FALSE;
		} 
		// return that category_brand deleted
      	return TRUE;
	}
	
	function message_display ($file,$cfg,$conn) {
		// determine if present
		$sqlstr = "SELECT * ";
		$sqlstr.= "FROM ~message_schedule ";
		$sqlstr.= "WHERE id = '".$file['id']."' ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		// execute the query
 		$response = $conn->GetRow($sqlstr);
       	if ($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// set the response error
			$this->error[] = "1065";
			// response
			return FALSE;
       	} elseif (!$response) {
			// response
			return FALSE;
       	}
		// set repsonse
		if($response['send_method'] == "sms") {
			$response['filename'] = "sms.txt";
			$response['filetype'] = "text/plain";
		} else {
			$response['filename'] = "email.html";
			$response['filetype'] = "text/html";
		}
		// return message
		return $response;
	}
	
	function message_log($params,$cfg,$conn) {
		// ensure that not viewing larger than set limit
		if ($params['searchinfo']['display'] > $cfg['display']['limit']) {
			// set to the maximum
			$params['searchinfo']['display'] = $cfg['display']['limit'];
		}
		$sqlstr = "SELECT * ";
		// FROM
		$sqlstr.= "FROM ~message_schedule ";
		// ORDER BY
		$sqlstr.= "ORDER BY ~message_schedule.id DESC ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		$result = $conn->SelectLimit($sqlstr,$cfg['message']['logs'],$cfg['message']['logs']*$params['searchinfo']['display']);
		if($result) {
			$all = $result->GetRows();
		}
		if($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while querying into database 
			$this->error[] = "1065";
			// response
			return FALSE;
		}
		$new_users = new user;
		// final status codes
		$final_code = array("0","3","4","5","6","7","8","9","10","12");
		foreach($all as $key => $value) {
			if($value['created_by'] == "0") {
				$all[$key]['creator_name'] = "TenderSystem";	
			} else {
				$users_info = $new_users->get_info($value['created_by'],$cfg,$conn);
				$all[$key]['creator_name'] = $users_info['name'][0]." ".$users_info['surname'];
			}
			
			if($value['user_id'] == "0") {
				$all[$key]['behalf'] = "TenderSystem";	
			} else {
				$users_info = $new_users->get_info($value['user_id'],$cfg,$conn);
				$all[$key]['behalf'] = $users_info['name'][0]." ".$users_info['surname'];
			}
			
			if($value['body'] !== "1" && $value['body'] !== "2" && $value['body'] !== "") {
				$all[$key]['body'] = "3";	
			}
			if($cfg['sms']['receipt'] == "query" && $value['send_method'] == "sms" && !in_array($value['receipt_status'],$final_code)) {
				if(!$this->sessionid) {
					if($this->create_sms_session($cfg,$conn) <= 0) {
						// instantiate the error class and log
						$new_error = new error;
						// convert error message
						require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
						// 1077 - No more sms credits
						$error_text[]= $lang['1077'];
						// log the error
						$new_error->log("Message","serious",$error_text,$cfg);
						unset($error_text);
					}
				}
				if($this->sessionid && $value['receipt_code']) {
					// create a session
					$send_url = str_replace("http/sendmsg","http/querymsg",$cfg['sms']['urlsend'])."?session_id=".$this->sessionid."&climsgid=".$value['receipt_code'];
					$ret = file($send_url);
					$info = explode(":",$ret[0]);
					if ($info[0] == "ERR") {
						// set the error
						$send_error = trim($send_status[1]);
						// instantiate the error class and log
						$new_error = new error;
						// convert error message
						require($cfg['file']."modules/generic/language/".$cfg['language']."/error.php");
						// 1078 - SMS application error:
						$error_text[] = $lang['1078'].": ".$info[1];
						// log the error
						$new_error->log("Message","serious",$error_text,$cfg);
						unset($error_text);
					} elseif($info[0] == "ID") {
						$this->update_receipt_status($value['id'],"127.0.0.1",$info[2],$cfg,$conn);
						$all[$key]['receipt_ip'] = "127.0.0.1";
						$all[$key]['receipt_status'] = intval($info[2]);
					}
				}
			}
		}
		$new_database->convertTime($all,$cfg);
		return $all;
	}
	
	function delete_message($id,$usersid,$cfg,$conn) {
		$new_database = new database;
		$update['status'] = "0";
		$update['deleted_by'] = $usersid;
		$new_database->setTime("deleted",$update,"",$cfg);
		$where = " id = ".$id." ";
		if(!$new_database->update_table("~message_schedule",$update,$where,$cfg,$conn)) {
			if(!empty($new_database->error)) {
				$this->error = array_merge($this->error,$new_database->error);	
			}
			return FALSE;
		} 
      	return TRUE;
	}
}
?>