<?php
if (empty($_COOKIE['CGISESSID'])) {
  echo "<div style='font-family: sans-serif; margin: auto; padding: 20px; border: 1px solid #ccc; border-radius: 10px; max-width: 400px; margin-top: 2em;'><h1 style='margin: 0;'>CEMS Login Error:</h1><br>This page has expired. <a href=Login>Please login to continue.</a></div>";
  return;
}

function getVal($ar,$keys) {
  foreach ($keys as $k) {
    if (isset($ar[$k]) && is_array($ar[$k]) && isset($ar[$k][0]) && is_string($ar[$k][0])) {
      return $ar[$k][0];
    }
  }
  return "";
}

function getSSOAttribNames() {
  $sso_attrib_names = [
    'saml_username_attrib' => ['urn:oid:0.9.2342.19200300.100.1.1/username','urn:oid:0.9.2342.19200300.100.1.1','urn:oid:1.3.6.1.4.1.5923.1.1.1.6','username','uid','NetID','http://schemas.xmlsoap.org/ws/2005/05/identity/claims/username','http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname','http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name','eduPersonPrincipalName'],
    'saml_firstname_attrib' => ['urn:oid:2.5.4.42/givenname','urn:oid:2.5.4.42','givenname','givenName','fname','firstname','firstName','first name','http://schemas.xmlsoap.org/ws/2005/05/identity/claims/first name','http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname','http://connectauthenticate/sso/first_name','urn:firstname'],
    'saml_lastname_attrib' => ['urn:oid:2.5.4.4/sn','urn:oid:2.5.4.4','sn','lname','lastname','last name','lastName','http://schemas.xmlsoap.org/ws/2005/05/identity/claims/last name','http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname','http://connectauthenticate/sso/last_name','urn:lastname'],
    'saml_status_attrib' => ['urn:oid:2.5.4.12','urn:oid:1.3.6.1.4.1.5923.1.1.1.5'],
    'saml_wk_phone_attrib' => ['urn:oid:2.5.4.20','telephoneNumber'],
    'saml_email_attrib' => ['urn:oid:0.9.2342.19200300.100.1.3/email','urn:oid:1.2.840.113549.1.9.1','urn:oid:0.9.2342.19200300.100.1.3','urn:oid:1.3.6.1.4.1.5923.1.1.1.6','email','mail','http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email','http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress','http://connectauthenticate/sso/email_address','urn:email'],
  ];

  $fn = '../../conf/cems.conf';
  if (file_exists($fn)) {
    $lines = file($fn);
    foreach ($lines as $line) {
      if (preg_match('/^(saml_\w+)\s+(.*)$/', $line, $matches)) {
        $key = $matches[1];
        $val = trim($matches[2], "\"' \n\r\t\v\x00");
        if (! empty($val)) {
          if ($key == "saml_authsource") {
            $sso_attrib_names[$key]=$val;
          }
          else if (array_key_exists($key, $sso_attrib_names)) {
            $sso_attrib_names[$key]=[$val];
          }
        }
      }
    }
  }

  if (! isset($sso_attrib_names["saml_authsource"])) {
    $sso_attrib_names["saml_authsource"] = 'default-sp';
  }

  //error_log(print_r(['$sso_attrib_names: ', $sso_attrib_names], true));
  return $sso_attrib_names;
}

// Set UTF-8 for proper handling of accented characters, etc
setlocale(LC_CTYPE, 'en_US.UTF-8');
putenv('LC_ALL=en_US.UTF-8');

// Initialize simplesaml >= 2.0 changed file paths and now requires namespaces
if (file_exists('../../simplesamlphp/src/_autoload.php')) {
  require_once('../../simplesamlphp/src/_autoload.php');
} else {
  require_once('../../simplesamlphp/lib/_autoload.php');
}
$cems_config = getSSOAttribNames();
$saml = new SimpleSAML\Auth\Simple($cems_config["saml_authsource"]);
$config = SimpleSAML\Configuration::getInstance();
$baseurlpath = $config->getString('baseurlpath');
$cemsurlbase = preg_replace('/\/simplesaml\/$/','',$baseurlpath);
$loginreturnurl = $cemsurlbase.'/CEMS/SimpleSAMLLogin.php';
//error_log("login returnto: ".$returnurl);
$saml->requireAuth( array('ReturnTo' => $loginreturnurl, ));
$attrs = $saml->getAttributes();

// FOR TESTING TODO REMOVE ONCE WORKING
//error_log(print_r($attrs, true));
$sessionID  = $_COOKIE['CGISESSID'];
$uid        = getVal($attrs, $cems_config['saml_username_attrib']);
$fname      = getVal($attrs, $cems_config['saml_firstname_attrib']);
$lname      = getVal($attrs, $cems_config['saml_lastname_attrib']);
$userstatus = getVal($attrs, $cems_config['saml_status_attrib']);
$wkphone    = getVal($attrs, $cems_config['saml_wk_phone_attrib']);
$email      = getVal($attrs, $cems_config['saml_email_attrib']);

// if uid is not in attributes, try and extract it from the authdata
if (empty($uid)) {
  // get nameID value (assume returned as XML)
  $nameid_xml_str = $saml->getAuthData('saml:sp:NameID');
  $nameid_xml_obj = new SimpleXMLElement($nameid_xml_str);
  $nameid = $nameid_xml_obj[0];
  $uid = $nameid_xml_obj[0];
}

$cmd = sprintf('perl ../../bin/authorize_session.pl -sessionid %s -fname %s -lname %s -email %s -username %s -status %s -wk_phone %s',
  escapeshellarg($sessionID),
  escapeshellarg($fname),
  escapeshellarg($lname),
  escapeshellarg($email),
  escapeshellarg($uid),
  escapeshellarg($userstatus),
  escapeshellarg($wkphone)
);

# error_log("cmd: ".$cmd);

$redirecturl = trim(`$cmd`);

if (preg_match("/^https?\:\/\//", $redirecturl)) {
  header("Location: $redirecturl");
} else {
  $attrs_dump = print_r($attrs, true);
  $msg = "ERROR: could not authorize session\nattributes: $attrs_dump\ncmd: $cmd\noutput: $redirecturl";
  error_log($msg);
  header("Content-Type: text/plain");
  echo $msg;
}
