<?php

include("webapp_auth_common.php");

class WebmeetingsAuthSimple {
	/**
	 * Constructor
	 *
	 * @param $room : room to generate simple pin for
	 * @param $time : time the meeting begins
	 */
	function WebmeetingsAuthSimple($time=null, $room=null) {
		$this->sharedsecret = PLUGIN_SPREEDWEBRTC_WEBMEETINGS_SHARED_SECRET;
		$this->time = $time ? $time : time() * 1000;
		$this->room = $room;
	}

	function getWebmeetingsAuthSimpleRoomPin($time=null, $room=null)
	{
		$time = $time ? $time : $this->time;
		$room = $room ? $room : $this->room;
		$room = $room ? $room : substr(preg_replace(MEETINGID_STRIP_REGEX, '', $GLOBALS['mapisession']->getEmailAddress()),0,MEETINGID_ROOMBASE_MAXLEN);
		$webmeetings_simple_epoch = intval(($time - 1420070400000) / (5*60000));
		$webmeetings_simple_epoch_base36 = str_pad(base_convert($webmeetings_simple_epoch,10,36), 4, "0", STR_PAD_LEFT);
		$hash = bin2hex(hash_hmac('sha256', $webmeetings_simple_epoch . ':' . $room, $this->sharedsecret, true));
		$hash_seg1 = substr($hash, 16, 4);
		$hash_seg2 = substr($hash, 32, 4);
		$hash_seg3 = substr($hash, 48, 4);
		$room_pin = $room . '-' . $webmeetings_simple_epoch_base36 . '-' . $hash_seg1 . '-' . $hash_seg2 . '-' . $hash_seg3;
		return $room_pin;
	}

	function getTimeFromWebmeetingsSimpleEpochBase36($webmeetings_simple_epoch_base36)
	{
		$time = (base_convert($webmeetings_simple_epoch_base36,36,10) * (5*60000)) + 1420070400000;
		return $time;
	}

	function checkWebmeetingsAuthSimpleRoomPinValid($room_pin)
	{
		$parts = explode('-', $room_pin);
		$room = $parts[0];
		$webmeetings_simple_epoch_base36 = $parts[1];
		$time = $this->getTimeFromWebmeetingsSimpleEpochBase36($webmeetings_simple_epoch_base36);
		$expected_room_pin = $this->getWebmeetingsAuthSimpleRoomPin($time, $room);
		return $room_pin == $expected_room_pin;
	}

	function checkWebmeetingsAuthSimpleRoomPinInTimeWindow($room_pin)
	{
		$parts = explode('-', $room_pin);
		$room = $parts[0];
		$webmeetings_simple_epoch_base36 = $parts[1];
		$time = $this->getTimeFromWebmeetingsSimpleEpochBase36($webmeetings_simple_epoch_base36);
		$now = time() * 1000;
		return $time - 4 * 3600000 <= $now && $now <= $time + 4 * 3600000;
	}

	function checkWebmeetingsAuthSimpleRoomPinTooEarly($room_pin)
	{
		$parts = explode('-', $room_pin);
		$room = $parts[0];
		$webmeetings_simple_epoch_base36 = $parts[1];
		$time = $this->getTimeFromWebmeetingsSimpleEpochBase36($webmeetings_simple_epoch_base36);
		$now = time() * 1000;
		return $now < $time - 4 * 3600000;
	}
}
?>