<?php
  
class TurnAuthConnector {
	
	var $url;
	var $user = "";
	var $pass = "";
	
	/**
	 * Constructor
	 * 
	 * @param $url : URL to turnserverauth webservice
	 */
	function TurnAuthConnector($url) {
		$this->url = $url;
	}

	/**
	 * setCredentials
	 * 
	 * @param $username
	 * @param $password
	 */
	public function setCredentials($username, $password) {
		$this->user = $username;
		$this->pass = $password;
	}
	
	/**
	 * getTurnAuth
	 *
	 * calls TurnAuth wegservice ang requests info and token
	 *
	 * @param $requestURL : the url to call
	 */
	public function getTurnAuthData() {
		$username = $this->user;
		$password = $this->pass;
		$error = NULL;
		$turndata = NULL;
		// Initialize the cURL session with the request URL
		$session = curl_init($this->url); 

		// Tell cURL to return the request data
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

		// Set the HTTP request authentication headers
		curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		curl_setopt($session, CURLOPT_USERPWD, "$username:$password");

		// Execute cURL on the session handle
		$response = curl_exec($session);

		if (empty($response)) {
    		// some kind of an error happened
    		$error = curl_error($session);
			curl_close($session); // close cURL session
			throw new ZarafaException(sprintf(_("Accessing the Kopano Web Meetings TURN authentication service failed.")));
		} else {
    		$info = curl_getinfo($session);
    		$http_code = $info['http_code'];
    		if ($http_code == '200') {
				// Decode the JSON response 
				$turndata = json_decode($response);
				curl_close($session); // close cURL session
    		} else {
				curl_close($session); // close cURL session
				throw new ZarafaException(sprintf(_("Accessing the Kopano Web Meetings TURN authentication service failed. HTTP code %s."), $http_code));
    		}
    	}
    	return $turndata;
	}
}
?>
