<?php
// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();
/*
osCommRes, Services Online 
http://www.oscommres.com 
Copyright (c) 2005 osCommRes 

Freeway eCommerce 
http://www.zac-ware.com/freeway 
Copyright (c) 2007 ZacWare 

Released under the GNU General Public License 
*/
  class clickatell {
    var $code, $title, $description, $enabled, $_connected;
	var $params,$host_url,$user_name,$password,$api_id;
	var $error_infos;
	var $session_track,$session_login_id;
	var $sent,$failed,$responses;
	var $error_code,$error_description;
	var $create_log;
	// class constructor
	function clickatell() {
		global $HTTP_SESSION_VARS,$PHP_SELF;
		$this->code = 'clickatell';
		$this->title = MODULE_SMS_CLICKATELL_TEXT_TITLE;
		$this->description = MODULE_SMS_CLICKATELL_TEXT_DESCRIPTION;
		$this->sort_order = MODULE_SMS_CLICKATELL_SORT_ORDER;
		$this->enabled = ((MODULE_SMS_CLICKATELL_STATUS == 'True') ? true : false);
		if (tep_session_is_registered('login_id') && $HTTP_SESSION_VARS['login_id']!='')
			$this->enabled=true;
		else if (basename($PHP_SELF) != FILENAME_SEND_MESSAGES_SCRIPT)
			$this->enabled=false;
		$this->host_url=MODULE_SMS_CLICKATELL_URL;
		//$this->host_url="http://api.clickatell.com";
		$this->user_name=MODULE_SMS_CLICKATELL_USERNAME;
		$this->password=MODULE_SMS_CLICKATELL_PASSWORD;
		$this->api_id=MODULE_SMS_CLICKATELL_API_ID;
		$this->session_track=false;
		$this->session_login_id="";
		$this->sent=array();
		$this->failed=array();
		$this->create_log=false;
		$this->error_infos=array("001"=>"Authentication failed",
								"002"=>"Unknown username or password",
								"003"=>"Sesssion ID expired",
								"004"=>"Account frozen",
								"005"=>"Missing session ID",
								"101"=>"Invalid or missing parameters",
								"102"=>"Invalid UDH. (User Data Header)",
								"103"=>"Unknown apimsgid (API Message ID)",
								"104"=>"Unknown climsgid (Client Message ID)",
								"105"=>"Invalid Destination Address",
								"106"=>"Invalid Source Address",
								"107"=>"Empty message",
								"108"=>"Invalid or missing api_id",
								"109"=>"Missing message ID",
								"110"=>"Error with email message",
								"111"=>"Invalid Protocol",
								"112"=>"Invalid msg_type",
								"113"=>"Max message parts exceeded *",
								"114"=>"Cannot route message **",
								"115"=>"Message Expired",
								"116"=>"Invalid Unicode Data",
								"201"=>"Invalid batch ID",
								"202"=>"No batch template",
								"301"=>"No credit left",
								"302"=>"Max allowed credit");
	}
	function send_sms($to,$from,$contents,$country){
		$to=trim($to);
		// fetch country code by passing country

		if (substr($to,0,1)=="0"){
			$country_query=tep_db_query("SELECT country_code from " . TABLE_COUNTRIES . " where countries_name='" . $country . "'");
			$country_result=tep_db_fetch_array($country_query);
			if ($country_result["country_code"]!=""){
				$to=$country_result["country_code"] . substr($to,1);
			}
		}
		$this->responses=array();
		if (!$this->_connected && $this->session_track){
		 if (!$this->connecthost()) return false;
		 $this->_connected=true;
		}

		$msg=$this->host_url . "/http/sendmsg?";
		if ($session_track==true && $this->session_login_id!=""){
			$msg.="session_login_id=" . $this->session_login_id;
		} else {
			$msg.="user=" . $this->user_name . "&password=" . $this->password ."&api_id=" . $this->api_id;
		}
		$msg.="&to=" . urlencode($to);
		$msg.="&from=" . urlencode(SMS_FROM_NAME);
		$msg.="&text=" . urlencode($contents);
		$result=$this->_send_msg($msg,"ID");
		//if ($result) $this->sent[$to]=$this->responses["ID"];
		//else $this->failed[$to]=$this->error_description;
		return $result;
	}
    function get_failed_messages(){
		if (sizeof($this->failed)<=0) return "";
		reset($this->failed);
		$result="SMS error:<br>";
		while(list($id,)=each($this->failed))
			$result.="To: " . $id . " - " . $this->failed[$id];

		return $result;
	}
	function connecthost(){
		$this->responses=array();
		$msg=$this->host_url . "/http/auth?user=" . $this->user_name;
		$msg.="&password=" . $this->password ."&api_id=" . $this->api_id;
		$result=$this->_send_msg($msg,"OK");
		if ($this->session_track==true && isset($this->responses["OK"])){
			$this->session_login_id=$this->responses["OK"];
		}
		return $result;
	}
	function _send_msg($msg,$return_response){
		// get response from url;
		$responses=array();
		ini_set('default_socket_timeout',    180);
		$response=@file($msg);
		if ($this->create_log) {
			$log_write=join("\n",$response);
			$handle=@fopen(DIR_FS_CATALOG_IMAGES . "sms.log","a");
			fwrite($handle,$log_write,strlen($log_write));
			fclose($handle);
		}
		if (sizeof($response)<=0) return false;
		$success=false;
		for($icnt=0;$icnt<sizeof($response);$icnt++){
			$cmd=split(":",$response[$icnt]);
			if (sizeof($cmd)<2) return false;
			if ($cmd[0]==$return_response){
				$responses[$return_response]=trim($cmd[1]);
				$success=true;
			} else if ($cmd[0]=="ERR") {
				//$this->error_code=trim($cmd[1]);
				$this->error_description=trim($cmd[1]);
			} else{
				$this->error_description="unknown error";
			}
		}
		return $success;
	}
	function get_error(){
		return $this->error_description;
	}	
	function set_option($name,$value){
		if (isset($this->$name)){
			$element=&$this->$name;
			$element=$value;
		}
	}
	// install related procedures
    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Clickatell sms Module', 'MODULE_SMS_CLICKATELL_STATUS', 'True', 'Do you want to include Clickatell SMS?',6, '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now());");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell Sort order of display.', 'MODULE_SMS_CLICKATELL_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.',6, '2', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell Host Url.', 'MODULE_SMS_CLICKATELL_URL', '', 'Gateway URL used to access',6, '3', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell Username.', 'MODULE_SMS_CLICKATELL_USERNAME', '', 'Username used to authenticate gateway',6, '4', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell Password.', 'MODULE_SMS_CLICKATELL_PASSWORD', '', 'Password used to authenticate gateway',6, '5', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell API id.', 'MODULE_SMS_CLICKATELL_API_ID', '', 'API id used to authenticate gateway',6, '6', now())");
    }

    function remove() {
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SMS_CLICKATELL_STATUS'");
        $this->_check = tep_db_num_rows($check_query);
      }
      return $this->_check;
    }

    function keys() {
      return array('MODULE_SMS_CLICKATELL_URL','MODULE_SMS_CLICKATELL_STATUS',  'MODULE_SMS_CLICKATELL_SORT_ORDER','MODULE_SMS_CLICKATELL_USERNAME','MODULE_SMS_CLICKATELL_PASSWORD','MODULE_SMS_CLICKATELL_API_ID');
    }
  }
?>
