<?php
/*
    borrowed from services_captiveportal_saml_federation.php

    Copyright (C) 2008 Shrew Soft Inc.
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/
/*
	pfSense_MODULE:	captive_portal
*/

##|+PRIV
##|*IDENT=page-services-captiveportal-saml-federation
##|*NAME=Service: Captive portal SAML federation manager
##|*DESCR=Allow access to the 'Service: Captive portal SAML federation manager' page.
##|*MATCH=services_captiveportal_saml_federation.php*
##|-PRIV

require("guiconfig.inc");
require_once("captiveportal_saml.inc");
require_once("certs.inc");

$pgtitle = array(gettext("Service"), gettext("Captive portal"),"SAML 2.0 Federations");
$shortcut_section = "captiveportal";


if (is_numericint($_GET['id']))
	$id = $_GET['id'];
if (isset($_POST['id']) && is_numericint($_POST['id']))
	$id = $_POST['id'];

if (!is_array($config['ca']))
	$config['ca'] = array();

$a_ca =& $config['ca'];

if (!is_array($config['cert']))
	$config['cert'] = array();

$a_cert =& $config['cert'];

$act = $_GET['act'];
if ($_POST['act'])
	$act = $_POST['act'];

if (!is_array($config['univnautes']))
        $config['univnautes'] = array();
$a_univnautes =& $config['univnautes'];

if (!is_array($a_univnautes['federations']))
        $a_univnautes['federations'] = array();
$federations =& $a_univnautes['federations'];

if (!is_array($federations['federation']))
        $federations['federation'] = array();
$a_federation =& $federations['federation'];


if ($act == "del") {

	if (!isset($a_federation[$id])) {
		pfSenseHeader("services_captiveportal_saml_federation.php");
		exit;
	}

	$name = $a_federation[$id]['descr'];
	unset($a_federation[$id]);
	write_config();

	/* reload federation (and geoinfos) */
	mwexec_bg("/usr/local/univnautes/sp/rc.sh syncdata");

	$savemsg = sprintf(gettext("Federation %s successfully deleted"), $name) . "<br/>";
	pfSenseHeader("services_captiveportal_saml_federation.php");
	exit;
}

if ($act == "edit") {
	if (!$a_federation[$id]) {
		pfSenseHeader("services_captiveportal_saml_federation.php");
		exit;
	}
	$pconfig['enable'] = isset($a_federation[$id]['enable']);
	$pconfig['refid'] = $a_federation[$id]['refid'];
	$pconfig['codename'] = $a_federation[$id]['codename'];
	$pconfig['descr'] = $a_federation[$id]['descr'];
	$pconfig['url'] = $a_federation[$id]['url'];
	$pconfig['metadata'] = base64_decode($a_federation[$id]['metadata']);
	$pconfig['certref'] = $a_federation[$id]['certref'];
}

if ($act == "new") {
	$pconfig['enable'] = true;
}

if ($_POST) {

	unset($input_errors);
	$input_errors = array();
	$pconfig = $_POST;

	/* input validation */
	$reqdfields = explode(" ", "codename descr certref");
	$reqdfieldsn = array(
			gettext("Codename"),
			gettext("Description"),
			gettext("Metadata Certificate"),
			gettext("HTTPS CA Certificate"));

	do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors);

	/* if this is an AJAX caller then handle via JSON */
	if (isAjax() && is_array($input_errors)) {
		input_errors2Ajax($input_errors);
		exit;
	}

	if (preg_match('/[^A-Za-z0-9_]/', $_POST['codename'])) {
		$input_errors[] = gettext("The codename can only contain letters, digits, and underscores (_).");
	}


        if(!$_POST['metadata'] && $_POST['url'] && !is_URL($_POST['url'])) {
            $input_errors[] = sprintf(gettext("The metadata URL must be a valid url."), $_POST['url']);
        } elseif(!($_POST['metadata'] || $_POST['url'])) {
            $input_errors[] = sprintf(gettext("Metadata URL or content must provided."), $_POST['metadata']);
        }

	/* save modifications */
	if (!$input_errors) {

		$federation = array();
		if (!isset($pconfig['refid']) || empty($pconfig['refid']))
			$federation['refid'] = uniqid('fed_');
		else
			$federation['refid'] = $pconfig['refid'];

		if (isset($id) && $a_federation[$id])
			$federation = $a_federation[$id];

		$federation['codename'] = $pconfig['codename'];
		$federation['descr'] = $pconfig['descr'];
		$federation['url'] = $pconfig['url'];
		$federation['metadata'] = base64_encode(utf8_encode(trim($pconfig['metadata'])));
		$federation['certref'] = $pconfig['certref'];

		if ($_POST['enable'])
			$federation['enable'] = true;
		else
			unset($federation['enable']);

		if (isset($id) && $a_federation[$id])
			$a_federation[$id] = $federation;
		else
			$a_federation[] = $federation;

                /* echo "<pre>";
                #print_r($config);
                print_r($id);
                print_r($a_federation);
                print_r($federation);
                exit; */

		write_config();

		/* reload federation (and geoinfos) */
		mwexec_bg("/usr/local/univnautes/sp/rc.sh syncdata");

		pfSenseHeader("services_captiveportal_saml_federation.php");
	}
}

