<?php
  
include_once('class.turnauth.php');

class WebmeetingsAuth {
	/**
	 * Constructor
	 * 
	 * @param $url : URL to turnserverauth webservice
	 */
	function WebmeetingsAuth($user_id, $displayname) {
		$this->sharedsecret = PLUGIN_SPREEDWEBRTC_WEBMEETINGS_SHARED_SECRET;
		$this->userid = $user_id ? $user_id : $GLOBALS['mapisession']->getEmailAddress();
		$this->fullname = $displayname ? $displayname : $GLOBALS["mapisession"]->getFullName();
		if (WebAppAuthentication::isAuthenticated()) {
			$this->userimage = $GLOBALS['mapisession']->getUserImage();
		} else {
			$this->userimage = NULL;
		}
	}

	function getWebmeetingsAuthToken()
	{
		$this->time = time() + PLUGIN_SPREEDWEBRTC_WEBMEETINGS_AUTHENTICATION_EXPIRES;
		$hash = base64_encode(hash_hmac('sha256', $this->time . ':' . $this->userid, $this->sharedsecret, true));
		return $hash;
	}

	function getWebmeetingsData() {
		$turn_ttl = 0;
		$turn_expires = 0;
		$turn_username = NULL;
		$turn_password = NULL;
		$turn_urls = NULL;
		$turndata = NULL;
		// if turn service used then get turn access info
		if (PLUGIN_SPREEDWEBRTC_TURN_USE_KOPANO_SERVICE) {
			if (!isset($this->turnAuthConnector)) {
				$this->turnAuthConnector = new TurnAuthConnector(PLUGIN_SPREEDWEBRTC_TURN_AUTHENTICATION_URL);
				$this->turnAuthConnector->setCredentials(
					PLUGIN_SPREEDWEBRTC_TURN_AUTHENTICATION_USER, 
					PLUGIN_SPREEDWEBRTC_TURN_AUTHENTICATION_PASSWORD
					);
			}
			$turndata = $this->turnAuthConnector->getTurnAuthData();

			if ($turndata) {
				$turn_ttl = $turndata->ttl;
				$turn_expires = time() + $turn_ttl;
				$turn_username = $turndata->username;
				$turn_password = $turndata->password;
				$turn_urls = $turndata->uris;
			}
		}

		$response = array(
			'secret' => $this->getWebmeetingsAuthToken(),
			'userid' => $this->userid,
			'timestamp' => $this->time,
			'fullname' => $this->fullname,
			'buddyPicture' => $this->userimage ? $this->userimage : '',
			'turn_ttl' => $turn_ttl,
			'turn_username' => $turn_username,
			'turn_password' => $turn_password,
			'turn_urls' => $turn_urls
			);
		return $response;

	}

}
?>
