<?php
require_once('/opt/secioss/share/simplesamlphp/www/_include.php');

require_once('SimpleSAML/Utilities.php');
require_once('SimpleSAML/Session.php');
require_once('SimpleSAML/XHTML/Template.php');

/* Load simpleSAMLphp, configuration and metadata */
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();

if (!isset($session) || !$session->isValid('saml2') ) {
  $params = array('RelayState' => SimpleSAML_Utilities::selfURL());
  if (isset($_GET['tenant'])) {
    $params['tenant'] = $_GET['tenant'];
  }
  SimpleSAML_Utilities::redirect(
    '/' . $config->getBaseURL() .
    'saml2/sp/initSSO.php',
    $params
    );
}

$attributes = $session->getAttributes();
$data = '';
foreach ($attributes as $key => $values) {
    $data .= ($data ? '#' : '').strtolower($key).'='.join(',', $values);
}

$nameid = $session->getNameID();
$_SERVER['REMOTE_USER'] = $nameid['value'];
$_SERVER['REMOTE_USER_DATA'] = $data;

if ($config->getValue('logout.cookies')) {
    $loggedin = true;
    foreach (preg_split('/, */', $config->getValue('logout.cookies')) as $cookie) {
        if (!isset($_COOKIE[$cookie])) {
            $loggedin = false;
            break;
        }
    }
    if ($loggedin) {
        $_SERVER['REMOTE_USER_LOGGEDIN'] = true;
    }
}
?>
