<?php
// Copyright 2008 fonolo. All Rights Reserved.
//
// +---------------------------------------------------------------------------+
// | fonolo PHP API client                                                     |
// +---------------------------------------------------------------------------+
// | Copyright (c) 2008 fonolo.                                                |
// | All rights reserved.                                                      |
// |                                                                           |
// | Redistribution and use in source and binary forms, with or without        |
// | modification, are permitted provided that the following conditions        |
// | are met:                                                                  |
// |                                                                           |
// | 1. Redistributions of source code must retain the above copyright         |
// |    notice, this list of conditions and the following disclaimer.          |
// | 2. Redistributions in binary form must reproduce the above copyright      |
// |    notice, this list of conditions and the following disclaimer in the    |
// |    documentation and/or other materials provided with the distribution.   |
// |                                                                           |
// | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR      |
// | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
// | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.   |
// | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,          |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT  |
// | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY     |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT       |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF  |
// | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.         |
// +---------------------------------------------------------------------------+
// | For help with this library, contact developers@fonolo.com                 |
// +---------------------------------------------------------------------------+

class fonolo_api {

	private $_auth_key;
	private $response_server;
	private $version;

	public function __construct($_auth_key=null) 
	{
		$this->auth_key = $_auth_key;
		$this->response_server = "https://json-rpc.live.fonolo.com/";
		$this->version = "1.1";
	}

	//
	// Set login, password
	//
	public function set_member_info($_auth_login, $_auth_pwd)
	{
		$this->auth_login = $_auth_login;
		$this->auth_pwd = $_auth_pwd;
	}	

	//
	//  This function makes a request to the response server.
	//
	public function get_json_contents($_method, $_params, $_as_array=false, $_nologin=false)
	{
		if(($this->auth_key == null) || strlen($this->auth_key) != 32)
		{
			$err_msg = "Invalid authorization key -> Make sure you call: \$fonolo = new fonolo_api(\"YOUR KEY\");";
			return $this->send_error($err_msg, $_as_array);
		}

		// set the request data array
		$request = array(
			'version'	=> $this->version,
			'method'	=> $_method,
			'params'	=> $_params
		);

		// json encoding the data request array
		$content = json_encode($request);

		if($content == "false")
		{
			$err_msg = "json_encode failed -> check the \$request array in the fonolo_api class";
			return $this->send_error($err_msg, $_as_array);			
		}

		// set the options array without username/password
		if($_nologin == "true")
		{
			$options = array(
				'http' => array (
					'method' => "POST",
					'header' => "Content-Type: application/json\r\n" .
						"X-Fonolo-Auth:". $this->auth_key ."\r\n",
					'content' => $content
				)
			);			
		}
		
		// set options array with username/pass
		else
		{
			$options = array(
				'http' => array (
					'method' => "POST",
					'header' => "Content-Type: application/json\r\n" .
						"X-Fonolo-Auth:". $this->auth_key ."\r\n".
						"X-Fonolo-Username:". $this->auth_login ."\r\n".
						"X-Fonolo-Password:". $this->auth_pwd ."\r\n",
					'content' => $content
				)
			);
		}

		// create context        				
		$c = stream_context_create($options);

		if(get_resource_type($c) != "stream-context")
		{
			$err_msg = "stream_context_create failed -> check the \$options array in the fonolo_api class";
			return $this->send_error($err_msg, $_as_array);
		}

		// make request to server
		$response = file_get_contents($this->response_server, false, $c);

		//decode the response as array or object
		($_as_array=="true") ? $data = json_decode($response, true) : $data = json_decode($response);       

		if($data == "false")
		{
			$err_msg = "json_encode \$response failed";
			return $this->send_error($err_msg, $_as_array);			
		}

		return $data;  		      

	}
	
	//
	// This function sends the error as array or object
	//
	public function send_error($_message, $_as_array=false)
	{
		if($_as_array==true)
		{
			$error["result"]["head"]["response_code"] = 900;
			$error["result"]["head"]["response_message"] = $_message;	
		}
		else
		{
			$error->result->head->response_code = 900;
			$error->result->head->response_message = $_message;	
		}
		return $error;
	}

	//
	// Deprecated Company Functions
	//
	public function search_companies($_search_string)
	{
		return this->company_search($_search_string);
	}
	public function lookup_company($_tree_id)
	{
		return this->company_details($_tree_id);
	}
	public function list_companies($_limit, $_page, $_date_since)
	{
		return this->company_list($_limit, $_page, $_date_since);
	}

	//
	// This function searches the company list by either a company id, or a search string.
	// @argument; either a company id, or a search string.
	// @return; returns search results, with a list of companies.
	//
	public function company_search($_search_string)
	{
		return $this->get_json_contents("company_search", array($_search_string));
	}

	//
	// This function returns a full list of companies from the fonolo.com database.
	// @argument; 
	//		$_limit is the max number of companies per page
	//		$_page is the page number, starting at 0
	//		$_date_since is the date 
	//
	// @return; returns the full list of companies from the fonolo.com database
	//
	public function company_list($_limit, $_page, $_date_since)
	{
		return $this->get_json_contents("company_list", array($_limit, $_page, $_date_since));
	}

	//
	// This function returns the phone tree for the given company id (tree id).
	// @arguments; provide the company id (tree id).
	// @return; returns the full phone tree.
	//
	public function company_details($_tree_id)
	{
		return $this->get_json_contents("company_details", array($_tree_id), "true");   
	}

	//
	// This function initiates a deep-dial to a specific location in the phone tree.
	// @arguments; provide the node id to deep dial to, and the phone number to call back.
	// @return; returns a session id of the call session.
	//
	public function call_start($_node_id, $_phone_number)
	{
		return $this->get_json_contents("call_start", array($_node_id, $_phone_number));
	}

	//
	// This function cancels an existing call, initiated from a call_start command.
	// @arguments: provide the session id returned from the call_start command.
	// @return; returns if the request was true/false.
	//
	public function call_cancel($_session_id)
	{
		return $this->get_json_contents("call_cancel", array($_session_id));
	}

	//
	// This function returns status details about an existing call, initiated from a call_start command.
	// @arguments: provide the session id returned from the call_start command.
	// @return; returns the details about the call session.
	//
	public function call_status($_session_id)
	{
		return $this->get_json_contents("call_status", array($_session_id));
	}

	//
	// Validates the given username and password against the fonolo database.
	// @arguments: Provide the username and password of the member account to validate.
	// @returns: Nothing.	
	//	
	public function check_member($_username, $_password)
	{		
		return $authorization = $this->get_json_contents("check_member", array($_username, $_password),false,true);
	}

	//
	// Validates that the given number belongs to the username and password provided.
	// @arguments: Provide the username, password and number of the of the member number to validate.
	// @returns: Nothing.	
	//	
	public function check_member_number($_username, $_password, $_phonenumber)
	{		
		return $authorization = $this->get_json_contents("check_member_number", array($_username, $_password, $_phonenumber),false,true);
	}		

}
?>
