<?php

require_once("auth.inc");
require_once("util.inc");
require_once("functions.inc");
require_once("captiveportal.inc");

header("Expires: 0");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Connection: close");

global $g, $config, $cpzone, $cpzoneid, $cpzoneprefix;

$cpzone = strtolower($_REQUEST['zone']);
$cpcfg = config_get_path("captiveportal/{$cpzone}");

if (empty($cpcfg)) {
	log_error("rfc8910.php - Submission to captiveportal with unknown parameter zone: " . htmlspecialchars($cpzone));
	portal_reply_page($redirurl, "error", gettext("Internal error"));
	ob_flush();
	return;
}

$cpzoneid = $cpcfg['zoneid'];
$clientip = $_SERVER['REMOTE_ADDR'];

if (is_array($cpcfg['allowedip'])) {
	foreach ($cpcfg['allowedip'] as $ipent) {
		if ($ipent['ip'] == $clientip) {
			if ($ipent['dir'] != 'to') {
				// 'clientip' is part of the 'allowedip' list
				ob_flush();
				return;
			}
		}
	}
}

$clientmac = pfSense_ip_to_mac($clientip);
if (!is_array($clientmac)) {
	if (!isset($cpcfg['nomacfilter']) || isset($cpcfg['passthrumacadd'])) {
		/* unable to find MAC address - shouldn't happen! - bail out */
		captiveportal_logportalauth("unauthenticated", "noclientmac", $clientip, "ERROR");
		echo "An error occurred.  Please check the system logs for more information.";
		log_error("Zone: {$cpzone} - Captive portal could not determine client's MAC address.  Disable MAC address filtering in captive portal if you do not need this functionality.");
		ob_flush();
		return;
	}
}
else if (is_array($cpcfg['passthrumac'])) {
	foreach ($cpcfg['passthrumac'] as $macent) {
		if ($macent['mac'] == $clientmac['macaddr']) {
			if ($macent['action'] == 'pass') {
				// 'clientmac' is part of the 'allowed MAC' list
				ob_flush();
				return;
			}
		}
	}
}

$cpsession = captiveportal_isip_logged($clientip);
$sessionid = $cpsession['sessionid'];
$rfc8910_url = 'https://' . $_SERVER['HTTP_HOST'] . '/index.php?zone=' . $cpzone;

ob_flush();
if (empty($cpsession)) {
/*	captiveportal_logportalauth("rfc8910", "EMPTY SESSION", $clientip, $cpzone); */
/*	$seconds_remaining = $cpcfg['timeout'] * 60; */
	$json_post  = array (
		"captive" => true,
		"user-portal-url" => "$rfc8910_url",
		"venue-info-url" => "$rfc8910_url"
);

echo json_encode($json_post, JSON_PRETTY_PRINT);

} else {
/*	captiveportal_logportalauth("rfc8910", "EXISTING SESSION", $clientip, $cpzone); */
/*	$seconds_remaining = (time()-$cpsession['allow_time'])+($cpcfg['timeout']*60); */
	$json_post  = array (
		"captive" => false,
		"user-portal-url" => "$rfc8910_url",
		"venue-info-url" => "$rfc8910_url"
);
echo json_encode($json_post, JSON_PRETTY_PRINT);

}
ob_flush();

return;
?>