<?php




	/**
	* 	Modified Twilio API classes to work for SugarOnDemand Instance.
	* 	Added additional helper methods.
	*	Implemented via cURL.
	*/


	class Services_Twilio
	{		
		protected $_twilio;
		protected $mode;
		protected $account_sid;
		protected $auth_token;
		protected $api_version;
		protected $number;


		public function __construct($Account_sid,$Auth_token,$api_version = NULL)
		{		
			/* configure the twilio Settings */
			$this->mode        = 'sandbox';
			$this->account_sid = $Account_sid;
			$this->auth_token  = $Auth_token;
			$this->api_version = '2010-04-01';
			//$this->number      = '+13107766837';			

			//initialize the client
			$this->_twilio = new TwilioRestClient($this->account_sid, $this->auth_token);
		}

		/**
		 * __call
		 *
		 * @desc Interface with rest client
		 *
		 */
		public function __call($method, $arguments)
		{
			if (!method_exists( $this->_twilio, $method) )
			{
				throw new Exception('Undefined method Twilio::' . $method . '() called');
			}

			//return call_user_func_array( array($this->_twilio, $method), $arguments);
			return custom_call_user_func_array(array($this->_twilio, $method),$arguments);
		}
		
		
		/**
		*	The Test call to test the Twilio API Credentials 
		*	Whether they are valid or invalid
		*/
		public function verify_twilio_creds()
		{
			$url = '/' . $this->api_version . '/Accounts';	
			$data = array();
			
			return $this->_twilio->request($url, 'GET', $data, $basic_auth = TRUE);			
		}
		
		
		function verify_appsid($application_sid)
		{
			$url = '/' . $this->api_version .'/Accounts/' . $this->account_sid . '/Applications/' . $application_sid;
			
			$data = array();
			
			return $this->_twilio->request($url, 'GET', $data, $basic_auth = TRUE); 	
		}
		
		
		public function send_sms($from, $to, $message,$callback = null)
		{
			$url = '/' . $this->api_version . '/Accounts/' . $this->account_sid . '/SMS/Messages';
			if($callback != null)
			{
				$data = array(
							'From'   => $from,
							'To'   => $to,
							'Body' => $message,
							'StatusCallback' => $callback,
				);
			}
			else
			{
				$data = array(
							'From'   => $from,
							'To'   => $to,
							'Body' => $message,);
			}

		
			return $this->_twilio->request($url, 'POST', $data,$basic_auth = TRUE);
		}
		
		/**
		 * Make Call
		 *
		 * @desc Make a simple Click to Call from phone to phone 
		 */
		public function make_call($source,$destination,$callback_url)
		{
			$url = '/' . $this->api_version . '/Accounts/' . $this->account_sid . '/Calls';
			
			$data = array(
						'From' => $source,
						'To' => $destination,
						'Url' => $callback_url,
						); 
				
			return $this->_twilio->request($url, 'POST',$data,$basic_auth = TRUE);		
		}
		
		
		
	}

  
    // Twilio REST Helpers
    // ========================================================================

    // ensure Curl is installed
    if(!extension_loaded("curl"))
        throw(new Exception(
            "Curl extension is required for TwilioRestClient to work"));

    /*
     * TwilioRestResponse holds all the REST response data
     * Before using the reponse, check IsError to see if an exception
     * occurred with the data sent to Twilio
     * ResponseXml will contain a SimpleXml object with the response xml
     * ResponseText contains the raw string response
     * Url and QueryString are from the request
     * HttpStatus is the response code of the request
     */
    class TwilioRestResponse {

        //public $ResponseText;
        public $ResponseXml;
        public $HttpStatus;
        public $Url;
        public $QueryString;
        public $IsError;
        public $ErrorMessage;

        public function __construct($url, $text, $status) {
            preg_match('/([^?]+)\??(.*)/', $url, $matches);
            $this->Url = $matches[1];
            $this->QueryString = $matches[2];
            //$this->ResponseText = $text;
            $this->HttpStatus = $status;
            if($this->HttpStatus != 204)
                $this->ResponseXml = @simplexml_load_string($text);

            if($this->IsError = ($status >= 400))
                $this->ErrorMessage =
                    (string)$this->ResponseXml->RestException->Message;

        }

    }

    /* TwilioRestClient throws TwilioException on error
     * Useful to catch this exception separately from general PHP
     * exceptions, if you want
     */
    class TwilioException extends Exception {}

    /*
     * TwilioRestBaseClient: the core Rest client, talks to the Twilio REST
     * API. Returns a TwilioRestResponse object for all responses if Twilio's
     * API was reachable Throws a TwilioException if Twilio's REST API was
     * unreachable
     */

    class TwilioRestClient {

        protected $AccountSid;
        protected $AuthToken;
        protected $Endpoint;
		protected $Endpoint_basic_auth;

        /*
         * __construct
         *   $username : Your AccountSid
         *   $password : Your account's AuthToken
         *   $endpoint : The Twilio REST Service URL, currently defaults to
         * the proper URL
		 *	
         */
        public function __construct($accountSid, $authToken){
		
            $this->AccountSid = $accountSid;
            $this->AuthToken = $authToken;
            $this->Endpoint = "https://api.twilio.com";			
			$this->Endpoint_basic_auth = "https://{$accountSid}:{$authToken}@api.twilio.com";
		}
		
        /*
         * sendRequst
         *   Sends a REST Request to the Twilio REST API
         *   $path : the URL (relative to the endpoint URL, after the /v1)
         *   $method : the HTTP method to use, defaults to GET
         *   $vars : for POST or PUT, a key/value associative array of data to
         * send, for GET will be appended to the URL as query params
         */
        public function request($path, $method = "GET", $vars = array(),$basic_auth = FALSE) {
            $fp = null;
            $tmpfile = "";
            $encoded = "";
            foreach($vars AS $key=>$value)
                $encoded .= "$key=".urlencode($value)."&";
            $encoded = substr($encoded, 0, -1);

            // construct full url
			$url = ($basic_auth == TRUE)? "{$this->Endpoint_basic_auth}$path" : "{$this->Endpoint}$path";            
			
			//~ $GLOBALS['log']->debug("final url formation => ");
			//~ $GLOBALS['log']->debug(print_r($url,1));
			
            // if GET and vars, append them
            if($method == "GET")
                $url .= (FALSE === strpos($path, '?')?"?":"&").$encoded;

            // initialize a new curl object
            $curl = curl_init($url);
										    
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cache-Control: no-cache",));			
            switch(strtoupper($method)) {
                case "GET":
                    curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
                    break;
                case "POST":
                    curl_setopt($curl, CURLOPT_POST, TRUE);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $vars);
                    break;
               
                default:
                    throw(new TwilioException("Unknown method $method"));
                    break;
            }
      
            // do the request. If FALSE, then an exception occurred
            if(FALSE === ($result = curl_exec($curl)))
                throw(new TwilioException(
                    "Curl failed with error " . curl_error($curl)));

            // get result code
            $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            return new TwilioRestResponse($url, $result, $responseCode);
            
        }
    }