include("head.inc");
?>

<body link="#000000" vlink="#000000" alink="#000000" onload="<?= $jsevents["body"]["onload"] ?>">
<?php include("fbegin.inc"); ?>

<?php
	if ($input_errors)
		print_input_errors($input_errors);
	if ($savemsg)
		print_info_box($savemsg);
?>

<table width="100%" border="0" cellpadding="0" cellspacing="0" summary="CA manager">
	<tr>
		<td><?php display_saml_tabs(basename(__FILE__));  ?></td>
	</tr>
	<tr>
		<td id="mainarea">
			<div class="tabcont">

				<?php if ($act == "new" || $act == "edit" || $act == gettext("Save") || $input_errors): ?>

				<form action="" method="post" name="iform" id="iform">
					<?php if ($act == "edit"): ?>
					<input type="hidden" name="edit" value="edit" id="edit" />
					<input type="hidden" name="id" value="<?php echo htmlspecialchars($id); ?>" id="id" />
					<input type="hidden" name="refid" value="<?php echo $pconfig['refid']; ?>" id="refid" />
					<?php endif; ?>
					<table width="100%" border="0" cellpadding="6" cellspacing="0" summary="main area">
						<tr>
                                                        <td width="22%" valign="top" class="vncellreq"><?=gettext("Code
 name");?></td>
                                                        <td width="78%" class="vtable">
                                                        <?php
                                                        if ($act == 'new') {
                                                        ?>
                                                        <input name="codename" type="text" class="formfld unknown" id="codename" size="20" value="<?=htmlspecialchars($pconfig['codename']);?>" placeholder="codename" />
                                                        <br/>Can not be changed after. The codename can only contain letters, digits, and underscores (_).
                                                        <?php } else { ?>
                                                        <input name="codename" type="hidden" value="<?=htmlspecialchars($pconfig['codename']);?>" /><?=$pconfig['codename'];?>
                                                        <?php }; ?>
                                                        </td>
                                                </tr>
						<tr>
							<td width="22%" valign="top" class="vtable">&nbsp;</td>
							<td width="78%" class="vtable">
							<input name="enable" type="checkbox" value="yes" <?php if ($pconfig['enable']) echo "checked"; ?>><strong><?=gettext("Enable this federation"); ?> </strong></td>
						</tr>
						<tr>
							<td width="22%" valign="top" class="vncellreq"><?=gettext("Description");?></td>
							<td width="78%" class="vtable">
								<input name="descr" type="text" class="formfld unknown" id="descr" size="65" value="<?=htmlspecialchars($pconfig['descr']);?>" />
							</td>
						</tr>
					</table>

					<table width="100%" border="0" cellpadding="6" cellspacing="0" id="existing" summary="existing">
						<tr>
							<td colspan="2" class="list" height="12"></td>
						</tr>
						<tr>
							<td colspan="2" valign="top" class="listtopic"><?=gettext("Federation");?></td>
						</tr>
						<tr>
							<td width="22%" valign="top" class="vncellreq"><?=gettext("Metadata URL");?></td>
							<td width="78%" class="vtable">
								<input name="url" type="text" class="formfld url" id="url" size="65" value="<?=htmlspecialchars($pconfig['url']);?>" placeholder="https://..." />
							</td>
						</tr>
						<tr>
							<td width="22%" valign="top" class="vncellreq"></td>
							<td width="78%" class="vtable"><?=gettext("or");?>
							</td>
						</tr>
						<tr>
							<td width="22%" valign="top" class="vncellreq"><?=gettext("Local metadata (xml)");?></td>
							<td width="78%" class="vtable">
								<textarea name="metadata" class="formpre" cols="65" rows="5" placeholder="<EntitiesDescriptor> ... </EntitiesDescriptor>"><?=htmlspecialchars(utf8_decode($pconfig['metadata']));?></textarea><br />
								If metadata are defined here, it disables the download URL above.
							</td>
						</tr>
						<tr>
							<td width="22%" valign="top" class="vncellreq"><?=gettext("Metadata certificate"); ?></td>
							<td width="78%" class="vtable">
								<?php if (count($a_cert)): ?>
								<select name="certref" id="certref" class="formselect">
									<option value="__none__">None</option>
									<?php
										foreach($a_cert as $cert):
											$selected = "";
											if ($pconfig['certref'] == $cert['refid'])
												$selected = "selected";
									?>
									<option value="<?=$cert['refid'];?>" <?=$selected;?>><?=$cert['descr'];?></option>
									<?php endforeach; ?>
								</select>
                                                                <br/><?=gettext("If None, metadata signature will not be checked."); ?>
								<?php else: ?>
									<b><?=gettext("No Certificates defined."); ?></b> <br/>Create one under <a href="system_certmanager.php">System &gt; Cert Manager</a>.
								<?php endif; ?>
							</td>
						</tr>

					</table>

					<table width="100%" border="0" cellpadding="6" cellspacing="0" summary="save">
						<tr>
							<td width="22%" valign="top">&nbsp;</td>
							<td width="78%">
								<input id="submit" name="save" type="submit" class="formbtn" value="<?=gettext("Save"); ?>" />
								<?php if (isset($id) && $a_ca[$id]): ?>
								<input name="id" type="hidden" value="<?=htmlspecialchars($id);?>" />
								<?php endif;?>
							</td>
						</tr>


					</table>
				</form>

				<?php else: ?>

				<table width="100%" border="0" cellpadding="0" cellspacing="0" summary="">
					<tr>
						<td width="10%" class="listhdrr"><?=gettext("Active");?></td>
						<td width="15%" class="listhdrr"><?=gettext("Codename");?></td>
						<td width="20%" class="listhdrr"><?=gettext("Description");?></td>
						<td width="50%" class="listhdrr"><?=gettext("URL or local metadata");?></td>
					</tr>
					<?php
						$i = 0;
						foreach($a_federation as $federation):
							$name = htmlspecialchars($federation['codename']);
							$descr = htmlspecialchars($federation['descr']);
							$url = htmlspecialchars($federation['url']);
							$metadata = htmlspecialchars(utf8_decode(base64_decode($federation['metadata'])));
					?>
					<tr>
						<td class="listlr"><?php
							if (isset($federation['enable'])) echo 'x';
						?></td>
						<td class="listr"><?=$name;?></td>
						<td class="listr"><em><?=$descr;?></em></td>
						<td class="listr"><?php
							if ($metadata)
								echo '<em>local metadata:</em> ' . substr($metadata,0,40) . ' ...';
							else
								echo $url;
						?>&nbsp;</td>
						<td valign="middle" nowrap class="list">
							<a href="services_captiveportal_saml_federation.php?act=edit&amp;id=<?=$i;?>">
								<img src="/themes/<?= $g['theme'];?>/images/icons/icon_e.gif" title="<?=gettext("edit");?>" alt="<?=gettext("edit");?>" width="17" height="17" border="0" />
							</a>
							<a href="services_captiveportal_saml_federation.php?act=del&amp;id=<?=$i;?>" onclick="return confirm('<?=gettext("Do you really want to delete this Federation?");?>')">
								<img src="/themes/<?= $g['theme'];?>/images/icons/icon_x.gif" title="<?=gettext("delete");?>" alt="<?=gettext("delete"); ?>" width="17" height="17" border="0" />
							</a>
						</td>
					</tr>
					<?php
							$i++;
						endforeach;
					?>
					<tr>
						<td class="list" colspan="5"></td>
						<td class="list">
							<a href="services_captiveportal_saml_federation.php?act=new">
								<img src="/themes/<?= $g['theme'];?>/images/icons/icon_plus.gif" title="<?=gettext("add or import ca");?>" alt="<?=gettext("add ca");?>" width="17" height="17" border="0" />
							</a>
						</td>
					</tr>
					<tr>
						<td colspan="5">
							<p>
								<?=gettext("Additional Federations can be added here.");?>
							</p>
						</td>
					</tr>
				</table>

				<?php endif; ?>

			</div>
		</td>
	</tr>
</table>
<?php include("fend.inc");?>
<script type="text/javascript">
//<![CDATA[

method_change();

//]]>
</script>

</body>
</html>
