<?php

/**
 * This PHP file is the webapp auth api calls to check it's KOPANO_WEBAPP cookie
 * and to retrieve tokens
 */

include("zarafa_session.php");
include("../config.php");
include_once('class.webmeetingsauth.php');

$webmeetingsAuth;

$token_secret = PLUGIN_SPREEDWEBRTC_WEBAUTH_ACCESS_TOKEN_SECRET;
$token_name = 'ACCESS_TOKEN';

$access_token = '';
if ($_POST && array_key_exists("access_token", $_POST)) {
	$access_token = $_POST['access_token'];
}
$client_id = '';
if ($_POST && array_key_exists("client_id", $_POST)) {
	$client_id = base64_encode($_POST['client_id']);
}
$client_secret = '';
if ($_POST && array_key_exists("client_secret", $_POST)) {
	$client_secret = base64_encode($_POST['client_secret']);
}

$data_mac = base64_decode($access_token);
$parts = explode('|', $data_mac);
$time = $parts[0];
$value = $parts[1];
$mac = $parts[2];
$time_value = $time . '|' . $value  . '|';

if ($time < time()) {
	header('HTTP/1.1 403 Unauthorized');
	echo json_encode(array('success' => false, 'code' => 'expired'));
	exit;
}

if ($mac != base64_encode(hash_hmac('sha256', $token_name . '|' . $time_value, $token_secret, true))) {
	header('HTTP/1.1 403 Unauthorized');
	echo json_encode(array('success' => false, 'code' => 'failed'));
	exit;
}

$value_parts = explode(':', $value);
$value_type = $value_parts[0];
$value_sessionid = $value_parts[1];
$value_user_id = $value_parts[2];
$value_displayname = $value_parts[3];
$value_client_id = $value_parts[4];
$value_client_secret = $value_parts[5];

if ($client_id != $value_client_id && $client_secret != $value_client_secret) {
	header('HTTP/1.1 403 Unauthorized');
	echo json_encode(array('success' => false, 'code' => 'bad_client'));
	exit;
}

if ($value_type == 'zarafa') {
	if ($value_sessionid !== $GLOBALS["mapisession"]->getSessionID()) {
		header('HTTP/1.1 403 Unauthorized');
		echo json_encode(array('success' => false, 'code' => 'invalid_session'));
		exit;
	}

	if (isset($_SESSION['username']) && $_SESSION['username'] !== $value_user_id) {
		header('HTTP/1.1 403 Unauthorized');
		echo json_encode(array('success' => false, 'code' => 'other_session_exists'));
		exit;
	}

	if (!$GLOBALS["mapisession"]->isLoggedOn()) {
		header('HTTP/1.1 403 Unauthorized');
		echo json_encode(array('success' => false, 'code' => 'session_ended'));
		exit;
	}
}

$webmeetingsAuth = new WebmeetingsAuth($value_user_id, $value_displayname);

$webmeetings_data = $webmeetingsAuth->getWebmeetingsData();

$token_response = array(
	'success' => true,
	'webmeetings_data' => $webmeetings_data
);

header("Content-Type: application/json");
header("Cache-Control: no-store");
header("Pragma: no-cache");
echo json_encode($token_response);
exit;

?>