try{
		
	$twilio_ext           = new Services_Twilio($_REQUEST['account_sid'],$_REQUEST['account_token']);
	
	/*
	 * Send SMS  Request
	 */
		
	if(isset($_REQUEST['action_name']) && $_REQUEST['action_name'] =="send_sms_to_user"){


       
       
       
       /*
        * Licence validation
        */
            $is_valid_key  = true;
            $message       = '';
            //$url  = "https://store.suitecrm.com/api/v1/key/validate?public_key=0b79130d203a9197c55efa800c957edc&key=".$_REQUEST['licence_key']."";
            //if($_REQUEST['add_on_type']==2){
            $url  = "https://store.suitecrm.com/api/v1/key/validate?public_key=a656a1e8ed65cb005311704442aff1a7&key=".$_REQUEST['licence_key']."";
            //}
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
            $result = curl_exec($curl);
            //die; 
            //print_r($result);
            
          if($result=='"Key is required."'){
			  
			$is_valid_key  = false;
			$message       = " Missing license key on API call";
			
		  }
          if($result=='"Public Key is required."'){
			  
			$is_valid_key  = false;
			$message       = " Missing public key on API call ";
			
		  }
          if($result=='"Public Key does not exist."'){
			  
			$is_valid_key  = false;
			$message       = "The public key does not exist in our system";
			
		  }
          if($result=='"Key is inactive."'){
			  
			$is_valid_key  = false;
			$message       = "The key has been marked as inactive by the SuiteCRM Store. This may happen if their is license key abuse or something is just not right on our side.";
			
		  }
          if($result=='"Key does not exist."'){
			
			$is_valid_key  = false;
			$message       = "The license key does not exist in our system";
			
		  }
		  
          if($result=='"User Count must be an integer."'){
			
			$is_valid_key  = false;
			$message       = "User Count is not a valid integer, must be greater than 0";
			
		  }
          if($result=='"Key is suspended by seller."'){
			
			$is_valid_key  = false;
			$message       = "Seller suspends a key/Key is suspended by seller";
			
		  }
        
       //~ $is_valid_key  = true;
		if(!$is_valid_key || $is_valid_key==false){
		  $sendmsg = array("HttpStatus"=>99999,"IsError"=>1,"ErrorMessage"=>$message);
		  (object)	$sendmsg ;
		}else{
		 $sendmsg = $twilio_ext->send_sms($_REQUEST['source_number'],$_REQUEST['destination_number'],$_REQUEST['sms_message']);
	    }
	    
	    /*
        * Create Log File 
        */
       
         $date = date('[Y-m-d H:i]:');
         file_put_contents('/var/www/old_dev/twilio_api/logs/' . date('Y-m-d') . '.log', $date . PHP_EOL . json_encode($_REQUEST) . PHP_EOL . json_encode($sendmsg) . PHP_EOL, FILE_APPEND | LOCK_EX);
         
         /** End Log File **********/
         
		print_r(json_encode($sendmsg));
		die;
	}
	
} catch (communicaitonException $e) {
		$GLOBALS['log']->fatal("Caught communicaitonException ('{$e->getMessage()}')\n{$e}\n");
	} catch (settingsException $e) {
		$GLOBALS['log']->fatal("Caught settingsException ('{$e->getMessage()}')\n{$e}\n");
	} catch (Exception $e) {
		$GLOBALS['log']->fatal("Caught Exception ('{$e->getMessage()}')\n{$e}\n");
	}	

